From b3d0afdd24a314829cbdbba5a7fb968f4a4baabf Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sat, 28 Nov 2026 14:16:22 +0000 Subject: [PATCH 1/2] MMD rigid-body physics with Bullet: PMX/PMD rigid bodies and joints, Poser integration, UI toggle Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CMakeLists.txt | 26 +++++- src/app/AppUi.cpp | 21 +++++ src/app/AppUi.h | 2 + src/app/main.cpp | 5 + src/model/Model.cpp | 26 ++++++ src/model/Model.h | 34 +++++++ src/model/PmdLoader.cpp | 48 ++++++++++ src/model/PmxLoader.cpp | 57 +++++++++++- src/model/Poser.cpp | 35 ++++++- src/model/Poser.h | 16 ++++ src/physics/PhysicsWorld.cpp | 175 +++++++++++++++++++++++++++++++++++ src/physics/PhysicsWorld.h | 37 ++++++++ tests/test_main.cpp | 58 ++++++++++++ 13 files changed, 537 insertions(+), 3 deletions(-) create mode 100644 src/physics/PhysicsWorld.cpp create mode 100644 src/physics/PhysicsWorld.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 9fd67f5..74f60b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -68,6 +68,27 @@ if(NOT WIN32) endif() # --- Core library: model formats + posing (no rendering) ------------------------- +# --- Bullet (MMD rigid-body physics) ----------------------------------------- +set(BUILD_BULLET2_DEMOS OFF CACHE BOOL "" FORCE) +set(BUILD_CPU_DEMOS OFF CACHE BOOL "" FORCE) +set(BUILD_OPENGL3_DEMOS OFF CACHE BOOL "" FORCE) +set(BUILD_EXTRAS OFF CACHE BOOL "" FORCE) +set(BUILD_UNIT_TESTS OFF CACHE BOOL "" FORCE) +set(BUILD_PYBULLET OFF CACHE BOOL "" FORCE) +set(BUILD_BULLET3 OFF CACHE BOOL "" FORCE) +set(USE_GRAPHICAL_BENCHMARK OFF CACHE BOOL "" FORCE) +set(INSTALL_LIBS OFF CACHE BOOL "" FORCE) +set(USE_MSVC_RUNTIME_LIBRARY_DLL ON CACHE BOOL "" FORCE) +set(CMAKE_POLICY_VERSION_MINIMUM 3.5 CACHE STRING "") +FetchContent_Declare(bullet + URL https://github.com/bulletphysics/bullet3/archive/refs/tags/3.25.tar.gz + URL_HASH SHA256=c45afb6399e3f68036ddb641c6bf6f552bf332d5ab6be62f7e6c54eda05ceb77) +FetchContent_GetProperties(bullet) +if(NOT bullet_POPULATED) + FetchContent_Populate(bullet) + add_subdirectory(${bullet_SOURCE_DIR} ${bullet_BINARY_DIR} EXCLUDE_FROM_ALL) +endif() + add_library(mr_core STATIC src/model/Model.cpp src/model/TextEncoding.cpp @@ -77,10 +98,13 @@ add_library(mr_core STATIC src/model/AssimpLoader.cpp src/model/ModelLoader.cpp src/model/Poser.cpp - src/model/Motion.cpp) + src/model/Motion.cpp + src/physics/PhysicsWorld.cpp) target_include_directories(mr_core PUBLIC src ${OPENSCENEGRAPH_INCLUDE_DIRS}) find_package(Threads REQUIRED) target_link_libraries(mr_core PUBLIC ${OPENSCENEGRAPH_LIBRARIES} assimp::assimp Threads::Threads) +target_include_directories(mr_core PRIVATE ${bullet_SOURCE_DIR}/src) +target_link_libraries(mr_core PRIVATE BulletDynamics BulletCollision LinearMath) if(NOT WIN32) target_link_libraries(mr_core PRIVATE Iconv::Iconv) endif() diff --git a/src/app/AppUi.cpp b/src/app/AppUi.cpp index a34136a..0d6bd78 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -99,6 +99,7 @@ void App::applyViewSettings() { modelNode_->setLightFollowsCamera(lightFollowsCamera_); modelNode_->setLightingModel(static_cast(lightingModel_)); modelNode_->setSelectedBone(selectedBone_); + modelNode_->poser().setPhysicsEnabled(physicsEnabled_); modelNode_->setSkinningMode(skinning_ == 1 ? SkinningMode::Hardware : SkinningMode::Software); } @@ -175,7 +176,13 @@ void App::setPlaying(bool playing) { } } +void App::setPhysicsEnabled(bool enabled) { + physicsEnabled_ = enabled; + if (modelNode_) modelNode_->poser().setPhysicsEnabled(enabled); +} + void App::setMotionFrame(float frame) { + if (modelNode_ && std::fabs(frame - motionFrame_) > 2.f) modelNode_->poser().resetPhysics(); motionFrame_ = std::max(0.f, frame); if (playing_) setPlaying(true); else audio_.seek(motionFrame_ / kMotionFps); @@ -300,8 +307,11 @@ void App::updateProjection() { void App::tick(double time) { const double dt = lastTick_ < 0.0 ? 0.0 : time - lastTick_; + const double realDt = lastTick_ < 0.0 ? 0.0 : std::clamp(time - lastTick_, 0.0, 0.1); lastTick_ = time; updateRender(); + // Renders advance exactly one frame per update, so physics is stepped by the frame time. + if (modelNode_) modelNode_->poser().stepPhysics(render_.active ? 1.f / 30.f : float(realDt)); updatePopOut(); updateProjection(); if (modelNode_) modelNode_->poser().setIkEnabled(ikEnabled_); @@ -424,6 +434,10 @@ void App::drawMenuBar() { changed |= ImGui::MenuItem("Backface culling", nullptr, &backfaceCulling_); changed |= ImGui::MenuItem("Light follows camera", nullptr, &lightFollowsCamera_); ImGui::MenuItem("Solve IK", nullptr, &ikEnabled_); + const bool hasPhysics = modelNode_ && modelNode_->poser().hasPhysics(); + if (ImGui::MenuItem("Physics", nullptr, &physicsEnabled_, hasPhysics)) setPhysicsEnabled(physicsEnabled_); + if (ImGui::MenuItem("Reset physics", nullptr, false, hasPhysics && physicsEnabled_)) + modelNode_->poser().resetPhysics(); ImGui::Separator(); changed |= ImGui::RadioButton("MMD toon shading", &lightingModel_, 0); changed |= ImGui::RadioButton("Lambert shading", &lightingModel_, 1); @@ -463,6 +477,13 @@ 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()); + if (!m.rigidBodies.empty()) { + ImGui::Text("Rigid bodies %zu Joints %zu", m.rigidBodies.size(), m.joints.size()); + bool physics = physicsEnabled_; + if (ImGui::Checkbox("Physics", &physics)) setPhysicsEnabled(physics); + ImGui::SameLine(); + if (ImGui::SmallButton("Reset##physics")) modelNode_->poser().resetPhysics(); + } ImGui::TextDisabled("Skinning: %s", modelNode_->activeSkinningMode() == SkinningMode::Hardware ? "GPU" : "CPU"); if (ImGui::Button("Reset pose")) modelNode_->poser().resetPose(); diff --git a/src/app/AppUi.h b/src/app/AppUi.h index debb76a..2cd1190 100644 --- a/src/app/AppUi.h +++ b/src/app/AppUi.h @@ -26,6 +26,7 @@ public: void frameModel(float azimuthDeg = 0.f, float elevationDeg = 0.f); void setShowSkeleton(bool show); void setGpuSkinning(bool enabled); + void setPhysicsEnabled(bool enabled); bool loadMotion(const std::string& path); void unloadMotion(); @@ -96,6 +97,7 @@ private: bool resetLayout_ = false; bool wantPopOut_ = false; bool showRenderDialog_ = false; + bool physicsEnabled_ = true; bool quitAfterRender_ = false; std::string audioPath_; struct RenderJob { diff --git a/src/app/main.cpp b/src/app/main.cpp index df3fbc2..34a3872 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -45,6 +45,7 @@ void printUsage() { " --camera FILE.vmd load an MMD camera motion\n" " --audio FILE load a song (.wav .mp3 .flac)\n" " --play start playback\n" + " --physics on|off rigid-body physics (default on)\n" " --pop-out show the 3D view in its own window\n" " --render DIR render PNG frames into DIR and exit\n" " --range A,B frames to render (default: whole timeline)\n" @@ -115,6 +116,7 @@ int main(int argc, char** argv) { float motionFrame = 0.f; bool play = false; bool popOut = false; + bool physics = true; std::string renderDir; int renderStart = 0, renderEnd = -1, renderW = 1920, renderH = 1080; std::vector> morphArgs, boneArgs; @@ -171,6 +173,8 @@ int main(int argc, char** argv) { motionFrame = std::strtof(next().c_str(), nullptr); } else if (a == "--play") { play = true; + } else if (a == "--physics") { + physics = next() != "off"; } else if (a == "--pop-out") { popOut = true; } else if (a == "--render") { @@ -245,6 +249,7 @@ int main(int argc, char** argv) { app.setMotionFrame(motionFrame); app.setPlaying(play); app.setViewportPoppedOut(popOut); + app.setPhysicsEnabled(physics); if (!renderDir.empty()) app.renderToFolder(renderDir, renderStart, renderEnd, renderW, renderH); } app.setShowSkeleton(skeleton); diff --git a/src/model/Model.cpp b/src/model/Model.cpp index 49aea32..c403b83 100644 --- a/src/model/Model.cpp +++ b/src/model/Model.cpp @@ -73,4 +73,30 @@ void validateIk(Bone& bone, int index, int boneCount) { bone.ikIterations = std::min(std::max(bone.ikIterations, 0), 256); } +namespace { + +// MMD applies Euler angles as Y * X * Z (column vectors); mirroring Z negates the X and Y angles. +osg::Quat mmdRotation(const osg::Vec3f& e) { + return osg::Quat(e.z(), osg::Z_AXIS) * osg::Quat(-e.x(), osg::X_AXIS) * osg::Quat(-e.y(), osg::Y_AXIS); +} + +osg::Vec3f mirrorZ(const osg::Vec3f& v) { return {v.x(), v.y(), -v.z()}; } + +} // namespace + +void setRigidBodyFromMmd(RigidBody& body, const osg::Vec3f& position, const osg::Vec3f& euler) { + body.position = mirrorZ(position); + body.rotation = mmdRotation(euler); +} + +void setJointFromMmd(Joint& joint, const osg::Vec3f& position, const osg::Vec3f& euler, const osg::Vec3f& linearLower, + const osg::Vec3f& linearUpper, const osg::Vec3f& angularLower, const osg::Vec3f& angularUpper) { + joint.position = mirrorZ(position); + joint.rotation = mmdRotation(euler); + joint.linearLower = {linearLower.x(), linearLower.y(), -linearUpper.z()}; + joint.linearUpper = {linearUpper.x(), linearUpper.y(), -linearLower.z()}; + joint.angularLower = {-angularUpper.x(), -angularUpper.y(), angularLower.z()}; + joint.angularUpper = {-angularLower.x(), -angularLower.y(), angularUpper.z()}; +} + } // namespace mr diff --git a/src/model/Model.h b/src/model/Model.h index 3ea6244..39458d3 100644 --- a/src/model/Model.h +++ b/src/model/Model.h @@ -127,6 +127,38 @@ struct Morph { std::vector boneOffsets; }; +enum class RigidShape : uint8_t { Sphere = 0, Box = 1, Capsule = 2 }; +// 0: follows its bone, 1: simulated and drives the bone, 2: simulated rotation, bone position. +enum class RigidMode : uint8_t { FollowBone = 0, Physics = 1, PhysicsWithBone = 2 }; + +struct RigidBody { + std::string name; + int bone = -1; + int group = 0; // 0..15 + uint16_t collisionMask = 0xFFFF; // groups this body collides with + RigidShape shape = RigidShape::Sphere; + osg::Vec3f size; // sphere: radius; box: half extents; capsule: radius, height + osg::Vec3f position; // model space at rest + osg::Quat rotation; + float mass = 0.f, linearDamping = 0.f, angularDamping = 0.f, restitution = 0.f, friction = 0.5f; + RigidMode mode = RigidMode::FollowBone; +}; + +// 6DOF spring joint between two rigid bodies (limits in the joint frame). +struct Joint { + std::string name; + int bodyA = -1, bodyB = -1; + osg::Vec3f position; + osg::Quat rotation; + osg::Vec3f linearLower, linearUpper, angularLower, angularUpper; + osg::Vec3f linearSpring, angularSpring; +}; + +// Convert MMD's left-handed rigid body / joint values (Euler angles in radians) to internal axes. +void setRigidBodyFromMmd(RigidBody& body, const osg::Vec3f& position, const osg::Vec3f& euler); +void setJointFromMmd(Joint& joint, const osg::Vec3f& position, const osg::Vec3f& euler, const osg::Vec3f& linearLower, + const osg::Vec3f& linearUpper, const osg::Vec3f& angularLower, const osg::Vec3f& angularUpper); + struct Model { SourceFormat format = SourceFormat::Assimp; std::string sourcePath; @@ -138,6 +170,8 @@ struct Model { std::vector materials; std::vector bones; std::vector morphs; + std::vector rigidBodies; + std::vector joints; std::vector warnings; int findBone(const std::string& boneName) const; diff --git a/src/model/PmdLoader.cpp b/src/model/PmdLoader.cpp index e0de56b..ae11394 100644 --- a/src/model/PmdLoader.cpp +++ b/src/model/PmdLoader.cpp @@ -255,11 +255,59 @@ private: if (r_.remaining() >= 1000) { for (int i = 0; i < 10; ++i) toonNames_[i] = sjis(r_, 100); } + if (r_.remaining() >= 4) parsePhysics(); } catch (const std::runtime_error&) { model_.warnings.push_back("PMD optional sections are truncated"); } } + void parsePhysics() { + const uint32_t bodyCount = r_.u32(); + std::vector bodies; + for (uint32_t i = 0; i < bodyCount; ++i) { + RigidBody b; + b.name = sjis(r_, 20); + const uint16_t bone = r_.u16(); + b.bone = bone < model_.bones.size() ? bone : -1; + b.group = r_.u8(); + b.collisionMask = r_.u16(); + b.shape = static_cast(std::min(r_.u8(), 2)); + b.size = r_.vec3(); + // PMD stores the position relative to the bone (or the first bone). + osg::Vec3f position = r_.vec3(); + const int anchor = b.bone >= 0 ? b.bone : (model_.bones.empty() ? -1 : 0); + if (anchor >= 0) { + const osg::Vec3f bonePos = model_.bones[anchor].restPosition; + position += osg::Vec3f(bonePos.x(), bonePos.y(), -bonePos.z()); + } + const osg::Vec3f rotation = r_.vec3(); + setRigidBodyFromMmd(b, position, rotation); + b.mass = r_.f32(); + b.linearDamping = r_.f32(); + b.angularDamping = r_.f32(); + b.restitution = r_.f32(); + b.friction = r_.f32(); + b.mode = static_cast(std::min(r_.u8(), 2)); + bodies.push_back(std::move(b)); + } + const uint32_t jointCount = r_.u32(); + std::vector joints; + for (uint32_t i = 0; i < jointCount; ++i) { + Joint j; + j.name = sjis(r_, 20); + j.bodyA = static_cast(r_.u32()); + j.bodyB = static_cast(r_.u32()); + const osg::Vec3f position = r_.vec3(), rotation = r_.vec3(); + const osg::Vec3f linLo = r_.vec3(), linHi = r_.vec3(), angLo = r_.vec3(), angHi = r_.vec3(); + setJointFromMmd(j, position, rotation, linLo, linHi, angLo, angHi); + j.linearSpring = r_.vec3(); + j.angularSpring = r_.vec3(); + joints.push_back(std::move(j)); + } + model_.rigidBodies = std::move(bodies); + model_.joints = std::move(joints); + } + void resolveToons() { for (size_t i = 0; i < model_.materials.size(); ++i) { int toon = toonIndices_[i]; diff --git a/src/model/PmxLoader.cpp b/src/model/PmxLoader.cpp index b45d9fb..ef3710c 100644 --- a/src/model/PmxLoader.cpp +++ b/src/model/PmxLoader.cpp @@ -46,7 +46,8 @@ public: parseMaterials(); parseBones(); parseMorphs(); - // Display frames, rigid bodies and joints are not needed for rendering/posing. + parseDisplayFrames(); + parsePhysics(); model_.normalizeWeights(); } @@ -326,6 +327,60 @@ private: } } + void parseDisplayFrames() { + const int32_t count = r_.i32(); + for (int32_t i = 0; i < count; ++i) { + text(); + text(); + r_.u8(); + const int32_t elements = r_.i32(); + for (int32_t e = 0; e < elements; ++e) + r_.signedIndex(r_.u8() == 0 ? h_.boneIndexSize : h_.morphIndexSize); + } + } + + void parsePhysics() { + const int boneCount = static_cast(model_.bones.size()); + const int32_t bodyCount = r_.i32(); + model_.rigidBodies.reserve(static_cast(std::max(bodyCount, 0))); + for (int32_t i = 0; i < bodyCount; ++i) { + RigidBody b; + b.name = text(); + text(); + b.bone = boneIndex(); + if (b.bone >= boneCount) b.bone = -1; + b.group = r_.u8(); + b.collisionMask = r_.u16(); + b.shape = static_cast(std::min(r_.u8(), 2)); + b.size = r_.vec3(); + const osg::Vec3f position = r_.vec3(); + const osg::Vec3f rotation = r_.vec3(); + setRigidBodyFromMmd(b, position, rotation); + b.mass = r_.f32(); + b.linearDamping = r_.f32(); + b.angularDamping = r_.f32(); + b.restitution = r_.f32(); + b.friction = r_.f32(); + b.mode = static_cast(std::min(r_.u8(), 2)); + model_.rigidBodies.push_back(std::move(b)); + } + const int32_t jointCount = r_.i32(); + for (int32_t i = 0; i < jointCount; ++i) { + Joint j; + j.name = text(); + text(); + const uint8_t type = r_.u8(); + j.bodyA = static_cast(r_.signedIndex(h_.rigidBodyIndexSize)); + j.bodyB = static_cast(r_.signedIndex(h_.rigidBodyIndexSize)); + const osg::Vec3f position = r_.vec3(), rotation = r_.vec3(); + const osg::Vec3f linLo = r_.vec3(), linHi = r_.vec3(), angLo = r_.vec3(), angHi = r_.vec3(); + setJointFromMmd(j, position, rotation, linLo, linHi, angLo, angHi); + j.linearSpring = r_.vec3(); + j.angularSpring = r_.vec3(); + if (type == 0) model_.joints.push_back(std::move(j)); + } + } + BinaryReader r_; Model& model_; PmxHeader h_; diff --git a/src/model/Poser.cpp b/src/model/Poser.cpp index e02d739..caa4853 100644 --- a/src/model/Poser.cpp +++ b/src/model/Poser.cpp @@ -1,4 +1,5 @@ #include "model/Poser.h" +#include "physics/PhysicsWorld.h" #include "model/Parallel.h" @@ -40,6 +41,15 @@ Poser::Poser(std::shared_ptr model) : model_(std::move(model)) { motion_.resize(boneCount); ikBoneEnabled_.assign(boneCount, 1); computeEvaluationOrder(); + if (!model_->rigidBodies.empty()) { + physics_ = std::make_unique(*model_); + const auto& driven = physics_->drivenBones(); + physicsChild_.assign(boneCount, 0); + for (int b : order_) { + const int p = model_->bones[b].parent; + physicsChild_[b] = !driven[b] && p >= 0 && (driven[p] || physicsChild_[p]); + } + } isIkLink_.assign(boneCount, 0); ikAffected_.resize(boneCount); @@ -209,8 +219,19 @@ void Poser::solveIk(int ikBone) { } } +Poser::~Poser() = default; + +void Poser::setPhysicsEnabled(bool enabled) { + if (enabled == physicsEnabled_) return; + physicsEnabled_ = enabled; + physicsReset_ = true; + firstUpdate_ = true; +} + bool Poser::update() { - if (!firstUpdate_ && poses_ == lastPoses_ && weights_ == lastWeights_ && motion_ == lastMotion_ && + const bool simulate = physics_ && physicsEnabled_; + if (!simulate) physicsDt_ = 0.f; + if (!firstUpdate_ && !(simulate && (physicsDt_ > 0.f || physicsReset_)) && poses_ == lastPoses_ && weights_ == lastWeights_ && motion_ == lastMotion_ && ikEnabled_ == lastIkEnabled_ && ikBoneEnabled_ == lastIkBoneEnabled_) return false; morphsChanged_ = firstUpdate_ || weights_ != lastWeights_; @@ -256,6 +277,18 @@ bool Poser::update() { updateGlobal(b); if (bone.isIK && ikEnabled_ && ikBoneEnabled_[b]) solveIk(b); } + if (simulate) { + if (physicsReset_) { + physics_->reset(globals_); + for (int i = 0; i < 30; ++i) physics_->step(1.f / 60.f, globals_); + physicsReset_ = false; + } + if (physicsDt_ > 0.f) physics_->step(std::min(physicsDt_, 0.1f), globals_); + physicsDt_ = 0.f; + physics_->apply(globals_); + for (int b : order_) + if (physicsChild_[b]) updateGlobal(b); + } for (size_t b = 0; b < bones.size(); ++b) skin_[b] = bones[b].inverseBind * globals_[b]; const size_t vertexCount = model.vertices.size(); diff --git a/src/model/Poser.h b/src/model/Poser.h index a922abb..6db62ac 100644 --- a/src/model/Poser.h +++ b/src/model/Poser.h @@ -7,6 +7,8 @@ namespace mr { +class PhysicsWorld; + // 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 }; @@ -33,6 +35,7 @@ struct MotionPose { class Poser { public: explicit Poser(std::shared_ptr model); + ~Poser(); const Model& model() const { return *model_; } std::vector& bonePoses() { return poses_; } @@ -42,6 +45,15 @@ public: std::vector& motionPoses() { return motion_; } // IK chains are solved after posing; per-bone flags come from motion files. void setIkEnabled(bool enabled) { ikEnabled_ = enabled; } + + // Rigid-body physics (only for models with rigid bodies). + bool hasPhysics() const { return physics_ != nullptr; } + const PhysicsWorld* physics() const { return physics_.get(); } + void setPhysicsEnabled(bool enabled); + bool physicsEnabled() const { return physicsEnabled_; } + void stepPhysics(float seconds) { physicsDt_ += seconds; } + // Snap bodies back to the current pose (e.g. after jumping on the timeline) and let them settle. + void resetPhysics() { physicsReset_ = true; } bool ikEnabled() const { return ikEnabled_; } std::vector& ikBoneEnabled() { return ikBoneEnabled_; } bool isIkLink(int bone) const { return bone >= 0 && bone < int(isIkLink_.size()) && isIkLink_[bone]; } @@ -81,6 +93,10 @@ private: std::vector> ikAffected_; // per IK bone: bones whose globals the chain moves, in order std::vector isIkLink_; bool firstUpdate_ = true; + std::unique_ptr physics_; + bool physicsEnabled_ = true, physicsReset_ = true; + float physicsDt_ = 0.f; + std::vector physicsChild_; // not simulated but below a simulated bone bool morphsChanged_ = true; SkinningMode mode_ = SkinningMode::Software; diff --git a/src/physics/PhysicsWorld.cpp b/src/physics/PhysicsWorld.cpp new file mode 100644 index 0000000..47b076d --- /dev/null +++ b/src/physics/PhysicsWorld.cpp @@ -0,0 +1,175 @@ +#include "physics/PhysicsWorld.h" + +#include + +#include + +namespace mr { + +namespace { + +btTransform toBt(const osg::Matrixf& m) { + const osg::Quat q = m.getRotate(); + const osg::Vec3f t = m.getTrans(); + return btTransform(btQuaternion(btScalar(q.x()), btScalar(q.y()), btScalar(q.z()), btScalar(q.w())), + btVector3(t.x(), t.y(), t.z())); +} + +osg::Matrixf toOsg(const btTransform& t) { + const btQuaternion q = t.getRotation(); + const btVector3& o = t.getOrigin(); + return osg::Matrixf::rotate(osg::Quat(q.x(), q.y(), q.z(), q.w())) * osg::Matrixf::translate(o.x(), o.y(), o.z()); +} + +btVector3 bt(const osg::Vec3f& v) { return btVector3(v.x(), v.y(), v.z()); } + +constexpr float kFixedStep = 1.f / 120.f; +constexpr int kMaxSubSteps = 12; + +} // namespace + +struct PhysicsWorld::Impl { + struct Body { + std::unique_ptr shape; + std::unique_ptr motion; + std::unique_ptr body; + osg::Matrixf offset; // body transform in its bone's space + osg::Matrixf invOffset; + osg::Matrixf rest; // model-space rest transform + int bone = -1; + RigidMode mode = RigidMode::FollowBone; + bool kinematic = true; + }; + + btDefaultCollisionConfiguration config; + btCollisionDispatcher dispatcher{&config}; + btDbvtBroadphase broadphase; + btSequentialImpulseConstraintSolver solver; + btDiscreteDynamicsWorld world{&dispatcher, &broadphase, &solver, &config}; + std::vector bodies; + std::vector> joints; + std::vector driven; + + osg::Matrixf target(const Body& b, const std::vector& globals) const { + return b.bone >= 0 && b.bone < int(globals.size()) ? b.offset * globals[b.bone] : b.rest; + } + + ~Impl() { + for (auto& j : joints) world.removeConstraint(j.get()); + for (auto& b : bodies) world.removeRigidBody(b.body.get()); + } +}; + +PhysicsWorld::PhysicsWorld(const Model& model) : impl_(std::make_unique()) { + Impl& w = *impl_; + w.world.setGravity(btVector3(0, -9.8f * 10.f, 0)); // MMD units: 1 unit is about 8 cm + w.driven.assign(model.bones.size(), 0); + w.bodies.reserve(model.rigidBodies.size()); + for (const RigidBody& rb : model.rigidBodies) { + Impl::Body b; + const osg::Vec3f s(std::max(rb.size.x(), 1e-3f), std::max(rb.size.y(), 1e-3f), std::max(rb.size.z(), 1e-3f)); + switch (rb.shape) { + case RigidShape::Sphere: b.shape = std::make_unique(s.x()); break; + case RigidShape::Box: b.shape = std::make_unique(bt(s)); break; + case RigidShape::Capsule: b.shape = std::make_unique(s.x(), s.y()); break; + } + b.bone = rb.bone >= 0 && rb.bone < int(model.bones.size()) ? rb.bone : -1; + b.mode = rb.mode; + b.rest = osg::Matrixf::rotate(rb.rotation) * osg::Matrixf::translate(rb.position); + const osg::Matrixf boneRest = b.bone >= 0 ? osg::Matrixf::inverse(model.bones[b.bone].inverseBind) : osg::Matrixf(); + b.offset = b.rest * osg::Matrixf::inverse(boneRest); + b.invOffset = osg::Matrixf::inverse(b.offset); + b.kinematic = rb.mode == RigidMode::FollowBone || rb.mass <= 0.f; + const btScalar mass = b.kinematic ? 0.f : rb.mass; + btVector3 inertia(0, 0, 0); + if (mass > 0.f) b.shape->calculateLocalInertia(mass, inertia); + b.motion = std::make_unique(toBt(b.rest)); + btRigidBody::btRigidBodyConstructionInfo info(mass, b.motion.get(), b.shape.get(), inertia); + info.m_linearDamping = rb.linearDamping; + info.m_angularDamping = rb.angularDamping; + info.m_restitution = rb.restitution; + info.m_friction = rb.friction; + info.m_additionalDamping = true; + b.body = std::make_unique(info); + if (b.kinematic) b.body->setCollisionFlags(b.body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); + b.body->setActivationState(DISABLE_DEACTIVATION); + const int group = 1 << std::clamp(rb.group, 0, 15); + w.world.addRigidBody(b.body.get(), group, rb.collisionMask); + if (!b.kinematic && b.bone >= 0) w.driven[b.bone] = 1; + w.bodies.push_back(std::move(b)); + } + for (const Joint& j : model.joints) { + if (j.bodyA < 0 || j.bodyB < 0 || j.bodyA >= int(w.bodies.size()) || j.bodyB >= int(w.bodies.size()) || + j.bodyA == j.bodyB) + continue; + btRigidBody& a = *w.bodies[j.bodyA].body; + btRigidBody& b = *w.bodies[j.bodyB].body; + const btTransform frame = toBt(osg::Matrixf::rotate(j.rotation) * osg::Matrixf::translate(j.position)); + auto c = std::make_unique(a, b, a.getWorldTransform().inverse() * frame, + b.getWorldTransform().inverse() * frame, true); + c->setLinearLowerLimit(bt(j.linearLower)); + c->setLinearUpperLimit(bt(j.linearUpper)); + c->setAngularLowerLimit(bt(j.angularLower)); + c->setAngularUpperLimit(bt(j.angularUpper)); + for (int i = 0; i < 3; ++i) { + if (j.linearSpring[i] != 0.f) { + c->enableSpring(i, true); + c->setStiffness(i, j.linearSpring[i]); + } + if (j.angularSpring[i] != 0.f) { + c->enableSpring(i + 3, true); + c->setStiffness(i + 3, j.angularSpring[i]); + } + } + w.world.addConstraint(c.get(), true); + w.joints.push_back(std::move(c)); + } +} + +PhysicsWorld::~PhysicsWorld() = default; + +size_t PhysicsWorld::bodyCount() const { return impl_->bodies.size(); } +size_t PhysicsWorld::jointCount() const { return impl_->joints.size(); } +const std::vector& PhysicsWorld::drivenBones() const { return impl_->driven; } + +void PhysicsWorld::reset(const std::vector& globals) { + Impl& w = *impl_; + for (auto& b : w.bodies) { + const btTransform t = toBt(w.target(b, globals)); + b.body->setWorldTransform(t); + b.body->setInterpolationWorldTransform(t); + b.motion->setWorldTransform(t); + b.body->setLinearVelocity(btVector3(0, 0, 0)); + b.body->setAngularVelocity(btVector3(0, 0, 0)); + b.body->setInterpolationLinearVelocity(btVector3(0, 0, 0)); + b.body->setInterpolationAngularVelocity(btVector3(0, 0, 0)); + b.body->clearForces(); + } +} + +void PhysicsWorld::step(float dt, const std::vector& globals) { + Impl& w = *impl_; + for (auto& b : w.bodies) + if (b.kinematic) b.motion->setWorldTransform(toBt(w.target(b, globals))); + w.world.stepSimulation(dt, kMaxSubSteps, kFixedStep); + // Mode 2 bodies rotate freely but stay pinned to their bone's position. + for (auto& b : w.bodies) { + if (b.kinematic || b.mode != RigidMode::PhysicsWithBone) continue; + btTransform t = b.body->getWorldTransform(); + t.setOrigin(toBt(w.target(b, globals)).getOrigin()); + b.body->setWorldTransform(t); + b.motion->setWorldTransform(t); + } +} + +void PhysicsWorld::apply(std::vector& globals) const { + const Impl& w = *impl_; + for (const auto& b : w.bodies) { + if (b.kinematic || b.bone < 0 || b.bone >= int(globals.size())) continue; + osg::Matrixf g = b.invOffset * toOsg(b.body->getWorldTransform()); + if (b.mode == RigidMode::PhysicsWithBone) g.setTrans(globals[b.bone].getTrans()); + globals[b.bone] = g; + } +} + +} // namespace mr diff --git a/src/physics/PhysicsWorld.h b/src/physics/PhysicsWorld.h new file mode 100644 index 0000000..f27ff7c --- /dev/null +++ b/src/physics/PhysicsWorld.h @@ -0,0 +1,37 @@ +#pragma once + +#include "model/Model.h" + +#include +#include + +namespace mr { + +// MMD rigid-body physics (hair, skirts, tails) on top of Bullet. Works in model space: +// bodies that follow bones are driven from the animated bone globals, and dynamic bodies +// write their simulated transforms back into the bones they are attached to. +class PhysicsWorld { +public: + explicit PhysicsWorld(const Model& model); + ~PhysicsWorld(); + PhysicsWorld(const PhysicsWorld&) = delete; + PhysicsWorld& operator=(const PhysicsWorld&) = delete; + + size_t bodyCount() const; + size_t jointCount() const; + // Bones whose global transform comes from the simulation. + const std::vector& drivenBones() const; + + // Teleports every body to its bone and clears velocities. + void reset(const std::vector& boneGlobals); + // Moves bone-following bodies to the animated pose and advances the simulation by dt seconds. + void step(float dt, const std::vector& boneGlobals); + // Overwrites the globals of physics-driven bones with the simulated result. + void apply(std::vector& boneGlobals) const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace mr diff --git a/tests/test_main.cpp b/tests/test_main.cpp index c9ce375..72516ab 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -289,6 +289,63 @@ void testFbx() { } // namespace +// A bone with a horizontal capsule hinged to a fixed body should swing down under gravity. +void testPhysics() { + auto model = std::make_shared(); + model->bones.resize(2); + const osg::Vec3f rootPos(0, 10, 0); + for (int i = 0; i < 2; ++i) { + mr::Bone& b = model->bones[i]; + b.name = i ? "arm" : "root"; + b.parent = i - 1; + b.restPosition = rootPos; + b.localBind = i ? osg::Matrixf() : osg::Matrixf::translate(rootPos); + b.inverseBind = osg::Matrixf::translate(-rootPos); + } + mr::RigidBody anchor; + anchor.bone = 0; + anchor.shape = mr::RigidShape::Sphere; + anchor.size = osg::Vec3f(0.5f, 0, 0); + anchor.position = rootPos; + anchor.collisionMask = 0; + mr::RigidBody arm; + arm.bone = 1; + arm.shape = mr::RigidShape::Capsule; + arm.size = osg::Vec3f(0.3f, 3.f, 0); + arm.position = rootPos + osg::Vec3f(2.5f, 0, 0); + arm.rotation = osg::Quat(osg::PI_2, osg::Z_AXIS); // lie along X + arm.mass = 1.f; + arm.group = 1; + arm.collisionMask = 0; + arm.mode = mr::RigidMode::Physics; + model->rigidBodies = {anchor, arm}; + mr::Joint hinge; + hinge.bodyA = 0; + hinge.bodyB = 1; + hinge.position = rootPos; + hinge.angularLower = osg::Vec3f(0, 0, -3.f); + hinge.angularUpper = osg::Vec3f(0, 0, 3.f); + model->joints = {hinge}; + + mr::Poser poser(model); + CHECK(poser.hasPhysics()); + poser.setPhysicsEnabled(false); + poser.update(); + const osg::Vec3f restTip = osg::Vec3f(3, 0, 0) * poser.boneGlobals()[1]; + CHECK(near(restTip.y(), 10.f)); + poser.setPhysicsEnabled(true); + poser.update(); // reset + settle + for (int i = 0; i < 60; ++i) { + poser.stepPhysics(1.f / 60.f); + poser.update(); + } + const osg::Vec3f tip = osg::Vec3f(3, 0, 0) * poser.boneGlobals()[1]; + std::printf("physics: arm tip %.2f %.2f %.2f\n", tip.x(), tip.y(), tip.z()); + CHECK(tip.y() < 8.f); // swung down + CHECK(near((tip - rootPos).length(), 3.f, 0.3f)); // still attached at the hinge + CHECK(near(poser.boneGlobals()[0].getTrans().y(), 10.f)); +} + int main() { testPmx(); testPmd(); @@ -296,6 +353,7 @@ int main() { testIk(); testVmd(); testCameraAndAudio(); + testPhysics(); if (g_failures == 0) std::printf("All tests passed\n"); return g_failures == 0 ? 0 : 1; } -- 2.54.1 From becfb7b7e85546902140d534d421c78321914f2d Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sat, 28 Nov 2026 14:16:33 +0000 Subject: [PATCH 2/2] Document physics Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index ac32730..7755685 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,10 @@ restores the default). * **File > Render...** writes a PNG frame sequence at any resolution (presets up to 4K and vertical), optionally with a transparent background. If `ffmpeg` is on the `PATH` it also encodes `render.mp4` with the song. +* **Physics**: models with rigid bodies and joints (hair, skirts, tails) are simulated with + Bullet, as in MMD. Toggle it in the Scene panel or **View > Physics** (`--physics off` on the + command line); **Reset physics** snaps everything back to the pose. Physics resets and settles + when you jump on the timeline, and renders step it exactly one frame at a time. * **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. -- 2.54.1