From 2ab57412caf247dde108f1ddb0c6819e716ba32f Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sun, 29 Nov 2026 07:31:34 +0000 Subject: [PATCH 1/4] Scene save/load (.mrscene) with relative paths, poses, motions, audio, view and settings Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CMakeLists.txt | 11 ++- README.md | 9 +- src/app/AppUi.cpp | 35 ++++++- src/app/AppUi.h | 10 +- src/app/FileBrowser.cpp | 39 ++++++-- src/app/FileBrowser.h | 8 +- src/app/SceneIo.cpp | 155 +++++++++++++++++++++++++++++ src/app/main.cpp | 32 ++++-- src/scene/SceneFile.cpp | 211 ++++++++++++++++++++++++++++++++++++++++ src/scene/SceneFile.h | 54 ++++++++++ tests/test_main.cpp | 63 ++++++++++++ 11 files changed, 605 insertions(+), 22 deletions(-) create mode 100644 src/app/SceneIo.cpp create mode 100644 src/scene/SceneFile.cpp create mode 100644 src/scene/SceneFile.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 3e64aa6..b99a05b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -90,6 +90,11 @@ if(NOT bullet_POPULATED) add_subdirectory(${bullet_SOURCE_DIR} ${bullet_BINARY_DIR} EXCLUDE_FROM_ALL) endif() +FetchContent_Declare(nlohmann_json + URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz + URL_HASH SHA256=d6c65aca6b1ed68e7a182f4757257b107ae403032760ed6ef121c9d55e81757d) +FetchContent_MakeAvailable(nlohmann_json) + add_library(mr_core STATIC src/model/Model.cpp src/model/TextEncoding.cpp @@ -100,12 +105,13 @@ add_library(mr_core STATIC src/model/ModelLoader.cpp src/model/Poser.cpp src/model/Motion.cpp - src/physics/PhysicsWorld.cpp) + src/physics/PhysicsWorld.cpp + src/scene/SceneFile.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) +target_link_libraries(mr_core PRIVATE BulletDynamics BulletCollision LinearMath nlohmann_json::nlohmann_json) if(NOT WIN32) target_link_libraries(mr_core PRIVATE Iconv::Iconv) endif() @@ -132,6 +138,7 @@ add_executable(model_renderer src/app/FileBrowser.cpp src/app/Timeline.cpp src/app/Render.cpp + src/app/SceneIo.cpp src/render/Grid.cpp src/render/ModelNode.cpp src/render/TextureLoader.cpp diff --git a/README.md b/README.md index ebfbfa7..14b5f28 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,12 @@ 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). +* **Scenes**: **File > Save scene** (Ctrl+S, Cmd+S on macOS) writes a `.mrscene` file with every + model and stage (Position, Rotation, Scale, Stage, visibility), each model's dance, bone pose + and morph edits, the camera motion, the song, the timeline frame, the 3D view's camera, the + View settings and the Render size. **File > Open...** (Ctrl+O) opens it again, and **New scene** + clears everything. Paths are stored relative to the scene file, so keep the scene next to (or + above) its `models/` folder and the whole folder can be moved or shared. The file is plain JSON. * **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. @@ -155,7 +161,8 @@ Command-line options (`--help`) allow scripted renders, e.g. (`--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; +`--no-grid` hides the floor grid; `model_renderer scene.mrscene` opens a scene and +`--save-scene FILE` saves one after loading; `--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 0adcaad..c57f797 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -97,6 +97,7 @@ bool App::loadModel(const std::string& path, bool stage) { auto item = std::make_unique(); item->node = new ModelNode(model); item->base = item->node->getMatrix(); + item->path = path; item->stage = stage || looksLikeStage(path, *model); item->name = model->name.empty() ? path.substr(path.find_last_of("/\\") + 1) : model->name; root_->addChild(item->node); @@ -175,11 +176,13 @@ bool App::loadMotion(const std::string& path) { if (!motion->cameraKeys.empty()) { camera_ = motion; cameraName_ = name; + cameraPath_ = path; } if (!motion->boneTracks.empty() || !motion->morphTracks.empty() || motion->cameraKeys.empty()) { if (SceneItem* item = activeItem()) { item->motion = motion; item->motionName = name; + item->motionPath = path; item->node->poser().resetMotion(); item->player.reset(new MotionPlayer(motion, item->node->model())); player_ = item->player.get(); @@ -212,12 +215,16 @@ void App::unloadMotion() { item->player.reset(); item->motion.reset(); item->motionName.clear(); + item->motionPath.clear(); item->node->poser().resetMotion(); } player_ = nullptr; camera_.reset(); + cameraPath_.clear(); restoreCamera(); audio_.unload(); + audioPath_.clear(); + audioName_.clear(); motionFrame_ = 0.f; } @@ -410,7 +417,9 @@ void App::openFile(const std::string& path) { const size_t n = std::strlen(ext); return lower.size() > n && lower.compare(lower.size() - n, n, ext) == 0; }; - if (endsWith(".vmd")) { + if (endsWith(".mrscene")) { + openScene(path); + } else if (endsWith(".vmd")) { loadMotion(path); } else if (endsWith(".wav") || endsWith(".mp3") || endsWith(".flac")) { loadAudio(path); @@ -452,7 +461,15 @@ void App::drawUi() { if (ImGui::Button("Dismiss")) loadError_.clear(); ImGui::End(); } - if (fileBrowser_.draw()) openFile(fileBrowser_.selectedPath()); + if (!ImGui::GetIO().WantTextInput) { + if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_S)) requestSaveScene(true); + else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_S)) requestSaveScene(false); + else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_O)) fileBrowser_.open(); + } + if (fileBrowser_.draw()) { + if (fileBrowser_.mode() == FileBrowser::Mode::Save) saveScene(fileBrowser_.selectedPath()); + else openFile(fileBrowser_.selectedPath()); + } drawModelWindow(); if (modelNode_) { drawBonesWindow(); @@ -491,6 +508,11 @@ void App::buildLayout(unsigned dockspace) { void App::drawMenuBar() { if (!ImGui::BeginMainMenuBar()) return; if (ImGui::BeginMenu("File")) { + if (ImGui::MenuItem("New scene")) newScene(); + if (ImGui::MenuItem("Open...", "Ctrl+O")) fileBrowser_.open(); + if (ImGui::MenuItem("Save scene", "Ctrl+S")) requestSaveScene(false); + if (ImGui::MenuItem("Save scene as...", "Ctrl+Shift+S")) requestSaveScene(true); + ImGui::Separator(); if (ImGui::MenuItem("Add model, motion or audio...")) fileBrowser_.open(); if (ImGui::MenuItem("Add stage...")) { openAsStage_ = true; @@ -498,6 +520,7 @@ void App::drawMenuBar() { } if (ImGui::MenuItem("Remove selected model", nullptr, false, active_ >= 0)) removeModel(active_); if (ImGui::MenuItem("Render...", nullptr, false, modelNode_ != nullptr)) openRenderDialog(); + ImGui::Separator(); if (ImGui::MenuItem("Quit")) viewer_.setDone(true); ImGui::EndMenu(); } @@ -539,6 +562,14 @@ void App::drawMenuBar() { ImGui::Text("Space: reset camera"); ImGui::EndMenu(); } + { + const bool recent = ImGui::GetTime() - sceneStatusTime_ < 4.0; + const std::string title = recent ? sceneStatus_ + : scenePath_.empty() ? std::string("Untitled scene") + : scenePath_.substr(scenePath_.find_last_of("/\\") + 1); + ImGui::SameLine(0.f, 24.f * imgui_->uiScale()); + ImGui::TextDisabled("%s", title.c_str()); + } ImGui::SameLine(ImGui::GetWindowWidth() - 90 * imgui_->uiScale()); ImGui::TextDisabled("%.0f FPS", ImGui::GetIO().Framerate); ImGui::EndMainMenuBar(); diff --git a/src/app/AppUi.h b/src/app/AppUi.h index ea7cc75..3b67ff4 100644 --- a/src/app/AppUi.h +++ b/src/app/AppUi.h @@ -26,6 +26,11 @@ public: bool loadModel(const std::string& path, bool stage = false); void selectModel(int index); void setModelScale(int index, float scale); + // Scene files (.mrscene): models, placement, poses, motions, audio, view and settings. + void newScene(); + bool openScene(const std::string& path); + bool saveScene(const std::string& path); + const std::string& scenePath() const { return scenePath_; } void removeModel(int index); size_t modelCount() const { return items_.size(); } void setShowGrid(bool show); @@ -81,7 +86,7 @@ private: osg::ref_ptr imgui_; struct SceneItem { osg::ref_ptr node; - std::string name; + std::string name, path, motionPath; bool stage = false, visible = true; osg::Vec3f position; // model space, Y up float rotationY = 0.f; // degrees @@ -94,6 +99,9 @@ private: SceneItem* activeItem() { return active_ >= 0 ? items_[active_].get() : nullptr; } void updatePlacement(SceneItem& item); void drawSceneList(); + void requestSaveScene(bool saveAs); + std::string scenePath_, cameraPath_, sceneStatus_; + double sceneStatusTime_ = -10.0; std::vector> items_; int active_ = -1; diff --git a/src/app/FileBrowser.cpp b/src/app/FileBrowser.cpp index 4ea6009..dfb72b3 100644 --- a/src/app/FileBrowser.cpp +++ b/src/app/FileBrowser.cpp @@ -15,7 +15,7 @@ namespace mr { namespace { bool isModelFile(const std::string& name) { std::string lower = toLowerAscii(name); - for (const char* ext : {".pmx", ".pmd", ".fbx", ".vmd", ".wav", ".mp3", ".flac", ".obj", ".gltf", ".glb", ".dae"}) + for (const char* ext : {".mrscene", ".pmx", ".pmd", ".fbx", ".x", ".vmd", ".wav", ".mp3", ".flac", ".obj", ".gltf", ".glb", ".dae"}) if (lower.size() >= std::strlen(ext) && lower.compare(lower.size() - std::strlen(ext), std::string::npos, ext) == 0) return true; return false; @@ -27,7 +27,16 @@ FileBrowser::FileBrowser() { currentDir_ = pathToUtf8(fs::current_path(ec)); } -void FileBrowser::open() { +void FileBrowser::open(Mode mode, const std::string& defaultPath, const std::string& saveExtension) { + mode_ = mode; + saveExtension_ = saveExtension; + nameBuffer_[0] = '\0'; + if (mode == Mode::Save && !defaultPath.empty()) { + const fs::path p = pathFromUtf8(defaultPath); + std::error_code ec; + if (p.has_parent_path() && fs::is_directory(p.parent_path(), ec)) currentDir_ = pathToUtf8(p.parent_path()); + std::snprintf(nameBuffer_, sizeof(nameBuffer_), "%s", pathToUtf8(p.filename()).c_str()); + } openRequested_ = true; refresh(); } @@ -52,12 +61,13 @@ void FileBrowser::refresh() { bool FileBrowser::draw() { if (openRequested_) { - ImGui::OpenPopup("Open model"); + ImGui::OpenPopup("###filebrowser"); openRequested_ = false; } bool chosen = false; ImGui::SetNextWindowSize(ImVec2(640, 460), ImGuiCond_FirstUseEver); - if (ImGui::BeginPopupModal("Open model", nullptr)) { + const bool saving = mode_ == Mode::Save; + if (ImGui::BeginPopupModal(saving ? "Save scene###filebrowser" : "Open###filebrowser", nullptr)) { if (ImGui::Button("Up")) { currentDir_ = pathToUtf8(pathFromUtf8(currentDir_).parent_path()); refresh(); @@ -70,12 +80,25 @@ bool FileBrowser::draw() { if (fs::is_directory(p, ec)) { currentDir_ = pathBuffer_; refresh(); - } else if (fs::is_regular_file(p, ec)) { + } else if (!saving && fs::is_regular_file(p, ec)) { selected_ = pathBuffer_; chosen = true; } } - ImGui::TextDisabled("Models: .pmx .pmd .fbx (also .obj .gltf .glb .dae) Motions: .vmd Audio: .wav .mp3 .flac"); + if (saving) { + ImGui::SetNextItemWidth(-80.f); + const bool enter = ImGui::InputText("##name", nameBuffer_, sizeof(nameBuffer_), ImGuiInputTextFlags_EnterReturnsTrue); + ImGui::SameLine(); + if ((ImGui::Button("Save") || enter) && nameBuffer_[0]) { + std::string name = nameBuffer_; + if (!saveExtension_.empty() && toLowerAscii(fs::path(name).extension().string()) != saveExtension_) + name += saveExtension_; + selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name)); + chosen = true; + } + } else { + ImGui::TextDisabled("Scenes: .mrscene Models: .pmx .pmd .fbx .x (also .obj .gltf .glb .dae) Motions: .vmd Audio: .wav .mp3 .flac"); + } if (!error_.empty()) ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "%s", error_.c_str()); ImGui::BeginChild("entries", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), ImGuiChildFlags_Borders); std::string enterDir; @@ -84,7 +107,9 @@ bool FileBrowser::draw() { if (ImGui::Selectable(label.c_str(), false, ImGuiSelectableFlags_AllowDoubleClick) && (dir || ImGui::IsMouseDoubleClicked(0))) { if (dir) enterDir = name; - else { + else if (saving) { + std::snprintf(nameBuffer_, sizeof(nameBuffer_), "%s", name.c_str()); + } else { selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name)); chosen = true; } diff --git a/src/app/FileBrowser.h b/src/app/FileBrowser.h index 28d2b9e..7f77a44 100644 --- a/src/app/FileBrowser.h +++ b/src/app/FileBrowser.h @@ -8,8 +8,11 @@ namespace mr { // Minimal ImGui file picker (ImGui has no native file dialog). class FileBrowser { public: + enum class Mode { Open, Save }; FileBrowser(); - void open(); + // Save mode asks for a file name (defaultPath may include a folder) and returns it with saveExtension. + void open(Mode mode = Mode::Open, const std::string& defaultPath = {}, const std::string& saveExtension = {}); + Mode mode() const { return mode_; } // Draws the popup; returns true when a file was chosen (see selectedPath()). bool draw(); const std::string& selectedPath() const { return selected_; } @@ -23,6 +26,9 @@ private: std::string selected_; std::string error_; bool openRequested_ = false; + Mode mode_ = Mode::Open; + char nameBuffer_[256] = {}; + std::string saveExtension_; }; } // namespace mr diff --git a/src/app/SceneIo.cpp b/src/app/SceneIo.cpp new file mode 100644 index 0000000..e015830 --- /dev/null +++ b/src/app/SceneIo.cpp @@ -0,0 +1,155 @@ +// Scene save/load: converts between the editor's state and mr::Scene (scene/SceneFile.h). +#include "app/AppUi.h" + +#include "scene/SceneFile.h" + +#include + +#include + +namespace mr { + +void App::newScene() { + unloadMotion(); + while (!items_.empty()) removeModel(static_cast(items_.size()) - 1); + scenePath_.clear(); + loadError_.clear(); +} + +void App::requestSaveScene(bool saveAs) { + if (!saveAs && !scenePath_.empty()) saveScene(scenePath_); + else fileBrowser_.open(FileBrowser::Mode::Save, scenePath_.empty() ? "scene.mrscene" : scenePath_, ".mrscene"); +} + +bool App::saveScene(const std::string& path) { + Scene scene; + for (const auto& item : items_) { + SceneModel m; + m.path = item->path; + m.stage = item->stage; + m.visible = item->visible; + m.position = item->position; + m.rotationY = item->rotationY; + m.scale = item->scale; + if (item->motion) m.motionPath = item->motionPath; + const Model& model = item->node->model(); + Poser& poser = item->node->poser(); + const auto& poses = poser.bonePoses(); + for (size_t b = 0; b < model.bones.size() && b < poses.size(); ++b) + if (poses[b] != BonePose()) m.bonePoses.emplace_back(model.bones[b].name, poses[b]); + // Morphs keyed by the motion are overwritten every frame, so only manual weights are kept. + std::vector keyed(model.morphs.size(), 0); + if (item->player) + for (const auto& binding : item->player->morphBindings()) keyed[binding.first] = 1; + const auto& weights = poser.morphWeights(); + for (size_t i = 0; i < model.morphs.size() && i < weights.size(); ++i) + if (!keyed[i] && weights[i] != 0.f) m.morphWeights.emplace_back(model.morphs[i].name, weights[i]); + scene.models.push_back(std::move(m)); + } + scene.activeModel = active_; + scene.cameraMotionPath = camera_ ? cameraPath_ : std::string(); + scene.audioPath = audio_.loaded() ? audioPath_ : std::string(); + scene.frame = motionFrame_; + scene.loop = loopMotion_; + scene.followCamera = useMotionCamera_; + scene.volume = volume_; + scene.view.valid = true; + manipulator_->getTransformation(scene.view.eye, scene.view.center, scene.view.up); + scene.showGrid = showGrid_; + scene.physics = physicsEnabled_; + scene.ik = ikEnabled_; + scene.gpuSkinning = skinning_ == 1; + scene.skeleton = showSkeleton_; + scene.wireframe = wireframe_; + scene.backfaceCulling = backfaceCulling_; + scene.lightFollowsCamera = lightFollowsCamera_; + scene.lightingModel = lightingModel_; + scene.renderWidth = render_.width; + scene.renderHeight = render_.height; + scene.renderTransparent = render_.transparent; + scene.renderMp4 = render_.mp4; + scene.renderAudio = render_.withAudio; + + std::string error; + if (!mr::saveScene(scene, path, error)) { + loadError_ = "Failed to save scene: " + error; + return false; + } + scenePath_ = path; + sceneStatus_ = "Saved " + path.substr(path.find_last_of("/\\") + 1); + sceneStatusTime_ = ImGui::GetCurrentContext() ? ImGui::GetTime() : 0.0; + return true; +} + +bool App::openScene(const std::string& path) { + Scene scene; + std::string error; + if (!mr::loadScene(path, scene, error)) { + loadError_ = "Failed to open scene: " + error; + return false; + } + newScene(); + std::string problems; + auto note = [&](const std::string& message) { problems += (problems.empty() ? "" : "\n") + message; }; + for (const SceneModel& m : scene.models) { + if (!loadModel(m.path, m.stage)) { + note(loadError_); + continue; + } + SceneItem& item = *items_.back(); + item.stage = m.stage; + item.visible = m.visible; + item.position = m.position; + item.rotationY = m.rotationY; + item.scale = m.scale; + updatePlacement(item); + const Model& model = item.node->model(); + Poser& poser = item.node->poser(); + for (const auto& [name, pose] : m.bonePoses) { + const int bone = model.findBone(name); + if (bone >= 0) poser.bonePoses()[bone] = pose; + } + for (const auto& [name, weight] : m.morphWeights) { + const int morph = model.findMorph(name); + if (morph >= 0) poser.morphWeights()[morph] = weight; + } + if (!m.motionPath.empty() && !loadMotion(m.motionPath)) note(loadError_); + } + // A dance .vmd that also holds camera keys has already set the camera. + if (!scene.cameraMotionPath.empty() && scene.cameraMotionPath != cameraPath_ && !loadMotion(scene.cameraMotionPath)) + note(loadError_); + if (!scene.audioPath.empty() && !loadAudio(scene.audioPath)) note(loadError_); + + showGrid_ = scene.showGrid; + setShowGrid(showGrid_); + physicsEnabled_ = scene.physics; + ikEnabled_ = scene.ik; + skinning_ = scene.gpuSkinning ? 1 : 0; + showSkeleton_ = scene.skeleton; + wireframe_ = scene.wireframe; + backfaceCulling_ = scene.backfaceCulling; + lightFollowsCamera_ = scene.lightFollowsCamera; + lightingModel_ = scene.lightingModel; + loopMotion_ = scene.loop; + useMotionCamera_ = scene.followCamera; + volume_ = scene.volume; + audio_.setVolume(volume_); + render_.width = scene.renderWidth; + render_.height = scene.renderHeight; + render_.transparent = scene.renderTransparent; + render_.mp4 = scene.renderMp4; + render_.withAudio = scene.renderAudio; + + if (!items_.empty()) selectModel(std::clamp(scene.activeModel, 0, static_cast(items_.size()) - 1)); + applyViewSettings(); + for (auto& item : items_) item->node->poser().resetPhysics(); + setMotionFrame(scene.frame); + if (scene.view.valid && !(camera_ && useMotionCamera_)) + manipulator_->setTransformation(scene.view.eye, scene.view.center, scene.view.up); + + scenePath_ = path; + if (!problems.empty()) loadError_ = "Some parts of the scene could not be loaded:\n" + problems; + return true; +} + +} // namespace mr diff --git a/src/app/main.cpp b/src/app/main.cpp index 14922f6..89e499f 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -1,4 +1,5 @@ #include "app/AppUi.h" +#include "model/PathUtil.h" #include "render/GpuCaps.h" #include "render/ModelNode.h" @@ -28,7 +29,7 @@ public: }; void printUsage() { - std::cout << "Usage: model_renderer [model.pmx|.pmd|.fbx] [options]\n" + std::cout << "Usage: model_renderer [model.pmx|.pmd|.fbx|scene.mrscene] [options]\n" " --size WxH window size (default 1280x800)\n" " --morph NAME=WEIGHT set a morph weight (repeatable)\n" " --bone NAME=RX,RY,RZ[,TX,TY,TZ] pose a bone, degrees (repeatable)\n" @@ -50,6 +51,7 @@ void printUsage() { " --scale S scale the first model\n" " --stage-scale S scale every --stage model\n" " --no-grid hide the floor grid\n" + " --save-scene FILE save the scene (.mrscene) after loading\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" @@ -124,6 +126,8 @@ int main(int argc, char** argv) { bool physics = true, grid = true; std::vector stagePaths, extraModels; float modelScale = 1.f, stageScale = 1.f; + std::string saveScenePath; + bool orbitSet = false, physicsSet = false; std::string renderDir; int renderStart = 0, renderEnd = -1, renderW = 1920, renderH = 1080; std::vector> morphArgs, boneArgs; @@ -158,6 +162,7 @@ int main(int argc, char** argv) { auto v = parseFloats(next()); if (v.size() >= 1) azimuth = v[0]; if (v.size() >= 2) elevation = v[1]; + orbitSet = true; } else if (a == "--skeleton") { skeleton = true; } else if (a == "--hide-ui") { @@ -192,6 +197,9 @@ int main(int argc, char** argv) { grid = false; } else if (a == "--physics") { physics = next() != "off"; + physicsSet = true; + } else if (a == "--save-scene") { + saveScenePath = next(); } else if (a == "--pop-out") { popOut = true; } else if (a == "--render") { @@ -228,16 +236,23 @@ int main(int argc, char** argv) { 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 bool isScene = modelPath.size() > 8 && mr::toLowerAscii(modelPath.substr(modelPath.size() - 8)) == ".mrscene"; + if (isScene) { + app.openScene(modelPath); + if (!app.loadError().empty()) std::cerr << app.loadError() << "\n"; + } else 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); + if (modelScale != 1.f) app.setModelScale(0, modelScale); + // Motions and --bone/--morph apply to the first model (or the scene's selected one). + if (app.modelCount() > 0 && !isScene) app.selectModel(0); + if (!grid) app.setShowGrid(false); const double loadMs = std::chrono::duration(std::chrono::steady_clock::now() - loadStart).count(); @@ -275,11 +290,12 @@ int main(int argc, char** argv) { app.setMotionFrame(motionFrame); app.setPlaying(play); } - app.setShowSkeleton(skeleton); - app.frameModel(azimuth, elevation); + if (skeleton || !isScene) app.setShowSkeleton(skeleton); + if (orbitSet || !isScene) app.frameModel(azimuth, elevation); } app.setViewportPoppedOut(popOut); - app.setPhysicsEnabled(physics); + if (physicsSet || !isScene) app.setPhysicsEnabled(physics); + if (!saveScenePath.empty() && !app.saveScene(saveScenePath)) std::cerr << app.loadError() << "\n"; 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/scene/SceneFile.cpp b/src/scene/SceneFile.cpp new file mode 100644 index 0000000..6257521 --- /dev/null +++ b/src/scene/SceneFile.cpp @@ -0,0 +1,211 @@ +#include "scene/SceneFile.h" + +#include "model/PathUtil.h" + +#include + +#include +#include +#include + +namespace fs = std::filesystem; +using json = nlohmann::ordered_json; + +namespace mr { + +namespace { + +json vec(const osg::Vec3f& v) { return json::array({v.x(), v.y(), v.z()}); } +json vec(const osg::Vec3d& v) { return json::array({v.x(), v.y(), v.z()}); } + +template +void readVec(const json& j, const char* key, V& out) { + auto it = j.find(key); + if (it == j.end() || !it->is_array() || it->size() != 3) return; + for (int i = 0; i < 3; ++i) out[i] = (*it)[i].get(); +} + +template +void read(const json& j, const char* key, T& out) { + auto it = j.find(key); + if (it != j.end() && !it->is_null()) out = it->get(); +} + +// Relative to the scene's folder when possible, always with forward slashes. +std::string relativePath(const std::string& path, const fs::path& baseDir) { + if (path.empty()) return {}; + std::error_code ec; + const fs::path p = pathFromUtf8(path); + fs::path rel = fs::relative(p, baseDir, ec); + if (ec || rel.empty() || p.root_name() != baseDir.root_name()) rel = p; + std::string out = pathToUtf8(rel); + std::replace(out.begin(), out.end(), '\\', '/'); + return out; +} + +std::string absolutePath(const std::string& stored, const fs::path& baseDir) { + if (stored.empty()) return {}; + fs::path p = pathFromUtf8(stored); + if (p.is_relative()) p = baseDir / p; + return pathToUtf8(p.lexically_normal().make_preferred()); +} + +} // namespace + +bool saveScene(const Scene& scene, const std::string& path, std::string& error) { + std::error_code ec; + const fs::path file = fs::absolute(pathFromUtf8(path), ec); + const fs::path dir = file.parent_path(); + json j; + j["format"] = "mr-scene"; + j["version"] = kSceneFormatVersion; + json models = json::array(); + for (const SceneModel& m : scene.models) { + json jm; + jm["path"] = relativePath(m.path, dir); + jm["stage"] = m.stage; + jm["visible"] = m.visible; + jm["position"] = vec(m.position); + jm["rotationY"] = m.rotationY; + jm["scale"] = m.scale; + if (!m.motionPath.empty()) jm["motion"] = relativePath(m.motionPath, dir); + json poses = json::object(); + for (const auto& [name, pose] : m.bonePoses) + poses[name] = {{"rotation", vec(pose.eulerDegrees)}, {"translation", vec(pose.translation)}}; + if (!poses.empty()) jm["bones"] = poses; + json morphs = json::object(); + for (const auto& [name, weight] : m.morphWeights) morphs[name] = weight; + if (!morphs.empty()) jm["morphs"] = morphs; + models.push_back(jm); + } + j["models"] = models; + j["activeModel"] = scene.activeModel; + j["timeline"] = {{"frame", scene.frame}, {"loop", scene.loop}}; + if (!scene.cameraMotionPath.empty()) j["timeline"]["camera"] = relativePath(scene.cameraMotionPath, dir); + j["timeline"]["followCamera"] = scene.followCamera; + if (!scene.audioPath.empty()) j["timeline"]["audio"] = relativePath(scene.audioPath, dir); + j["timeline"]["volume"] = scene.volume; + if (scene.view.valid) + j["view"] = {{"eye", vec(scene.view.eye)}, {"center", vec(scene.view.center)}, {"up", vec(scene.view.up)}}; + j["settings"] = {{"grid", scene.showGrid}, + {"physics", scene.physics}, + {"ik", scene.ik}, + {"gpuSkinning", scene.gpuSkinning}, + {"skeleton", scene.skeleton}, + {"wireframe", scene.wireframe}, + {"backfaceCulling", scene.backfaceCulling}, + {"lightFollowsCamera", scene.lightFollowsCamera}, + {"shading", scene.lightingModel == 1 ? "lambert" : "toon"}}; + j["render"] = {{"width", scene.renderWidth}, + {"height", scene.renderHeight}, + {"transparent", scene.renderTransparent}, + {"mp4", scene.renderMp4}, + {"audio", scene.renderAudio}}; + + const fs::path tmp = fs::path(file).concat(".tmp"); + { + std::ofstream out(tmp, std::ios::binary | std::ios::trunc); + if (!out) { + error = "Cannot write " + path; + return false; + } + out << j.dump(2) << "\n"; + if (!out) { + error = "Failed writing " + path; + return false; + } + } + fs::rename(tmp, file, ec); // replace atomically so a failed save never truncates the old scene + if (ec) { + fs::remove(tmp, ec); + error = "Cannot replace " + path + ": " + ec.message(); + return false; + } + return true; +} + +bool loadScene(const std::string& path, Scene& scene, std::string& error) { + std::vector bytes; + if (!readFileBytes(path, bytes)) { + error = "Cannot read " + path; + return false; + } + json j = json::parse(bytes.begin(), bytes.end(), nullptr, false); + if (j.is_discarded() || !j.is_object()) { + error = path + " is not a valid scene file"; + return false; + } + if (j.value("format", std::string()) != "mr-scene") { + error = path + " is not a model renderer scene"; + return false; + } + if (j.value("version", 0) > kSceneFormatVersion) { + error = path + " was saved by a newer version of the program"; + return false; + } + std::error_code ec; + const fs::path dir = fs::absolute(pathFromUtf8(path), ec).parent_path(); + try { + scene = Scene(); + for (const json& jm : j.value("models", json::array())) { + SceneModel m; + m.path = absolutePath(jm.value("path", std::string()), dir); + read(jm, "stage", m.stage); + read(jm, "visible", m.visible); + readVec(jm, "position", m.position); + read(jm, "rotationY", m.rotationY); + read(jm, "scale", m.scale); + if (!(m.scale > 0.f)) m.scale = 1.f; + m.motionPath = absolutePath(jm.value("motion", std::string()), dir); + if (auto it = jm.find("bones"); it != jm.end() && it->is_object()) + for (const auto& [name, jp] : it->items()) { + BonePose pose; + readVec(jp, "rotation", pose.eulerDegrees); + readVec(jp, "translation", pose.translation); + m.bonePoses.emplace_back(name, pose); + } + if (auto it = jm.find("morphs"); it != jm.end() && it->is_object()) + for (const auto& [name, w] : it->items()) m.morphWeights.emplace_back(name, w.get()); + if (!m.path.empty()) scene.models.push_back(std::move(m)); + } + read(j, "activeModel", scene.activeModel); + if (auto it = j.find("timeline"); it != j.end() && it->is_object()) { + read(*it, "frame", scene.frame); + read(*it, "loop", scene.loop); + scene.cameraMotionPath = absolutePath(it->value("camera", std::string()), dir); + read(*it, "followCamera", scene.followCamera); + scene.audioPath = absolutePath(it->value("audio", std::string()), dir); + read(*it, "volume", scene.volume); + } + if (auto it = j.find("view"); it != j.end() && it->is_object()) { + readVec(*it, "eye", scene.view.eye); + readVec(*it, "center", scene.view.center); + readVec(*it, "up", scene.view.up); + scene.view.valid = true; + } + if (auto it = j.find("settings"); it != j.end() && it->is_object()) { + read(*it, "grid", scene.showGrid); + read(*it, "physics", scene.physics); + read(*it, "ik", scene.ik); + read(*it, "gpuSkinning", scene.gpuSkinning); + read(*it, "skeleton", scene.skeleton); + read(*it, "wireframe", scene.wireframe); + read(*it, "backfaceCulling", scene.backfaceCulling); + read(*it, "lightFollowsCamera", scene.lightFollowsCamera); + scene.lightingModel = it->value("shading", std::string("toon")) == "lambert" ? 1 : 0; + } + if (auto it = j.find("render"); it != j.end() && it->is_object()) { + read(*it, "width", scene.renderWidth); + read(*it, "height", scene.renderHeight); + read(*it, "transparent", scene.renderTransparent); + read(*it, "mp4", scene.renderMp4); + read(*it, "audio", scene.renderAudio); + } + } catch (const json::exception& e) { + error = path + ": " + e.what(); + return false; + } + return true; +} + +} // namespace mr diff --git a/src/scene/SceneFile.h b/src/scene/SceneFile.h new file mode 100644 index 0000000..e49ecd4 --- /dev/null +++ b/src/scene/SceneFile.h @@ -0,0 +1,54 @@ +#pragma once +// Scene files (.mrscene): which models, stages, motions and audio make up a scene, how they are +// placed and posed, and the editor's view settings. JSON, with file paths stored relative to the +// scene file so a project folder can be moved or shared as a whole. +#include "model/Poser.h" + +#include +#include + +#include +#include +#include + +namespace mr { + +struct SceneModel { + std::string path; // absolute in memory + bool stage = false, visible = true; + osg::Vec3f position; + float rotationY = 0.f; // degrees + float scale = 1.f; + std::string motionPath; + std::vector> bonePoses; // by bone name; non-rest poses only + std::vector> morphWeights; // by morph name; non-zero only +}; + +struct SceneView { + bool valid = false; + osg::Vec3d eye, center, up{0.0, 0.0, 1.0}; +}; + +struct Scene { + std::vector models; + int activeModel = -1; + std::string cameraMotionPath, audioPath; + float frame = 0.f; + bool loop = true, followCamera = true; + float volume = 1.f; + SceneView view; + + bool showGrid = true, physics = true, ik = true, gpuSkinning = true; + bool skeleton = false, wireframe = false, backfaceCulling = true, lightFollowsCamera = false; + int lightingModel = 0; // 0 MMD toon, 1 Lambert + + int renderWidth = 1920, renderHeight = 1080; + bool renderTransparent = false, renderMp4 = true, renderAudio = true; +}; + +constexpr int kSceneFormatVersion = 1; + +bool saveScene(const Scene& scene, const std::string& path, std::string& error); +bool loadScene(const std::string& path, Scene& scene, std::string& error); + +} // namespace mr diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 72516ab..e541736 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -4,9 +4,11 @@ #include "model/Motion.h" #include "model/PathUtil.h" #include "model/Poser.h" +#include "scene/SceneFile.h" #include #include +#include #include namespace { @@ -346,6 +348,66 @@ void testPhysics() { CHECK(near(poser.boneGlobals()[0].getTrans().y(), 10.f)); } +// Scene files round-trip and store paths relative to the scene file. +void testSceneFile() { + namespace fs = std::filesystem; + const fs::path dir = fs::temp_directory_path() / "mr_scene_test"; + fs::remove_all(dir); + fs::create_directories(dir / "project" / "models"); + mr::Scene scene; + mr::SceneModel m; + m.path = mr::pathToUtf8(dir / "project" / "models" / "ステージ.x"); + m.stage = true; + m.visible = false; + m.position.set(1.f, 2.f, 3.f); + m.rotationY = 45.f; + m.scale = 10.f; + m.motionPath = mr::pathToUtf8(dir / "dance.vmd"); + mr::BonePose pose; + pose.eulerDegrees.set(10.f, 20.f, 30.f); + m.bonePoses.emplace_back("頭", pose); + m.morphWeights.emplace_back("まばたき", 0.5f); + scene.models.push_back(m); + scene.activeModel = 0; + scene.frame = 120.f; + scene.audioPath = mr::pathToUtf8(dir / "project" / "song.wav"); + scene.view.valid = true; + scene.view.eye.set(0, -40, 10); + scene.lightingModel = 1; + scene.renderWidth = 1280; + const std::string file = mr::pathToUtf8(dir / "project" / "test.mrscene"); + std::string error; + CHECK(mr::saveScene(scene, file, error)); + std::vector bytes; + CHECK(mr::readFileBytes(file, bytes)); + const std::string text(bytes.begin(), bytes.end()); + CHECK(text.find("\"models/ステージ.x\"") != std::string::npos); + CHECK(text.find("\"../dance.vmd\"") != std::string::npos); + + mr::Scene loaded; + CHECK(mr::loadScene(file, loaded, error)); + CHECK(loaded.models.size() == 1); + if (loaded.models.size() == 1) { + const mr::SceneModel& l = loaded.models[0]; + CHECK(fs::equivalent(mr::pathFromUtf8(l.path).parent_path(), dir / "project" / "models")); + CHECK(mr::pathToUtf8(mr::pathFromUtf8(l.path).filename()) == "ステージ.x"); + CHECK(fs::path(mr::pathFromUtf8(l.motionPath)).lexically_normal() == (dir / "dance.vmd").lexically_normal()); + CHECK(l.stage && !l.visible); + CHECK(near(l.position, osg::Vec3f(1.f, 2.f, 3.f)) && near(l.rotationY, 45.f) && near(l.scale, 10.f)); + CHECK(l.bonePoses.size() == 1 && l.bonePoses[0].first == "頭" && + near(l.bonePoses[0].second.eulerDegrees, osg::Vec3f(10.f, 20.f, 30.f))); + CHECK(l.morphWeights.size() == 1 && l.morphWeights[0].first == "まばたき" && near(l.morphWeights[0].second, 0.5f)); + } + CHECK(loaded.activeModel == 0 && near(loaded.frame, 120.f) && loaded.view.valid && loaded.view.eye.y() == -40.0); + CHECK(loaded.lightingModel == 1 && loaded.renderWidth == 1280); + CHECK(!loaded.audioPath.empty() && loaded.cameraMotionPath.empty()); + + const std::string bad = mr::pathToUtf8(dir / "bad.mrscene"); + { std::FILE* f = std::fopen(bad.c_str(), "wb"); std::fputs("{\"format\":\"other\"}", f); std::fclose(f); } + CHECK(!mr::loadScene(bad, loaded, error)); + fs::remove_all(dir); +} + int main() { testPmx(); testPmd(); @@ -354,6 +416,7 @@ int main() { testVmd(); testCameraAndAudio(); testPhysics(); + testSceneFile(); if (g_failures == 0) std::printf("All tests passed\n"); return g_failures == 0 ? 0 : 1; } -- 2.54.1 From 2e2551c0ec91dd47ca1e8cd8695f9968b7965d01 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sun, 29 Nov 2026 08:34:21 +0000 Subject: [PATCH 2/4] Fix double-click on macOS, add Open scene menu item and file browser Open button, free memory on New scene, --reload-test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 4 ++-- src/app/AppUi.cpp | 4 ++-- src/app/FileBrowser.cpp | 41 ++++++++++++++++++++++----------- src/app/FileBrowser.h | 5 +++-- src/app/SceneIo.cpp | 7 ++++++ src/app/main.cpp | 50 +++++++++++++++++++++++++++++++++++++++++ src/ui/ImGuiOsg.cpp | 6 ++--- 7 files changed, 94 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 14b5f28..6ae7f4c 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ restores the default). * **Scenes**: **File > Save scene** (Ctrl+S, Cmd+S on macOS) writes a `.mrscene` file with every model and stage (Position, Rotation, Scale, Stage, visibility), each model's dance, bone pose and morph edits, the camera motion, the song, the timeline frame, the 3D view's camera, the - View settings and the Render size. **File > Open...** (Ctrl+O) opens it again, and **New scene** + View settings and the Render size. **File > Open scene...** (Ctrl+O) opens it again, and **New scene** clears everything. Paths are stored relative to the scene file, so keep the scene next to (or above) its `models/` folder and the whole folder can be moved or shared. The file is plain JSON. * **File > Add model, motion or audio...** (or **Add media...** in the Timeline) picks a model, @@ -162,7 +162,7 @@ Command-line options (`--help`) allow scripted renders, e.g. `--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; `model_renderer scene.mrscene` opens a scene and -`--save-scene FILE` saves one after loading; +`--save-scene FILE` saves one after loading (`--reload-test N` reopens it N times and prints memory use); `--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 c57f797..3f01bf4 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -464,7 +464,7 @@ void App::drawUi() { if (!ImGui::GetIO().WantTextInput) { if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_S)) requestSaveScene(true); else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_S)) requestSaveScene(false); - else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_O)) fileBrowser_.open(); + else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_O)) fileBrowser_.open(FileBrowser::Mode::Open, {}, ".mrscene"); } if (fileBrowser_.draw()) { if (fileBrowser_.mode() == FileBrowser::Mode::Save) saveScene(fileBrowser_.selectedPath()); @@ -509,7 +509,7 @@ void App::drawMenuBar() { if (!ImGui::BeginMainMenuBar()) return; if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("New scene")) newScene(); - if (ImGui::MenuItem("Open...", "Ctrl+O")) fileBrowser_.open(); + if (ImGui::MenuItem("Open scene...", "Ctrl+O")) fileBrowser_.open(FileBrowser::Mode::Open, {}, ".mrscene"); if (ImGui::MenuItem("Save scene", "Ctrl+S")) requestSaveScene(false); if (ImGui::MenuItem("Save scene as...", "Ctrl+Shift+S")) requestSaveScene(true); ImGui::Separator(); diff --git a/src/app/FileBrowser.cpp b/src/app/FileBrowser.cpp index dfb72b3..094d9d0 100644 --- a/src/app/FileBrowser.cpp +++ b/src/app/FileBrowser.cpp @@ -27,9 +27,9 @@ FileBrowser::FileBrowser() { currentDir_ = pathToUtf8(fs::current_path(ec)); } -void FileBrowser::open(Mode mode, const std::string& defaultPath, const std::string& saveExtension) { +void FileBrowser::open(Mode mode, const std::string& defaultPath, const std::string& extension) { mode_ = mode; - saveExtension_ = saveExtension; + extension_ = extension; nameBuffer_[0] = '\0'; if (mode == Mode::Save && !defaultPath.empty()) { const fs::path p = pathFromUtf8(defaultPath); @@ -44,13 +44,16 @@ void FileBrowser::open(Mode mode, const std::string& defaultPath, const std::str void FileBrowser::refresh() { entries_.clear(); error_.clear(); + highlighted_.clear(); std::snprintf(pathBuffer_, sizeof(pathBuffer_), "%s", currentDir_.c_str()); std::error_code ec; for (const auto& e : fs::directory_iterator(pathFromUtf8(currentDir_), fs::directory_options::skip_permission_denied, ec)) { std::string name = pathToUtf8(e.path().filename()); if (name.empty() || name[0] == '.') continue; bool dir = e.is_directory(ec); - if (dir || isModelFile(name)) entries_.push_back({name, dir}); + const bool listed = extension_.empty() ? isModelFile(name) + : toLowerAscii(e.path().extension().string()) == extension_; + if (dir || listed) entries_.push_back({name, dir}); } if (ec) error_ = ec.message(); std::sort(entries_.begin(), entries_.end(), [](const auto& a, const auto& b) { @@ -67,7 +70,7 @@ bool FileBrowser::draw() { bool chosen = false; ImGui::SetNextWindowSize(ImVec2(640, 460), ImGuiCond_FirstUseEver); const bool saving = mode_ == Mode::Save; - if (ImGui::BeginPopupModal(saving ? "Save scene###filebrowser" : "Open###filebrowser", nullptr)) { + if (ImGui::BeginPopupModal(saving ? "Save scene###filebrowser" : extension_ == ".mrscene" ? "Open scene###filebrowser" : "Open###filebrowser", nullptr)) { if (ImGui::Button("Up")) { currentDir_ = pathToUtf8(pathFromUtf8(currentDir_).parent_path()); refresh(); @@ -91,12 +94,12 @@ bool FileBrowser::draw() { ImGui::SameLine(); if ((ImGui::Button("Save") || enter) && nameBuffer_[0]) { std::string name = nameBuffer_; - if (!saveExtension_.empty() && toLowerAscii(fs::path(name).extension().string()) != saveExtension_) - name += saveExtension_; + if (!extension_.empty() && toLowerAscii(fs::path(name).extension().string()) != extension_) + name += extension_; selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name)); chosen = true; } - } else { + } else if (extension_.empty()) { ImGui::TextDisabled("Scenes: .mrscene Models: .pmx .pmd .fbx .x (also .obj .gltf .glb .dae) Motions: .vmd Audio: .wav .mp3 .flac"); } if (!error_.empty()) ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "%s", error_.c_str()); @@ -104,12 +107,15 @@ bool FileBrowser::draw() { std::string enterDir; for (const auto& [name, dir] : entries_) { std::string label = dir ? "[dir] " + name : name; - if (ImGui::Selectable(label.c_str(), false, ImGuiSelectableFlags_AllowDoubleClick) && - (dir || ImGui::IsMouseDoubleClicked(0))) { - if (dir) enterDir = name; - else if (saving) { - std::snprintf(nameBuffer_, sizeof(nameBuffer_), "%s", name.c_str()); - } else { + if (!ImGui::Selectable(label.c_str(), !dir && name == highlighted_, ImGuiSelectableFlags_AllowDoubleClick)) + continue; + if (dir) { + enterDir = name; + } else if (saving) { + std::snprintf(nameBuffer_, sizeof(nameBuffer_), "%s", name.c_str()); + } else { + highlighted_ = name; + if (ImGui::IsMouseDoubleClicked(0)) { selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name)); chosen = true; } @@ -120,6 +126,15 @@ bool FileBrowser::draw() { currentDir_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(enterDir)); refresh(); } + if (!saving) { + ImGui::BeginDisabled(highlighted_.empty()); + if (ImGui::Button("Open")) { + selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(highlighted_)); + chosen = true; + } + ImGui::EndDisabled(); + ImGui::SameLine(); + } if (ImGui::Button("Cancel") || chosen) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } diff --git a/src/app/FileBrowser.h b/src/app/FileBrowser.h index 7f77a44..8d541af 100644 --- a/src/app/FileBrowser.h +++ b/src/app/FileBrowser.h @@ -11,7 +11,8 @@ public: enum class Mode { Open, Save }; FileBrowser(); // Save mode asks for a file name (defaultPath may include a folder) and returns it with saveExtension. - void open(Mode mode = Mode::Open, const std::string& defaultPath = {}, const std::string& saveExtension = {}); + // extension: the file type saved (Save mode) or the only type listed (Open mode); empty lists everything. + void open(Mode mode = Mode::Open, const std::string& defaultPath = {}, const std::string& extension = {}); Mode mode() const { return mode_; } // Draws the popup; returns true when a file was chosen (see selectedPath()). bool draw(); @@ -28,7 +29,7 @@ private: bool openRequested_ = false; Mode mode_ = Mode::Open; char nameBuffer_[256] = {}; - std::string saveExtension_; + std::string extension_, highlighted_; }; } // namespace mr diff --git a/src/app/SceneIo.cpp b/src/app/SceneIo.cpp index e015830..ce8fb72 100644 --- a/src/app/SceneIo.cpp +++ b/src/app/SceneIo.cpp @@ -7,6 +7,10 @@ #include +#if defined(__GLIBC__) +#include +#endif + namespace mr { void App::newScene() { @@ -14,6 +18,9 @@ void App::newScene() { while (!items_.empty()) removeModel(static_cast(items_.size()) - 1); scenePath_.clear(); loadError_.clear(); +#if defined(__GLIBC__) + malloc_trim(0); // glibc keeps freed model data otherwise; macOS and Windows return it on their own +#endif } void App::requestSaveScene(bool saveAs) { diff --git a/src/app/main.cpp b/src/app/main.cpp index 89e499f..e9a3be9 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -12,6 +12,16 @@ #include #include #include + +#if defined(_WIN32) +#define NOMINMAX +#include +#include +#elif defined(__APPLE__) +#include +#else +#include +#endif #include #include #include @@ -52,6 +62,7 @@ void printUsage() { " --stage-scale S scale every --stage model\n" " --no-grid hide the floor grid\n" " --save-scene FILE save the scene (.mrscene) after loading\n" + " --reload-test N reopen the scene N times and print memory use, then exit\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" @@ -68,6 +79,26 @@ std::vector parseFloats(const std::string& s) { return out; } +// Resident memory of this process, for leak checks. +double residentBytes() { +#if defined(_WIN32) + PROCESS_MEMORY_COUNTERS pmc{}; + return K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)) ? double(pmc.WorkingSetSize) : 0.0; +#elif defined(__APPLE__) + mach_task_basic_info info{}; + mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; + return task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast(&info), &count) == KERN_SUCCESS + ? double(info.resident_size) : 0.0; +#else + long pages = 0, resident = 0; + if (std::FILE* f = std::fopen("/proc/self/statm", "r")) { + if (std::fscanf(f, "%ld %ld", &pages, &resident) != 2) resident = 0; + std::fclose(f); + } + return double(resident) * double(sysconf(_SC_PAGESIZE)); +#endif +} + // Times idle frames, frames that re-pose the model, and the CPU deformation alone. void runBenchmark(osgViewer::Viewer& viewer, mr::ModelNode* node, int frames) { using Clock = std::chrono::steady_clock; @@ -128,6 +159,7 @@ int main(int argc, char** argv) { float modelScale = 1.f, stageScale = 1.f; std::string saveScenePath; bool orbitSet = false, physicsSet = false; + int reloadTest = 0; std::string renderDir; int renderStart = 0, renderEnd = -1, renderW = 1920, renderH = 1080; std::vector> morphArgs, boneArgs; @@ -198,6 +230,8 @@ int main(int argc, char** argv) { } else if (a == "--physics") { physics = next() != "off"; physicsSet = true; + } else if (a == "--reload-test") { + reloadTest = std::max(1, std::atoi(next().c_str())); } else if (a == "--save-scene") { saveScenePath = next(); } else if (a == "--pop-out") { @@ -301,6 +335,22 @@ int main(int argc, char** argv) { if (uiScale != 1.f) app.imgui()->setUiScale(uiScale); viewer.realize(); + if (reloadTest > 0) { + // Reopens the scene (or clears it with New scene) repeatedly; memory should level off. + const std::string scene = app.scenePath(); + for (int r = 0; r <= reloadTest && !viewer.done(); ++r) { + if (r > 0) { + if (scene.empty()) app.newScene(); + else app.openScene(scene); + } + for (int f = 0; f < 30; ++f) viewer.frame(); + std::printf("reload %d: %zu models, %.0f MB resident\n", r, app.modelCount(), residentBytes() / 1048576.0); + } + app.newScene(); + for (int f = 0; f < 30; ++f) viewer.frame(); + std::printf("after New scene: %.0f MB resident\n", residentBytes() / 1048576.0); + return 0; + } if (benchFrames > 0) { runBenchmark(viewer, app.modelNode(), benchFrames); return 0; diff --git a/src/ui/ImGuiOsg.cpp b/src/ui/ImGuiOsg.cpp index 793cc53..a61b821 100644 --- a/src/ui/ImGuiOsg.cpp +++ b/src/ui/ImGuiOsg.cpp @@ -144,16 +144,14 @@ public: switch (ea.getEventType()) { case E::PUSH: + case E::DOUBLECLICK: // macOS sends the second press of a double-click as DOUBLECLICK, not PUSH case E::RELEASE: { mousePos(); updateMods(); int b = button(); - if (b >= 0) io.AddMouseButtonEvent(b, ea.getEventType() == E::PUSH); + if (b >= 0) io.AddMouseButtonEvent(b, ea.getEventType() != E::RELEASE); return io.WantCaptureMouse; } - case E::DOUBLECLICK: - mousePos(); - return io.WantCaptureMouse; case E::DRAG: case E::MOVE: mousePos(); -- 2.54.1 From a48caace287092937aa32a0fe0fa78fcb1832c89 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sun, 29 Nov 2026 08:37:36 +0000 Subject: [PATCH 3/4] Return freed memory to macOS after New scene; report phys_footprint on macOS Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/app/SceneIo.cpp | 7 ++++++- src/app/main.cpp | 14 ++++++++------ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/app/SceneIo.cpp b/src/app/SceneIo.cpp index ce8fb72..39c5926 100644 --- a/src/app/SceneIo.cpp +++ b/src/app/SceneIo.cpp @@ -9,6 +9,8 @@ #if defined(__GLIBC__) #include +#elif defined(__APPLE__) +#include #endif namespace mr { @@ -18,8 +20,11 @@ void App::newScene() { while (!items_.empty()) removeModel(static_cast(items_.size()) - 1); scenePath_.clear(); loadError_.clear(); + // Hand the freed model data back to the OS; the allocators otherwise keep it for reuse. #if defined(__GLIBC__) - malloc_trim(0); // glibc keeps freed model data otherwise; macOS and Windows return it on their own + malloc_trim(0); +#elif defined(__APPLE__) + malloc_zone_pressure_relief(nullptr, 0); #endif } diff --git a/src/app/main.cpp b/src/app/main.cpp index e9a3be9..bfe4d16 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -85,10 +85,12 @@ double residentBytes() { PROCESS_MEMORY_COUNTERS pmc{}; return K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)) ? double(pmc.WorkingSetSize) : 0.0; #elif defined(__APPLE__) - mach_task_basic_info info{}; - mach_msg_type_number_t count = MACH_TASK_BASIC_INFO_COUNT; - return task_info(mach_task_self(), MACH_TASK_BASIC_INFO, reinterpret_cast(&info), &count) == KERN_SUCCESS - ? double(info.resident_size) : 0.0; + // phys_footprint is what Activity Monitor reports as Memory; resident_size also counts freed pages + // the system hasn't reclaimed yet. + task_vm_info_data_t info{}; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + return task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast(&info), &count) == KERN_SUCCESS + ? double(info.phys_footprint) : 0.0; #else long pages = 0, resident = 0; if (std::FILE* f = std::fopen("/proc/self/statm", "r")) { @@ -344,11 +346,11 @@ int main(int argc, char** argv) { else app.openScene(scene); } for (int f = 0; f < 30; ++f) viewer.frame(); - std::printf("reload %d: %zu models, %.0f MB resident\n", r, app.modelCount(), residentBytes() / 1048576.0); + std::printf("reload %d: %zu models, %.0f MB in use\n", r, app.modelCount(), residentBytes() / 1048576.0); } app.newScene(); for (int f = 0; f < 30; ++f) viewer.frame(); - std::printf("after New scene: %.0f MB resident\n", residentBytes() / 1048576.0); + std::printf("after New scene: %.0f MB in use\n", residentBytes() / 1048576.0); return 0; } if (benchFrames > 0) { -- 2.54.1 From 269e107b7092142380e8cad92b854cbffcaec083 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Sun, 29 Nov 2026 09:34:32 +0000 Subject: [PATCH 4/4] Keep the pop-out viewport window alive when docking so the main view keeps its GL objects Closing the pop-out's graphics context made OSG delete GL objects shared with the main window (textures lose their CPU images after upload, so models came back black). Docking now hides the window and reuses it; the window's close button docks instead of closing. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CMakeLists.txt | 11 ++++++ src/app/AppUi.cpp | 37 ++++++++++++++++++-- src/app/AppUi.h | 4 +++ src/app/WindowVisibility.cpp | 28 +++++++++++++++ src/app/WindowVisibility.h | 15 ++++++++ src/app/WindowVisibility.mm | 66 ++++++++++++++++++++++++++++++++++++ src/app/main.cpp | 14 +++++++- 7 files changed, 171 insertions(+), 4 deletions(-) create mode 100644 src/app/WindowVisibility.cpp create mode 100644 src/app/WindowVisibility.h create mode 100644 src/app/WindowVisibility.mm diff --git a/CMakeLists.txt b/CMakeLists.txt index b99a05b..d0fe9a0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,6 +146,17 @@ add_executable(model_renderer src/render/GpuCaps.cpp src/ui/ImGuiOsg.cpp) target_link_libraries(model_renderer PRIVATE mr_core mr_audio imgui OpenGL::GL) +if(APPLE) + enable_language(OBJCXX) + target_sources(model_renderer PRIVATE src/app/WindowVisibility.mm) + target_link_libraries(model_renderer PRIVATE "-framework Cocoa") +else() + target_sources(model_renderer PRIVATE src/app/WindowVisibility.cpp) + if(NOT WIN32) + find_package(X11 REQUIRED) + target_link_libraries(model_renderer PRIVATE X11::X11) + endif() +endif() if(MSVC) target_compile_options(mr_core PRIVATE /W3 /utf-8) diff --git a/src/app/AppUi.cpp b/src/app/AppUi.cpp index 3f01bf4..5f38eb5 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -1,4 +1,5 @@ #include "app/AppUi.h" +#include "app/WindowVisibility.h" #include "model/ModelLoader.h" #include "render/GpuCaps.h" @@ -285,6 +286,18 @@ void App::updatePopOut() { osg::Camera* master = viewer_.getCamera(); if (popCamera_ && !(popCamera_->getGraphicsContext() && popCamera_->getGraphicsContext()->valid())) wantPopOut_ = false; // the window was closed + if (wantPopOut_ && !popCamera_ && parkedPopCamera_) { + osg::GraphicsContext* gc = parkedPopCamera_->getGraphicsContext(); + if (gc && gc->valid()) { + // Drop events queued while hidden, such as repeated close requests. + if (auto* window = dynamic_cast(gc)) window->getEventQueue()->clear(); + popCamera_ = parkedPopCamera_; + setWindowVisible(gc, true); + viewer_.addSlave(popCamera_.get(), true); + master->setCullMask(0); + } + parkedPopCamera_ = nullptr; + } if (wantPopOut_ && !popCamera_) { osg::GraphicsContext* mainGc = master->getGraphicsContext(); osg::ref_ptr traits = new osg::GraphicsContext::Traits; @@ -308,6 +321,7 @@ void App::updatePopOut() { return; } gc->realize(); + prepareReusableWindow(gc.get()); popCamera_ = new osg::Camera; popCamera_->setGraphicsContext(gc.get()); popCamera_->setViewport(0, 0, traits->width, traits->height); @@ -325,9 +339,13 @@ void App::updatePopOut() { } else if (!wantPopOut_ && popCamera_) { const unsigned index = viewer_.findSlaveIndexForCamera(popCamera_.get()); if (index < viewer_.getNumSlaves()) viewer_.removeSlave(index); - osg::ref_ptr gc = popCamera_->getGraphicsContext(); - popCamera_->setGraphicsContext(nullptr); - if (gc && gc->valid()) gc->close(); + osg::GraphicsContext* gc = popCamera_->getGraphicsContext(); + if (gc && gc->valid()) { + setWindowVisible(gc, false); + parkedPopCamera_ = popCamera_; + } else { + popCamera_->setGraphicsContext(nullptr); + } popCamera_ = nullptr; master->setCullMask(~0u); } @@ -339,6 +357,19 @@ void App::updatePopOut() { popCamera_->setViewMatrix(manipulator_->getInverseMatrix()); } +void App::catchPopOutClose() { + auto* window = popCamera_ ? dynamic_cast(popCamera_->getGraphicsContext()) : nullptr; + if (!window || !window->valid()) return; + window->checkEvents(); + osgGA::EventQueue::Events events; + window->getEventQueue()->takeEvents(events); + for (const auto& event : events) { + const osgGA::GUIEventAdapter* ea = event->asGUIEventAdapter(); + if (ea && ea->getEventType() == osgGA::GUIEventAdapter::CLOSE_WINDOW) wantPopOut_ = false; + else window->getEventQueue()->addEvent(event.get()); + } +} + void App::drawViewportOverlay() { if (viewRect_.z() < 8.f) return; ImGui::SetNextWindowPos(ImVec2(viewRect_.x() + 8.f, viewRect_.y() + 8.f)); diff --git a/src/app/AppUi.h b/src/app/AppUi.h index 3b67ff4..6452fbd 100644 --- a/src/app/AppUi.h +++ b/src/app/AppUi.h @@ -50,6 +50,8 @@ public: void tick(double time); void setViewportPoppedOut(bool popped) { wantPopOut_ = popped; } bool viewportPoppedOut() const { return popCamera_.valid(); } + // Call before the viewer's event traversal: turns closing the pop-out window into docking it back. + void catchPopOutClose(); // Batch render (command line): renders frames [start, end] into dir, then quits. void renderToFolder(const std::string& dir, int start, int end, int width, int height); ImGuiOsg* imgui() { return imgui_.get(); } @@ -147,6 +149,8 @@ private: std::shared_ptr> encodeResult; } render_; osg::ref_ptr popCamera_; // renders the scene into the separate viewport window + // Hidden pop-out kept for reuse: closing its context would also delete GL objects shared with the main window. + osg::ref_ptr parkedPopCamera_; float timelineZoom_ = 4.f; // pixels per frame float timelineScroll_ = 0.f; // frame at the left edge AudioPlayer audio_; diff --git a/src/app/WindowVisibility.cpp b/src/app/WindowVisibility.cpp new file mode 100644 index 0000000..b7a60f0 --- /dev/null +++ b/src/app/WindowVisibility.cpp @@ -0,0 +1,28 @@ +#include "app/WindowVisibility.h" + +#include + +#if defined(_WIN32) +#include +#else +#include +#endif + +namespace mr { + +void setWindowVisible(osg::GraphicsContext* gc, bool visible) { +#if defined(_WIN32) + if (auto* window = dynamic_cast(gc)) + ShowWindow(window->getHWND(), visible ? SW_SHOW : SW_HIDE); +#else + if (auto* window = dynamic_cast(gc)) { + if (visible) XMapRaised(window->getDisplay(), window->getWindow()); + else XUnmapWindow(window->getDisplay(), window->getWindow()); + XFlush(window->getDisplay()); + } +#endif +} + +void prepareReusableWindow(osg::GraphicsContext*) {} + +} // namespace mr diff --git a/src/app/WindowVisibility.h b/src/app/WindowVisibility.h new file mode 100644 index 0000000..e164c58 --- /dev/null +++ b/src/app/WindowVisibility.h @@ -0,0 +1,15 @@ +#pragma once + +namespace osg { +class GraphicsContext; +} + +namespace mr { + +// Shows or hides an OSG window without closing its graphics context. +void setWindowVisible(osg::GraphicsContext* gc, bool visible); + +// Makes the window's close button send one close event, so the window can be hidden and shown again. +void prepareReusableWindow(osg::GraphicsContext* gc); + +} // namespace mr diff --git a/src/app/WindowVisibility.mm b/src/app/WindowVisibility.mm new file mode 100644 index 0000000..31b6ef3 --- /dev/null +++ b/src/app/WindowVisibility.mm @@ -0,0 +1,66 @@ +#include "app/WindowVisibility.h" + +#import +#import +#include + +// OSG's Cocoa window keeps reporting a close request on every frame once its close button is clicked, until the +// context is closed. This target reports a single close event instead. +@interface MrCloseButtonTarget : NSObject { + osgViewer::GraphicsWindowCocoa* window_; +} +- (instancetype)initWithWindow:(osgViewer::GraphicsWindowCocoa*)window; +- (void)closeClicked:(id)sender; +@end + +@implementation MrCloseButtonTarget +- (instancetype)initWithWindow:(osgViewer::GraphicsWindowCocoa*)window { + if ((self = [super init])) window_ = window; + return self; +} +- (void)closeClicked:(id)sender { + (void)sender; + window_->getEventQueue()->closeWindow(); +} +@end + +namespace mr { + +namespace { +char closeTargetKey; + +NSWindow* nsWindowOf(osg::GraphicsContext* gc) { + auto* window = dynamic_cast(gc); + return window ? (NSWindow*)window->getWindow() : nil; +} +} // namespace + +void setWindowVisible(osg::GraphicsContext* gc, bool visible) { + NSWindow* nsWindow = nsWindowOf(gc); + if (!nsWindow) return; + if (visible) { + [nsWindow makeKeyAndOrderFront:nil]; + return; + } + [nsWindow orderOut:nil]; + for (NSWindow* other in [NSApp orderedWindows]) { + if (other != nsWindow && [other isVisible]) { + [other makeKeyAndOrderFront:nil]; + break; + } + } +} + +void prepareReusableWindow(osg::GraphicsContext* gc) { + NSWindow* nsWindow = nsWindowOf(gc); + if (!nsWindow) return; + MrCloseButtonTarget* target = + [[MrCloseButtonTarget alloc] initWithWindow:static_cast(gc)]; + objc_setAssociatedObject(nsWindow, &closeTargetKey, target, OBJC_ASSOCIATION_RETAIN); + [target release]; + NSButton* closeButton = [nsWindow standardWindowButton:NSWindowCloseButton]; + [closeButton setTarget:target]; + [closeButton setAction:@selector(closeClicked:)]; +} + +} // namespace mr diff --git a/src/app/main.cpp b/src/app/main.cpp index bfe4d16..7ade291 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -28,6 +29,16 @@ namespace { +// Runs a hook before each event traversal, ahead of the viewer's own handling of window events. +class EditorViewer : public osgViewer::Viewer { +public: + std::function beforeEvents; + void eventTraversal() override { + if (beforeEvents) beforeEvents(); + osgViewer::Viewer::eventTraversal(); + } +}; + // Ignores mouse/keyboard events that ImGui already consumed. class GuiAwareManipulator : public osgGA::TrackballManipulator { public: @@ -257,7 +268,7 @@ int main(int argc, char** argv) { } } - osgViewer::Viewer viewer; + EditorViewer viewer; viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded); viewer.setUpViewInWindow(80, 80, width, height); viewer.getCamera()->setClearColor(osg::Vec4(0.22f, 0.24f, 0.28f, 1.f)); @@ -269,6 +280,7 @@ int main(int argc, char** argv) { viewer.setCameraManipulator(manipulator); mr::App app(viewer, root, manipulator); + viewer.beforeEvents = [&app] { app.catchPopOutClose(); }; viewer.setRealizeOperation(new mr::GpuCapsProbe(viewer.getRealizeOperation())); app.setGpuSkinning(gpuSkinning); const auto loadStart = std::chrono::steady_clock::now(); -- 2.54.1