Files
3d-model-renderer/src/app/main.cpp
T
gs5579andDevin AI 95383f8353 Add VMD camera playback and synced audio via miniaudio
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 06:26:44 +00:00

253 lines
11 KiB
C++

#include "app/AppUi.h"
#include "render/GpuCaps.h"
#include "render/ModelNode.h"
#include <osg/Group>
#include <osgViewer/Viewer>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace {
// Ignores mouse/keyboard events that ImGui already consumed.
class GuiAwareManipulator : public osgGA::TrackballManipulator {
public:
GuiAwareManipulator() { setAllowThrow(false); }
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) override {
if (ea.getHandled()) return false;
return osgGA::TrackballManipulator::handle(ea, aa);
}
};
void printUsage() {
std::cout << "Usage: model_renderer [model.pmx|.pmd|.fbx] [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"
" --orbit AZ,EL initial camera azimuth/elevation in degrees\n"
" --skeleton show the skeleton overlay\n"
" --hide-ui hide the ImGui overlay\n"
" --ui-scale S scale the UI (e.g. 2 on high-DPI screens)\n"
" --screenshot FILE render, save a PNG and exit\n"
" --frames N frames to render before the screenshot (default 5)\n"
" --list print bone and morph names after loading\n"
" --skinning gpu|cpu hardware or software skinning (default gpu)\n"
" --motion FILE.vmd load an MMD motion\n"
" --frame N motion frame to show (30 per second)\n"
" --camera FILE.vmd load an MMD camera motion\n"
" --audio FILE load a song (.wav .mp3 .flac)\n"
" --play start playback\n"
" --bench N time N idle and N animated frames, then exit\n";
}
std::vector<float> parseFloats(const std::string& s) {
std::vector<float> out;
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, ',')) out.push_back(std::strtof(item.c_str(), nullptr));
return out;
}
// 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;
auto ms = [](Clock::duration d) { return std::chrono::duration<double, std::milli>(d).count(); };
auto start = Clock::now();
viewer.frame();
std::printf("first frame: %.0f ms\n", ms(Clock::now() - start));
for (int f = 0; f < 10; ++f) viewer.frame();
start = Clock::now();
for (int f = 0; f < frames; ++f) viewer.frame();
const double idle = ms(Clock::now() - start) / frames;
std::printf("idle frame: %.2f ms\n", idle);
if (node)
std::printf("skinning: %s (%s)\n",
node->activeSkinningMode() == mr::SkinningMode::Hardware ? "GPU" : "CPU",
mr::gpuCaps().renderer.c_str());
if (!node) return;
mr::Poser& poser = node->poser();
const mr::Model& model = node->model();
int morph = -1;
for (size_t i = 0; i < model.morphs.size() && morph < 0; ++i)
if (model.morphs[i].type == mr::MorphType::Vertex) morph = static_cast<int>(i);
std::vector<int> influence(model.bones.size(), 0);
for (const auto& v : model.vertices)
for (int k = 0; k < 4; ++k)
if (v.bones[k] >= 0) ++influence[v.bones[k]];
const int bone = static_cast<int>(std::max_element(influence.begin(), influence.end()) - influence.begin());
auto animate = [&](int f) {
if (morph >= 0) poser.morphWeights()[morph] = (f % 20) / 20.f;
if (!model.bones.empty()) poser.bonePoses()[bone].eulerDegrees.set(0.f, 0.f, float(f % 30));
};
start = Clock::now();
for (int f = 0; f < frames; ++f) {
animate(f + 1);
viewer.frame();
}
const double animated = ms(Clock::now() - start) / frames;
start = Clock::now();
for (int f = 0; f < frames; ++f) {
animate(f + 2);
poser.update();
}
const double deform = ms(Clock::now() - start) / frames;
std::printf("animated frame: %.2f ms\ndeform only: %.2f ms\n", animated, deform);
}
} // namespace
int main(int argc, char** argv) {
std::string modelPath, screenshot, motionPath, cameraPath, audioPath;
float motionFrame = 0.f;
bool play = false;
std::vector<std::pair<std::string, std::string>> morphArgs, boneArgs;
int width = 1280, height = 800, frames = 5, benchFrames = 0;
float azimuth = 0.f, elevation = 0.f, uiScale = 1.f;
bool skeleton = false, hideUi = false, listNames = false, gpuSkinning = true;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
auto next = [&]() -> std::string {
if (i + 1 >= argc) {
std::cerr << "Missing value for " << a << "\n";
std::exit(2);
}
return argv[++i];
};
auto split = [](const std::string& kv) {
size_t eq = kv.rfind('=');
return eq == std::string::npos ? std::make_pair(kv, std::string())
: std::make_pair(kv.substr(0, eq), kv.substr(eq + 1));
};
if (a == "-h" || a == "--help") {
printUsage();
return 0;
} else if (a == "--size") {
std::sscanf(next().c_str(), "%dx%d", &width, &height);
} else if (a == "--morph") {
morphArgs.push_back(split(next()));
} else if (a == "--bone") {
boneArgs.push_back(split(next()));
} else if (a == "--orbit") {
auto v = parseFloats(next());
if (v.size() >= 1) azimuth = v[0];
if (v.size() >= 2) elevation = v[1];
} else if (a == "--skeleton") {
skeleton = true;
} else if (a == "--hide-ui") {
hideUi = true;
} else if (a == "--ui-scale") {
uiScale = std::strtof(next().c_str(), nullptr);
} else if (a == "--screenshot") {
screenshot = next();
} else if (a == "--list") {
listNames = true;
} else if (a == "--skinning") {
gpuSkinning = next() != "cpu";
} else if (a == "--motion") {
motionPath = next();
} else if (a == "--camera") {
cameraPath = next();
} else if (a == "--audio") {
audioPath = next();
} else if (a == "--frame") {
motionFrame = std::strtof(next().c_str(), nullptr);
} else if (a == "--play") {
play = true;
} else if (a == "--bench") {
benchFrames = std::max(1, std::atoi(next().c_str()));
} else if (a == "--frames") {
frames = std::max(1, std::atoi(next().c_str()));
} else if (!a.empty() && a[0] != '-') {
modelPath = a;
} else {
std::cerr << "Unknown option " << a << "\n";
printUsage();
return 2;
}
}
osgViewer::Viewer 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));
viewer.setKeyEventSetsDone(0); // Escape should not quit while typing in the UI
osg::ref_ptr<osg::Group> root = new osg::Group;
viewer.setSceneData(root);
osg::ref_ptr<GuiAwareManipulator> manipulator = new GuiAwareManipulator;
viewer.setCameraManipulator(manipulator);
mr::App app(viewer, root, manipulator);
viewer.setRealizeOperation(new mr::GpuCapsProbe(viewer.getRealizeOperation()));
app.setGpuSkinning(gpuSkinning);
const auto loadStart = std::chrono::steady_clock::now();
if (!modelPath.empty() && !app.loadModel(modelPath)) std::cerr << app.loadError() << "\n";
const double loadMs =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - loadStart).count();
if (auto* node = app.modelNode()) {
const mr::Model& model = node->model();
std::cout << "Loaded '" << model.name << "': " << model.vertices.size() << " vertices, "
<< model.indices.size() / 3 << " triangles, " << model.materials.size() << " materials, "
<< model.bones.size() << " bones, " << model.morphs.size() << " morphs in " << int(loadMs)
<< " ms\n";
for (const auto& w : model.warnings) std::cout << " warning: " << w << "\n";
if (listNames) {
for (const auto& b : model.bones) std::cout << " bone: " << b.name << "\n";
for (const auto& m : model.morphs) std::cout << " morph: '" << m.name << "'\n";
}
for (const auto& [name, value] : morphArgs) {
int idx = model.findMorph(name);
if (idx < 0) std::cerr << "No morph named " << name << "\n";
else node->poser().morphWeights()[idx] = std::strtof(value.c_str(), nullptr);
}
for (const auto& [name, value] : boneArgs) {
int idx = model.findBone(name);
auto v = parseFloats(value);
if (idx < 0) {
std::cerr << "No bone named " << name << "\n";
continue;
}
auto& pose = node->poser().bonePoses()[idx];
for (size_t k = 0; k < 3 && k < v.size(); ++k) pose.eulerDegrees[k] = v[k];
for (size_t k = 3; k < 6 && k < v.size(); ++k) pose.translation[k - 3] = v[k];
}
for (const std::string& path : {motionPath, cameraPath})
if (!path.empty() && !app.loadMotion(path)) std::cerr << app.loadError() << "\n";
if (!audioPath.empty() && !app.loadAudio(audioPath)) std::cerr << app.loadError() << "\n";
if (!motionPath.empty() || !cameraPath.empty() || !audioPath.empty()) {
app.setMotionFrame(motionFrame);
app.setPlaying(play);
}
app.setShowSkeleton(skeleton);
app.frameModel(azimuth, elevation);
}
app.imgui()->setUiVisible(!hideUi);
if (uiScale != 1.f) app.imgui()->setUiScale(uiScale);
viewer.realize();
if (benchFrames > 0) {
runBenchmark(viewer, app.modelNode(), benchFrames);
return 0;
}
if (!screenshot.empty()) {
for (int f = 0; f < frames && !viewer.done(); ++f) viewer.frame();
app.imgui()->requestScreenshot(screenshot);
viewer.frame();
return 0;
}
while (!viewer.done()) viewer.frame();
return 0;
}