diff --git a/CMakeLists.txt b/CMakeLists.txt index 74f60b6..3e64aa6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,7 +15,7 @@ option(MR_FETCH_ASSIMP "Download and build Assimp if it is not installed" ON) include(FetchContent) # --- OpenSceneGraph ----------------------------------------------------------- -find_package(OpenSceneGraph 3.6 REQUIRED COMPONENTS osgDB osgGA osgViewer osgUtil) +find_package(OpenSceneGraph 3.6 REQUIRED COMPONENTS osgDB osgGA osgViewer osgUtil osgText) find_package(OpenGL REQUIRED) # --- Assimp -------------------------------------------------------------------- @@ -31,6 +31,7 @@ if(NOT assimp_FOUND) set(ASSIMP_BUILD_FBX_IMPORTER ON CACHE BOOL "" FORCE) set(ASSIMP_BUILD_OBJ_IMPORTER ON CACHE BOOL "" FORCE) set(ASSIMP_BUILD_GLTF_IMPORTER ON CACHE BOOL "" FORCE) + set(ASSIMP_BUILD_X_IMPORTER ON CACHE BOOL "" FORCE) # DirectX .x: MMD accessories and stages set(ASSIMP_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(ASSIMP_BUILD_ASSIMP_TOOLS OFF CACHE BOOL "" FORCE) set(ASSIMP_INSTALL OFF CACHE BOOL "" FORCE) @@ -131,6 +132,7 @@ add_executable(model_renderer src/app/FileBrowser.cpp src/app/Timeline.cpp src/app/Render.cpp + src/render/Grid.cpp src/render/ModelNode.cpp src/render/TextureLoader.cpp src/render/Shaders.cpp diff --git a/README.md b/README.md index 7755685..ebfbfa7 100644 --- a/README.md +++ b/README.md @@ -112,8 +112,16 @@ the **Timeline** at the bottom and the 3D view in the middle. Drag a panel's tab float it; the layout is saved to `~/.model_renderer_layout.ini` (**View > Reset panel layout** restores the default). -* **File > Open** (or **Add media...** in the Timeline) picks a model, a dance `.vmd`, a camera - `.vmd` or a song (`.wav`/`.mp3`/`.flac`); camera files are detected automatically. +* **File > Add model, motion or audio...** (or **Add media...** in the Timeline) picks a model, + a dance `.vmd`, a camera `.vmd` or a song (`.wav`/`.mp3`/`.flac`); camera files are detected + automatically. A dance `.vmd` applies to the model selected in the Scene panel. +* **Scene**: several models can be loaded at once. The list selects which one the Bones, Morphs + and Timeline panels edit, with a visibility checkbox and `x` to remove each one. **Position**, + **Rotation** and **Scale** place the selected model. +* **Stages** (**Add stage...**) are environment models such as a room or beach, as PMX, PMD or + DirectX `.x` (the format most classic MMD stages and accessories use). They get no + physics and don't move the camera when added. Files with "stage" or "ステージ" in the name, or + very large models, are marked as stages automatically; the **Stage** checkbox changes it. * **Bones**: select a bone, then use the rotation sliders / move fields. `*` marks posed bones. Bones the motion drives can still be offset. Bones in an IK chain follow their IK bone while **View > Solve IK** is on. @@ -131,7 +139,8 @@ restores the default). 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, +* **View**: floor grid with labelled X (red), Y (green) and Z (blue) axes (hidden in renders), + 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. @@ -144,6 +153,9 @@ Command-line options (`--help`) allow scripted renders, e.g. `--motion dance.vmd --camera camera.vmd --audio song.wav --play` plays a full MMD scene (`--frame N` jumps to a frame, `--pop-out` opens the separate viewport window); +`--add model.pmx` and `--stage stage.pmx` add more models (motions apply to the first); +`--scale S` and `--stage-scale S` resize the first model and the stages; +`--no-grid` hides the floor grid; `--render DIR [--range A,B] [--render-size WxH]` renders PNG frames without opening the UI flow; `tools/make_test_vmd.py --demo out.vmd` writes a short demo motion. `--skinning gpu|cpu` picks the skinning path; `--bench N` prints load, frame and deformation times. diff --git a/src/app/AppUi.cpp b/src/app/AppUi.cpp index 0d6bd78..0adcaad 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -2,6 +2,7 @@ #include "model/ModelLoader.h" #include "render/GpuCaps.h" +#include "render/Grid.h" #include #include @@ -39,6 +40,14 @@ const char* panelName(MorphPanel p) { } } +bool looksLikeStage(const std::string& path, const Model& model) { + for (const std::string& s : {path, model.name}) + if (containsCaseInsensitive(s, "stage") || s.find("ステージ") != std::string::npos) return true; + osg::Vec3f lo, hi; + model.computeBounds(lo, hi); + return (hi - lo).length() > 120.f; // a character is about 20 units tall +} + } // namespace namespace { @@ -63,9 +72,16 @@ App::App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulato root_->addUpdateCallback(new TickCallback(this)); viewer_.getCamera()->setProjectionResizePolicy(osg::Camera::FIXED); imgui_->attach(viewer_); + grid_ = createGrid(50.f, 5.f); + root_->addChild(grid_); } -bool App::loadModel(const std::string& path) { +void App::setShowGrid(bool show) { + showGrid_ = show; + grid_->setNodeMask(show ? kGridNodeMask : 0u); +} + +bool App::loadModel(const std::string& path, bool stage) { std::string error; auto model = mr::loadModel(path, error); if (!model) { @@ -73,34 +89,74 @@ bool App::loadModel(const std::string& path) { return false; } loadError_.clear(); - if (modelNode_) root_->removeChild(modelNode_); std::string glyphs = model->name + model->comment; for (const auto& b : model->bones) glyphs += b.name + b.nameEn; for (const auto& mo : model->morphs) glyphs += mo.name + mo.nameEn; for (const auto& ma : model->materials) glyphs += ma.name; imgui_->addGlyphs(glyphs); - modelNode_ = new ModelNode(model); - root_->addChild(modelNode_); - player_.reset(motion_ ? new MotionPlayer(motion_, *model) : nullptr); - selectedBone_ = -1; - boneFilter_[0] = '\0'; - morphFilter_[0] = '\0'; - lightingModel_ = model->format == SourceFormat::Assimp ? 1 : 0; - applyViewSettings(); - frameModel(); + auto item = std::make_unique(); + item->node = new ModelNode(model); + item->base = item->node->getMatrix(); + item->stage = stage || looksLikeStage(path, *model); + item->name = model->name.empty() ? path.substr(path.find_last_of("/\\") + 1) : model->name; + root_->addChild(item->node); + const bool firstCharacter = + !item->stage && std::none_of(items_.begin(), items_.end(), [](const auto& i) { return !i->stage; }); + const bool frame = items_.empty() || !item->stage; + items_.push_back(std::move(item)); + if (firstCharacter) lightingModel_ = model->format == SourceFormat::Assimp ? 1 : 0; + selectModel(static_cast(items_.size()) - 1); + if (frame) frameModel(); return true; } +void App::selectModel(int index) { + if (modelNode_) modelNode_->setSelectedBone(-1); + active_ = index >= 0 && index < static_cast(items_.size()) ? index : -1; + SceneItem* item = activeItem(); + modelNode_ = item ? item->node.get() : nullptr; + player_ = item ? item->player.get() : nullptr; + selectedBone_ = -1; + boneFilter_[0] = '\0'; + morphFilter_[0] = '\0'; + applyViewSettings(); +} + +void App::removeModel(int index) { + if (index < 0 || index >= static_cast(items_.size())) return; + root_->removeChild(items_[index]->node); + items_.erase(items_.begin() + index); + modelNode_ = nullptr; + player_ = nullptr; + selectModel(items_.empty() ? -1 : std::min(index, static_cast(items_.size()) - 1)); +} + +void App::setModelScale(int index, float scale) { + if (index < 0 || index >= static_cast(items_.size()) || scale <= 0.f) return; + items_[index]->scale = scale; + updatePlacement(*items_[index]); +} + +void App::updatePlacement(SceneItem& item) { + item.node->setMatrix(osg::Matrix::scale(item.scale, item.scale, item.scale) * + osg::Matrix::rotate(osg::DegreesToRadians(item.rotationY), osg::Y_AXIS) * + osg::Matrix::translate(item.position) * item.base); +} + void App::applyViewSettings() { - if (!modelNode_) return; - modelNode_->setShowSkeleton(showSkeleton_); - modelNode_->setBackfaceCulling(backfaceCulling_); - modelNode_->setWireframe(wireframe_); - modelNode_->setLightFollowsCamera(lightFollowsCamera_); - modelNode_->setLightingModel(static_cast(lightingModel_)); - modelNode_->setSelectedBone(selectedBone_); - modelNode_->poser().setPhysicsEnabled(physicsEnabled_); - modelNode_->setSkinningMode(skinning_ == 1 ? SkinningMode::Hardware : SkinningMode::Software); + for (auto& item : items_) { + ModelNode* node = item->node.get(); + const bool active = node == modelNode_; + node->setShowSkeleton(showSkeleton_ && active); + node->setBackfaceCulling(backfaceCulling_); + node->setWireframe(wireframe_); + node->setLightFollowsCamera(lightFollowsCamera_); + node->setLightingModel(static_cast(lightingModel_)); + node->setSelectedBone(active ? selectedBone_ : -1); + node->poser().setPhysicsEnabled(physicsEnabled_ && !item->stage); + node->setSkinningMode(skinning_ == 1 ? SkinningMode::Hardware : SkinningMode::Software); + node->setNodeMask(item->visible ? ~0u : 0u); + } } void App::setGpuSkinning(bool enabled) { @@ -121,11 +177,14 @@ bool App::loadMotion(const std::string& path) { cameraName_ = name; } if (!motion->boneTracks.empty() || !motion->morphTracks.empty() || motion->cameraKeys.empty()) { - motion_ = motion; - motionName_ = name; - if (modelNode_) { - modelNode_->poser().resetMotion(); - player_.reset(new MotionPlayer(motion_, modelNode_->model())); + if (SceneItem* item = activeItem()) { + item->motion = motion; + item->motionName = name; + item->node->poser().resetMotion(); + item->player.reset(new MotionPlayer(motion, item->node->model())); + player_ = item->player.get(); + } else { + loadError_ = "Load a model before its motion: " + name; } } setPlaying(false); @@ -149,18 +208,23 @@ bool App::loadAudio(const std::string& path) { void App::unloadMotion() { setPlaying(false); - player_.reset(); - motion_.reset(); + for (auto& item : items_) { + item->player.reset(); + item->motion.reset(); + item->motionName.clear(); + item->node->poser().resetMotion(); + } + player_ = nullptr; camera_.reset(); restoreCamera(); audio_.unload(); motionFrame_ = 0.f; - if (modelNode_) modelNode_->poser().resetMotion(); } float App::timelineEnd() const { float end = 0.f; - if (motion_) end = std::max(end, static_cast(motion_->lastFrame)); + for (const auto& item : items_) + if (item->motion) end = std::max(end, static_cast(item->motion->lastFrame)); if (camera_) end = std::max(end, static_cast(camera_->lastFrame)); if (audio_.loaded()) end = std::max(end, static_cast(audio_.length()) * kMotionFps); return end; @@ -178,11 +242,12 @@ void App::setPlaying(bool playing) { void App::setPhysicsEnabled(bool enabled) { physicsEnabled_ = enabled; - if (modelNode_) modelNode_->poser().setPhysicsEnabled(enabled); + applyViewSettings(); } void App::setMotionFrame(float frame) { - if (modelNode_ && std::fabs(frame - motionFrame_) > 2.f) modelNode_->poser().resetPhysics(); + if (std::fabs(frame - motionFrame_) > 2.f) + for (auto& item : items_) item->node->poser().resetPhysics(); motionFrame_ = std::max(0.f, frame); if (playing_) setPlaying(true); else audio_.seek(motionFrame_ / kMotionFps); @@ -190,7 +255,8 @@ void App::setMotionFrame(float frame) { } void App::applyFrame() { - if (player_ && modelNode_) player_->apply(motionFrame_, modelNode_->poser()); + for (auto& item : items_) + if (item->player) item->player->apply(motionFrame_, item->node->poser()); if (camera_ && useMotionCamera_) applyCamera(); } @@ -311,11 +377,14 @@ void App::tick(double time) { 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)); + for (auto& item : items_) { + item->node->poser().stepPhysics(render_.active ? 1.f / 30.f : float(realDt)); + item->node->poser().setIkEnabled(ikEnabled_); + } updatePopOut(); updateProjection(); - if (modelNode_) modelNode_->poser().setIkEnabled(ikEnabled_); - if (!player_ && !camera_ && !audio_.loaded()) return; + const bool anyMotion = std::any_of(items_.begin(), items_.end(), [](const auto& i) { return i->player != nullptr; }); + if (!anyMotion && !camera_ && !audio_.loaded()) return; if (playing_) { // The sound card's clock drives playback while the song plays, so motion stays in sync. if (audio_.playing()) motionFrame_ = static_cast(audio_.position()) * kMotionFps; @@ -346,8 +415,9 @@ void App::openFile(const std::string& path) { } else if (endsWith(".wav") || endsWith(".mp3") || endsWith(".flac")) { loadAudio(path); } else { - loadModel(path); + loadModel(path, openAsStage_); } + openAsStage_ = false; } void App::setShowSkeleton(bool show) { @@ -383,15 +453,14 @@ void App::drawUi() { ImGui::End(); } if (fileBrowser_.draw()) openFile(fileBrowser_.selectedPath()); + drawModelWindow(); if (modelNode_) { - drawModelWindow(); drawBonesWindow(); drawMorphsWindow(); } else { - for (const char* name : {"Scene", "Bones", "Morphs"}) { + for (const char* name : {"Bones", "Morphs"}) { ImGui::Begin(name); - ImGui::TextDisabled("No model loaded."); - if (name[0] == 'S' && ImGui::Button("Open model...")) fileBrowser_.open(); + ImGui::TextDisabled("No model selected."); ImGui::End(); } } @@ -422,13 +491,19 @@ void App::buildLayout(unsigned dockspace) { void App::drawMenuBar() { if (!ImGui::BeginMainMenuBar()) return; if (ImGui::BeginMenu("File")) { - if (ImGui::MenuItem("Open model or motion...")) fileBrowser_.open(); + if (ImGui::MenuItem("Add model, motion or audio...")) fileBrowser_.open(); + if (ImGui::MenuItem("Add stage...")) { + openAsStage_ = true; + fileBrowser_.open(); + } + if (ImGui::MenuItem("Remove selected model", nullptr, false, active_ >= 0)) removeModel(active_); if (ImGui::MenuItem("Render...", nullptr, false, modelNode_ != nullptr)) openRenderDialog(); if (ImGui::MenuItem("Quit")) viewer_.setDone(true); ImGui::EndMenu(); } if (ImGui::BeginMenu("View")) { bool changed = false; + if (ImGui::MenuItem("Floor grid", nullptr, &showGrid_)) setShowGrid(showGrid_); changed |= ImGui::MenuItem("Skeleton", nullptr, &showSkeleton_); changed |= ImGui::MenuItem("Wireframe", nullptr, &wireframe_); changed |= ImGui::MenuItem("Backface culling", nullptr, &backfaceCulling_); @@ -469,15 +544,64 @@ void App::drawMenuBar() { ImGui::EndMainMenuBar(); } +void App::drawSceneList() { + int remove = -1; + const float scale = imgui_->uiScale(); + for (size_t i = 0; i < items_.size(); ++i) { + SceneItem& item = *items_[i]; + ImGui::PushID(static_cast(i)); + if (ImGui::Checkbox("##visible", &item.visible)) applyViewSettings(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Show / hide"); + ImGui::SameLine(); + const std::string label = (item.stage ? "[Stage] " : "") + item.name + + (item.motion ? " (" + item.motionName + ")" : std::string()); + if (ImGui::Selectable(label.c_str(), static_cast(i) == active_, 0, + ImVec2(ImGui::GetContentRegionAvail().x - 28.f * scale, 0))) + selectModel(static_cast(i)); + ImGui::SameLine(); + if (ImGui::SmallButton("x")) remove = static_cast(i); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Remove from scene"); + ImGui::PopID(); + } + if (items_.empty()) ImGui::TextDisabled("No models in the scene."); + if (ImGui::Button("Add model...")) fileBrowser_.open(); + ImGui::SameLine(); + if (ImGui::Button("Add stage...")) { + openAsStage_ = true; + fileBrowser_.open(); + } + if (remove >= 0) removeModel(remove); +} + void App::drawModelWindow() { - const Model& m = modelNode_->model(); ImGui::Begin("Scene"); - ImGui::TextWrapped("%s", m.name.c_str()); + drawSceneList(); + if (!modelNode_) { + ImGui::End(); + return; + } + SceneItem& item = *activeItem(); + const Model& m = modelNode_->model(); + ImGui::SeparatorText(item.name.c_str()); + if (ImGui::Checkbox("Stage", &item.stage)) applyViewSettings(); + if (ImGui::IsItemHovered()) ImGui::SetTooltip("Environment model: physics off, camera not reframed on load"); + bool moved = ImGui::DragFloat3("Position", item.position.ptr(), 0.05f, 0.f, 0.f, "%.2f"); + moved |= ImGui::DragFloat("Rotation", &item.rotationY, 0.5f, -180.f, 180.f, "%.1f deg"); + moved |= ImGui::DragFloat("Scale", &item.scale, 0.005f, 0.01f, 100.f, "%.3fx", + ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_AlwaysClamp); + if (moved) updatePlacement(item); + ImGui::SameLine(); + if (ImGui::SmallButton("Reset##placement")) { + item.position = osg::Vec3f(); + item.rotationY = 0.f; + item.scale = 1.f; + updatePlacement(item); + } ImGui::TextDisabled("%s", m.format == SourceFormat::PMX ? "PMX" : m.format == SourceFormat::PMD ? "PMD" : "Assimp"); 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()) { + if (!m.rigidBodies.empty() && !item.stage) { ImGui::Text("Rigid bodies %zu Joints %zu", m.rigidBodies.size(), m.joints.size()); bool physics = physicsEnabled_; if (ImGui::Checkbox("Physics", &physics)) setPhysicsEnabled(physics); diff --git a/src/app/AppUi.h b/src/app/AppUi.h index 2cd1190..ea7cc75 100644 --- a/src/app/AppUi.h +++ b/src/app/AppUi.h @@ -13,6 +13,7 @@ #include #include +#include namespace mr { @@ -20,9 +21,16 @@ class App { public: App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulator* manipulator); - bool loadModel(const std::string& path); + // Adds a model to the scene and makes it the active one. Stages are environments: + // no physics, and the camera is not reframed when they are added. + bool loadModel(const std::string& path, bool stage = false); + void selectModel(int index); + void setModelScale(int index, float scale); + void removeModel(int index); + size_t modelCount() const { return items_.size(); } + void setShowGrid(bool show); const std::string& loadError() const { return loadError_; } - ModelNode* modelNode() { return modelNode_.get(); } + ModelNode* modelNode() { return modelNode_; } void frameModel(float azimuthDeg = 0.f, float elevationDeg = 0.f); void setShowSkeleton(bool show); void setGpuSkinning(bool enabled); @@ -71,7 +79,29 @@ private: osg::ref_ptr root_; osg::ref_ptr manipulator_; osg::ref_ptr imgui_; - osg::ref_ptr modelNode_; + struct SceneItem { + osg::ref_ptr node; + std::string name; + bool stage = false, visible = true; + osg::Vec3f position; // model space, Y up + float rotationY = 0.f; // degrees + float scale = 1.f; + osg::Matrix base; // ModelNode's model-to-world matrix + std::shared_ptr motion; + std::unique_ptr player; + std::string motionName; + }; + SceneItem* activeItem() { return active_ >= 0 ? items_[active_].get() : nullptr; } + void updatePlacement(SceneItem& item); + void drawSceneList(); + + std::vector> items_; + int active_ = -1; + ModelNode* modelNode_ = nullptr; // active model + MotionPlayer* player_ = nullptr; // active model's motion + osg::ref_ptr grid_; + bool showGrid_ = true; + bool openAsStage_ = false; FileBrowser fileBrowser_; std::string loadError_; @@ -82,9 +112,6 @@ private: int lightingModel_ = 0; int skinning_ = 1; // 1 hardware (GPU), 0 software (CPU) bool ikEnabled_ = true; - std::shared_ptr motion_; - std::unique_ptr player_; - std::string motionName_; float motionFrame_ = 0.f; bool playing_ = false; bool loopMotion_ = true; diff --git a/src/app/Render.cpp b/src/app/Render.cpp index c75f03d..68f3188 100644 --- a/src/app/Render.cpp +++ b/src/app/Render.cpp @@ -1,4 +1,5 @@ #include "app/AppUi.h" +#include "render/Grid.h" #include #include #include @@ -79,7 +80,7 @@ void App::startRender() { cam->attach(osg::Camera::COLOR_BUFFER, render_.image.get(), 4, 0); cam->setReferenceFrame(osg::Transform::ABSOLUTE_RF); cam->setInheritanceMask(cam->getInheritanceMask() & ~osg::CullSettings::CULL_MASK); - cam->setCullMask(~0u); + cam->setCullMask(~kGridNodeMask); osg::Vec4 clear = master->getClearColor(); if (render_.transparent) clear.a() = 0.f; cam->setClearColor(clear); diff --git a/src/app/main.cpp b/src/app/main.cpp index 34a3872..14922f6 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -45,6 +45,11 @@ void printUsage() { " --camera FILE.vmd load an MMD camera motion\n" " --audio FILE load a song (.wav .mp3 .flac)\n" " --play start playback\n" + " --add FILE add another model to the scene (repeatable)\n" + " --stage FILE add a stage/environment model (repeatable)\n" + " --scale S scale the first model\n" + " --stage-scale S scale every --stage model\n" + " --no-grid hide the floor grid\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" @@ -116,7 +121,9 @@ int main(int argc, char** argv) { float motionFrame = 0.f; bool play = false; bool popOut = false; - bool physics = true; + bool physics = true, grid = true; + std::vector stagePaths, extraModels; + float modelScale = 1.f, stageScale = 1.f; std::string renderDir; int renderStart = 0, renderEnd = -1, renderW = 1920, renderH = 1080; std::vector> morphArgs, boneArgs; @@ -173,6 +180,16 @@ int main(int argc, char** argv) { motionFrame = std::strtof(next().c_str(), nullptr); } else if (a == "--play") { play = true; + } else if (a == "--stage") { + stagePaths.push_back(next()); + } else if (a == "--add") { + extraModels.push_back(next()); + } else if (a == "--scale") { + modelScale = std::strtof(next().c_str(), nullptr); + } else if (a == "--stage-scale") { + stageScale = std::strtof(next().c_str(), nullptr); + } else if (a == "--no-grid") { + grid = false; } else if (a == "--physics") { physics = next() != "off"; } else if (a == "--pop-out") { @@ -212,6 +229,15 @@ int main(int argc, char** argv) { app.setGpuSkinning(gpuSkinning); const auto loadStart = std::chrono::steady_clock::now(); if (!modelPath.empty() && !app.loadModel(modelPath)) std::cerr << app.loadError() << "\n"; + for (const auto& path : extraModels) + if (!app.loadModel(path)) std::cerr << app.loadError() << "\n"; + for (const auto& path : stagePaths) { + if (app.loadModel(path, true)) app.setModelScale(static_cast(app.modelCount()) - 1, stageScale); + else std::cerr << app.loadError() << "\n"; + } + app.setModelScale(0, modelScale); + if (app.modelCount() > 0) app.selectModel(0); // motions and --bone/--morph apply to the first model + app.setShowGrid(grid); const double loadMs = std::chrono::duration(std::chrono::steady_clock::now() - loadStart).count(); @@ -248,13 +274,13 @@ int main(int argc, char** argv) { if (!motionPath.empty() || !cameraPath.empty() || !audioPath.empty()) { 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); app.frameModel(azimuth, elevation); } + app.setViewportPoppedOut(popOut); + app.setPhysicsEnabled(physics); + if (!renderDir.empty()) app.renderToFolder(renderDir, renderStart, renderEnd, renderW, renderH); app.imgui()->setUiVisible(!hideUi); if (uiScale != 1.f) app.imgui()->setUiScale(uiScale); diff --git a/src/model/AssimpLoader.cpp b/src/model/AssimpLoader.cpp index e7154eb..3bec550 100644 --- a/src/model/AssimpLoader.cpp +++ b/src/model/AssimpLoader.cpp @@ -222,7 +222,9 @@ private: aiString name; if (src->Get(AI_MATKEY_NAME, name) == AI_SUCCESS) m.name = name.C_Str(); aiColor4D c; - if (src->Get(AI_MATKEY_COLOR_DIFFUSE, c) == AI_SUCCESS) m.diffuse.set(c.r, c.g, c.b, 1.f); + // DirectX .x keeps material alpha in the diffuse colour rather than in an opacity key. + if (src->Get(AI_MATKEY_COLOR_DIFFUSE, c) == AI_SUCCESS) + m.diffuse.set(c.r, c.g, c.b, c.a > 0.01f ? std::min(c.a, 1.f) : 1.f); if (src->Get(AI_MATKEY_COLOR_SPECULAR, c) == AI_SUCCESS) m.specular.set(c.r, c.g, c.b); if (src->Get(AI_MATKEY_COLOR_AMBIENT, c) == AI_SUCCESS) m.ambient.set(c.r, c.g, c.b); float f = 0.f; diff --git a/src/render/Grid.cpp b/src/render/Grid.cpp new file mode 100644 index 0000000..641c42f --- /dev/null +++ b/src/render/Grid.cpp @@ -0,0 +1,80 @@ +#include "render/Grid.h" + +#include +#include +#include +#include +#include + +namespace mr { + +namespace { + +osg::Geometry* lineGeometry(osg::Vec3Array* verts, osg::Vec4Array* colors, float width) { + auto* geom = new osg::Geometry; + geom->setVertexArray(verts); + geom->setColorArray(colors, osg::Array::BIND_PER_VERTEX); + geom->addPrimitiveSet(new osg::DrawArrays(GL_LINES, 0, static_cast(verts->size()))); + geom->getOrCreateStateSet()->setAttributeAndModes(new osg::LineWidth(width)); + return geom; +} + +void addLine(osg::Vec3Array* v, osg::Vec4Array* c, const osg::Vec3& a, const osg::Vec3& b, const osg::Vec4& color) { + v->push_back(a); + v->push_back(b); + c->push_back(color); + c->push_back(color); +} + +osgText::Text* label(const char* text, const osg::Vec3& pos, const osg::Vec4& color) { + auto* t = new osgText::Text; + t->setText(text); + t->setPosition(pos); + t->setColor(color); + t->setCharacterSizeMode(osgText::Text::SCREEN_COORDS); + t->setCharacterSize(18.f); + t->setAxisAlignment(osgText::Text::SCREEN); + t->setAlignment(osgText::Text::CENTER_CENTER); + return t; +} + +} // namespace + +osg::Node* createGrid(float halfExtent, float spacing) { + // World is Z-up: MMD X = world X, MMD Y = world Z, MMD +Z (away from the model's front) = world +Y. + const float h = halfExtent, z = 0.01f; // lifted slightly to avoid fighting with stage floors + const int n = static_cast(halfExtent / spacing); + const osg::Vec4 minor(0.42f, 0.45f, 0.50f, 0.45f), major(0.55f, 0.58f, 0.64f, 0.7f); + auto* gv = new osg::Vec3Array; + auto* gc = new osg::Vec4Array; + for (int i = -n; i <= n; ++i) { + if (i == 0) continue; + const float c = static_cast(i) * spacing; + const osg::Vec4& color = i % 2 == 0 ? major : minor; + addLine(gv, gc, {-h, c, z}, {h, c, z}, color); + addLine(gv, gc, {c, -h, z}, {c, h, z}, color); + } + const osg::Vec4 red(0.95f, 0.30f, 0.30f, 1.f), green(0.40f, 0.90f, 0.35f, 1.f), blue(0.35f, 0.55f, 1.f, 1.f); + const float up = spacing * 3.f; + auto* av = new osg::Vec3Array; + auto* ac = new osg::Vec4Array; + addLine(av, ac, {-h, 0, z}, {h, 0, z}, red); + addLine(av, ac, {0, -h, z}, {0, h, z}, blue); + addLine(av, ac, {0, 0, z}, {0, 0, up}, green); + + auto* geode = new osg::Geode; + geode->addDrawable(lineGeometry(gv, gc, 1.f)); + geode->addDrawable(lineGeometry(av, ac, 2.f)); + geode->addDrawable(label("X", {h + spacing * 0.4f, 0, z}, red)); + geode->addDrawable(label("Y", {0, 0, up + spacing * 0.3f}, green)); + geode->addDrawable(label("Z", {0, h + spacing * 0.4f, z}, blue)); + osg::StateSet* ss = geode->getOrCreateStateSet(); + ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF); + ss->setMode(GL_BLEND, osg::StateAttribute::ON); + ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); + ss->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); + geode->setNodeMask(kGridNodeMask); + return geode; +} + +} // namespace mr diff --git a/src/render/Grid.h b/src/render/Grid.h new file mode 100644 index 0000000..87c4cda --- /dev/null +++ b/src/render/Grid.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +namespace mr { + +// Node mask of the floor grid; final renders cull it. +constexpr unsigned kGridNodeMask = 0x2; + +// Floor grid on the MMD ground plane (world z = 0) with labelled X (red), Y (green, up) and Z (blue) axes. +osg::Node* createGrid(float halfExtent, float spacing); + +} // namespace mr