Scene save/load (.mrscene) #8

Merged
dev merged 4 commits from devin/1795937342-scene-files into main 2026-12-01 00:57:49 -05:00
15 changed files with 862 additions and 34 deletions

No files matched your search

+20 -2
View File
@@ -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
@@ -139,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)
+8 -1
View File
@@ -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 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,
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 (`--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.
+67 -5
View File
@@ -1,4 +1,5 @@
#include "app/AppUi.h"
#include "app/WindowVisibility.h"
#include "model/ModelLoader.h"
#include "render/GpuCaps.h"
@@ -97,6 +98,7 @@ bool App::loadModel(const std::string& path, bool stage) {
auto item = std::make_unique<SceneItem>();
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 +177,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 +216,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;
}
@@ -278,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<osgViewer::GraphicsWindow*>(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<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
@@ -301,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);
@@ -318,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<osg::GraphicsContext> 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);
}
@@ -332,6 +357,19 @@ void App::updatePopOut() {
popCamera_->setViewMatrix(manipulator_->getInverseMatrix());
}
void App::catchPopOutClose() {
auto* window = popCamera_ ? dynamic_cast<osgViewer::GraphicsWindow*>(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));
@@ -410,7 +448,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 +492,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(FileBrowser::Mode::Open, {}, ".mrscene");
}
if (fileBrowser_.draw()) {
if (fileBrowser_.mode() == FileBrowser::Mode::Save) saveScene(fileBrowser_.selectedPath());
else openFile(fileBrowser_.selectedPath());
}
drawModelWindow();
if (modelNode_) {
drawBonesWindow();
@@ -491,6 +539,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 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();
if (ImGui::MenuItem("Add model, motion or audio...")) fileBrowser_.open();
if (ImGui::MenuItem("Add stage...")) {
openAsStage_ = true;
@@ -498,6 +551,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 +593,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();
+13 -1
View File
@@ -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);
@@ -45,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(); }
@@ -81,7 +88,7 @@ private:
osg::ref_ptr<ImGuiOsg> imgui_;
struct SceneItem {
osg::ref_ptr<ModelNode> 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 +101,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<std::unique_ptr<SceneItem>> items_;
int active_ = -1;
@@ -139,6 +149,8 @@ private:
std::shared_ptr<std::atomic<int>> encodeResult;
} render_;
osg::ref_ptr<osg::Camera> 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<osg::Camera> parkedPopCamera_;
float timelineZoom_ = 4.f; // pixels per frame
float timelineScroll_ = 0.f; // frame at the left edge
AudioPlayer audio_;
+51 -11
View File
@@ -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& extension) {
mode_ = mode;
extension_ = extension;
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();
}
@@ -35,13 +44,16 @@ void FileBrowser::open() {
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) {
@@ -52,12 +64,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" : extension_ == ".mrscene" ? "Open scene###filebrowser" : "Open###filebrowser", nullptr)) {
if (ImGui::Button("Up")) {
currentDir_ = pathToUtf8(pathFromUtf8(currentDir_).parent_path());
refresh();
@@ -70,21 +83,39 @@ 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 (!extension_.empty() && toLowerAscii(fs::path(name).extension().string()) != extension_)
name += extension_;
selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name));
chosen = true;
}
} 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());
ImGui::BeginChild("entries", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), ImGuiChildFlags_Borders);
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 (!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;
}
@@ -95,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();
}
+8 -1
View File
@@ -8,8 +8,12 @@ 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.
// 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();
const std::string& selectedPath() const { return selected_; }
@@ -23,6 +27,9 @@ private:
std::string selected_;
std::string error_;
bool openRequested_ = false;
Mode mode_ = Mode::Open;
char nameBuffer_[256] = {};
std::string extension_, highlighted_;
};
} // namespace mr
+167
View File
@@ -0,0 +1,167 @@
// Scene save/load: converts between the editor's state and mr::Scene (scene/SceneFile.h).
#include "app/AppUi.h"
#include "scene/SceneFile.h"
#include <imgui.h>
#include <algorithm>
#if defined(__GLIBC__)
#include <malloc.h>
#elif defined(__APPLE__)
#include <malloc/malloc.h>
#endif
namespace mr {
void App::newScene() {
unloadMotion();
while (!items_.empty()) removeModel(static_cast<int>(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);
#elif defined(__APPLE__)
malloc_zone_pressure_relief(nullptr, 0);
#endif
}
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<uint8_t> 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<int>(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
+28
View File
@@ -0,0 +1,28 @@
#include "app/WindowVisibility.h"
#include <osg/GraphicsContext>
#if defined(_WIN32)
#include <osgViewer/api/Win32/GraphicsWindowWin32>
#else
#include <osgViewer/api/X11/GraphicsWindowX11>
#endif
namespace mr {
void setWindowVisible(osg::GraphicsContext* gc, bool visible) {
#if defined(_WIN32)
if (auto* window = dynamic_cast<osgViewer::GraphicsWindowWin32*>(gc))
ShowWindow(window->getHWND(), visible ? SW_SHOW : SW_HIDE);
#else
if (auto* window = dynamic_cast<osgViewer::GraphicsWindowX11*>(gc)) {
if (visible) XMapRaised(window->getDisplay(), window->getWindow());
else XUnmapWindow(window->getDisplay(), window->getWindow());
XFlush(window->getDisplay());
}
#endif
}
void prepareReusableWindow(osg::GraphicsContext*) {}
} // namespace mr
+15
View File
@@ -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
+66
View File
@@ -0,0 +1,66 @@
#include "app/WindowVisibility.h"
#import <Cocoa/Cocoa.h>
#import <objc/runtime.h>
#include <osgViewer/api/Cocoa/GraphicsWindowCocoa>
// 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<osgViewer::GraphicsWindowCocoa*>(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<osgViewer::GraphicsWindowCocoa*>(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
+89 -9
View File
@@ -1,4 +1,5 @@
#include "app/AppUi.h"
#include "model/PathUtil.h"
#include "render/GpuCaps.h"
#include "render/ModelNode.h"
@@ -9,14 +10,35 @@
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <functional>
#include <cstdlib>
#include <iostream>
#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#include <psapi.h>
#elif defined(__APPLE__)
#include <mach/mach.h>
#else
#include <unistd.h>
#endif
#include <sstream>
#include <string>
#include <vector>
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<void()> beforeEvents;
void eventTraversal() override {
if (beforeEvents) beforeEvents();
osgViewer::Viewer::eventTraversal();
}
};
// Ignores mouse/keyboard events that ImGui already consumed.
class GuiAwareManipulator : public osgGA::TrackballManipulator {
public:
@@ -28,7 +50,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 +72,8 @@ 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"
" --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"
@@ -66,6 +90,28 @@ std::vector<float> 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__)
// 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<task_info_t>(&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")) {
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;
@@ -124,6 +170,9 @@ int main(int argc, char** argv) {
bool physics = true, grid = true;
std::vector<std::string> stagePaths, extraModels;
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<std::pair<std::string, std::string>> morphArgs, boneArgs;
@@ -158,6 +207,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 +242,11 @@ int main(int argc, char** argv) {
grid = false;
} 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") {
popOut = true;
} else if (a == "--render") {
@@ -213,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));
@@ -225,19 +280,27 @@ 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();
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<int>(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<double, std::milli>(std::chrono::steady_clock::now() - loadStart).count();
@@ -275,16 +338,33 @@ 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);
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 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 in use\n", residentBytes() / 1048576.0);
return 0;
}
if (benchFrames > 0) {
runBenchmark(viewer, app.modelNode(), benchFrames);
return 0;
+211
View File
@@ -0,0 +1,211 @@
#include "scene/SceneFile.h"
#include "model/PathUtil.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <filesystem>
#include <fstream>
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 <typename V>
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<typename V::value_type>();
}
template <typename T>
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<T>();
}
// 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<uint8_t> 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<float>());
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
+54
View File
@@ -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 <osg/Vec3d>
#include <osg/Vec3f>
#include <string>
#include <utility>
#include <vector>
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<std::pair<std::string, BonePose>> bonePoses; // by bone name; non-rest poses only
std::vector<std::pair<std::string, float>> 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<SceneModel> 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
+2 -4
View File
@@ -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();
+63
View File
@@ -4,9 +4,11 @@
#include "model/Motion.h"
#include "model/PathUtil.h"
#include "model/Poser.h"
#include "scene/SceneFile.h"
#include <cmath>
#include <cstdio>
#include <filesystem>
#include <string>
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<uint8_t> 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;
}