From c3cb85487513008046e0fbd06810c79ac33a548d Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sat, 28 Nov 2026 05:59:55 +0000 Subject: [PATCH 1/3] Add GPU (hardware) skinning path with CPU fallback Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CMakeLists.txt | 1 + src/app/AppUi.cpp | 16 +++++ src/app/AppUi.h | 2 + src/app/main.cpp | 12 +++- src/model/Poser.cpp | 26 +++++--- src/model/Poser.h | 17 ++++- src/render/GpuCaps.cpp | 32 +++++++++ src/render/GpuCaps.h | 28 ++++++++ src/render/ModelNode.cpp | 140 +++++++++++++++++++++++++++++++++++++-- src/render/ModelNode.h | 16 +++++ src/render/Shaders.cpp | 39 ++++++++++- src/render/Shaders.h | 6 ++ 12 files changed, 317 insertions(+), 18 deletions(-) create mode 100644 src/render/GpuCaps.cpp create mode 100644 src/render/GpuCaps.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 60b9de7..3106394 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -92,6 +92,7 @@ add_executable(model_renderer src/render/ModelNode.cpp src/render/TextureLoader.cpp src/render/Shaders.cpp + src/render/GpuCaps.cpp src/ui/ImGuiOsg.cpp) target_link_libraries(model_renderer PRIVATE mr_core imgui OpenGL::GL) diff --git a/src/app/AppUi.cpp b/src/app/AppUi.cpp index 9859e39..d6e8160 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -1,6 +1,7 @@ #include "app/AppUi.h" #include "model/ModelLoader.h" +#include "render/GpuCaps.h" #include @@ -75,6 +76,12 @@ void App::applyViewSettings() { modelNode_->setLightFollowsCamera(lightFollowsCamera_); modelNode_->setLightingModel(static_cast(lightingModel_)); modelNode_->setSelectedBone(selectedBone_); + modelNode_->setSkinningMode(skinning_ == 1 ? SkinningMode::Hardware : SkinningMode::Software); +} + +void App::setGpuSkinning(bool enabled) { + skinning_ = enabled ? 1 : 0; + applyViewSettings(); } void App::setShowSkeleton(bool show) { @@ -136,6 +143,13 @@ void App::drawMenuBar() { changed |= ImGui::RadioButton("MMD toon shading", &lightingModel_, 0); changed |= ImGui::RadioButton("Lambert shading", &lightingModel_, 1); ImGui::Separator(); + const bool gpuOk = gpuCaps().skinning; + ImGui::BeginDisabled(!gpuOk); + changed |= ImGui::RadioButton("GPU skinning (hardware)", &skinning_, 1); + ImGui::EndDisabled(); + changed |= ImGui::RadioButton("CPU skinning (software)", &skinning_, 0); + if (!gpuOk && gpuCaps().probed) ImGui::TextDisabled("This GPU cannot do hardware skinning"); + ImGui::Separator(); float scale = imgui_->uiScale(); if (ImGui::SliderFloat("UI scale", &scale, 0.75f, 2.5f, "%.2f")) imgui_->setUiScale(scale); if (ImGui::MenuItem("Reset camera")) frameModel(); @@ -163,6 +177,8 @@ void App::drawModelWindow() { ImGui::Text("Vertices %zu Triangles %zu", m.vertices.size(), m.indices.size() / 3); ImGui::Text("Materials %zu Textures %zu", m.materials.size(), m.textures.size()); ImGui::Text("Bones %zu Morphs %zu", m.bones.size(), m.morphs.size()); + ImGui::TextDisabled("Skinning: %s", + modelNode_->activeSkinningMode() == SkinningMode::Hardware ? "GPU" : "CPU"); if (ImGui::Button("Reset pose")) modelNode_->poser().resetPose(); ImGui::SameLine(); if (ImGui::Button("Reset morphs")) modelNode_->poser().resetMorphs(); diff --git a/src/app/AppUi.h b/src/app/AppUi.h index d725c4d..0af81da 100644 --- a/src/app/AppUi.h +++ b/src/app/AppUi.h @@ -20,6 +20,7 @@ public: ModelNode* modelNode() { return modelNode_.get(); } void frameModel(float azimuthDeg = 0.f, float elevationDeg = 0.f); void setShowSkeleton(bool show); + void setGpuSkinning(bool enabled); ImGuiOsg* imgui() { return imgui_.get(); } void drawUi(); @@ -45,6 +46,7 @@ private: bool wireframe_ = false; bool lightFollowsCamera_ = false; int lightingModel_ = 0; + int skinning_ = 1; // 1 hardware (GPU), 0 software (CPU) bool showDemo_ = false; bool onlyVisibleBones_ = true; int selectedBone_ = -1; diff --git a/src/app/main.cpp b/src/app/main.cpp index 05f1ead..63b268a 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -1,5 +1,6 @@ #include "app/AppUi.h" +#include "render/GpuCaps.h" #include "render/ModelNode.h" #include @@ -38,6 +39,7 @@ void printUsage() { " --screenshot FILE render, save a PNG and exit\n" " --frames N frames to render before the screenshot (default 5)\n" " --list print bone and morph names after loading\n" + " --skinning gpu|cpu hardware or software skinning (default gpu)\n" " --bench N time N idle and N animated frames, then exit\n"; } @@ -61,6 +63,10 @@ void runBenchmark(osgViewer::Viewer& viewer, mr::ModelNode* node, int frames) { for (int f = 0; f < frames; ++f) viewer.frame(); const double idle = ms(Clock::now() - start) / frames; std::printf("idle frame: %.2f ms\n", idle); + if (node) + std::printf("skinning: %s (%s)\n", + node->activeSkinningMode() == mr::SkinningMode::Hardware ? "GPU" : "CPU", + mr::gpuCaps().renderer.c_str()); if (!node) return; mr::Poser& poser = node->poser(); @@ -100,7 +106,7 @@ int main(int argc, char** argv) { std::vector> morphArgs, boneArgs; int width = 1280, height = 800, frames = 5, benchFrames = 0; float azimuth = 0.f, elevation = 0.f, uiScale = 1.f; - bool skeleton = false, hideUi = false, listNames = false; + bool skeleton = false, hideUi = false, listNames = false, gpuSkinning = true; for (int i = 1; i < argc; ++i) { std::string a = argv[i]; @@ -139,6 +145,8 @@ int main(int argc, char** argv) { screenshot = next(); } else if (a == "--list") { listNames = true; + } else if (a == "--skinning") { + gpuSkinning = next() != "cpu"; } else if (a == "--bench") { benchFrames = std::max(1, std::atoi(next().c_str())); } else if (a == "--frames") { @@ -164,6 +172,8 @@ int main(int argc, char** argv) { viewer.setCameraManipulator(manipulator); mr::App app(viewer, root, manipulator); + viewer.setRealizeOperation(new mr::GpuCapsProbe(viewer.getRealizeOperation())); + app.setGpuSkinning(gpuSkinning); const auto loadStart = std::chrono::steady_clock::now(); if (!modelPath.empty() && !app.loadModel(modelPath)) std::cerr << app.loadError() << "\n"; const double loadMs = diff --git a/src/model/Poser.cpp b/src/model/Poser.cpp index 115380c..6dd6512 100644 --- a/src/model/Poser.cpp +++ b/src/model/Poser.cpp @@ -104,8 +104,15 @@ void Poser::accumulateMorph(int morph, float weight, int depth) { } } +void Poser::setSkinningMode(SkinningMode mode) { + if (mode == mode_) return; + mode_ = mode; + firstUpdate_ = true; +} + bool Poser::update() { if (!firstUpdate_ && poses_ == lastPoses_ && weights_ == lastWeights_) return false; + morphsChanged_ = firstUpdate_ || weights_ != lastWeights_; firstUpdate_ = false; lastPoses_ = poses_; lastWeights_ = weights_; @@ -148,15 +155,18 @@ bool Poser::update() { } const size_t vertexCount = model.vertices.size(); - morphed_.resize(vertexCount); - parallelFor(vertexCount, kMinVerticesPerThread, [&](size_t begin, size_t end) { - for (size_t i = begin; i < end; ++i) morphed_[i] = model.vertices[i].position; - }); - for (size_t i = 0; i < effective_.size(); ++i) { - const float w = effective_[i]; - if (w == 0.f || model.morphs[i].type != MorphType::Vertex) continue; - for (const auto& o : model.morphs[i].vertexOffsets) morphed_[o.vertex] += o.offset * w; + if (morphsChanged_) { + morphed_.resize(vertexCount); + parallelFor(vertexCount, kMinVerticesPerThread, [&](size_t begin, size_t end) { + for (size_t i = begin; i < end; ++i) morphed_[i] = model.vertices[i].position; + }); + for (size_t i = 0; i < effective_.size(); ++i) { + const float w = effective_[i]; + if (w == 0.f || model.morphs[i].type != MorphType::Vertex) continue; + for (const auto& o : model.morphs[i].vertexOffsets) morphed_[o.vertex] += o.offset * w; + } } + if (mode_ == SkinningMode::Hardware) return true; positions_.resize(vertexCount); normals_.resize(vertexCount); diff --git a/src/model/Poser.h b/src/model/Poser.h index 636f538..09bd154 100644 --- a/src/model/Poser.h +++ b/src/model/Poser.h @@ -7,6 +7,10 @@ namespace mr { +// Software: the CPU skins every vertex. Hardware: the CPU only computes bone matrices and +// morphed rest positions; the vertex shader does the skinning. +enum class SkinningMode { Software, Hardware }; + struct BonePose { // Both are expressed in model-space axes (X right, Y up, Z toward the viewer) at the bone's pivot, // so posing behaves the same regardless of how a format orients its bone frames. @@ -30,9 +34,18 @@ public: void resetMorphs(); // Recomputes the deformed mesh if anything changed. Returns true when it did. - bool update(); + void setSkinningMode(SkinningMode mode); + SkinningMode skinningMode() const { return mode_; } + // Returns false when nothing changed since the last call. + bool update(); + bool morphsChangedInLastUpdate() const { return morphsChanged_; } + + // Skinned vertices; only maintained in Software mode. const std::vector& positions() const { return positions_; } + const std::vector& morphedPositions() const { return morphed_; } + // Per-bone rest-space -> posed-space matrices (row-vector convention: p' = p * M). + const std::vector& skinMatrices() const { return skin_; } const std::vector& normals() const { return normals_; } const std::vector& boneGlobals() const { return globals_; } const std::vector& effectiveMorphWeights() const { return effective_; } @@ -45,6 +58,8 @@ private: std::vector poses_, lastPoses_; std::vector weights_, lastWeights_; bool firstUpdate_ = true; + bool morphsChanged_ = true; + SkinningMode mode_ = SkinningMode::Software; std::vector order_; std::vector bindRotation_; // rest-pose global rotation of each bone diff --git a/src/render/GpuCaps.cpp b/src/render/GpuCaps.cpp new file mode 100644 index 0000000..f029414 --- /dev/null +++ b/src/render/GpuCaps.cpp @@ -0,0 +1,32 @@ +#include "render/GpuCaps.h" + +#include +#include +#include +#include + +#ifndef GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#endif + +namespace mr { + +namespace { +GpuCaps caps; +} + +const GpuCaps& gpuCaps() { return caps; } + +void GpuCapsProbe::operator()(osg::GraphicsContext* gc) { + const unsigned contextID = gc->getState()->getContextID(); + GLint vertexUnits = 0; + glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vertexUnits); + const bool floatTextures = osg::isGLExtensionOrVersionSupported(contextID, "GL_ARB_texture_float", 3.0f); + const GLubyte* renderer = glGetString(GL_RENDERER); + caps.renderer = renderer ? reinterpret_cast(renderer) : ""; + caps.skinning = vertexUnits > 0 && floatTextures; + caps.probed = true; + if (next_) (*next_)(gc); +} + +} // namespace mr diff --git a/src/render/GpuCaps.h b/src/render/GpuCaps.h new file mode 100644 index 0000000..383d16f --- /dev/null +++ b/src/render/GpuCaps.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +#include + +namespace mr { + +struct GpuCaps { + bool probed = false; + bool skinning = false; // vertex texture fetch + float textures + std::string renderer; +}; + +const GpuCaps& gpuCaps(); + +// Realize operation that queries the GL context once it exists, then runs `next` (if any). +class GpuCapsProbe : public osg::GraphicsOperation { +public: + explicit GpuCapsProbe(osg::Operation* next = nullptr) + : osg::GraphicsOperation("GpuCapsProbe", false), next_(next) {} + void operator()(osg::GraphicsContext* gc) override; + +private: + osg::ref_ptr next_; +}; + +} // namespace mr diff --git a/src/render/ModelNode.cpp b/src/render/ModelNode.cpp index 472c2f8..14c279b 100644 --- a/src/render/ModelNode.cpp +++ b/src/render/ModelNode.cpp @@ -1,6 +1,7 @@ #include "render/ModelNode.h" #include "model/Parallel.h" +#include "render/GpuCaps.h" #include "render/Shaders.h" #include "render/TextureLoader.h" @@ -27,6 +28,20 @@ public: } }; +// In hardware mode the vertex arrays hold rest positions, so bounds come from the posed skeleton. +class PosedBoundsCallback : public osg::Drawable::ComputeBoundingBoxCallback { +public: + explicit PosedBoundsCallback(const ModelNode* node) : node_(node) {} + osg::BoundingBox computeBound(const osg::Drawable& drawable) const override { + if (node_->activeSkinningMode() == SkinningMode::Hardware && node_->posedBounds().valid()) + return node_->posedBounds(); + return drawable.computeBoundingBox(); + } + +private: + const ModelNode* node_; +}; + } // namespace ModelNode::ModelNode(std::shared_ptr model) : model_(std::move(model)), poser_(model_) { @@ -54,6 +69,7 @@ ModelNode::ModelNode(std::shared_ptr model) : model_(std::move(model)), p preloadTextureImages(); buildMesh(); + buildSkinning(); buildSkeleton(); setShowSkeleton(false); updateDeformation(); @@ -142,6 +158,7 @@ void ModelNode::buildMesh() { GL_TRIANGLES, model.indices.begin() + m.indexOffset, model.indices.begin() + m.indexOffset + m.indexCount); geom->addPrimitiveSet(elements); geom->setStateSet(buildMaterialState(m, static_cast(i))); + geom->setComputeBoundingBoxCallback(new PosedBoundsCallback(this)); geode->addDrawable(geom); geometries_.push_back(geom); } @@ -149,6 +166,96 @@ void ModelNode::buildMesh() { addChild(meshGroup_); } +void ModelNode::buildSkinning() { + const Model& model = *model_; + const size_t boneCount = model.bones.size(); + osg::StateSet* ss = getOrCreateStateSet(); + skinningUniform_ = new osg::Uniform("u_skinning", 0); + ss->addUniform(skinningUniform_); + + osg::ref_ptr indices = new osg::Vec4Array(model.vertices.size()); + osg::ref_ptr weights = new osg::Vec4Array(model.vertices.size()); + for (size_t i = 0; i < model.vertices.size(); ++i) { + const Vertex& v = model.vertices[i]; + for (int k = 0; k < 4; ++k) { + const bool used = v.bones[k] >= 0 && v.weights[k] > 0.f; + (*indices)[i][k] = used ? float(v.bones[k]) : 0.f; + (*weights)[i][k] = used ? v.weights[k] : 0.f; + } + } + for (auto& g : geometries_) { + g->setVertexAttribArray(kBoneIndexAttrib, indices, osg::Array::BIND_PER_VERTEX); + g->setVertexAttribArray(kBoneWeightAttrib, weights, osg::Array::BIND_PER_VERTEX); + } + + boneRestPositions_.resize(boneCount); + for (size_t b = 0; b < boneCount; ++b) + boneRestPositions_[b] = osg::Matrixf::inverse(model.bones[b].inverseBind).getTrans(); + float morphReach = 0.f; + for (const auto& m : model.morphs) + for (const auto& o : m.vertexOffsets) morphReach = std::max(morphReach, o.offset.length()); + for (const auto& v : model.vertices) { + if (v.bones[0] < 0) { + unskinnedBounds_.expandBy(v.position); + continue; + } + int main = 0; + for (int k = 1; k < 4; ++k) + if (v.bones[k] >= 0 && v.weights[k] > v.weights[main]) main = k; + boneReach_ = std::max(boneReach_, (v.position - boneRestPositions_[v.bones[main]]).length()); + } + boneReach_ += morphReach; + if (unskinnedBounds_.valid()) { + const osg::Vec3f pad(morphReach, morphReach, morphReach); + unskinnedBounds_.expandBy(unskinnedBounds_._max + pad); + unskinnedBounds_.expandBy(unskinnedBounds_._min - pad); + } + if (boneCount == 0) return; + + const int columns = static_cast(std::min(boneCount, kBonesPerTextureRow)); + const int rows = static_cast((boneCount + kBonesPerTextureRow - 1) / kBonesPerTextureRow); + boneImage_ = new osg::Image; + boneImage_->allocateImage(columns * 3, rows, 1, GL_RGBA, GL_FLOAT); + boneImage_->setInternalTextureFormat(GL_RGBA32F_ARB); + std::fill(reinterpret_cast(boneImage_->data()), + reinterpret_cast(boneImage_->data()) + columns * 3 * rows * 4, 0.f); + boneImage_->setDataVariance(osg::Object::DYNAMIC); + boneTexture_ = new osg::Texture2D(boneImage_); + boneTexture_->setDataVariance(osg::Object::DYNAMIC); + boneTexture_->setResizeNonPowerOfTwoHint(false); + boneTexture_->setUseHardwareMipMapGeneration(false); + boneTexture_->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST); + boneTexture_->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST); + boneTexture_->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); + boneTexture_->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); + ss->setTextureAttribute(kBoneTextureUnit, boneTexture_); + ss->addUniform(new osg::Uniform("u_boneTexture", static_cast(kBoneTextureUnit))); + ss->addUniform(new osg::Uniform("u_boneTexSize", osg::Vec2f(float(columns * 3), float(rows)))); +} + +void ModelNode::uploadBoneMatrices() { + const auto& skin = poser_.skinMatrices(); + const auto& bones = model_->bones; + float* data = reinterpret_cast(boneImage_->data()); + const int width = boneImage_->s(); + posedBounds_ = unskinnedBounds_; + const osg::Vec3f reach(boneReach_, boneReach_, boneReach_); + for (size_t b = 0; b < skin.size(); ++b) { + const osg::Matrixf& m = skin[b]; + float* texel = data + ((b / kBonesPerTextureRow) * width + (b % kBonesPerTextureRow) * 3) * 4; + for (int k = 0; k < 3; ++k) + for (int r = 0; r < 4; ++r) texel[k * 4 + r] = m(r, k); + if (bones[b].isSkinBone) { + const osg::Vec3f p = boneRestPositions_[b] * m; + posedBounds_.expandBy(p - reach); + posedBounds_.expandBy(p + reach); + } + } + boneImage_->dirty(); +} + +void ModelNode::setSkinningMode(SkinningMode mode) { requestedSkinning_ = mode; } + void ModelNode::buildSkeleton() { const Model& model = *model_; for (size_t i = 0; i < model.bones.size(); ++i) @@ -219,13 +326,34 @@ void ModelNode::updateSkeleton() { } void ModelNode::updateDeformation() { + const bool hardware = + requestedSkinning_ == SkinningMode::Hardware && gpuCaps().skinning && boneImage_.valid(); + const SkinningMode wanted = hardware ? SkinningMode::Hardware : SkinningMode::Software; + if (wanted != activeSkinning_) { + activeSkinning_ = wanted; + poser_.setSkinningMode(wanted); + skinningUniform_->set(hardware ? 1 : 0); + if (hardware) { + for (size_t i = 0; i < model_->vertices.size(); ++i) (*normals_)[i] = model_->vertices[i].normal; + normals_->dirty(); + } + } if (poser_.update()) { - const auto& p = poser_.positions(); - const auto& n = poser_.normals(); - std::copy(p.begin(), p.end(), positions_->begin()); - std::copy(n.begin(), n.end(), normals_->begin()); - positions_->dirty(); - normals_->dirty(); + if (activeSkinning_ == SkinningMode::Software) { + const auto& p = poser_.positions(); + const auto& n = poser_.normals(); + std::copy(p.begin(), p.end(), positions_->begin()); + std::copy(n.begin(), n.end(), normals_->begin()); + positions_->dirty(); + normals_->dirty(); + } else { + uploadBoneMatrices(); + if (poser_.morphsChangedInLastUpdate()) { + const auto& p = poser_.morphedPositions(); + std::copy(p.begin(), p.end(), positions_->begin()); + positions_->dirty(); + } + } for (auto& g : geometries_) g->dirtyBound(); skeletonDirty_ = true; } diff --git a/src/render/ModelNode.h b/src/render/ModelNode.h index d0de081..24810d4 100644 --- a/src/render/ModelNode.h +++ b/src/render/ModelNode.h @@ -29,6 +29,10 @@ public: void setWireframe(bool enabled); void setLightingModel(LightingModel lighting); void setLightFollowsCamera(bool follow); + // Hardware falls back to Software when the GPU cannot do it. + void setSkinningMode(SkinningMode mode); + SkinningMode activeSkinningMode() const { return activeSkinning_; } + const osg::BoundingBox& posedBounds() const { return posedBounds_; } // World-space bounding sphere of the rest pose. osg::BoundingSphere restBound() const; @@ -40,6 +44,8 @@ private: osg::StateSet* buildMaterialState(const Material& material, int order); void preloadTextureImages(); osg::Texture2D* texture(int index, bool clamp); + void buildSkinning(); + void uploadBoneMatrices(); void buildSkeleton(); void updateSkeleton(); @@ -61,6 +67,16 @@ private: int selectedBone_ = -1; bool skeletonDirty_ = true; + SkinningMode requestedSkinning_ = SkinningMode::Hardware; + SkinningMode activeSkinning_ = SkinningMode::Software; + osg::ref_ptr boneImage_; + osg::ref_ptr boneTexture_; + osg::ref_ptr skinningUniform_; + std::vector boneRestPositions_; + float boneReach_ = 0.f; // max distance of a vertex (incl. morphs) from its main bone + osg::BoundingBox unskinnedBounds_; // vertices without bones + osg::BoundingBox posedBounds_; + osg::ref_ptr lightingUniform_; osg::ref_ptr lightFollowUniform_; osg::ref_ptr lightDirUniform_; diff --git a/src/render/Shaders.cpp b/src/render/Shaders.cpp index 6586732..94afd9d 100644 --- a/src/render/Shaders.cpp +++ b/src/render/Shaders.cpp @@ -5,14 +5,47 @@ namespace mr { namespace { // GLSL 1.20 so the same shaders run on macOS legacy contexts, Windows and Linux. +// Hardware skinning reads bone matrices from a float texture: bone b occupies texels +// (b % 1024) * 3 + k, row b / 1024, where texel k holds column k of its 4x3 matrix. const char* kVertexShader = R"(#version 120 +uniform int u_skinning; +uniform sampler2D u_boneTexture; +uniform vec2 u_boneTexSize; +attribute vec4 a_boneIndices; +attribute vec4 a_boneWeights; varying vec3 v_normal; varying vec3 v_viewPos; varying vec2 v_uv; + +vec4 boneColumn(float bone, float k) { + vec2 texel = vec2(mod(bone, 1024.0) * 3.0 + k, floor(bone / 1024.0)); + return texture2DLod(u_boneTexture, (texel + 0.5) / u_boneTexSize, 0.0); +} + +void skin(float bone, float weight, vec4 pos, vec3 nrm, inout vec3 outPos, inout vec3 outNrm) { + vec4 c0 = boneColumn(bone, 0.0); + vec4 c1 = boneColumn(bone, 1.0); + vec4 c2 = boneColumn(bone, 2.0); + outPos += weight * vec3(dot(pos, c0), dot(pos, c1), dot(pos, c2)); + outNrm += weight * vec3(dot(nrm, c0.xyz), dot(nrm, c1.xyz), dot(nrm, c2.xyz)); +} + void main() { - vec4 viewPos = gl_ModelViewMatrix * gl_Vertex; + vec4 pos = gl_Vertex; + vec3 nrm = gl_Normal; + if (u_skinning == 1 && a_boneWeights.x > 0.0) { + vec3 p = vec3(0.0); + vec3 n = vec3(0.0); + skin(a_boneIndices.x, a_boneWeights.x, pos, nrm, p, n); + if (a_boneWeights.y > 0.0) skin(a_boneIndices.y, a_boneWeights.y, pos, nrm, p, n); + if (a_boneWeights.z > 0.0) skin(a_boneIndices.z, a_boneWeights.z, pos, nrm, p, n); + if (a_boneWeights.w > 0.0) skin(a_boneIndices.w, a_boneWeights.w, pos, nrm, p, n); + pos = vec4(p, 1.0); + nrm = n; + } + vec4 viewPos = gl_ModelViewMatrix * pos; v_viewPos = viewPos.xyz; - v_normal = gl_NormalMatrix * gl_Normal; + v_normal = gl_NormalMatrix * nrm; v_uv = gl_MultiTexCoord0.xy; gl_Position = gl_ProjectionMatrix * viewPos; } @@ -83,6 +116,8 @@ osg::ref_ptr createModelProgram() { program->setName("ModelProgram"); program->addShader(new osg::Shader(osg::Shader::VERTEX, kVertexShader)); program->addShader(new osg::Shader(osg::Shader::FRAGMENT, kFragmentShader)); + program->addBindAttribLocation("a_boneIndices", kBoneIndexAttrib); + program->addBindAttribLocation("a_boneWeights", kBoneWeightAttrib); return program; } diff --git a/src/render/Shaders.h b/src/render/Shaders.h index 75c8d9c..767022a 100644 --- a/src/render/Shaders.h +++ b/src/render/Shaders.h @@ -4,6 +4,12 @@ namespace mr { +// Generic attribute slots for skinning data; 6 and 7 do not alias any fixed-function attribute. +constexpr unsigned kBoneIndexAttrib = 6; +constexpr unsigned kBoneWeightAttrib = 7; +constexpr unsigned kBoneTextureUnit = 3; +constexpr int kBonesPerTextureRow = 1024; + osg::ref_ptr createModelProgram(); } // namespace mr -- 2.54.1 From f415f4a4c3d6c585f3fe24b4805e6cc58e4797ea Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sat, 28 Nov 2026 06:01:33 +0000 Subject: [PATCH 2/3] Test hardware skinning math; document skinning modes Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 11 +++++++++-- tests/test_main.cpp | 31 +++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1f50e07..6159b17 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Built with C++17, [OpenSceneGraph](https://github.com/openscenegraph/OpenSceneGr .pmx ──► PmxLoader ─┐ .pmd ──► PmdLoader ─┼─► mr::Model ──► mr::Poser ──► ModelNode (OSG geometry + GLSL) ──► osgViewer .fbx ──► Assimp ──┘ (one format) (morphs + skinning, ImGui overlay (bones, morphs, view) - on the CPU) + CPU or GPU skinning) ``` * PMX and PMD use their own loaders because Assimp cannot read PMD and drops PMX morphs. @@ -21,6 +21,10 @@ Built with C++17, [OpenSceneGraph](https://github.com/openscenegraph/OpenSceneGr * Bone rotations in the UI are in model-space axes at the bone pivot, so they behave the same for MMD and FBX rigs. * Shaders are GLSL 1.20 so they run on macOS's legacy OpenGL context as well as Linux and Windows. +* Skinning has two paths, switchable under **View**: hardware (default; bone matrices go to the + vertex shader in a float texture) and software (`Poser` skins every vertex on the CPU, using all + cores). Hardware falls back to software if the GPU lacks vertex texture fetch or float textures. + Morphs are applied on the CPU in both modes and only re-uploaded when morph weights change. Supported: textures (incl. MMD sphere `.sph`/`.spa` and toon maps), vertex/group/bone/flip morphs, BDEF1/2/4 weights (SDEF/QDEF approximated as linear blend). Not yet: IK solving, physics, UV and @@ -104,7 +108,8 @@ Linux) so MMD bone and morph names display correctly. * **File > Open** picks a model; you can also pass the path on the command line. * **Bones**: select a bone, then use the rotation sliders / move fields. `*` marks posed bones. * **Morphs**: sliders grouped as Eye / Mouth / Eyebrow / Other, as in MMD. -* **View**: skeleton overlay, wireframe, culling, MMD toon vs Lambert shading, UI scale (use 2 on Retina). +* **View**: skeleton overlay, wireframe, culling, MMD toon vs Lambert shading, GPU vs CPU skinning, + UI scale (use 2 on Retina). * Camera: left drag orbits, middle drag pans, right drag or wheel zooms, Space resets. Command-line options (`--help`) allow scripted renders, e.g. @@ -114,6 +119,8 @@ Command-line options (`--help`) allow scripted renders, e.g. --orbit 20,10 --hide-ui --screenshot out.png ``` +`--skinning gpu|cpu` picks the skinning path; `--bench N` prints load, frame and deformation times. + ## Tests ```sh diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 98b3e25..4d5ddb5 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -89,6 +89,37 @@ void testPmx() { q.getRotate(angle, axis); CHECK(near(static_cast(angle), static_cast(osg::PI * 0.75), 1e-3f)); CHECK(near(static_cast(axis.z()), 1.f, 1e-3f)); + + // Hardware mode: emulating the vertex shader (texel k = column k of the bone matrix) on the + // CPU-provided skin matrices and morphed positions must match software skinning. + poser.morphWeights()[0] = 0.5f; + poser.update(); + mr::Poser gpu(model); + gpu.setSkinningMode(mr::SkinningMode::Hardware); + gpu.bonePoses() = poser.bonePoses(); + gpu.morphWeights() = poser.morphWeights(); + CHECK(gpu.update()); + CHECK(gpu.morphsChangedInLastUpdate()); + float maxErr = 0.f; + for (size_t i = 0; i < model->vertices.size(); ++i) { + const mr::Vertex& v = model->vertices[i]; + const osg::Vec4f pos(gpu.morphedPositions()[i], 1.f); + osg::Vec3f p = pos.asVec3(); + if (v.bones[0] >= 0) { + p.set(0, 0, 0); + for (int k = 0; k < 4; ++k) { + if (v.bones[k] < 0) continue; + const osg::Matrixf& m = gpu.skinMatrices()[v.bones[k]]; + for (int c = 0; c < 3; ++c) + p[c] += v.weights[k] * (pos * osg::Vec4f(m(0, c), m(1, c), m(2, c), m(3, c))); + } + } + maxErr = std::max(maxErr, (p - poser.positions()[i]).length()); + } + CHECK(maxErr < 1e-4f); + gpu.bonePoses()[1].eulerDegrees.set(0, 0, 45); + CHECK(gpu.update()); + CHECK(!gpu.morphsChangedInLastUpdate()); } void testPmd() { -- 2.54.1 From e6f388ecdb7427afcbae6aca9d1e5f7c74888174 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sat, 28 Nov 2026 06:01:39 +0000 Subject: [PATCH 3/3] Fix hardware skinning test build Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- tests/test_main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 4d5ddb5..971da20 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -104,7 +104,7 @@ void testPmx() { for (size_t i = 0; i < model->vertices.size(); ++i) { const mr::Vertex& v = model->vertices[i]; const osg::Vec4f pos(gpu.morphedPositions()[i], 1.f); - osg::Vec3f p = pos.asVec3(); + osg::Vec3f p = gpu.morphedPositions()[i]; if (v.bones[0] >= 0) { p.set(0, 0, 0); for (int k = 0; k < 4; ++k) { -- 2.54.1