2#include <assimp/scene.h>
3#include <glm/gtc/quaternion.hpp>
4#include <glm/gtx/matrix_decompose.hpp>
27 for (
auto& part :
parts) {
28 if (
auto*
entity = ecs::try_get(part.entity)) ecs::DestroyEntity(
entity);
29 if (
auto*
entity = ecs::try_get(part.outline)) ecs::DestroyEntity(
entity);
31 if (
auto* gfx = ModuleManager::getInstance<graphics::Graphics>(
"Graphics"); gfx && !
providerLifetime.expired()) {
32 for (
auto& part :
parts)
33 if (gfx->releaseMesh(part.mesh))
delete part.mesh;
42 auto* fs = filesystem::Filesystem::create();
43 std::unique_ptr<filesystem::FileData>
file(fs->read(std::string(
path)));
44 if (!
file)
throw std::runtime_error(
"VRM file could not be read");
45 auto parsed =
parseVrm({
static_cast<const std::byte*
>(
file->getData()),
file->getSize()});
46 if (!parsed.ok())
return R::failure(parsed.status());
47 auto* gfx = ModuleManager::getInstance<graphics::Graphics>(
"Graphics");
48 if (!gfx || gfx->getBackendName() !=
"vulkan")
50 "VRM import requires an initialized graphics provider",
52 auto candidate = std::make_unique<VrmRuntime>();
53 candidate->document = std::move(parsed).takeValue();
54 candidate->providerLifetime = gfx->resourceLifetime();
55 auto&
d = candidate->document;
57 candidate->model.reset(model3d::Model3D::create()->newModelData(
file.get(),
".glb"));
59 candidate->player = std::make_unique<animation::AnimPlayer>(candidate->skeleton.get());
60 candidate->nodeBones.resize(
d.nodes.size(), -1);
61 for (
size_t n = 0;
n <
d.nodes.size(); ++
n) {
62 if (!
d.nodes[
n].empty()) candidate->nodeBones[
n] = candidate->skeleton->findBone(
d.nodes[
n]);
64 auto requireNode = [&](
int node) {
65 if (
node >= 0 && candidate->nodeBones[
node] < 0)
66 throw std::runtime_error(
"Cannot resolve VRM node: " +
d.nodes[
node]);
69 for (
auto&
c :
d.colliders) requireNode(
c.node);
70 for (
auto&
s :
d.springs) {
71 requireNode(
s.center);
72 for (
auto& j :
s.joints) requireNode(j.node);
74 std::vector<VrmAtlasRect> rectangles;
76 candidate->textures.push_back(atlas);
77 for (
auto&
m :
d.materials) candidate->surfaces.push_back(
buildVrmSurface(*gfx,
m, *atlas, rectangles));
78 const auto*
scene = candidate->model->getScene();
79 for (
size_t n = 0;
n <
d.nodes.size(); ++
n) {
80 if (
d.nodeMeshes[
n] < 0)
continue;
81 const auto*
node =
scene->mRootNode->FindNode(
d.nodes[
n].c_str());
82 if (!
node)
throw std::runtime_error(
"Cannot resolve VRM mesh node: " +
d.nodes[
n]);
83 const auto&
slots =
d.meshMaterials[
d.nodeMeshes[
n]];
85 throw std::runtime_error(
"VRM primitive mapping changed during decode");
86 for (
unsigned p = 0;
p <
node->mNumMeshes; ++
p) {
91 if (part.
material < 0)
throw std::runtime_error(
"VRM primitive is missing its material");
92 candidate->parts.push_back(std::move(part));
93 auto&
owned = candidate->parts.back();
95 if (!
owned.mesh)
throw std::runtime_error(
"Mesh upload failed");
96 if (candidate->model->hasBones(
owned.sourceMesh)) {
98 candidate->skeleton.get()));
100 throw std::runtime_error(
"VRM GPU skin upload failed");
102 auto*
entity = graphics::Renderable3D::create();
104 entity->setVisible(
false);
106 entity->setMaterial(candidate->surfaces[
owned.material]->material.get());
107 if (
auto*
material = candidate->surfaces[
owned.material]->outlineMaterial.get()) {
108 auto* outline = graphics::Renderable3D::create();
109 owned.outline = ecs::handle_of(outline);
110 outline->setVisible(
false);
111 outline->setMesh(
owned.mesh);
116 if (candidate->parts.empty())
throw std::runtime_error(
"VRM contains no renderable primitives");
117 candidate->particles_.resize(
d.springs.size());
118 for (
size_t i = 0; i <
d.springs.size(); ++i) candidate->particles_[i].resize(
d.springs[i].joints.size());
119 return R::success(std::move(candidate));
120 }
catch (
const std::exception& e) {
128 for (
auto& part :
parts) {
129 glm::mat4 partWorld =
matrix;
130 if (!part.skin &&
nodeBones[part.node] >= 0) {
131 glm::mat4 nodeMatrix(1);
132 player->getPose()->getWorldMatrix(
nodeBones[part.node], &nodeMatrix[0][0]);
133 partWorld *= nodeMatrix;
135 glm::vec3
scale, translation, skew;
137 glm::vec4 perspective;
138 glm::decompose(partWorld,
scale,
rotation, translation, skew, perspective);
141 for (
auto handle : {part.entity, part.outline})
143 entity->setPosition(translation.x, translation.y, translation.z);
154 for (
auto& part :
parts)
155 if (part.skin && !part.skin->updateGpuMesh(part.mesh, &
pose))
156 throw std::runtime_error(
"VRM skin palette no longer matches imported skeleton");
161 float blink = 0, mouth = 0, look = 0;
162 auto overrideValue = [](
const std::string& mode,
float weight) {
163 return mode ==
"block" &&
weight > 0 ? 1.f : mode ==
"blend" ?
weight : 0.f;
166 float w = std::clamp(avatar.
getParameter(e.name) + (gazeWeights_.contains(e.name) ? gazeWeights_[e.name] : 0.f),
168 if (e.binary)
w =
w > .5f ? 1.f : 0.f;
170 blink += overrideValue(e.overrideBlink,
w);
171 mouth += overrideValue(e.overrideMouth,
w);
172 look += overrideValue(e.overrideLookAt,
w);
175 s->current =
s->base;
177 s->uvOffset = {0, 0};
179 for (
auto& part :
parts) {
180 part.mesh->clearMorphWeights();
181 for (
int i = 0; i < part.mesh->getMorphCount(); ++i) {
182 auto name = part.mesh->getMorphName(i);
188 float suppression = 0;
189 if (e.name ==
"blink" || e.name ==
"blinkLeft" || e.name ==
"blinkRight") suppression = blink;
190 if (e.name ==
"aa" || e.name ==
"ih" || e.name ==
"ou" || e.name ==
"ee" || e.name ==
"oh") suppression = mouth;
191 if (e.name ==
"lookUp" || e.name ==
"lookDown" || e.name ==
"lookLeft" || e.name ==
"lookRight")
193 float w =
weights[i] * (1 - std::clamp(suppression, 0.f, 1.f));
194 if (e.binary && suppression > 0)
w = 0;
195 for (
const auto& bind : e.morphs)
196 for (
auto& part :
parts)
197 if (part.node == bind.node) {
198 auto name = part.mesh->getMorphName(bind.index);
199 part.mesh->setMorphWeight(
name, part.mesh->getMorphWeight(
name) + bind.weight *
w);
201 for (
const auto&
b : e.colors) {
203 auto add = [&](
auto&
out,
const auto& base) {
204 for (
size_t c = 0;
c <
out.size(); ++
c)
out[
c] += (
b.target[
c] - base[
c]) *
w;
206 if (
b.type ==
"color")
207 add(
s.current.color,
s.base.color);
208 else if (
b.type ==
"emissionColor")
209 add(
s.current.emission,
s.base.emission);
210 else if (
b.type ==
"shadeColor")
211 add(
s.current.shade,
s.base.shade);
212 else if (
b.type ==
"matcapColor")
213 add(
s.current.matcap,
s.base.matcap);
214 else if (
b.type ==
"rimColor")
215 add(
s.current.rim,
s.base.rim);
216 else if (
b.type ==
"outlineColor")
217 add(
s.current.outline,
s.base.outline);
219 for (
const auto&
b : e.uvs)
220 for (
int c = 0;
c < 2; ++
c) {
225 auto* gfx = ModuleManager::getInstance<graphics::Graphics>(
"Graphics");
227 for (
auto& part :
parts)
228 if (part.mesh->isMorphDirty()) gfx->bakeMeshMorph(part.mesh);
eve::EntitySpatialPose pose
std::array< float, 4 > rotation
std::array< float, 3 > scale
std::array< uint32_t, 16 > material
std::weak_ptr< PrimitiveScene > scene
const EntityFact * entity
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
static AnimSkeleton * loadSkeletonFromModel(const model3d::ModelData *model)
ModelData wrappers (AnimImporterModel.cpp; requires model3d).
Evaluated local (and optional world) pose for an AnimSkeleton. Script type: AnimPose.
static AnimSkin * fromModel(const model3d::ModelData *model, int meshIndex, const AnimSkeleton *skeleton)
Build skin binding for meshIndex on model, mapping bone names onto skeleton. Throws if the mesh has n...
Unified avatar instance. Kind is a string: "image" | "live2d" | "vroid". Script-facing API avoids ove...
float getParameter(const std::string &name) const
Returns the parameter.
bool hasParameter(const std::string &name) const
True when parameter.
static eve::Result< std::unique_ptr< VrmRuntime > > prepare(std::string_view path)
Prepare.
std::vector< int > nodeBones
void animate(AvatarInstance &avatar, animation::AnimPose &pose, float dt)
Animate.
std::vector< std::unique_ptr< VrmSurface > > surfaces
void morphs(AvatarInstance &avatar)
Morphs.
std::vector< graphics::Texture * > textures
std::vector< Part > parts
void sync(AvatarInstance &avatar, const glm::mat4 &world, bool visible)
Synchronizes .
std::weak_ptr< const void > providerLifetime
std::unique_ptr< animation::AnimPlayer > player
VrmRuntime()
Constructs a VrmRuntime.
~VrmRuntime()
Releases VrmRuntime resources.
EVENGINE_API_BACKENDS public API.
eve::Result< VrmDocument > parseVrm(std::span< const std::byte > bytes)
Validate a self-contained GLB's VRM extension before publishing runtime state.
graphics::Texture & buildVrmAtlas(graphics::Graphics &gfx, const VrmDocument &d, std::vector< VrmAtlasRect > &rects)
Prepare an atlas using the provider's owning resource factory. @ownership Graphics owns the result; c...
std::unique_ptr< VrmSurface > buildVrmSurface(graphics::Graphics &gfx, const VrmMaterial &data, graphics::Texture &atlas, const std::vector< VrmAtlasRect > &rects)
Builds vrm surface.
void eulerYxzFromQuat(const glm::qua< T, glm::defaultp > &q, T &yaw, T &pitch, T &roll)
Quaternion overload of eulerYxzFromMatrix(); float and double both work.
std::vector< VrmExpression > expressions