diff --git a/CMakeLists.txt b/CMakeLists.txt index 1faea1b92..80ccc1df5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -387,6 +387,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" @@ -798,6 +799,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 df5d62622..7c8f0d846 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -573,6 +573,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 68b3acca9..d16bf9914 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -242,6 +242,28 @@ Domyślne `modelformat legacy` zostawia pliki `.eu07m` 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 bde8e34ef..bbd927c6d 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1335,6 +1335,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 b18817399..b6df14651 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/geometrybank.h" #include "model/material.h" #include "gl/query.h" +#include "model/skinning.h" #include @@ -162,6 +163,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 @@ -184,6 +188,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; @@ -313,6 +320,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 ); @@ -336,6 +344,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 20c5f44a9..c517b6d81 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -116,6 +116,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; @@ -141,7 +142,8 @@ 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); auto const parts{parts_of(m_model, node)}; Submodel.b_Anim = parts.animation; @@ -254,6 +256,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 @@ -287,6 +291,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) { @@ -347,6 +384,18 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { for (std::uint32_t idx = 0; idx < model.nodes.size(); ++idx) builder.build(idx, Root[idx]); builder.fill_geometry(); + // 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..f20bdf3e3 --- /dev/null +++ b/model/skinning.cpp @@ -0,0 +1,127 @@ +/* +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) +{ + glm::mat4 const identity{1.f}; + return std::ranges::all_of(Palette, [&](glm::mat4 const &Matrix) { + for (int column = 0; column < 4; ++column) + { + for (int row = 0; row < 4; ++row) + { + if (std::abs(Matrix[column][row] - identity[column][row]) > Tolerance) + { + return false; + } + } + } + return true; + }); +} + +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; +} + +} // 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}}; + out.normal = direction(rotation, rest.normal); + out.tangent = glm::vec4{direction(rotation, glm::vec3{rest.tangent}), rest.tangent.w}; + } +} + +} // namespace skinning diff --git a/model/skinning.h b/model/skinning.h new file mode 100644 index 000000000..6de1540cb --- /dev/null +++ b/model/skinning.h @@ -0,0 +1,66 @@ +/* +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 (within Tolerance): the rest pose +bool rest_pose(std::span Palette, float Tolerance = 1e-5f); + +// 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 1b348c25d..c4a52d44e 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 @@ -2236,6 +2237,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); +} + void scene_walk::Render(TSubModel *Submodel) { glDebug("Render TSubModel"); @@ -2314,7 +2326,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; @@ -2344,13 +2356,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: @@ -2368,7 +2380,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: @@ -2395,7 +2407,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; } @@ -3348,7 +3360,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; @@ -3373,7 +3385,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: @@ -3491,14 +3503,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 0ce9206ec..174d96bca 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -163,6 +163,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(TTrack *Track); void Render(scene::basic_cell::path_sequence::const_iterator First, scene::basic_cell::path_sequence::const_iterator Last); // renders the per-track sleeper instances (TTrack::m_sleeper_local_transforms) via GPU instancing. diff --git a/rendering/common/skincache.cpp b/rendering/common/skincache.cpp new file mode 100644 index 000000000..9a23ce500 --- /dev/null +++ b/rendering/common/skincache.cpp @@ -0,0 +1,134 @@ +/* +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 palette{skinning::palette(Submodel.posed_transform(), joints, skin.inverse_bind)}; + cached.posed = (false == skinning::rest_pose(palette)); + 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 29663ec23..6dabd2c7b 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -29,6 +29,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 #include @@ -765,6 +766,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 c92d5728f..1bc026f4b 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 @@ -870,6 +871,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..39f4970ec --- /dev/null +++ b/tests/unit/test_skinning.cpp @@ -0,0 +1,198 @@ +#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)); + std::vector const moved{glm::translate(glm::mat4{1.f}, glm::vec3{0.f, 0.1f, 0.f})}; + CHECK_FALSE(skinning::rest_pose(moved)); +} + +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.eu07m"}; + std::ofstream output{path, std::ios::binary}; + output.write(reinterpret_cast(file.data()), static_cast(file.size())); + CHECK(output.good()); +}