From 2e7c1abdaca39ad663623d4244c222cc23faed9b Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:12:08 +0100 Subject: [PATCH] feat(model): skinned parts of EU07M models move with their joints, skinned on the CPU (#539) * feat(model): skinned parts of EU07M models move with their joints, skinned on the CPU Stage 4 of the EU07M model format. A primitive with a skin (SKIN, SKJT, weights in VSKN or VSKW) was drawn in its bind pose. Now it follows the joints of its skin, in both renderers. - The joints are nodes of the model, so they're posed as before: animation events, the .mmd, SetRotate / SetTranslate from the vehicle code. The matrix of a joint is world(joint) * inverse bind(joint), world being the transform of the joint from the root of the model with the animations of the instance drawn (TSubModel::posed_transform()); the vertices lie in the bind pose in the space of the model, the transform of the node of the mesh left out, as in glTF. - The loader keeps the bind pose and the weights of a skinned primitive (skinning::skinned_geometry on the submodel) and the skins of the model (TModel3d::skins()). - The first pass of a frame to draw a skinned submodel of an instance works out the palette and, when it changed, moves the vertices on the CPU: positions by the blended matrix, normals and tangents by its rotation (model/skinning.cpp, gfx::skin_cache in rendering/common/skincache.cpp). The geometry of the instance is made or replaced before the passes of the next frame (flush() in the frame setup of both renderers), as nothing the passes draw may change while they draw (gfx::walk_sync): the vertices follow the joints a frame late. In the bind pose the shared geometry of the model is drawn; an instance not drawn for 600 frames lets go of its own. - Fix: a node with range_max_sq 0, which the spec gives as no limit, was never drawn (a model made anew rather than converted from E3D); it keeps the default range of a submodel now. - The editor self-test gets "animate ", which turns a submodel of an instance as an animation event does, since the editor doesn't run the events. Not in this commit: the skinning in a compute shader, bounds of the posed submodel, motion vectors and ray tracing of the moved vertices. Checked: a tube of two joints in two instances, one turned by 60 degrees at its middle, bends smoothly while the other stays straight, in Vulkan and GL 4.6, with gfx.gpucull 0 and 1 (time let run in the editor for the test only). Unit tests 1194/1194, 5 new ones for the weights, the bind pose, the blending and the file. Not built with GCC here. * fix(model): EU07M review of #539: a model made anew keeps its transforms, normals of scaled joints, the rest pose far from the origin - A node of a model made anew (legacy_flags 0) with a transform gets 0x8000, as a converted one has it: the walk and posed_transform() left such nodes out, so a skin was drawn off its place in the bind pose (the tube: the upper half 2 m off) and jumped when an animation set 0x4000 on the joint. - Normals are skinned by the cofactors of the blended rotation (the direction of its inverse transpose), with the sign of its determinant, not by the rotation: a joint scaled unevenly tilted the normals of its part. - rest_pose() takes the translation within the tolerance times the distance from the origin of the mesh and the joints (palette_scale()): the float chain rounds in proportion to it, and a model a few kilometres out counted as posed in the bind pose, with a geometry copy and a skinning pass of its own. Tests: the rest pose far from the origin, the normals of a stretched and of a mirroring joint. * fix(model): a mirroring joint turns the handedness of the tangent frame too, so the bitangent mirrors with the surface * feat(model): .r3a and .r3p in what this branch adds, as below it The model files are .r3a and the family store .r3p, selected with modelformat r3a (2fe1064f9 on feat/e4d-compact). * feat(model): .ng3d and .ng3p in what this branch adds, as below it The model files are .ng3d and the family store .ng3p, selected with modelformat ng3d (8637101d9 on feat/e4d-compact). --- CMakeLists.txt | 2 + application/editormodeselftest.cpp | 2 + application/editormodeselftestscene.cpp | 16 ++ docs/eu07m-format.md | 22 +++ model/Model3d.cpp | 27 +++ model/Model3d.h | 10 ++ model/eu07m/eu07m_load.cpp | 55 +++++- model/skinning.cpp | 158 +++++++++++++++++ model/skinning.h | 70 ++++++++ rendering/common/scenewalk.cpp | 30 +++- rendering/common/scenewalk.h | 2 + rendering/common/skincache.cpp | 135 ++++++++++++++ rendering/common/skincache.h | 72 ++++++++ rendering/opengl46/opengl46renderer.cpp | 3 + rendering/vulkan14/vulkan14frame.cpp | 3 + tests/unit/test_skinning.cpp | 222 ++++++++++++++++++++++++ 16 files changed, 819 insertions(+), 10 deletions(-) create mode 100644 model/skinning.cpp create mode 100644 model/skinning.h create mode 100644 rendering/common/skincache.cpp create mode 100644 rendering/common/skincache.h create mode 100644 tests/unit/test_skinning.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4cbf05057..ff99626c9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -437,6 +437,7 @@ set(SOURCES "rendering/common/localshadows.cpp" "rendering/common/cabprobe.cpp" "rendering/common/skyocclusion.cpp" +"rendering/common/skincache.cpp" "rendering/common/texturealpha.cpp" "rendering/common/terrainmaterials.cpp" "rendering/common/grassfield.cpp" @@ -866,6 +867,7 @@ set(CORE_SOURCES "model/eu07m/eu07m_io.cpp" "model/eu07m/eu07m_build.cpp" "model/eu07m/eu07m_dump.cpp" +"model/skinning.cpp" "${DEPS_DIR}/zstd/zstd.c" # the codecs of the vertex and index streams of EU07M "${DEPS_DIR}/meshoptimizer/src/vertexcodec.cpp" diff --git a/application/editormodeselftest.cpp b/application/editormodeselftest.cpp index 367cea0d3..30c3f7ad9 100644 --- a/application/editormodeselftest.cpp +++ b/application/editormodeselftest.cpp @@ -99,6 +99,8 @@ editor_mode::selftest_result editor_mode::selftest_dispatch(std::string const &c // key [ctrl] a key or right button event, as the window gives it // lineside the tab of the objects along the track in the track window // event queues the event +// animate turns a submodel of a model instance to the angles, as an animation event does (the +// editor doesn't run the events); the animation goes by the simulation time // memcell logs the memory cell // bendpanel unfolds the bend section of the toolset // openscenerypopup the window of File / Open scenery, its list searched for zz_ diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index 93387ff72..4f772d3a2 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -574,6 +574,22 @@ editor_mode::selftest_result editor_mode::selftest_scene(std::string const &comm WriteLog("SELFTEST event " + name + (event != nullptr ? " queued" : ": no such event")); return selftest_result::handled; } + if (command == "animate") + { + std::string node; + std::string submodel; + glm::vec3 angles{0.f}; + words >> node >> submodel >> angles.x >> angles.y >> angles.z; + auto *model{simulation::Instances.find(node)}; + auto container{model != nullptr ? model->GetContainer(submodel) : nullptr}; + if (container != nullptr) + { + container->WillBeAnimated(); + container->SetRotateAnim(angles, 1000.0); + } + WriteLog(format("SELFTEST animate %s %s: %s", node.c_str(), submodel.c_str(), container != nullptr ? "turning" : "no such submodel")); + return selftest_result::handled; + } if (command == "memcell") { std::string name; diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 123115653..809646da1 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -245,6 +245,28 @@ Domyślne `modelformat legacy` zostawia pliki `.ng3d` w spokoju. strumieni przy pierwszym odczycie. - Gwiazdy (`STAR`) trzymają kolor w normalnej, więc idą jako `gfx::basic_vertex` również w Vulkanie. +### Skinning + +Prymityw ze skórą (`skin` ≥ 0, wagi w `VSKN` albo `VSKW`) jest rysowany przez jointy swojej skóry, w obu rendererach. + +- **Układ.** Wierzchołki leżą w pozie bindu, w przestrzeni modelu, a transform węzła siatki jest pomijany, jak w glTF. + Macierz jointu to `świat(joint) · odwrotny bind(joint)`, gdzie świat to transform węzła jointu od korzenia modelu, z + animacjami egzemplarza. Odwrotny bind w `SKJT` odwraca więc świat jointu w pozie bindu. +- **Pozy.** Jointy to zwykłe węzły modelu, więc ustawia się je jak dotąd: eventy `animation`, animacje z `.mmd` i kod + pojazdów (`GetFromName`, `SetRotate`, `SetTranslate`). Osobne API nie jest potrzebne. +- **Wierzchołki.** Przejście renderera, które pierwsze w klatce rysuje skinowany submodel egzemplarza, liczy na CPU + paletę jointów i, jeśli zmieniła się od poprzedniej klatki, przesuwa wierzchołki (`gfx::skin_cache`, + `rendering/common/skincache.cpp`, matematyka w `model/skinning.cpp`). Pozycje idą przez mieszaną macierz, a normalne i + tangensy przez jej obrót. Geometria egzemplarza jest robiona i podmieniana przed przejściami następnej klatki, bo w + trakcie przejść nic, co rysują, się nie zmienia (`gfx::walk_sync`). Wierzchołki nadążają więc za jointami z + opóźnieniem jednej klatki, a w pierwszej klatce egzemplarz jest w pozie bindu. +- Dopóki jointy są w pozie bindu, rysowana jest geometria modelu, wspólna dla wszystkich egzemplarzy. Egzemplarz + niewidziany przez 600 klatek oddaje swoją geometrię. +- **Ograniczenia tej wersji:** skinning na CPU (compute shader to następny krok), granice submodelu z pozy bindu, + wektory ruchu i ray tracing bez ruchu jointów. +- Węzeł z `range_max_sq` 0 nie ma limitu odległości; wcześniej taki węzeł (model zrobiony od nowa, nie przekonwertowany + z E3D) nie był w ogóle rysowany. + ### Instancjonowanie modeli ze światłami Z `gfx.instancedlights 1` w `eu07.ini` modele ze światłami (`lights`, `Light_On##` / `Light_Off##`), np. głowice semaforów, diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 37ac9a523..30a684a63 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1337,6 +1337,33 @@ void TSubModel::RaAnimation(glm::mat4 &m, TAnimType a) } }; +glm::mat4 TSubModel::posed_transform() +{ + glm::mat4 result{1.f}; + for (auto *submodel = this; submodel != nullptr; submodel = submodel->Parent) + { + if ((submodel->iFlags & 0xC000) == 0) + { + continue; + } + glm::mat4 local{1.f}; + if (submodel->fMatrix) + { + local = glm::make_mat4(submodel->fMatrix->readArray()); + } + // a billboard turns by the modelview of the draw, which there's none of here + if ((submodel->b_aAnim != TAnimType::at_None) && (submodel->b_aAnim != TAnimType::at_Billboard)) + { + // RaAnimation() lets go of the matrix of a quaternion animation once applied: kept for the draw which follows + auto const animmatrix{submodel->mAnimMatrix}; + submodel->RaAnimation(local, submodel->b_aAnim); + submodel->mAnimMatrix = animmatrix; + } + result = local * result; + } + return result; +} + //--------------------------------------------------------------------------- void TSubModel::serialize_geometry(std::ostream &Output, bool const Packed, bool const Indexed, bool const UserData) const diff --git a/model/Model3d.h b/model/Model3d.h index 62341cdfc..0a241c679 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Float3d.h" #include "rendering/geometrybank.h" #include "model/material.h" +#include "model/skinning.h" #include @@ -164,6 +165,9 @@ public: // chwilowo // the compact streams of a submodel loaded from EU07M, in place of Vertices till they go to the renderer (Insert_Compact()) gfx::position_array CompactPositions; gfx::compact_array CompactAttributes; + // a submodel of an EU07M model skinned by the joints of a skin: its bind pose, for the renderer to move the vertices by the pose of + // the joints of each instance (rendering/common/skincache.h) + std::shared_ptr m_skin; float m_boundingradius { 0 }; std::uintptr_t iAnimOwner{ 0 }; // roboczy numer egzemplarza, który ustawił animację TAnimType b_aAnim{ TAnimType::at_None }; // kody animacji oddzielnie, bo zerowane @@ -186,6 +190,9 @@ public: int SeekFaceNormal( std::vector const &Masks, int const Startface, unsigned int const Mask, glm::vec3 const &Position, gfx::vertex_array const &Vertices ); void RaAnimation(TAnimType a); void RaAnimation(glm::mat4 &m, TAnimType a); + // the transform of the submodel from the root of the model, with the animations of the instance drawn (iInstance), in the order the + // walk of the renderer applies them: the matrix, then the animation, of each submodel flagged as transformed (0xC000) + glm::mat4 posed_transform(); // returns true if the submodel is a smoke emitter attachment point, false otherwise bool is_emitter() const; @@ -314,6 +321,7 @@ private: std::vector m_lodbounds; // filled on first use, see lod_bounds() bool m_lodboundsfound { false }; std::uint32_t m_stateversion { 0 }; // see state_version() + std::vector m_skins; // of an EU07M model, the skinned submodels refer to them void finish_binary( bool dynamic, bool hastangents ); @@ -337,6 +345,8 @@ public: return m_stateversion; } void state_changed() { ++m_stateversion; } + std::vector const & skins() const { + return m_skins; } TSubModel * AddToNamed(const char *Name, TSubModel *SubModel); nameoffset_sequence const & find_smoke_sources(); void AddTo(TSubModel *tmp, TSubModel *SubModel); diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index 1595eb2e8..509afcd15 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -119,6 +119,7 @@ class submodel_builder { void geometry(eu07m::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel); void fill(geometry_job const &Job) const; void indices(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const; + void skinned(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const; int texture(std::string_view Name); eu07m::model const &m_model; @@ -144,8 +145,13 @@ void submodel_builder::build(std::uint32_t const Index, TSubModel &Submodel) { } Submodel.iFlags = node.legacy_flags; Submodel.fSquareMinDist = node.range_min_sq; - Submodel.fSquareMaxDist = node.range_max_sq; + // 0 is no limit (a model made anew); a converted one carries the range of its E3D submodel. the submodel keeps its default + Submodel.fSquareMaxDist = node.range_max_sq > 0.f ? node.range_max_sq : Submodel.fSquareMaxDist; transform(Index, Submodel); + // a model made anew has no E3D flags (legacy_flags 0): a node of it with a transform keeps it as one converted from E3D does + // (0x8000), or the walk and posed_transform() would leave it out, and with it the joints of the skins + if ((node.legacy_flags == 0) && (Submodel.iMatrix >= 0) && (m_transforms[Index] != glm::mat4{1.f})) + Submodel.iFlags |= 0x8000; auto const parts{parts_of(m_model, node)}; Submodel.b_Anim = parts.animation; Submodel.eType = TP_ROTATOR; @@ -257,6 +263,8 @@ void submodel_builder::fill(geometry_job const &Job) const { submodel.CompactAttributes.resize(primitive.vertex_count); std::memcpy(submodel.CompactPositions.data(), m_model.positions.data() + primitive.base_vertex, primitive.vertex_count * sizeof(glm::vec3)); std::memcpy(submodel.CompactAttributes.data(), m_model.vertex_attributes.data() + primitive.base_vertex, primitive.vertex_count * sizeof(gfx::compact_attributes)); + if (primitive.skin >= 0) + skinned(primitive, submodel); return; } // the stars keep their colours in the normals of basic_vertex. each vertex is written once: reserved and appended, without the @@ -290,6 +298,39 @@ void submodel_builder::indices(eu07m::primitive_record const &Primitive, TSubMod } } +// the bind pose and the weights of a skinned primitive, which the renderer moves by the joints of each instance. the bind pose goes to the +// renderer as well (Insert_Compact()), drawn as long as the joints stay in it +void submodel_builder::skinned(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const { + auto skin{std::make_shared()}; + skin->skin = Primitive.skin; + skin->indices = Submodel.Indices; + skin->rest.reserve(Primitive.vertex_count); + skin->weights.reserve(Primitive.vertex_count); + auto const wide{m_model.weights.size() != m_model.vertex_count()}; + for (std::uint32_t idx = 0; idx < Primitive.vertex_count; ++idx) { + auto const source{std::size_t{Primitive.base_vertex} + idx}; + auto const &position{m_model.positions[source]}; + auto const &attribute{m_model.vertex_attributes[source]}; + auto const frame{eu07m::decode_qtangent(attribute.qtangent)}; + gfx::basic_vertex vertex; + vertex.position = {position[0], position[1], position[2]}; + vertex.normal = frame.normal; + vertex.tangent = glm::vec4{frame.tangent, frame.handedness}; + vertex.texture = {attribute.uv[0], attribute.uv[1]}; + skin->rest.push_back(vertex); + if (wide) { + auto const &weights{m_model.weights_wide[source]}; + skin->weights.push_back(skinning::unpack(weights.joints, weights.weights)); + } + else { + auto const &weights{m_model.weights[source]}; + std::array const joints{weights.joints[0], weights.joints[1], weights.joints[2], weights.joints[3]}; + skin->weights.push_back(skinning::unpack(joints, weights.weights)); + } + } + Submodel.m_skin = std::move(skin); +} + void submodel_builder::fill_geometry() { auto const threads{static_cast(vertex_count) < parallel_vertex_threshold ? 1u : std::clamp(std::thread::hardware_concurrency(), 1u, parallel_thread_limit)}; if (threads <= 1 || m_jobs.size() <= 1) { @@ -382,6 +423,18 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { ErrorLog("Bad model: \"" + FileName + "\" can't be built: " + Error.what(), logtype::model); return false; } + // the skins, with their joints as the submodels of the nodes + m_skins.clear(); + for (auto const &record : model.skins) { + skinning::skin skin; + for (auto const &joint : std::span{model.skin_joints}.subspan(record.joint_first, record.joint_count)) { + skin.joints.push_back(&Root[joint.node]); + auto const &bind{joint.inverse_bind}; + skin.inverse_bind.emplace_back(glm::vec4{bind[0], bind[1], bind[2], 0.f}, glm::vec4{bind[3], bind[4], bind[5], 0.f}, glm::vec4{bind[6], bind[7], bind[8], 0.f}, + glm::vec4{bind[9], bind[10], bind[11], 1.f}); + } + m_skins.push_back(std::move(skin)); + } m_vertexcount += builder.vertex_count; m_indexcount += builder.index_count; // the tangents come with the vertices diff --git a/model/skinning.cpp b/model/skinning.cpp new file mode 100644 index 000000000..3333072a7 --- /dev/null +++ b/model/skinning.cpp @@ -0,0 +1,158 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" + +#include "model/skinning.h" + +#include +#include +#include + +namespace skinning +{ + +template vertex_weights unpack(std::array const &Joints, std::array const &Weights) +{ + vertex_weights result; + result.joints = Joints; + auto total{0.f}; + for (std::size_t idx = 0; idx < 4; ++idx) + { + result.weights[idx] = static_cast(Weights[idx]) / static_cast(std::numeric_limits::max()); + total += result.weights[idx]; + } + if (total <= 0.f) + { + result.joints = {}; + result.weights = {1.f, 0.f, 0.f, 0.f}; + return result; + } + // the weights of the file add up to the largest value of the type; the rounding of the division is made up for here + for (auto &weight : result.weights) + { + weight /= total; + } + return result; +} + +template vertex_weights unpack(std::array const &, std::array const &); +template vertex_weights unpack(std::array const &, std::array const &); + +std::vector palette(glm::mat4 const &Mesh, std::span const Joints, std::span const InverseBind) +{ + auto const tomesh{glm::inverse(Mesh)}; + std::vector result; + result.reserve(Joints.size()); + for (std::size_t idx = 0; idx < Joints.size(); ++idx) + { + auto const inversebind{idx < InverseBind.size() ? InverseBind[idx] : glm::mat4{1.f}}; + result.emplace_back(tomesh * Joints[idx] * inversebind); + } + return result; +} + +bool rest_pose(std::span const Palette, float const Tolerance, float const Scale) +{ + glm::mat4 const identity{1.f}; + // the translation is rounded in proportion to the distances the palette was made of + auto const translation{Tolerance * std::max(1.f, Scale)}; + return std::ranges::all_of(Palette, [&identity, Tolerance, translation](glm::mat4 const &Matrix) { + for (int column = 0; column < 4; ++column) + { + auto const limit{column == 3 ? translation : Tolerance}; + for (int row = 0; row < 4; ++row) + { + if (std::abs(Matrix[column][row] - identity[column][row]) > limit) + { + return false; + } + } + } + return true; + }); +} + +float palette_scale(glm::mat4 const &Mesh, std::span const Joints) +{ + auto const reach{[](glm::mat4 const &Matrix) { return std::max({std::abs(Matrix[3][0]), std::abs(Matrix[3][1]), std::abs(Matrix[3][2])}); }}; + auto scale{reach(Mesh)}; + for (auto const &joint : Joints) + { + scale = std::max(scale, reach(joint)); + } + return scale; +} + +namespace +{ + +glm::mat4 blended(vertex_weights const &Weights, std::span const Palette) +{ + glm::mat4 result{0.f}; + for (std::size_t idx = 0; idx < 4; ++idx) + { + auto const weight{Weights.weights[idx]}; + if (weight <= 0.f) + { + continue; + } + auto const joint{static_cast(Weights.joints[idx])}; + result += weight * (joint < Palette.size() ? Palette[joint] : glm::mat4{1.f}); + } + return result; +} + +glm::vec3 direction(glm::mat3 const &Rotation, glm::vec3 const &Vector) +{ + auto const moved{Rotation * Vector}; + auto const length{glm::length(moved)}; + return length > 0.f ? moved / length : Vector; +} + +// what moves the normals: the inverse transpose of the rotation, here as its cofactors (the same direction, without the +// division), with the sign of the determinant so a mirroring matrix keeps the normals facing out. the rotation itself would +// tilt the normals of a part squashed by a scale +glm::mat3 normal_matrix(glm::mat3 const &Rotation, bool const Mirrors) +{ + glm::mat3 const cofactors{glm::cross(Rotation[1], Rotation[2]), glm::cross(Rotation[2], Rotation[0]), glm::cross(Rotation[0], Rotation[1])}; + return Mirrors ? -cofactors : cofactors; +} + +// the rotation turns the space inside out (a negative determinant): the normals take the sign, and so does the handedness of +// the tangent frame, or the bitangent rebuilt from the normal and the tangent points the other way +bool mirrors(glm::mat3 const &Rotation) +{ + return glm::dot(Rotation[0], glm::cross(Rotation[1], Rotation[2])) < 0.f; +} + +} // namespace + +void skin_vertices(std::span const Rest, std::span const Weights, std::span const Palette, std::span const Out) +{ + auto const count{std::min(Rest.size(), Out.size())}; + for (std::size_t idx = 0; idx < count; ++idx) + { + auto const &rest{Rest[idx]}; + auto &out{Out[idx]}; + out = rest; + if (idx >= Weights.size()) + { + continue; + } + auto const matrix{blended(Weights[idx], Palette)}; + glm::mat3 const rotation{matrix}; + out.position = glm::vec3{matrix * glm::vec4{rest.position, 1.f}}; + auto const mirrored{mirrors(rotation)}; + out.normal = direction(normal_matrix(rotation, mirrored), rest.normal); + out.tangent = glm::vec4{direction(rotation, glm::vec3{rest.tangent}), mirrored ? -rest.tangent.w : rest.tangent.w}; + } +} + +} // namespace skinning diff --git a/model/skinning.h b/model/skinning.h new file mode 100644 index 000000000..6024d077c --- /dev/null +++ b/model/skinning.h @@ -0,0 +1,70 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "rendering/geometrybank.h" + +#include +#include +#include +#include + +#include + +class TSubModel; + +// the skinning of the vertices of a submodel by the joints of a skin (EU07M SKIN, SKJT, VSKN / VSKW). the vertices lie in the bind +// pose, in the space of the model; the matrix of a joint is world(joint) * inverse bind(joint), world being the posed transform of +// the joint from the root of the model +namespace skinning +{ + +// the joints of a vertex (into the joints of its skin) and their weights, which add up to 1 +struct vertex_weights +{ + std::array joints{}; + std::array weights{}; +}; + +// a skin of a model: its joints and their inverse bind matrices +struct skin +{ + std::vector joints; + std::vector inverse_bind; +}; + +// what a skinned submodel keeps for the skinning: its vertices in the bind pose, its indices and the weights of its vertices +struct skinned_geometry +{ + int skin{-1}; // into the skins of the model + gfx::vertex_array rest; + gfx::index_array indices; + std::vector weights; +}; + +// the weights of 8 or 16 bits of the file made into floats adding up to 1; a vertex without weights follows joint 0 +template vertex_weights unpack(std::array const &Joints, std::array const &Weights); + +// the matrices the vertices of a submodel are skinned by, in the space of the submodel: inverse(Mesh) * Joint[j] * InverseBind[j], +// Mesh and Joint posed from the root of the model, so the placement of the instance cancels out +std::vector palette(glm::mat4 const &Mesh, std::span Joints, std::span InverseBind); + +// true when every matrix of the palette leaves the vertices where they are: the rest pose. the rotation within Tolerance, the +// translation within Tolerance times Scale (at least 1), the distance from the origin of what the palette was made of +// (palette_scale()), as the float chain rounds in proportion to it +bool rest_pose(std::span Palette, float Tolerance = 1e-5f, float Scale = 1.f); +// the largest distance from the origin along an axis of the mesh and the joints a palette is made of +float palette_scale(glm::mat4 const &Mesh, std::span Joints); + +// the vertices moved by the palette: positions by the blended matrix, normals and tangents by its rotation, renormalised. a joint out +// of the palette counts as the identity. Out has as many vertices as Rest +void skin_vertices(std::span Rest, std::span Weights, std::span Palette, std::span Out); + +} // namespace skinning diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index 48cf7ed18..10064734d 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "model/AnimModel.h" #include "model/Model3d.h" #include "rendering/common/skyocclusion.h" +#include "rendering/common/skincache.h" #include #include #include @@ -2237,6 +2238,17 @@ void scene_walk::prepare_group_instance(scene_walk &Walk, TAnimModel *Instance, Instance->RaPrepare(); } +gfx::geometry_handle scene_walk::submodel_geometry(TSubModel *Submodel) +{ + if ((Submodel->m_skin == nullptr) || (TSubModel::pRoot == nullptr)) + { + return Submodel->m_geometry.handle; + } + // the pose of the joints may be another in the next frame: the walk isn't kept (Record_Indirect_Draws()) + m_indirectchanging = true; + return gfx::skin_cache::instance().geometry(*Submodel, *TSubModel::pRoot, m_framestamp); +} + // opaque characters of a text display, laid out in a row the same way as the translucent ones void scene_walk::Render_text(TSubModel *Submodel) { @@ -2346,7 +2358,7 @@ void scene_walk::Render(TSubModel *Submodel) model_ubs.emission = Submodel->f4Emision.a; // main draw call - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); // post-draw reset model_ubs.emission = 0.0f; @@ -2376,13 +2388,13 @@ void scene_walk::Render(TSubModel *Submodel) // również 0 walk_shadow_material(Submodel->m_material); } - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); break; } case rendermode::pickscenery: { walk_program( walk_shader::pick ); - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); break; } case rendermode::pickcontrols: @@ -2400,7 +2412,7 @@ void scene_walk::Render(TSubModel *Submodel) model_ubs.param[0] = glm::vec4(pick_color(m_pickcontrolsitems.size()), 1.0f); } - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); break; } default: @@ -2427,7 +2439,7 @@ void scene_walk::Render(TSubModel *Submodel) // main draw call model_ubs.param[1].x = 8.0f; - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); } break; } @@ -3380,7 +3392,7 @@ void scene_walk::Render_Alpha(TSubModel *Submodel) model_ubs.emission = Submodel->f4Emision.a; // main draw call - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); model_ubs.emission = 0.0f; break; @@ -3405,7 +3417,7 @@ void scene_walk::Render_Alpha(TSubModel *Submodel) { walk_shadow_material(Submodel->m_material); } - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); break; } default: @@ -3523,14 +3535,14 @@ void scene_walk::Render_Alpha(TSubModel *Submodel) model_ubs.param[1].x = pointsize * fogfactor * 4.0f; model_ubs.param[0] = glm::vec4(glm::vec3(lightcolor), Submodel->fVisible * std::min(1.f, lightlevel) * 0.5f); - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); } model_ubs.param[1].x = pointsize * 4.0f; model_ubs.param[0] = glm::vec4(glm::vec3(lightcolor), Submodel->fVisible * std::min(1.f, lightlevel)); walk_light_query(Submodel, true); - walk_draw(Submodel->m_geometry.handle); + walk_draw(submodel_geometry(Submodel)); walk_light_query(Submodel, false); diff --git a/rendering/common/scenewalk.h b/rendering/common/scenewalk.h index fab87edd8..443bfa9e9 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -164,6 +164,8 @@ class scene_walk bool Render(TModel3d *Model, material_data const *Material, float const Squaredistance, glm::dvec3 const &Position, glm::vec3 const &Angle); bool Render(TModel3d *Model, material_data const *Material, float const Squaredistance); void Render(TSubModel *Submodel); + // the geometry a submodel is drawn with: its own, or for a skinned one that of the instance drawn (gfx::skin_cache) + gfx::geometry_handle submodel_geometry(TSubModel *Submodel); void Render_children(TSubModel *Submodel); // opaque sub-models under the given one void Render_text(TSubModel *Submodel); // opaque characters of a text display void Render(TTrack *Track); diff --git a/rendering/common/skincache.cpp b/rendering/common/skincache.cpp new file mode 100644 index 000000000..68398ed23 --- /dev/null +++ b/rendering/common/skincache.cpp @@ -0,0 +1,135 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" + +#include "rendering/common/skincache.h" + +#include "model/Model3d.h" +#include "rendering/renderer.h" + +#include + +namespace gfx +{ + +namespace +{ + +// frames an instance keeps its skinned geometry without being drawn +constexpr unsigned int kept_frames{600}; + +} // namespace + +skin_cache &skin_cache::instance() +{ + static skin_cache cache; + return cache; +} + +std::size_t skin_cache::key_hash::operator()(key const &Key) const noexcept +{ + return std::hash{}(Key.owner) ^ (std::hash{}(Key.submodel) * 31u); +} + +geometry_handle skin_cache::geometry(TSubModel &Submodel, TModel3d const &Model, unsigned int const Frame) +{ + auto const &source{Submodel.m_skin}; + auto const &skins{Model.skins()}; + if ((source == nullptr) || (source->skin < 0) || (static_cast(source->skin) >= skins.size())) + { + return Submodel.m_geometry.handle; + } + std::scoped_lock lock{m_mutex}; + auto &cached{m_entries[key{TSubModel::iInstance, &Submodel}]}; + if (cached.source == nullptr) + { + cached.source = source; + cached.type = Submodel.eType; + } + if (cached.frame != Frame) + { + // the first pass of the frame to draw the instance works out its pose; the joints are set up for the instance drawn + cached.frame = Frame; + auto const &skin{skins[source->skin]}; + std::vector joints; + joints.reserve(skin.joints.size()); + for (auto *joint : skin.joints) + { + joints.emplace_back(joint != nullptr ? joint->posed_transform() : glm::mat4{1.f}); + } + auto const mesh{Submodel.posed_transform()}; + auto palette{skinning::palette(mesh, joints, skin.inverse_bind)}; + cached.posed = (false == skinning::rest_pose(palette, 1e-5f, skinning::palette_scale(mesh, joints))); + if (cached.posed && (palette != cached.palette)) + { + cached.vertices.resize(source->rest.size()); + skinning::skin_vertices(source->rest, source->weights, palette, cached.vertices); + cached.pending = true; + } + cached.palette = std::move(palette); + } + if ((false == cached.posed) || (cached.handle == null_handle)) + { + return Submodel.m_geometry.handle; + } + return cached.handle; +} + +void skin_cache::flush(unsigned int const Frame) +{ + std::scoped_lock lock{m_mutex}; + for (auto it = m_entries.begin(); it != m_entries.end();) + { + auto &cached{it->second}; + if (Frame - cached.frame > kept_frames) + { + if (cached.handle != null_handle) + { + GfxRenderer->Erase(cached.handle); + } + it = m_entries.erase(it); + continue; + } + ++it; + if (false == cached.pending) + { + continue; + } + cached.pending = false; + // the renderer takes the arrays over + auto vertices{cached.vertices}; + auto indices{cached.source->indices}; + gfx::userdata_array userdata; + if (cached.handle == null_handle) + { + if (m_bank == null_handle) + { + m_bank = GfxRenderer->Create_Bank(); + } + cached.handle = indices.empty() ? GfxRenderer->Insert(vertices, userdata, m_bank, cached.type) : GfxRenderer->Insert(indices, vertices, userdata, m_bank, cached.type); + } + else if (indices.empty()) + { + GfxRenderer->Replace(vertices, userdata, cached.handle, cached.type); + } + else + { + GfxRenderer->Replace_Indexed(indices, vertices, userdata, cached.handle); + } + } +} + +std::size_t skin_cache::size() const +{ + std::scoped_lock lock{m_mutex}; + return m_entries.size(); +} + +} // namespace gfx diff --git a/rendering/common/skincache.h b/rendering/common/skincache.h new file mode 100644 index 000000000..af2189d36 --- /dev/null +++ b/rendering/common/skincache.h @@ -0,0 +1,72 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "model/skinning.h" +#include "rendering/geometrybank.h" + +#include +#include +#include +#include +#include + +class TModel3d; +class TSubModel; + +namespace gfx +{ + +// the skinned submodels of the instances drawn (EU07M skins), moved by the pose of the joints of each instance. the walks of the passes +// work out the vertices once a frame for each instance and submodel, on the CPU, when the pose changed; the geometry is made and +// replaced by flush(), before the walks of the next frame, as nothing the walks draw may change while they draw (gfx::walk_sync). so +// the vertices drawn follow the joints a frame late, and the first frame an instance is seen it's drawn in the bind pose +class skin_cache +{ + public: + static skin_cache &instance(); + // in a walk: the geometry to draw the skinned Submodel of Model with, for the instance drawn (TSubModel::iInstance). the bind + // pose of the submodel while its joints stay in it, or till its own geometry is made + geometry_handle geometry(TSubModel &Submodel, TModel3d const &Model, unsigned int Frame); + // on the main thread, before the walks of a frame: the vertices worked out go to the renderer, the instances not drawn for a while + // let go of theirs + void flush(unsigned int Frame); + // the entries kept and the geometry made, for the statistics + std::size_t size() const; + + private: + struct key + { + std::uintptr_t owner{0}; + TSubModel const *submodel{nullptr}; + bool operator==(key const &) const = default; + }; + struct key_hash + { + std::size_t operator()(key const &Key) const noexcept; + }; + struct entry + { + std::shared_ptr source; + int type{0}; + unsigned int frame{0}; // the frame the pose was worked out in + std::vector palette; + gfx::vertex_array vertices; + bool posed{false}; // the joints aren't in the bind pose + bool pending{false}; // the vertices are to go to the renderer + geometry_handle handle{}; + }; + + mutable std::mutex m_mutex; + std::unordered_map m_entries; + geometrybank_handle m_bank{}; +}; + +} // namespace gfx diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index d7b1cb24f..1d4b55fe9 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -30,6 +30,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46geometrybank.h" #include "rendering/screenshot.h" #include "rendering/editoroverlay.h" +#include "rendering/common/skincache.h" #include "vehicle/DynObj.h" #include #include @@ -779,6 +780,8 @@ bool opengl46_renderer::Render() ++m_instancerecordsversion; m_nodestateversion = scene::node_state_version; } + // the skinned submodels worked out by the walks of the last frame go to the geometry, before the walks of this one + gfx::skin_cache::instance().flush(m_framestamp); // the sleeper records of tracks out of sight for a while, and the records of the models drawn on their own Expire_Indirect_Records(); // scenery lamps which get shadows in this frame. their maps hold the scenery as of the version of the instance records diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 672fa0e00..3ad8b3f60 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -32,6 +32,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/utilities.h" #include "utilities/color.h" +#include "rendering/common/skincache.h" #include @@ -871,6 +872,8 @@ bool vulkan14_renderer::Render() ++m_instancerecordsversion; m_nodestateversion = scene::node_state_version; } + // the skinned submodels worked out by the walks of the last frame go to the geometry, before the walks of this one + gfx::skin_cache::instance().flush(m_framestamp); // what the maps of the occlusion of the sky were given, copied to them scene.skyocclusion.flush(m_commands); // the sleeper records of tracks out of sight for a while, and the records of the models drawn on their own diff --git a/tests/unit/test_skinning.cpp b/tests/unit/test_skinning.cpp new file mode 100644 index 000000000..981358b7d --- /dev/null +++ b/tests/unit/test_skinning.cpp @@ -0,0 +1,222 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_io.h" +#include "model/skinning.h" +#include + +#include + +#include +#include +#include +#include + +namespace { + +bool close_to(glm::vec3 const &A, glm::vec3 const &B, float const Tolerance = 1e-4f) { + return glm::length(A - B) <= Tolerance; +} + +gfx::basic_vertex vertex_at(glm::vec3 const &Position) { + gfx::basic_vertex vertex; + vertex.position = Position; + vertex.normal = {0.f, 1.f, 0.f}; + vertex.tangent = {1.f, 0.f, 0.f, 1.f}; + return vertex; +} + +// a tube along +z, 4 m long, skinned to two joints: the base at the origin and the tip at z = 2, child of the base. the vertices follow +// the base below z = 1.5, the tip above z = 2.5 and both in between. the tip turned bends the tube (EU07M_SKINNED_TUBE in the scratch +// folder is this model, for a look in the game) +eu07m::model skinned_tube() { + eu07m::model model; + auto const node{[&model](std::string_view const Name, std::int32_t const Parent, std::uint32_t const Flags) { + eu07m::node_record record; + record.name = model.intern(Name); + record.parent = Parent; + record.legacy_flags = Flags; + model.nodes.push_back(record); + return static_cast(model.nodes.size() - 1); + }}; + // the order of the nodes is the order of the walk: a subtree right after its node + auto const root{node("tube_root", -1, 0x8000)}; + auto const tube{node("tube", static_cast(root), 0x10)}; + auto const base{node("tube_base", static_cast(root), 0xC000)}; + auto const tip{node("tube_tip", static_cast(base), 0xC000)}; + model.nodes[root].subtree_end = 4; + model.nodes[tube].subtree_end = 2; + model.nodes[base].subtree_end = 4; + model.nodes[tip].subtree_end = 4; + model.nodes[tip].translation = {0.f, 0.f, 2.f}; + + eu07m::material_record material; + material.diffuse = {0.9f, 0.4f, 0.1f, 1.f}; + model.materials.push_back(material); + + constexpr int sides{16}; + constexpr int rings{21}; + constexpr float radius{0.3f}; + for (int ring = 0; ring < rings; ++ring) { + auto const z{4.f * static_cast(ring) / static_cast(rings - 1)}; + // the tip takes over between 1.5 and 2.5 m + auto const tipweight{std::clamp(z - 1.5f, 0.f, 1.f)}; + auto const tipbyte{static_cast(std::lround(tipweight * 255.f))}; + for (int side = 0; side < sides; ++side) { + auto const angle{2.f * std::numbers::pi_v * static_cast(side) / static_cast(sides)}; + glm::vec3 const normal{std::cos(angle), std::sin(angle), 0.f}; + model.positions.push_back({radius * normal.x, radius * normal.y, z}); + eu07m::attributes attribute; + attribute.qtangent = eu07m::encode_qtangent({normal, {0.f, 0.f, 1.f}, 1.f}); + attribute.uv = {static_cast(side) / sides, z}; + model.vertex_attributes.push_back(attribute); + eu07m::skin_weights weights; + weights.joints = {0, 1, 0, 0}; + weights.weights = {static_cast(255 - tipbyte), tipbyte, 0, 0}; + model.weights.push_back(weights); + } + } + for (int ring = 0; ring + 1 < rings; ++ring) { + for (int side = 0; side < sides; ++side) { + auto const a{static_cast(ring * sides + side)}; + auto const b{static_cast(ring * sides + (side + 1) % sides)}; + auto const c{static_cast(a + sides)}; + auto const d{static_cast(b + sides)}; + for (auto const index : {a, b, d, a, d, c}) + model.indices16.push_back(index); + } + } + eu07m::primitive_record primitive; + primitive.vertex_count = static_cast(model.positions.size()); + primitive.index_count = static_cast(model.indices16.size()); + primitive.node = tube; + primitive.material = 0; + primitive.skin = 0; + primitive.flags = static_cast(eu07m::topology::triangles) | eu07m::primitive_flags::indexed | eu07m::primitive_flags::opaque; + model.primitives.push_back(primitive); + model.meshes.push_back({0, 1, 0, 0}); + model.nodes[tube].mesh = 0; + + model.skins.push_back({0, 2, static_cast(root), 0}); + eu07m::skin_joint_record basejoint; + basejoint.node = base; + basejoint.inverse_bind = {1.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, 0.f}; + auto tipjoint{basejoint}; + tipjoint.node = tip; + tipjoint.inverse_bind[11] = -2.f; // the inverse of the tip at z = 2 + model.skin_joints = {basejoint, tipjoint}; + + eu07m::build_name_index(model); + eu07m::compute_bounds(model); + return model; +} + +} // namespace + +TEST_CASE("skinning: the weights of the file add up to 1") { + auto const narrow{skinning::unpack(std::array{0, 1, 0, 0}, std::array{128, 127, 0, 0})}; + CHECK(narrow.weights[0] + narrow.weights[1] == doctest::Approx(1.f)); + CHECK(narrow.weights[0] == doctest::Approx(128.f / 255.f)); + CHECK(narrow.joints[1] == 1); + auto const wide{skinning::unpack(std::array{3, 300, 0, 0}, std::array{65535, 0, 0, 0})}; + CHECK(wide.weights[0] == doctest::Approx(1.f)); + CHECK(wide.joints[1] == 300); + // without weights the vertex follows joint 0 + auto const none{skinning::unpack(std::array{5, 6, 0, 0}, std::array{0, 0, 0, 0})}; + CHECK(none.joints[0] == 0); + CHECK(none.weights[0] == doctest::Approx(1.f)); +} + +TEST_CASE("skinning: the bind pose leaves the vertices where they are") { + auto const tipbind{glm::translate(glm::mat4{1.f}, glm::vec3{0.f, 0.f, 2.f})}; + std::vector const joints{glm::mat4{1.f}, tipbind}; + std::vector const inversebind{glm::mat4{1.f}, glm::inverse(tipbind)}; + auto const palette{skinning::palette(glm::mat4{1.f}, joints, inversebind)}; + CHECK(skinning::rest_pose(palette)); + // the placement of the model is in both the mesh and the joints, and cancels out + auto const placed{glm::translate(glm::rotate(glm::mat4{1.f}, 0.7f, glm::vec3{0.f, 1.f, 0.f}), glm::vec3{10.f, 5.f, -3.f})}; + std::vector const placedjoints{placed, placed * tipbind}; + CHECK(skinning::rest_pose(skinning::palette(placed, placedjoints, inversebind), 1e-4f)); + // the default tolerance, scaled by the distances the palette was made of: a model far from the origin is at rest as well + auto const distant{glm::translate(glm::mat4{1.f}, glm::vec3{1500.f, 40.f, -2300.f})}; + std::vector const distantjoints{distant, distant * tipbind}; + CHECK(skinning::rest_pose(skinning::palette(distant, distantjoints, inversebind), 1e-5f, skinning::palette_scale(distant, distantjoints))); + std::vector const moved{glm::translate(glm::mat4{1.f}, glm::vec3{0.f, 0.1f, 0.f})}; + CHECK_FALSE(skinning::rest_pose(moved)); + CHECK_FALSE(skinning::rest_pose(moved, 1e-5f, skinning::palette_scale(distant, distantjoints))); +} + +TEST_CASE("skinning: the normals of a part scaled unevenly stay square to its surface") { + // a joint stretched twice along x: a surface at 45 degrees leans towards y, its normal towards x less + std::vector const palette{glm::scale(glm::mat4{1.f}, glm::vec3{2.f, 1.f, 1.f})}; + auto vertex{vertex_at({0.f, 0.f, 0.f})}; + vertex.normal = glm::normalize(glm::vec3{1.f, 1.f, 0.f}); + std::vector const rest{vertex}; + std::vector const weights{{{0, 0, 0, 0}, {1.f, 0.f, 0.f, 0.f}}}; + std::vector out(1); + skinning::skin_vertices(rest, weights, palette, out); + CHECK(close_to(out[0].normal, glm::normalize(glm::vec3{0.5f, 1.f, 0.f}))); + CHECK(out[0].tangent.w == doctest::Approx(vertex.tangent.w)); + // a mirroring joint keeps the normal facing out, and turns the handedness of the tangent frame, so the bitangent rebuilt + // from the normal and the tangent mirrors with the surface + std::vector const mirror{glm::scale(glm::mat4{1.f}, glm::vec3{-1.f, 1.f, 1.f})}; + skinning::skin_vertices(rest, weights, mirror, out); + CHECK(close_to(out[0].normal, glm::normalize(glm::vec3{-1.f, 1.f, 0.f}))); + CHECK(out[0].tangent.w == doctest::Approx(-vertex.tangent.w)); +} + +TEST_CASE("skinning: a joint turned moves its vertices, blended by the weights") { + auto const tipbind{glm::translate(glm::mat4{1.f}, glm::vec3{0.f, 0.f, 2.f})}; + // the tip turned by 90 degrees about x at its place: +z goes to -y, +y to +z + auto const tipposed{tipbind * glm::rotate(glm::mat4{1.f}, std::numbers::pi_v / 2.f, glm::vec3{1.f, 0.f, 0.f})}; + std::vector const joints{glm::mat4{1.f}, tipposed}; + std::vector const inversebind{glm::mat4{1.f}, glm::inverse(tipbind)}; + auto const palette{skinning::palette(glm::mat4{1.f}, joints, inversebind)}; + CHECK_FALSE(skinning::rest_pose(palette)); + + std::vector const rest{vertex_at({0.f, 0.f, 1.f}), vertex_at({0.f, 0.f, 3.f}), vertex_at({0.f, 0.f, 2.f})}; + std::vector weights(3); + weights[0] = {{0, 0, 0, 0}, {1.f, 0.f, 0.f, 0.f}}; + weights[1] = {{1, 0, 0, 0}, {1.f, 0.f, 0.f, 0.f}}; + weights[2] = {{0, 1, 0, 0}, {0.5f, 0.5f, 0.f, 0.f}}; + std::vector out(rest.size()); + skinning::skin_vertices(rest, weights, palette, out); + // the base doesn't move + CHECK(close_to(out[0].position, {0.f, 0.f, 1.f})); + CHECK(close_to(out[0].normal, {0.f, 1.f, 0.f})); + // 1 m past the tip along z turns to 1 m along -y; the normal +y turns to +z + CHECK(close_to(out[1].position, {0.f, -1.f, 2.f})); + CHECK(close_to(out[1].normal, {0.f, 0.f, 1.f})); + CHECK(out[1].tangent.w == doctest::Approx(1.f)); + // the pivot stays put whatever the weights + CHECK(close_to(out[2].position, {0.f, 0.f, 2.f})); + CHECK(glm::length(out[2].normal) == doctest::Approx(1.f)); +} + +TEST_CASE("skinning: a joint the palette hasn't counts as the identity") { + std::vector const rest{vertex_at({1.f, 2.f, 3.f})}; + std::vector const weights{{{7, 0, 0, 0}, {1.f, 0.f, 0.f, 0.f}}}; + std::vector const palette{glm::translate(glm::mat4{1.f}, glm::vec3{5.f, 0.f, 0.f})}; + std::vector out(1); + skinning::skin_vertices(rest, weights, palette, out); + CHECK(close_to(out[0].position, {1.f, 2.f, 3.f})); +} + +TEST_CASE("skinning: the skinned tube is a valid EU07M file") { + auto const model{skinned_tube()}; + auto const file{eu07m::write(model, {true, 9})}; + eu07m::model read; + auto const result{eu07m::read(file, read, {true, true})}; + REQUIRE(result.ok); + CHECK(read.skins.size() == 1); + CHECK(read.skin_joints.size() == 2); + CHECK(read.weights.size() == read.positions.size()); + CHECK(read.primitives[0].skin == 0); + // kept in the scratch folder for a look in the game + auto const path{std::filesystem::path{EU07_UNIT_TESTS_SCRATCH} / "skinned_tube.ng3d"}; + std::ofstream output{path, std::ios::binary}; + output.write(reinterpret_cast(file.data()), static_cast(file.size())); + CHECK(output.good()); +}