OSG + Assimp + ImGui model renderer: PMX/PMD/FBX, bone posing, morph sliders #1

Open
dev wants to merge 3 commits from devin/1795773104-osg-model-renderer into main
pull from: devin/1795773104-osg-model-renderer
41 changed files with 3886 additions and 0 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
models/
build*/
.cache/
imgui.ini
*.png.tmp
.DS_Store
/screenshots/
+111
View File
@@ -0,0 +1,111 @@
cmake_minimum_required(VERSION 3.16)
project(ModelRenderer VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()
option(MR_BUILD_TESTS "Build unit tests" ON)
option(MR_FETCH_ASSIMP "Download and build Assimp if it is not installed" ON)
include(FetchContent)
# --- OpenSceneGraph -----------------------------------------------------------
find_package(OpenSceneGraph 3.6 REQUIRED COMPONENTS osgDB osgGA osgViewer osgUtil)
find_package(OpenGL REQUIRED)
# --- Assimp --------------------------------------------------------------------
find_package(assimp CONFIG QUIET)
if(NOT assimp_FOUND)
if(NOT MR_FETCH_ASSIMP)
message(FATAL_ERROR "Assimp not found. Install it or configure with -DMR_FETCH_ASSIMP=ON")
endif()
message(STATUS "Assimp not found on the system, fetching it (FBX importer only)")
set(ASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT OFF CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_ALL_EXPORTERS_BY_DEFAULT OFF CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_FBX_IMPORTER ON CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_OBJ_IMPORTER ON CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_GLTF_IMPORTER ON CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_ASSIMP_TOOLS OFF CACHE BOOL "" FORCE)
set(ASSIMP_INSTALL OFF CACHE BOOL "" FORCE)
set(ASSIMP_WARNINGS_AS_ERRORS OFF CACHE BOOL "" FORCE)
set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
FetchContent_Declare(assimp
URL https://github.com/assimp/assimp/archive/refs/tags/v5.4.3.tar.gz
URL_HASH SHA256=66dfbaee288f2bc43172440a55d0235dfc7bf885dda6435c038e8000e79582cb)
FetchContent_MakeAvailable(assimp)
endif()
# --- Dear ImGui ----------------------------------------------------------------
FetchContent_Declare(imgui
URL https://github.com/ocornut/imgui/archive/refs/tags/v1.91.5.tar.gz
URL_HASH SHA256=2aa2d169c569368439e5d5667e0796d09ca5cc6432965ce082e516937d7db254)
FetchContent_MakeAvailable(imgui)
add_library(imgui STATIC
${imgui_SOURCE_DIR}/imgui.cpp
${imgui_SOURCE_DIR}/imgui_draw.cpp
${imgui_SOURCE_DIR}/imgui_tables.cpp
${imgui_SOURCE_DIR}/imgui_widgets.cpp
${imgui_SOURCE_DIR}/imgui_demo.cpp
${imgui_SOURCE_DIR}/backends/imgui_impl_opengl2.cpp)
target_include_directories(imgui PUBLIC ${imgui_SOURCE_DIR} ${imgui_SOURCE_DIR}/backends)
target_link_libraries(imgui PUBLIC OpenGL::GL)
if(APPLE)
target_compile_definitions(imgui PUBLIC GL_SILENCE_DEPRECATION IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
target_link_libraries(imgui PUBLIC "-framework ApplicationServices")
endif()
# --- Text encoding (Shift-JIS for PMD) -------------------------------------------
if(NOT WIN32)
find_package(Iconv REQUIRED)
endif()
# --- Core library: model formats + posing (no rendering) -------------------------
add_library(mr_core STATIC
src/model/Model.cpp
src/model/TextEncoding.cpp
src/model/PathUtil.cpp
src/model/PmxLoader.cpp
src/model/PmdLoader.cpp
src/model/AssimpLoader.cpp
src/model/ModelLoader.cpp
src/model/Poser.cpp)
target_include_directories(mr_core PUBLIC src ${OPENSCENEGRAPH_INCLUDE_DIRS})
target_link_libraries(mr_core PUBLIC ${OPENSCENEGRAPH_LIBRARIES} assimp::assimp)
if(NOT WIN32)
target_link_libraries(mr_core PRIVATE Iconv::Iconv)
endif()
# --- Viewer application ----------------------------------------------------------
add_executable(model_renderer
src/app/main.cpp
src/app/AppUi.cpp
src/app/FileBrowser.cpp
src/render/ModelNode.cpp
src/render/TextureLoader.cpp
src/render/Shaders.cpp
src/ui/ImGuiOsg.cpp)
target_link_libraries(model_renderer PRIVATE mr_core imgui OpenGL::GL)
if(MSVC)
target_compile_options(mr_core PRIVATE /W3 /utf-8)
target_compile_options(model_renderer PRIVATE /W3 /utf-8)
target_compile_definitions(mr_core PUBLIC NOMINMAX _USE_MATH_DEFINES)
else()
target_compile_options(mr_core PRIVATE -Wall -Wextra)
target_compile_options(model_renderer PRIVATE -Wall -Wextra)
endif()
if(MR_BUILD_TESTS)
enable_testing()
add_executable(mr_tests tests/test_main.cpp)
target_link_libraries(mr_tests PRIVATE mr_core)
target_compile_definitions(mr_tests PRIVATE MR_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/data")
add_test(NAME mr_tests COMMAND mr_tests)
endif()
+101
View File
@@ -1 +1,102 @@
# 3d-model-renderer
A cross-platform (Linux, macOS, Windows) viewer for **PMX / PMD** (MikuMikuDance) and **FBX** models
that lets you pose bones and drive vertex morphs (eyes, mouth, eyebrows) from an on-screen UI.
Built with C++17, [OpenSceneGraph](https://github.com/openscenegraph/OpenSceneGraph) (rendering),
[Assimp](https://github.com/assimp/assimp) (FBX and other formats) and [Dear ImGui](https://github.com/ocornut/imgui) (UI).
## How it works
```
.pmx ──► PmxLoader ─┐
.pmd ──► PmdLoader ─┼─► mr::Model ──► mr::Poser ──► ModelNode (OSG geometry + GLSL) ──► osgViewer
.fbx ──► Assimp ──┘ (one format) (morphs + skinning, ImGui overlay (bones, morphs, view)
on the CPU)
```
* PMX and PMD use their own loaders because Assimp cannot read PMD and drops PMX morphs.
* Every format is converted into one internal model (right-handed, +Y up, facing +Z), so rendering,
posing and morphing share a single code path.
* Bone rotations in the UI are in model-space axes at the bone pivot, so they behave the same for
MMD and FBX rigs.
* Shaders are GLSL 1.20 so they run on macOS's legacy OpenGL context as well as Linux and Windows.
Supported: textures (incl. MMD sphere `.sph`/`.spa` and toon maps), vertex/group/bone/flip morphs,
BDEF1/2/4 weights (SDEF/QDEF approximated as linear blend). Not yet: IK solving, physics, UV and
material morphs, edge outlines, animation playback (VMD).
## Building
You need CMake ≥ 3.16, a C++17 compiler, OpenSceneGraph 3.6 and (optionally) Assimp. If Assimp is not
installed CMake downloads and builds it (`-DMR_FETCH_ASSIMP=ON` forces that). Dear ImGui is always downloaded.
### macOS
```sh
xcode-select --install
brew install cmake ninja open-scene-graph assimp
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
./build/model_renderer path/to/model.pmx
```
### Linux (Debian / Ubuntu)
```sh
sudo apt install build-essential cmake ninja-build libopenscenegraph-dev libassimp-dev \
libgl1-mesa-dev fonts-noto-cjk xclip
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
./build/model_renderer path/to/model.pmx
```
Copy/paste in text fields uses `xclip` or `xsel` on X11 and `wl-clipboard` on Wayland.
Fedora: `sudo dnf install cmake ninja-build gcc-c++ OpenSceneGraph-devel assimp-devel google-noto-sans-cjk-fonts`.
### Windows (Visual Studio 2022 + vcpkg)
```bat
git clone https://github.com/microsoft/vcpkg C:\vcpkg && C:\vcpkg\bootstrap-vcpkg.bat
C:\vcpkg\vcpkg install osg assimp --triplet x64-windows
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake
cmake --build build --config Release
build\Release\model_renderer.exe path\to\model.pmx
```
A Japanese font is picked up automatically (Hiragino on macOS, Meiryo/Yu Gothic on Windows, Noto CJK on
Linux) so MMD bone and morph names display correctly.
## Using it
* **File > Open** picks a model; you can also pass the path on the command line.
* **Bones**: select a bone, then use the rotation sliders / move fields. `*` marks posed bones.
* **Morphs**: sliders grouped as Eye / Mouth / Eyebrow / Other, as in MMD.
* **View**: skeleton overlay, wireframe, culling, MMD toon vs Lambert shading, UI scale (use 2 on Retina).
* Camera: left drag orbits, middle drag pans, right drag or wheel zooms, Space resets.
Command-line options (`--help`) allow scripted renders, e.g.
```sh
./build/model_renderer miku.pmd --morph あ=1 --morph まばたき=1 --bone 左腕=0,0,-40 \
--orbit 20,10 --hide-ui --screenshot out.png
```
## Tests
```sh
cmake -S . -B build -DMR_BUILD_TESTS=ON && cmake --build build && ctest --test-dir build
```
The test models in `tests/data` are generated by `tools/make_test_models.py` (PMX/PMD) and
`tools/make_test_fbx.py` (FBX, run with `blender -b -P`).
## Layout
| Path | Contents |
| --- | --- |
| `src/model` | Internal model, PMX/PMD/Assimp loaders, `Poser` (morphs + skinning) |
| `src/render` | OSG scene node, shaders, texture loading |
| `src/ui` | ImGui ↔ OpenSceneGraph integration |
| `src/app` | Application, UI panels, file browser, command line |
+273
View File
@@ -0,0 +1,273 @@
#include "app/AppUi.h"
#include "model/ModelLoader.h"
#include <imgui.h>
#include <algorithm>
#include <cmath>
#include <cstring>
namespace mr {
namespace {
bool containsCaseInsensitive(const std::string& text, const char* filter) {
if (!filter || !*filter) return true;
std::string a = text, b = filter;
auto lower = [](std::string& s) {
for (auto& c : s)
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
};
lower(a);
lower(b);
return a.find(b) != std::string::npos;
}
const char* panelName(MorphPanel p) {
switch (p) {
case MorphPanel::Eye: return "Eye";
case MorphPanel::Mouth: return "Mouth";
case MorphPanel::Eyebrow: return "Eyebrow";
case MorphPanel::Other: return "Other";
default: return "System";
}
}
} // namespace
App::App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulator* manipulator)
: viewer_(viewer), root_(root), manipulator_(manipulator) {
imgui_ = new ImGuiOsg([this]() { drawUi(); });
imgui_->attach(viewer_);
}
bool App::loadModel(const std::string& path) {
std::string error;
auto model = mr::loadModel(path, error);
if (!model) {
loadError_ = "Failed to load " + path + ": " + error;
return false;
}
loadError_.clear();
if (modelNode_) root_->removeChild(modelNode_);
std::string glyphs = model->name + model->comment;
for (const auto& b : model->bones) glyphs += b.name + b.nameEn;
for (const auto& mo : model->morphs) glyphs += mo.name + mo.nameEn;
for (const auto& ma : model->materials) glyphs += ma.name;
imgui_->addGlyphs(glyphs);
modelNode_ = new ModelNode(model);
root_->addChild(modelNode_);
selectedBone_ = -1;
boneFilter_[0] = '\0';
morphFilter_[0] = '\0';
lightingModel_ = model->format == SourceFormat::Assimp ? 1 : 0;
applyViewSettings();
frameModel();
return true;
}
void App::applyViewSettings() {
if (!modelNode_) return;
modelNode_->setShowSkeleton(showSkeleton_);
modelNode_->setBackfaceCulling(backfaceCulling_);
modelNode_->setWireframe(wireframe_);
modelNode_->setLightFollowsCamera(lightFollowsCamera_);
modelNode_->setLightingModel(static_cast<LightingModel>(lightingModel_));
modelNode_->setSelectedBone(selectedBone_);
}
void App::setShowSkeleton(bool show) {
showSkeleton_ = show;
applyViewSettings();
}
void App::frameModel(float azimuthDeg, float elevationDeg) {
if (!modelNode_) return;
osg::BoundingSphere bs = modelNode_->restBound();
modelRadius_ = std::max(bs.radius(), 1e-3f);
const double dist = modelRadius_ / std::sin(osg::DegreesToRadians(15.0)) * 1.05;
const double az = osg::DegreesToRadians(static_cast<double>(azimuthDeg));
const double el = osg::DegreesToRadians(static_cast<double>(elevationDeg));
// Models face -Y in the world, so the default camera sits on the -Y side.
osg::Vec3d dir(std::sin(az) * std::cos(el), -std::cos(az) * std::cos(el), std::sin(el));
manipulator_->setHomePosition(bs.center() + dir * dist, bs.center(), osg::Vec3d(0, 0, 1));
viewer_.home();
}
void App::drawUi() {
drawMenuBar();
if (!loadError_.empty()) {
ImGui::SetNextWindowPos(ImVec2(10, 40), ImGuiCond_Always);
ImGui::Begin("Error", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse);
ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "%s", loadError_.c_str());
if (ImGui::Button("Dismiss")) loadError_.clear();
ImGui::End();
}
if (fileBrowser_.draw()) loadModel(fileBrowser_.selectedPath());
if (modelNode_) {
drawModelWindow();
drawBonesWindow();
drawMorphsWindow();
} else {
ImGui::SetNextWindowPos(ImVec2(10, 40), ImGuiCond_FirstUseEver);
ImGui::Begin("Welcome", nullptr, ImGuiWindowFlags_AlwaysAutoResize);
ImGui::Text("Open a .pmx, .pmd or .fbx model with File > Open.");
if (ImGui::Button("Open model...")) fileBrowser_.open();
ImGui::End();
}
if (showDemo_) ImGui::ShowDemoWindow(&showDemo_);
}
void App::drawMenuBar() {
if (!ImGui::BeginMainMenuBar()) return;
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("Open...")) fileBrowser_.open();
if (ImGui::MenuItem("Quit")) viewer_.setDone(true);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("View")) {
bool changed = false;
changed |= ImGui::MenuItem("Skeleton", nullptr, &showSkeleton_);
changed |= ImGui::MenuItem("Wireframe", nullptr, &wireframe_);
changed |= ImGui::MenuItem("Backface culling", nullptr, &backfaceCulling_);
changed |= ImGui::MenuItem("Light follows camera", nullptr, &lightFollowsCamera_);
ImGui::Separator();
changed |= ImGui::RadioButton("MMD toon shading", &lightingModel_, 0);
changed |= ImGui::RadioButton("Lambert shading", &lightingModel_, 1);
ImGui::Separator();
float scale = imgui_->uiScale();
if (ImGui::SliderFloat("UI scale", &scale, 0.75f, 2.5f, "%.2f")) imgui_->setUiScale(scale);
if (ImGui::MenuItem("Reset camera")) frameModel();
ImGui::MenuItem("ImGui demo", nullptr, &showDemo_);
if (changed) applyViewSettings();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Help")) {
ImGui::Text("Left drag: orbit Middle drag: pan Right drag / wheel: zoom");
ImGui::Text("Space: reset camera");
ImGui::EndMenu();
}
ImGui::SameLine(ImGui::GetWindowWidth() - 90 * imgui_->uiScale());
ImGui::TextDisabled("%.0f FPS", ImGui::GetIO().Framerate);
ImGui::EndMainMenuBar();
}
void App::drawModelWindow() {
const Model& m = modelNode_->model();
ImGui::SetNextWindowPos(ImVec2(10, 35), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(300, 210), ImGuiCond_FirstUseEver);
ImGui::Begin("Model");
ImGui::TextWrapped("%s", m.name.c_str());
ImGui::TextDisabled("%s", m.format == SourceFormat::PMX ? "PMX" : m.format == SourceFormat::PMD ? "PMD" : "Assimp");
ImGui::Text("Vertices %zu Triangles %zu", m.vertices.size(), m.indices.size() / 3);
ImGui::Text("Materials %zu Textures %zu", m.materials.size(), m.textures.size());
ImGui::Text("Bones %zu Morphs %zu", m.bones.size(), m.morphs.size());
if (ImGui::Button("Reset pose")) modelNode_->poser().resetPose();
ImGui::SameLine();
if (ImGui::Button("Reset morphs")) modelNode_->poser().resetMorphs();
if (!m.comment.empty() && ImGui::CollapsingHeader("Comment")) ImGui::TextWrapped("%s", m.comment.c_str());
if (!m.warnings.empty() && ImGui::CollapsingHeader("Warnings")) {
for (const auto& w : m.warnings) ImGui::BulletText("%s", w.c_str());
}
ImGui::End();
}
void App::drawBoneEditor() {
if (selectedBone_ < 0) {
ImGui::TextDisabled("Select a bone below to pose it.");
return;
}
const Bone& bone = modelNode_->model().bones[selectedBone_];
BonePose& pose = modelNode_->poser().bonePoses()[selectedBone_];
ImGui::Text("%s", bone.name.c_str());
if (!bone.nameEn.empty()) {
ImGui::SameLine();
ImGui::TextDisabled("(%s)", bone.nameEn.c_str());
}
ImGui::SliderFloat("Rot X", &pose.eulerDegrees.x(), -180.f, 180.f, "%.1f deg");
ImGui::SliderFloat("Rot Y", &pose.eulerDegrees.y(), -180.f, 180.f, "%.1f deg");
ImGui::SliderFloat("Rot Z", &pose.eulerDegrees.z(), -180.f, 180.f, "%.1f deg");
ImGui::DragFloat3("Move", pose.translation.ptr(), modelRadius_ * 0.002f);
if (ImGui::Button("Reset bone")) pose = BonePose();
}
void App::drawBonesWindow() {
const Model& m = modelNode_->model();
const auto& poses = modelNode_->poser().bonePoses();
ImGuiIO& io = ImGui::GetIO();
ImGui::SetNextWindowPos(ImVec2(10, 255), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(300, io.DisplaySize.y - 265), ImGuiCond_FirstUseEver);
ImGui::Begin("Bones");
drawBoneEditor();
ImGui::Separator();
ImGui::SetNextItemWidth(-1);
ImGui::InputTextWithHint("##bonefilter", "Filter bones", boneFilter_, sizeof(boneFilter_));
ImGui::Checkbox("Only visible / skinning bones", &onlyVisibleBones_);
ImGui::BeginChild("bonelist");
int shown = 0;
for (size_t i = 0; i < m.bones.size(); ++i) {
const Bone& b = m.bones[i];
if (onlyVisibleBones_ && !b.visible && !b.isSkinBone) continue;
if (!containsCaseInsensitive(b.name, boneFilter_) && !containsCaseInsensitive(b.nameEn, boneFilter_)) continue;
int depth = 0;
for (int p = b.parent; p >= 0 && depth < 32; p = m.bones[p].parent) ++depth;
if (*boneFilter_) depth = 0;
++shown;
const bool posed = poses[i] != BonePose();
std::string label = std::string(static_cast<size_t>(std::min(depth, 12)) * 2, ' ') + (posed ? "* " : "") +
b.name + "##" + std::to_string(i);
if (ImGui::Selectable(label.c_str(), selectedBone_ == static_cast<int>(i))) {
selectedBone_ = static_cast<int>(i);
modelNode_->setSelectedBone(selectedBone_);
}
}
if (shown == 0) ImGui::TextDisabled(*boneFilter_ ? "No bones match the filter." : "No bones to show.");
ImGui::EndChild();
ImGui::End();
}
void App::drawMorphsWindow() {
const Model& m = modelNode_->model();
auto& weights = modelNode_->poser().morphWeights();
ImGuiIO& io = ImGui::GetIO();
ImGui::SetNextWindowPos(ImVec2(io.DisplaySize.x - 330, 35), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(320, io.DisplaySize.y - 45), ImGuiCond_FirstUseEver);
ImGui::Begin("Morphs");
ImGui::SetNextItemWidth(-1);
ImGui::InputTextWithHint("##morphfilter", "Filter morphs", morphFilter_, sizeof(morphFilter_));
if (m.morphs.empty()) ImGui::TextDisabled("This model has no morphs.");
int shown = 0;
for (const auto& morph : m.morphs)
shown += containsCaseInsensitive(morph.name, morphFilter_) || containsCaseInsensitive(morph.nameEn, morphFilter_);
if (!m.morphs.empty() && shown == 0) ImGui::TextDisabled("No morphs match the filter.");
const MorphPanel order[] = {MorphPanel::Eye, MorphPanel::Mouth, MorphPanel::Eyebrow, MorphPanel::Other,
MorphPanel::System};
for (MorphPanel panel : order) {
int count = 0;
for (const auto& morph : m.morphs) count += morph.panel == panel;
if (count == 0) continue;
std::string header = std::string(panelName(panel)) + " (" + std::to_string(count) + ")";
if (!ImGui::CollapsingHeader(header.c_str(), panel != MorphPanel::System ? ImGuiTreeNodeFlags_DefaultOpen : 0))
continue;
for (size_t i = 0; i < m.morphs.size(); ++i) {
const Morph& morph = m.morphs[i];
if (morph.panel != panel) continue;
if (!containsCaseInsensitive(morph.name, morphFilter_) && !containsCaseInsensitive(morph.nameEn, morphFilter_))
continue;
const bool supported = morph.type == MorphType::Vertex || morph.type == MorphType::Group ||
morph.type == MorphType::Bone || morph.type == MorphType::Flip;
ImGui::BeginDisabled(!supported);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.5f);
std::string label = morph.name + "##m" + std::to_string(i);
ImGui::SliderFloat(label.c_str(), &weights[i], 0.f, 1.f, "%.2f");
ImGui::EndDisabled();
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
ImGui::SetTooltip("%s%s", morph.nameEn.empty() ? morph.name.c_str() : morph.nameEn.c_str(),
supported ? "" : " (UV/material morphs are not supported yet)");
}
}
ImGui::End();
}
} // namespace mr
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include "app/FileBrowser.h"
#include "render/ModelNode.h"
#include "ui/ImGuiOsg.h"
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
#include <string>
namespace mr {
class App {
public:
App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulator* manipulator);
bool loadModel(const std::string& path);
ModelNode* modelNode() { return modelNode_.get(); }
void frameModel(float azimuthDeg = 0.f, float elevationDeg = 0.f);
void setShowSkeleton(bool show);
ImGuiOsg* imgui() { return imgui_.get(); }
void drawUi();
private:
void drawMenuBar();
void drawModelWindow();
void drawBonesWindow();
void drawBoneEditor();
void drawMorphsWindow();
void applyViewSettings();
osgViewer::Viewer& viewer_;
osg::ref_ptr<osg::Group> root_;
osg::ref_ptr<osgGA::TrackballManipulator> manipulator_;
osg::ref_ptr<ImGuiOsg> imgui_;
osg::ref_ptr<ModelNode> modelNode_;
FileBrowser fileBrowser_;
std::string loadError_;
bool showSkeleton_ = false;
bool backfaceCulling_ = true;
bool wireframe_ = false;
bool lightFollowsCamera_ = false;
int lightingModel_ = 0;
bool showDemo_ = false;
bool onlyVisibleBones_ = true;
int selectedBone_ = -1;
char boneFilter_[128] = {};
char morphFilter_[128] = {};
float modelRadius_ = 1.f;
};
} // namespace mr
+104
View File
@@ -0,0 +1,104 @@
#include "app/FileBrowser.h"
#include "model/PathUtil.h"
#include <imgui.h>
#include <algorithm>
#include <cstring>
#include <filesystem>
namespace fs = std::filesystem;
namespace mr {
namespace {
bool isModelFile(const std::string& name) {
std::string lower = toLowerAscii(name);
for (const char* ext : {".pmx", ".pmd", ".fbx", ".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;
}
} // namespace
FileBrowser::FileBrowser() {
std::error_code ec;
currentDir_ = pathToUtf8(fs::current_path(ec));
}
void FileBrowser::open() {
openRequested_ = true;
refresh();
}
void FileBrowser::refresh() {
entries_.clear();
error_.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});
}
if (ec) error_ = ec.message();
std::sort(entries_.begin(), entries_.end(), [](const auto& a, const auto& b) {
if (a.second != b.second) return a.second;
return toLowerAscii(a.first) < toLowerAscii(b.first);
});
}
bool FileBrowser::draw() {
if (openRequested_) {
ImGui::OpenPopup("Open model");
openRequested_ = false;
}
bool chosen = false;
ImGui::SetNextWindowSize(ImVec2(640, 460), ImGuiCond_FirstUseEver);
if (ImGui::BeginPopupModal("Open model", nullptr)) {
if (ImGui::Button("Up")) {
currentDir_ = pathToUtf8(pathFromUtf8(currentDir_).parent_path());
refresh();
}
ImGui::SameLine();
ImGui::SetNextItemWidth(-1);
if (ImGui::InputText("##path", pathBuffer_, sizeof(pathBuffer_), ImGuiInputTextFlags_EnterReturnsTrue)) {
std::error_code ec;
fs::path p = pathFromUtf8(pathBuffer_);
if (fs::is_directory(p, ec)) {
currentDir_ = pathBuffer_;
refresh();
} else if (fs::is_regular_file(p, ec)) {
selected_ = pathBuffer_;
chosen = true;
}
}
ImGui::TextDisabled("Supported: .pmx .pmd .fbx (also .obj .gltf .glb .dae)");
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 {
selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name));
chosen = true;
}
}
}
ImGui::EndChild();
if (!enterDir.empty()) {
currentDir_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(enterDir));
refresh();
}
if (ImGui::Button("Cancel") || chosen) ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
return chosen;
}
} // namespace mr
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <string>
#include <vector>
namespace mr {
// Minimal ImGui file picker (ImGui has no native file dialog).
class FileBrowser {
public:
FileBrowser();
void open();
// Draws the popup; returns true when a file was chosen (see selectedPath()).
bool draw();
const std::string& selectedPath() const { return selected_; }
private:
void refresh();
std::string currentDir_;
char pathBuffer_[1024] = {};
std::vector<std::pair<std::string, bool>> entries_; // name, isDirectory
std::string selected_;
std::string error_;
bool openRequested_ = false;
};
} // namespace mr
+152
View File
@@ -0,0 +1,152 @@
#include "app/AppUi.h"
#include <osg/Group>
#include <osgViewer/Viewer>
#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";
}
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;
}
} // namespace
int main(int argc, char** argv) {
std::string modelPath, screenshot;
std::vector<std::pair<std::string, std::string>> morphArgs, boneArgs;
int width = 1280, height = 800, frames = 5;
float azimuth = 0.f, elevation = 0.f, uiScale = 1.f;
bool skeleton = false, hideUi = false;
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 == "--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);
if (!modelPath.empty() && !app.loadModel(modelPath)) std::cerr << "Failed to load " << modelPath << "\n";
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\n";
for (const auto& w : model.warnings) std::cout << " warning: " << w << "\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];
}
app.setShowSkeleton(skeleton);
app.frameModel(azimuth, elevation);
}
app.imgui()->setUiVisible(!hideUi);
if (uiScale != 1.f) app.imgui()->setUiScale(uiScale);
viewer.realize();
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;
}
+290
View File
@@ -0,0 +1,290 @@
#include "model/AssimpLoader.h"
#include "model/PathUtil.h"
#include <assimp/Importer.hpp>
#include <assimp/config.h>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <algorithm>
#include <map>
#include <stdexcept>
namespace mr {
namespace {
// Assimp uses column vectors; OSG uses row vectors, so transpose.
osg::Matrixf toOsg(const aiMatrix4x4& m) {
return osg::Matrixf(m.a1, m.b1, m.c1, m.d1,
m.a2, m.b2, m.c2, m.d2,
m.a3, m.b3, m.c3, m.d3,
m.a4, m.b4, m.c4, m.d4);
}
MorphPanel guessPanel(const std::string& name) {
std::string n = toLowerAscii(name);
auto has = [&](const char* s) { return n.find(s) != std::string::npos; };
if (has("brow")) return MorphPanel::Eyebrow;
if (has("eye") || has("blink") || has("wink")) return MorphPanel::Eye;
if (has("mouth") || has("mth") || has("jaw") || has("lip") || has("viseme") || has("tongue"))
return MorphPanel::Mouth;
return MorphPanel::Other;
}
class AssimpConverter {
public:
AssimpConverter(const aiScene* scene, const std::string& path, Model& model)
: scene_(scene), model_(model), baseDir_(pathFromUtf8(path).parent_path()), sourcePath_(path) {}
void convert() {
model_.format = SourceFormat::Assimp;
model_.sourcePath = sourcePath_;
model_.name = pathToUtf8(pathFromUtf8(sourcePath_).stem());
addNode(scene_->mRootNode, -1);
skinInverseSet_.assign(model_.bones.size(), false);
convertNodeMeshes(scene_->mRootNode);
for (auto& entry : morphOrder_) model_.morphs.push_back(std::move(morphs_[entry]));
model_.normalizeWeights();
}
private:
void addNode(const aiNode* node, int parent) {
int idx = static_cast<int>(model_.bones.size());
nodeIndex_[node] = idx;
Bone b;
b.name = node->mName.C_Str();
if (b.name.empty()) b.name = "node" + std::to_string(idx);
b.parent = parent;
b.localBind = toOsg(node->mTransformation);
osg::Matrixf global = parent >= 0 ? b.localBind * globalBind_[parent] : b.localBind;
b.inverseBind = osg::Matrixf::inverse(global);
b.restPosition = global.getTrans();
b.translatable = true;
model_.bones.push_back(b);
globalBind_.push_back(global);
for (unsigned i = 0; i < node->mNumChildren; ++i) addNode(node->mChildren[i], idx);
}
void convertNodeMeshes(const aiNode* node) {
int nodeIdx = nodeIndex_[node];
for (unsigned i = 0; i < node->mNumMeshes; ++i)
convertMesh(scene_->mMeshes[node->mMeshes[i]], nodeIdx);
for (unsigned i = 0; i < node->mNumChildren; ++i) convertNodeMeshes(node->mChildren[i]);
}
static void addWeight(Vertex& v, int bone, float w) {
int slot = -1;
for (int k = 0; k < 4; ++k) {
if (v.bones[k] == bone) {
v.weights[k] += w;
return;
}
if (v.bones[k] < 0) {
slot = k;
break;
}
}
if (slot < 0) {
slot = static_cast<int>(std::min_element(v.weights, v.weights + 4) - v.weights);
if (v.weights[slot] >= w) return;
}
v.bones[slot] = bone;
v.weights[slot] = w;
}
void convertMesh(const aiMesh* mesh, int nodeIdx) {
if (!(mesh->mPrimitiveTypes & aiPrimitiveType_TRIANGLE)) return;
const osg::Matrixf& meshGlobal = globalBind_[nodeIdx];
const osg::Matrixf meshGlobalInv = osg::Matrixf::inverse(meshGlobal);
const uint32_t base = static_cast<uint32_t>(model_.vertices.size());
for (unsigned i = 0; i < mesh->mNumVertices; ++i) {
Vertex v;
const aiVector3D& p = mesh->mVertices[i];
v.position = osg::Vec3f(p.x, p.y, p.z) * meshGlobal;
if (mesh->HasNormals()) {
const aiVector3D& n = mesh->mNormals[i];
v.normal = osg::Matrixf::transform3x3(meshGlobalInv, osg::Vec3f(n.x, n.y, n.z));
v.normal.normalize();
}
if (mesh->HasTextureCoords(0)) v.uv.set(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y);
model_.vertices.push_back(v);
}
if (mesh->HasBones()) {
for (unsigned bi = 0; bi < mesh->mNumBones; ++bi) {
const aiBone* bone = mesh->mBones[bi];
const aiNode* boneNode = scene_->mRootNode->FindNode(bone->mName);
if (!boneNode) {
model_.warnings.push_back(std::string("Skin bone without node: ") + bone->mName.C_Str());
continue;
}
int boneIdx = nodeIndex_[boneNode];
osg::Matrixf inverseBind = meshGlobalInv * toOsg(bone->mOffsetMatrix);
if (!skinInverseSet_[boneIdx]) {
model_.bones[boneIdx].inverseBind = inverseBind;
skinInverseSet_[boneIdx] = true;
} else if (!inverseBind.isNaN() && !matricesClose(inverseBind, model_.bones[boneIdx].inverseBind)) {
model_.warnings.push_back("Bone '" + model_.bones[boneIdx].name +
"' has different bind poses across meshes");
}
for (unsigned wi = 0; wi < bone->mNumWeights; ++wi) {
const aiVertexWeight& w = bone->mWeights[wi];
if (w.mVertexId < mesh->mNumVertices && w.mWeight > 0.f)
addWeight(model_.vertices[base + w.mVertexId], boneIdx, w.mWeight);
}
}
} else {
// Rigid mesh: attach to its node so posing the node moves it.
for (unsigned i = 0; i < mesh->mNumVertices; ++i) {
Vertex& v = model_.vertices[base + i];
v.bones[0] = nodeIdx;
v.weights[0] = 1.f;
}
}
Material mat = convertMaterial(scene_->mMaterials[mesh->mMaterialIndex]);
mat.indexOffset = static_cast<uint32_t>(model_.indices.size());
for (unsigned f = 0; f < mesh->mNumFaces; ++f) {
const aiFace& face = mesh->mFaces[f];
if (face.mNumIndices != 3) continue;
for (int k = 0; k < 3; ++k) model_.indices.push_back(base + face.mIndices[k]);
}
mat.indexCount = static_cast<uint32_t>(model_.indices.size()) - mat.indexOffset;
if (mat.indexCount > 0) model_.materials.push_back(mat);
for (unsigned a = 0; a < mesh->mNumAnimMeshes; ++a) {
const aiAnimMesh* anim = mesh->mAnimMeshes[a];
if (!anim->mVertices || anim->mNumVertices != mesh->mNumVertices) continue;
std::string name = anim->mName.length > 0 ? anim->mName.C_Str()
: std::string(mesh->mName.C_Str()) + ".shape" + std::to_string(a);
auto it = morphs_.find(name);
if (it == morphs_.end()) {
Morph m;
m.name = name;
m.type = MorphType::Vertex;
m.panel = guessPanel(name);
it = morphs_.emplace(name, std::move(m)).first;
morphOrder_.push_back(name);
}
for (unsigned i = 0; i < mesh->mNumVertices; ++i) {
const aiVector3D d = anim->mVertices[i] - mesh->mVertices[i];
if (d.SquareLength() < 1e-12f) continue;
osg::Vec3f delta = osg::Matrixf::transform3x3(osg::Vec3f(d.x, d.y, d.z), meshGlobal);
it->second.vertexOffsets.push_back({base + i, delta});
}
}
}
static bool matricesClose(const osg::Matrixf& a, const osg::Matrixf& b) {
for (int r = 0; r < 4; ++r)
for (int c = 0; c < 4; ++c)
if (std::abs(a(r, c) - b(r, c)) > 1e-3f * std::max(1.f, std::abs(b(r, c)))) return false;
return true;
}
Material convertMaterial(const aiMaterial* src) {
Material m;
aiString name;
if (src->Get(AI_MATKEY_NAME, name) == AI_SUCCESS) m.name = name.C_Str();
aiColor4D c;
if (src->Get(AI_MATKEY_COLOR_DIFFUSE, c) == AI_SUCCESS) m.diffuse.set(c.r, c.g, c.b, 1.f);
if (src->Get(AI_MATKEY_COLOR_SPECULAR, c) == AI_SUCCESS) m.specular.set(c.r, c.g, c.b);
if (src->Get(AI_MATKEY_COLOR_AMBIENT, c) == AI_SUCCESS) m.ambient.set(c.r, c.g, c.b);
float f = 0.f;
if (src->Get(AI_MATKEY_OPACITY, f) == AI_SUCCESS && f > 0.01f) m.diffuse.a() = std::min(f, 1.f);
if (src->Get(AI_MATKEY_SHININESS, f) == AI_SUCCESS) m.shininess = f;
float strength = 1.f;
if (src->Get(AI_MATKEY_SHININESS_STRENGTH, strength) == AI_SUCCESS) m.specular *= strength;
int twoSided = 0;
if (src->Get(AI_MATKEY_TWOSIDED, twoSided) == AI_SUCCESS) m.doubleSided = twoSided != 0;
aiString texPath;
if (src->GetTexture(aiTextureType_DIFFUSE, 0, &texPath) == AI_SUCCESS ||
src->GetTexture(aiTextureType_BASE_COLOR, 0, &texPath) == AI_SUCCESS) {
m.texture = addTexture(texPath.C_Str());
if (m.texture >= 0 && m.diffuse.x() + m.diffuse.y() + m.diffuse.z() < 0.01f)
m.diffuse.set(1.f, 1.f, 1.f, m.diffuse.a());
}
return m;
}
int addTexture(const std::string& raw) {
if (raw.empty()) return -1;
auto it = textureLookup_.find(raw);
if (it != textureLookup_.end()) return it->second;
Texture t;
if (const aiTexture* embedded = scene_->GetEmbeddedTexture(raw.c_str())) {
if (embedded->mHeight == 0) {
const auto* bytes = reinterpret_cast<const uint8_t*>(embedded->pcData);
t.encodedData.assign(bytes, bytes + embedded->mWidth);
t.formatHint = embedded->achFormatHint;
} else {
t.rawWidth = static_cast<int>(embedded->mWidth);
t.rawHeight = static_cast<int>(embedded->mHeight);
t.rawRGBA.reserve(static_cast<size_t>(t.rawWidth) * t.rawHeight * 4);
for (unsigned i = 0; i < embedded->mWidth * embedded->mHeight; ++i) {
const aiTexel& px = embedded->pcData[i];
t.rawRGBA.insert(t.rawRGBA.end(), {px.r, px.g, px.b, px.a});
}
}
} else {
t.path = findTextureFile(raw);
if (t.path.empty()) {
model_.warnings.push_back("Texture not found: " + raw);
textureLookup_[raw] = -1;
return -1;
}
}
int idx = static_cast<int>(model_.textures.size());
model_.textures.push_back(std::move(t));
textureLookup_[raw] = idx;
return idx;
}
// FBX files often store absolute paths from the author's machine; fall back to the file name.
std::string findTextureFile(const std::string& raw) {
std::string normalized = raw;
std::replace(normalized.begin(), normalized.end(), '\\', '/');
std::string resolved = resolveRelativePath(baseDir_, normalized);
if (!resolved.empty()) return resolved;
std::string fileName = normalized.substr(normalized.find_last_of('/') + 1);
const std::string stem = pathToUtf8(pathFromUtf8(sourcePath_).stem());
for (const std::string& dir : {std::string("."), std::string("textures"), std::string("Textures"),
std::string("texture"), stem + ".fbm"}) {
resolved = resolveRelativePath(baseDir_, dir + "/" + fileName);
if (!resolved.empty()) return resolved;
}
return {};
}
const aiScene* scene_;
Model& model_;
std::filesystem::path baseDir_;
std::string sourcePath_;
std::map<const aiNode*, int> nodeIndex_;
std::vector<osg::Matrixf> globalBind_;
std::vector<bool> skinInverseSet_;
std::map<std::string, int> textureLookup_;
std::map<std::string, Morph> morphs_;
std::vector<std::string> morphOrder_;
};
} // namespace
void loadWithAssimp(const std::string& path, Model& model) {
Assimp::Importer importer;
importer.SetPropertyBool(AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS, false);
importer.SetPropertyInteger(AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4);
const unsigned flags = aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_GenSmoothNormals |
aiProcess_LimitBoneWeights | aiProcess_SortByPType | aiProcess_ValidateDataStructure;
const aiScene* scene = importer.ReadFile(path, flags);
if (!scene || !scene->mRootNode || (scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE))
throw std::runtime_error(std::string("Assimp: ") + importer.GetErrorString());
AssimpConverter(scene, path, model).convert();
}
} // namespace mr
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include "model/Model.h"
#include <string>
namespace mr {
// Loads FBX (and any other Assimp-supported format). Throws std::runtime_error on failure.
void loadWithAssimp(const std::string& path, Model& model);
} // namespace mr
+101
View File
@@ -0,0 +1,101 @@
#pragma once
#include <osg/Quat>
#include <osg/Vec2f>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#include <string>
#include <vector>
namespace mr {
// Little-endian reader over an in-memory file. Throws std::runtime_error on overrun.
class BinaryReader {
public:
explicit BinaryReader(const std::vector<uint8_t>& data) : data_(data) {}
size_t position() const { return pos_; }
size_t remaining() const { return data_.size() - pos_; }
bool atEnd() const { return pos_ >= data_.size(); }
void skip(size_t n) {
require(n);
pos_ += n;
}
const uint8_t* bytes(size_t n) {
require(n);
const uint8_t* p = data_.data() + pos_;
pos_ += n;
return p;
}
template <typename T>
T read() {
T value;
std::memcpy(&value, bytes(sizeof(T)), sizeof(T));
return value;
}
uint8_t u8() { return read<uint8_t>(); }
int8_t i8() { return read<int8_t>(); }
uint16_t u16() { return read<uint16_t>(); }
int16_t i16() { return read<int16_t>(); }
uint32_t u32() { return read<uint32_t>(); }
int32_t i32() { return read<int32_t>(); }
float f32() { return read<float>(); }
osg::Vec2f vec2() {
float x = f32(), y = f32();
return {x, y};
}
osg::Vec3f vec3() {
float x = f32(), y = f32(), z = f32();
return {x, y, z};
}
osg::Vec4f vec4() {
float x = f32(), y = f32(), z = f32(), w = f32();
return {x, y, z, w};
}
// Signed index of 1, 2 or 4 bytes (PMX bone/texture/material/morph indices).
int32_t signedIndex(int size) {
switch (size) {
case 1: return i8();
case 2: return i16();
case 4: return i32();
default: throw std::runtime_error("invalid index size");
}
}
// Unsigned index of 1 or 2 bytes, signed for 4 bytes (PMX vertex indices).
int64_t vertexIndex(int size) {
switch (size) {
case 1: return u8();
case 2: return u16();
case 4: return i32();
default: throw std::runtime_error("invalid vertex index size");
}
}
std::string fixedString(size_t n) {
const uint8_t* p = bytes(n);
size_t len = 0;
while (len < n && p[len] != 0) ++len;
return std::string(reinterpret_cast<const char*>(p), len);
}
private:
void require(size_t n) const {
if (n > data_.size() - pos_) throw std::runtime_error("unexpected end of file");
}
const std::vector<uint8_t>& data_;
size_t pos_ = 0;
};
} // namespace mr
+64
View File
@@ -0,0 +1,64 @@
#include "model/Model.h"
#include <algorithm>
#include <limits>
namespace mr {
int Model::findBone(const std::string& boneName) const {
for (size_t i = 0; i < bones.size(); ++i)
if (bones[i].name == boneName || (!bones[i].nameEn.empty() && bones[i].nameEn == boneName))
return static_cast<int>(i);
return -1;
}
int Model::findMorph(const std::string& morphName) const {
for (size_t i = 0; i < morphs.size(); ++i)
if (morphs[i].name == morphName || (!morphs[i].nameEn.empty() && morphs[i].nameEn == morphName))
return static_cast<int>(i);
return -1;
}
void Model::computeBounds(osg::Vec3f& minOut, osg::Vec3f& maxOut) const {
const float inf = std::numeric_limits<float>::max();
minOut.set(inf, inf, inf);
maxOut.set(-inf, -inf, -inf);
for (const auto& v : vertices) {
for (int k = 0; k < 3; ++k) {
minOut[k] = std::min(minOut[k], v.position[k]);
maxOut[k] = std::max(maxOut[k], v.position[k]);
}
}
if (vertices.empty()) {
minOut.set(-1, -1, -1);
maxOut.set(1, 1, 1);
}
}
void Model::normalizeWeights() {
const int boneCount = static_cast<int>(bones.size());
for (auto& v : vertices) {
// Merge duplicate bones and drop invalid/zero entries, keeping valid influences at the front.
int outBones[4] = {-1, -1, -1, -1};
float outWeights[4] = {0.f, 0.f, 0.f, 0.f};
int count = 0;
float sum = 0.f;
for (int k = 0; k < 4; ++k) {
const int b = v.bones[k];
const float w = v.weights[k];
if (b < 0 || b >= boneCount || !(w > 0.f)) continue;
int slot = 0;
while (slot < count && outBones[slot] != b) ++slot;
if (slot == count) outBones[count++] = b;
outWeights[slot] += w;
sum += w;
}
for (int k = 0; k < 4; ++k) {
v.bones[k] = outBones[k];
v.weights[k] = sum > 0.f ? outWeights[k] / sum : 0.f;
if (outBones[k] >= 0) bones[outBones[k]].isSkinBone = true;
}
}
}
} // namespace mr
+128
View File
@@ -0,0 +1,128 @@
#pragma once
#include <osg/Matrixf>
#include <osg/Quat>
#include <osg/Vec2f>
#include <osg/Vec3f>
#include <osg/Vec4f>
#include <cstdint>
#include <string>
#include <vector>
namespace mr {
// Internal model representation shared by every loader.
// Coordinate system: right-handed, +Y up, model faces +Z.
// Matrices follow the OSG row-vector convention (v' = v * M, child * parent).
enum class SourceFormat { PMX, PMD, Assimp };
struct Vertex {
osg::Vec3f position;
osg::Vec3f normal;
osg::Vec2f uv; // OpenGL convention: (0,0) is the bottom-left of the image
int32_t bones[4] = {-1, -1, -1, -1};
float weights[4] = {0.f, 0.f, 0.f, 0.f};
};
enum class SphereMode { None, Multiply, Add, SubTexture };
struct Texture {
std::string path; // resolved absolute path (UTF-8), empty if embedded
std::vector<uint8_t> encodedData; // embedded compressed image (png/jpg/...)
std::string formatHint; // extension hint for encodedData
int rawWidth = 0, rawHeight = 0; // embedded uncompressed RGBA8 when > 0
std::vector<uint8_t> rawRGBA;
};
struct Material {
std::string name;
osg::Vec4f diffuse{1.f, 1.f, 1.f, 1.f};
osg::Vec3f specular{0.f, 0.f, 0.f};
float shininess = 0.f;
osg::Vec3f ambient{0.f, 0.f, 0.f};
int texture = -1; // index into Model::textures
int sphereTexture = -1;
SphereMode sphereMode = SphereMode::None;
int toonTexture = -1; // model-provided toon texture
int sharedToon = -1; // built-in MMD toon (0..9) when toonTexture < 0
bool doubleSided = false;
bool drawEdge = false;
osg::Vec4f edgeColor{0.f, 0.f, 0.f, 1.f};
float edgeSize = 1.f;
uint32_t indexOffset = 0; // into Model::indices
uint32_t indexCount = 0;
};
struct Bone {
std::string name;
std::string nameEn;
int parent = -1;
osg::Matrixf localBind; // rest transform relative to parent
osg::Matrixf inverseBind; // model space -> bone space at rest
osg::Vec3f restPosition; // bone head in model space at rest
bool rotatable = true;
bool translatable = false;
bool visible = true;
bool isSkinBone = false; // influences at least one vertex
int inheritParent = -1; // MMD "append" (付与) source bone
float inheritWeight = 0.f;
bool inheritRotation = false;
bool inheritTranslation = false;
bool isIK = false;
int layer = 0;
bool afterPhysics = false;
};
enum class MorphType { Group, Vertex, Bone, UV, Material, Flip, Impulse };
// MMD morph panel: 0 = system/hidden, 1 = eyebrow, 2 = eye, 3 = mouth, 4 = other
enum class MorphPanel { System = 0, Eyebrow = 1, Eye = 2, Mouth = 3, Other = 4 };
struct VertexMorphOffset {
uint32_t vertex;
osg::Vec3f offset;
};
struct GroupMorphOffset {
int morph;
float weight;
};
struct BoneMorphOffset {
int bone;
osg::Vec3f translation;
osg::Quat rotation;
};
struct Morph {
std::string name;
std::string nameEn;
MorphPanel panel = MorphPanel::Other;
MorphType type = MorphType::Vertex;
std::vector<VertexMorphOffset> vertexOffsets;
std::vector<GroupMorphOffset> groupOffsets; // Group and Flip
std::vector<BoneMorphOffset> boneOffsets;
};
struct Model {
SourceFormat format = SourceFormat::Assimp;
std::string sourcePath;
std::string name;
std::string comment;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices; // triangles, counter-clockwise front faces
std::vector<Texture> textures;
std::vector<Material> materials;
std::vector<Bone> bones;
std::vector<Morph> morphs;
std::vector<std::string> warnings;
int findBone(const std::string& boneName) const;
int findMorph(const std::string& morphName) const;
void computeBounds(osg::Vec3f& minOut, osg::Vec3f& maxOut) const;
void normalizeWeights();
};
} // namespace mr
+40
View File
@@ -0,0 +1,40 @@
#include "model/ModelLoader.h"
#include "model/AssimpLoader.h"
#include "model/PathUtil.h"
#include "model/PmdLoader.h"
#include "model/PmxLoader.h"
#include <exception>
namespace mr {
std::shared_ptr<Model> loadModel(const std::string& utf8Path, std::string& error) {
auto model = std::make_shared<Model>();
try {
std::vector<uint8_t> data;
if (!readFileBytes(utf8Path, data)) {
error = "Cannot read file: " + utf8Path;
return nullptr;
}
if (data.size() >= 4 && data[0] == 'P' && data[1] == 'M' && data[2] == 'X' && data[3] == ' ') {
loadPmx(data, utf8Path, *model);
} else if (data.size() >= 3 && data[0] == 'P' && data[1] == 'm' && data[2] == 'd') {
loadPmd(data, utf8Path, *model);
} else {
data.clear();
data.shrink_to_fit();
loadWithAssimp(utf8Path, *model);
}
} catch (const std::exception& e) {
error = e.what();
return nullptr;
}
if (model->vertices.empty() || model->indices.empty()) {
error = "Model contains no triangles";
return nullptr;
}
return model;
}
} // namespace mr
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "model/Model.h"
#include <memory>
#include <string>
namespace mr {
// Detects the format (PMX, PMD or anything Assimp reads, e.g. FBX) and loads it.
// Returns nullptr and fills `error` on failure.
std::shared_ptr<Model> loadModel(const std::string& utf8Path, std::string& error);
} // namespace mr
+95
View File
@@ -0,0 +1,95 @@
#include "model/PathUtil.h"
#include <algorithm>
#include <fstream>
#include <system_error>
namespace fs = std::filesystem;
namespace mr {
fs::path pathFromUtf8(const std::string& utf8) {
#if defined(__cpp_char8_t)
return fs::path(std::u8string(utf8.begin(), utf8.end()));
#else
return fs::u8path(utf8);
#endif
}
std::string pathToUtf8(const fs::path& p) {
#if defined(__cpp_char8_t)
auto u8 = p.u8string();
return std::string(u8.begin(), u8.end());
#else
return p.u8string();
#endif
}
std::string toLowerAscii(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
return static_cast<char>((c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c);
});
return s;
}
std::string resolveRelativePath(const fs::path& baseDir, const std::string& relative) {
if (relative.empty()) return {};
std::string rel = relative;
std::replace(rel.begin(), rel.end(), '\\', '/');
std::error_code ec;
fs::path direct = pathFromUtf8(rel);
if (direct.is_relative()) direct = baseDir / direct;
if (fs::is_regular_file(direct, ec)) return pathToUtf8(direct.lexically_normal());
// Case-insensitive walk, component by component.
fs::path current = baseDir;
size_t start = 0;
while (start <= rel.size()) {
size_t end = rel.find('/', start);
if (end == std::string::npos) end = rel.size();
std::string part = rel.substr(start, end - start);
start = end + 1;
if (part.empty() || part == ".") {
if (end == rel.size()) break;
continue;
}
if (part == "..") {
current = current.parent_path();
if (end == rel.size()) break;
continue;
}
fs::path exact = current / pathFromUtf8(part);
if (fs::exists(exact, ec)) {
current = exact;
} else {
std::string lowered = toLowerAscii(part);
bool found = false;
for (const auto& entry : fs::directory_iterator(current, ec)) {
if (toLowerAscii(pathToUtf8(entry.path().filename())) == lowered) {
current = entry.path();
found = true;
break;
}
}
if (!found) return {};
}
if (end == rel.size()) break;
}
if (fs::is_regular_file(current, ec)) return pathToUtf8(current.lexically_normal());
return {};
}
bool readFileBytes(const std::string& utf8Path, std::vector<uint8_t>& out) {
std::ifstream in(pathFromUtf8(utf8Path), std::ios::binary);
if (!in) return false;
in.seekg(0, std::ios::end);
std::streamoff size = in.tellg();
if (size < 0) return false;
in.seekg(0, std::ios::beg);
out.resize(static_cast<size_t>(size));
if (size > 0) in.read(reinterpret_cast<char*>(out.data()), size);
return static_cast<bool>(in) || in.eof();
}
} // namespace mr
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include <cstdint>
#include <filesystem>
#include <string>
#include <vector>
namespace mr {
std::filesystem::path pathFromUtf8(const std::string& utf8);
std::string pathToUtf8(const std::filesystem::path& p);
// Resolves a texture path written inside a model file (may use backslashes and
// differ in letter case from the file on disk). Returns empty string if missing.
std::string resolveRelativePath(const std::filesystem::path& baseDir, const std::string& relative);
bool readFileBytes(const std::string& utf8Path, std::vector<uint8_t>& out);
std::string toLowerAscii(std::string s);
} // namespace mr
+269
View File
@@ -0,0 +1,269 @@
#include "model/PmdLoader.h"
#include "model/BinaryReader.h"
#include "model/PathUtil.h"
#include "model/TextEncoding.h"
#include <map>
#include <stdexcept>
namespace mr {
namespace {
osg::Vec3f toRH(const osg::Vec3f& v) { return {v.x(), v.y(), -v.z()}; }
std::string sjis(BinaryReader& r, size_t n) { return shiftJisToUtf8(r.fixedString(n)); }
class PmdParser {
public:
PmdParser(const std::vector<uint8_t>& data, Model& model) : r_(data), model_(model) {}
void parse(const std::string& sourcePath) {
baseDir_ = pathFromUtf8(sourcePath).parent_path();
const uint8_t* magic = r_.bytes(3);
if (!(magic[0] == 'P' && magic[1] == 'm' && magic[2] == 'd')) throw std::runtime_error("not a PMD file");
r_.f32(); // version
model_.format = SourceFormat::PMD;
model_.sourcePath = sourcePath;
model_.name = sjis(r_, 20);
model_.comment = sjis(r_, 256);
parseVertices();
parseFaces();
parseMaterials();
parseBones();
parseIK();
parseMorphs();
parseOptionalSections();
resolveToons();
model_.normalizeWeights();
}
private:
void parseVertices() {
uint32_t count = r_.u32();
if (static_cast<size_t>(count) * 38 > r_.remaining()) throw std::runtime_error("invalid PMD vertex count");
model_.vertices.resize(count);
for (auto& v : model_.vertices) {
v.position = toRH(r_.vec3());
v.normal = toRH(r_.vec3());
osg::Vec2f uv = r_.vec2();
v.uv.set(uv.x(), 1.0f - uv.y());
v.bones[0] = r_.u16();
v.bones[1] = r_.u16();
float w = r_.u8() / 100.0f;
v.weights[0] = w;
v.weights[1] = 1.0f - w;
r_.u8(); // edge flag
}
}
void parseFaces() {
uint32_t count = r_.u32();
if (count % 3 != 0 || static_cast<size_t>(count) * 2 > r_.remaining())
throw std::runtime_error("invalid PMD face count");
model_.indices.resize(count);
for (uint32_t i = 0; i < count; i += 3) {
uint32_t a = r_.u16(), b = r_.u16(), c = r_.u16();
if (a >= model_.vertices.size() || b >= model_.vertices.size() || c >= model_.vertices.size())
throw std::runtime_error("PMD face index out of range");
model_.indices[i] = a;
model_.indices[i + 1] = c;
model_.indices[i + 2] = b;
}
}
int addTexture(const std::string& raw) {
auto it = textureLookup_.find(raw);
if (it != textureLookup_.end()) return it->second;
Texture t;
t.path = resolveRelativePath(baseDir_, raw);
if (t.path.empty()) {
model_.warnings.push_back("Texture not found: " + raw);
t.path = pathToUtf8(baseDir_ / pathFromUtf8(raw));
}
int idx = static_cast<int>(model_.textures.size());
model_.textures.push_back(std::move(t));
textureLookup_[raw] = idx;
return idx;
}
void parseMaterials() {
uint32_t count = r_.u32();
if (static_cast<size_t>(count) * 70 > r_.remaining()) throw std::runtime_error("invalid PMD material count");
model_.materials.resize(count);
toonIndices_.resize(count, -1);
uint32_t offset = 0;
for (uint32_t i = 0; i < count; ++i) {
Material& m = model_.materials[i];
m.name = "material" + std::to_string(i);
m.diffuse = r_.vec4();
m.shininess = r_.f32();
m.specular = r_.vec3();
m.ambient = r_.vec3();
int toon = r_.u8();
toonIndices_[i] = toon < 10 ? toon : -1;
m.drawEdge = r_.u8() != 0;
m.doubleSided = m.diffuse.a() < 1.0f; // MMD disables culling for translucent PMD materials
uint32_t indexCount = r_.u32();
if (static_cast<size_t>(offset) + indexCount > model_.indices.size())
throw std::runtime_error("PMD material index range out of bounds");
m.indexOffset = offset;
m.indexCount = indexCount;
offset += indexCount;
std::string tex = sjis(r_, 20);
std::string main = tex, sphere;
size_t star = tex.find('*');
if (star != std::string::npos) {
main = tex.substr(0, star);
sphere = tex.substr(star + 1);
} else {
std::string ext = toLowerAscii(tex.size() >= 4 ? tex.substr(tex.size() - 4) : "");
if (ext == ".sph" || ext == ".spa") {
sphere = tex;
main.clear();
}
}
if (!main.empty()) m.texture = addTexture(main);
if (!sphere.empty()) {
m.sphereTexture = addTexture(sphere);
std::string ext = toLowerAscii(sphere.size() >= 4 ? sphere.substr(sphere.size() - 4) : "");
m.sphereMode = ext == ".spa" ? SphereMode::Add : SphereMode::Multiply;
}
}
}
void parseBones() {
uint16_t count = r_.u16();
model_.bones.resize(count);
for (auto& b : model_.bones) {
b.name = sjis(r_, 20);
uint16_t parent = r_.u16();
uint16_t tail = r_.u16();
uint8_t type = r_.u8();
uint16_t ikParent = r_.u16();
b.restPosition = toRH(r_.vec3());
b.parent = parent == 0xFFFF ? -1 : parent;
b.translatable = type == 1 || type == 2;
b.isIK = type == 2;
b.visible = type != 7 && type != 4 && type != 6;
if (type == 5 && ikParent != 0xFFFF) { // rotation influenced by another bone
b.inheritParent = ikParent;
b.inheritWeight = 1.0f;
b.inheritRotation = true;
} else if (type == 9 && tail != 0xFFFF && ikParent <= 100) {
// Rotation linked: follows the tail bone's rotation by (ik field)%.
b.inheritParent = tail;
b.inheritWeight = ikParent / 100.0f;
b.inheritRotation = true;
}
}
const int n = static_cast<int>(model_.bones.size());
for (int i = 0; i < n; ++i) {
Bone& b = model_.bones[i];
if (b.parent >= n || b.parent == i) b.parent = -1;
if (b.inheritParent >= n || b.inheritParent == i) {
b.inheritParent = -1;
b.inheritRotation = false;
}
osg::Vec3f parentPos = b.parent >= 0 ? model_.bones[b.parent].restPosition : osg::Vec3f();
b.localBind = osg::Matrixf::translate(b.restPosition - parentPos);
b.inverseBind = osg::Matrixf::translate(-b.restPosition);
}
}
void parseIK() {
uint16_t count = r_.u16();
for (uint16_t i = 0; i < count; ++i) {
r_.u16(); // IK bone
r_.u16(); // target
uint8_t chain = r_.u8();
r_.u16(); // iterations
r_.f32(); // limit
r_.skip(2u * chain);
}
}
void parseMorphs() {
uint16_t count = r_.u16();
std::vector<uint32_t> baseIndices;
for (uint16_t i = 0; i < count; ++i) {
std::string name = sjis(r_, 20);
uint32_t vertexCount = r_.u32();
uint8_t type = r_.u8();
if (static_cast<size_t>(vertexCount) * 16 > r_.remaining()) throw std::runtime_error("invalid PMD morph");
if (type == 0) { // base morph: list of affected vertices
baseIndices.resize(vertexCount);
for (uint32_t k = 0; k < vertexCount; ++k) {
baseIndices[k] = r_.u32();
r_.vec3();
}
continue;
}
Morph m;
m.name = name;
m.type = MorphType::Vertex;
m.panel = type <= 4 ? static_cast<MorphPanel>(type) : MorphPanel::Other;
for (uint32_t k = 0; k < vertexCount; ++k) {
uint32_t idx = r_.u32();
osg::Vec3f d = toRH(r_.vec3());
if (idx < baseIndices.size() && baseIndices[idx] < model_.vertices.size())
m.vertexOffsets.push_back({baseIndices[idx], d});
}
model_.morphs.push_back(std::move(m));
}
}
void parseOptionalSections() {
// Display lists, English names and custom toon names are optional; ignore truncation.
try {
uint8_t morphDisplayCount = r_.u8();
r_.skip(2u * morphDisplayCount);
uint8_t boneFrameCount = r_.u8();
r_.skip(50u * boneFrameCount);
uint32_t boneDisplayCount = r_.u32();
r_.skip(3u * boneDisplayCount);
if (r_.atEnd()) return;
if (r_.u8() == 1) { // English names
r_.skip(20 + 256);
for (auto& b : model_.bones) b.nameEn = r_.fixedString(20);
for (auto& m : model_.morphs) m.nameEn = r_.fixedString(20);
r_.skip(50u * boneFrameCount);
}
if (r_.remaining() >= 1000) {
for (int i = 0; i < 10; ++i) toonNames_[i] = sjis(r_, 100);
}
} catch (const std::runtime_error&) {
model_.warnings.push_back("PMD optional sections are truncated");
}
}
void resolveToons() {
for (size_t i = 0; i < model_.materials.size(); ++i) {
int toon = toonIndices_[i];
if (toon < 0) continue;
std::string name = toonNames_[toon];
if (name.empty()) name = (toon < 9 ? "toon0" : "toon") + std::to_string(toon + 1) + ".bmp";
std::string resolved = resolveRelativePath(baseDir_, name);
if (!resolved.empty()) model_.materials[i].toonTexture = addTexture(name);
else model_.materials[i].sharedToon = toon;
}
}
BinaryReader r_;
Model& model_;
std::filesystem::path baseDir_;
std::map<std::string, int> textureLookup_;
std::vector<int> toonIndices_;
std::string toonNames_[10];
};
} // namespace
void loadPmd(const std::vector<uint8_t>& data, const std::string& sourcePath, Model& model) {
PmdParser(data, model).parse(sourcePath);
}
} // namespace mr
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "model/Model.h"
#include <cstdint>
#include <string>
#include <vector>
namespace mr {
// Parses PMD 1.0 data. Throws std::runtime_error on malformed input.
void loadPmd(const std::vector<uint8_t>& data, const std::string& sourcePath, Model& model);
} // namespace mr
+337
View File
@@ -0,0 +1,337 @@
#include "model/PmxLoader.h"
#include "model/BinaryReader.h"
#include "model/PathUtil.h"
#include "model/TextEncoding.h"
#include <algorithm>
#include <stdexcept>
namespace mr {
namespace {
// PMX is left-handed (D3D). Mirroring Z converts it to our right-handed space.
osg::Vec3f toRH(const osg::Vec3f& v) { return {v.x(), v.y(), -v.z()}; }
osg::Quat toRH(const osg::Quat& q) { return osg::Quat(-q.x(), -q.y(), q.z(), q.w()); }
struct PmxHeader {
float version = 2.0f;
int encoding = 0; // 0 = UTF-16LE, 1 = UTF-8
int additionalUV = 0;
int vertexIndexSize = 4;
int textureIndexSize = 4;
int materialIndexSize = 4;
int boneIndexSize = 4;
int morphIndexSize = 4;
int rigidBodyIndexSize = 4;
};
class PmxParser {
public:
PmxParser(const std::vector<uint8_t>& data, Model& model) : r_(data), model_(model) {}
void parse(const std::string& sourcePath) {
parseHeader();
model_.format = SourceFormat::PMX;
model_.sourcePath = sourcePath;
model_.name = text();
text(); // English name
model_.comment = text();
text(); // English comment
parseVertices();
parseFaces();
parseTextures(pathFromUtf8(sourcePath).parent_path());
parseMaterials();
parseBones();
parseMorphs();
// Display frames, rigid bodies and joints are not needed for rendering/posing.
model_.normalizeWeights();
}
private:
std::string text() {
int32_t len = r_.i32();
if (len < 0) throw std::runtime_error("negative string length");
const char* p = reinterpret_cast<const char*>(r_.bytes(static_cast<size_t>(len)));
if (h_.encoding == 0) return utf16leToUtf8(p, static_cast<size_t>(len));
return std::string(p, static_cast<size_t>(len));
}
int boneIndex() { return r_.signedIndex(h_.boneIndexSize); }
void parseHeader() {
const uint8_t* magic = r_.bytes(4);
if (!(magic[0] == 'P' && magic[1] == 'M' && magic[2] == 'X' && magic[3] == ' '))
throw std::runtime_error("not a PMX file");
h_.version = r_.f32();
int count = r_.u8();
if (count < 8) throw std::runtime_error("PMX header too short");
const uint8_t* g = r_.bytes(static_cast<size_t>(count));
h_.encoding = g[0];
h_.additionalUV = g[1];
h_.vertexIndexSize = g[2];
h_.textureIndexSize = g[3];
h_.materialIndexSize = g[4];
h_.boneIndexSize = g[5];
h_.morphIndexSize = g[6];
h_.rigidBodyIndexSize = g[7];
if (h_.additionalUV > 4) throw std::runtime_error("invalid PMX additional UV count");
}
void parseVertices() {
int32_t count = r_.i32();
if (count < 0) throw std::runtime_error("invalid vertex count");
model_.vertices.resize(static_cast<size_t>(count));
for (auto& v : model_.vertices) {
v.position = toRH(r_.vec3());
v.normal = toRH(r_.vec3());
osg::Vec2f uv = r_.vec2();
v.uv.set(uv.x(), 1.0f - uv.y());
r_.skip(16u * static_cast<size_t>(h_.additionalUV));
int type = r_.u8();
switch (type) {
case 0: // BDEF1
v.bones[0] = boneIndex();
v.weights[0] = 1.f;
break;
case 1: // BDEF2
case 3: // SDEF (approximated as BDEF2)
v.bones[0] = boneIndex();
v.bones[1] = boneIndex();
v.weights[0] = r_.f32();
v.weights[1] = 1.f - v.weights[0];
if (type == 3) r_.skip(36); // C, R0, R1
break;
case 2: // BDEF4
case 4: // QDEF (approximated as BDEF4)
for (int k = 0; k < 4; ++k) v.bones[k] = boneIndex();
for (int k = 0; k < 4; ++k) v.weights[k] = r_.f32();
break;
default: throw std::runtime_error("unknown PMX weight type");
}
r_.f32(); // edge scale
}
}
void parseFaces() {
int32_t count = r_.i32();
if (count < 0 || count % 3 != 0) throw std::runtime_error("invalid PMX face count");
model_.indices.resize(static_cast<size_t>(count));
const int64_t vertexCount = static_cast<int64_t>(model_.vertices.size());
for (int32_t i = 0; i < count; i += 3) {
int64_t a = r_.vertexIndex(h_.vertexIndexSize);
int64_t b = r_.vertexIndex(h_.vertexIndexSize);
int64_t c = r_.vertexIndex(h_.vertexIndexSize);
if (a < 0 || b < 0 || c < 0 || a >= vertexCount || b >= vertexCount || c >= vertexCount)
throw std::runtime_error("PMX face index out of range");
// Mirroring Z flips the winding; PMX front faces are clockwise in D3D.
model_.indices[i] = static_cast<uint32_t>(a);
model_.indices[i + 1] = static_cast<uint32_t>(c);
model_.indices[i + 2] = static_cast<uint32_t>(b);
}
}
void parseTextures(const std::filesystem::path& baseDir) {
int32_t count = r_.i32();
if (count < 0) throw std::runtime_error("invalid texture count");
model_.textures.resize(static_cast<size_t>(count));
for (auto& t : model_.textures) {
std::string raw = text();
t.path = resolveRelativePath(baseDir, raw);
if (t.path.empty()) {
model_.warnings.push_back("Texture not found: " + raw);
t.path = pathToUtf8(baseDir / pathFromUtf8(raw));
}
}
}
int textureIndex() {
int idx = r_.signedIndex(h_.textureIndexSize);
return (idx >= 0 && idx < static_cast<int>(model_.textures.size())) ? idx : -1;
}
void parseMaterials() {
int32_t count = r_.i32();
if (count < 0) throw std::runtime_error("invalid material count");
uint32_t offset = 0;
model_.materials.resize(static_cast<size_t>(count));
for (auto& m : model_.materials) {
m.name = text();
text(); // English name
m.diffuse = r_.vec4();
m.specular = r_.vec3();
m.shininess = r_.f32();
m.ambient = r_.vec3();
uint8_t flags = r_.u8();
m.doubleSided = (flags & 0x01) != 0;
m.drawEdge = (flags & 0x10) != 0;
m.edgeColor = r_.vec4();
m.edgeSize = r_.f32();
m.texture = textureIndex();
m.sphereTexture = textureIndex();
int sphereMode = r_.u8();
m.sphereMode = sphereMode == 1 ? SphereMode::Multiply
: sphereMode == 2 ? SphereMode::Add
: sphereMode == 3 ? SphereMode::SubTexture
: SphereMode::None;
if (m.sphereTexture < 0) m.sphereMode = SphereMode::None;
int sharedToonFlag = r_.u8();
if (sharedToonFlag == 0) {
m.toonTexture = textureIndex();
} else {
int toon = r_.u8();
m.sharedToon = (toon <= 9) ? toon : -1;
}
text(); // memo
int32_t indexCount = r_.i32();
if (indexCount < 0 || static_cast<size_t>(offset) + indexCount > model_.indices.size())
throw std::runtime_error("PMX material index range out of bounds");
m.indexOffset = offset;
m.indexCount = static_cast<uint32_t>(indexCount);
offset += static_cast<uint32_t>(indexCount);
}
}
void parseBones() {
int32_t count = r_.i32();
if (count < 0) throw std::runtime_error("invalid bone count");
model_.bones.resize(static_cast<size_t>(count));
for (auto& b : model_.bones) {
b.name = text();
b.nameEn = text();
b.restPosition = toRH(r_.vec3());
b.parent = boneIndex();
b.layer = r_.i32();
uint16_t flags = r_.u16();
b.rotatable = (flags & 0x0002) != 0;
b.translatable = (flags & 0x0004) != 0;
b.visible = (flags & 0x0008) != 0;
b.isIK = (flags & 0x0020) != 0;
b.inheritRotation = (flags & 0x0100) != 0;
b.inheritTranslation = (flags & 0x0200) != 0;
b.afterPhysics = (flags & 0x1000) != 0;
if (flags & 0x0001) boneIndex(); // tail bone
else r_.vec3(); // tail offset
if (flags & (0x0100 | 0x0200)) {
b.inheritParent = boneIndex();
b.inheritWeight = r_.f32();
}
if (flags & 0x0400) r_.vec3(); // fixed axis
if (flags & 0x0800) { // local axes
r_.vec3();
r_.vec3();
}
if (flags & 0x2000) r_.i32(); // external parent key
if (flags & 0x0020) {
boneIndex(); // IK target
r_.i32(); // loop count
r_.f32(); // limit angle
int32_t links = r_.i32();
if (links < 0) throw std::runtime_error("invalid IK link count");
for (int32_t i = 0; i < links; ++i) {
boneIndex();
if (r_.u8()) {
r_.vec3();
r_.vec3();
}
}
}
}
const int n = static_cast<int>(model_.bones.size());
for (int i = 0; i < n; ++i) {
Bone& b = model_.bones[i];
if (b.parent < 0 || b.parent >= n || b.parent == i) b.parent = -1;
if (b.inheritParent < 0 || b.inheritParent >= n || b.inheritParent == i) {
b.inheritParent = -1;
b.inheritRotation = b.inheritTranslation = false;
}
osg::Vec3f parentPos = b.parent >= 0 ? model_.bones[b.parent].restPosition : osg::Vec3f();
b.localBind = osg::Matrixf::translate(b.restPosition - parentPos);
b.inverseBind = osg::Matrixf::translate(-b.restPosition);
}
}
void parseMorphs() {
int32_t count = r_.i32();
if (count < 0) throw std::runtime_error("invalid morph count");
model_.morphs.resize(static_cast<size_t>(count));
const auto vertexCount = static_cast<int64_t>(model_.vertices.size());
for (auto& m : model_.morphs) {
m.name = text();
m.nameEn = text();
int panel = r_.u8();
m.panel = (panel >= 0 && panel <= 4) ? static_cast<MorphPanel>(panel) : MorphPanel::Other;
int type = r_.u8();
int32_t offsets = r_.i32();
if (offsets < 0) throw std::runtime_error("invalid morph offset count");
switch (type) {
case 0: // group
case 9: // flip
m.type = type == 0 ? MorphType::Group : MorphType::Flip;
for (int32_t i = 0; i < offsets; ++i) {
int idx = r_.signedIndex(h_.morphIndexSize);
float w = r_.f32();
if (idx >= 0 && idx < count) m.groupOffsets.push_back({idx, w});
}
break;
case 1: // vertex
m.type = MorphType::Vertex;
m.vertexOffsets.reserve(static_cast<size_t>(offsets));
for (int32_t i = 0; i < offsets; ++i) {
int64_t idx = r_.vertexIndex(h_.vertexIndexSize);
osg::Vec3f d = toRH(r_.vec3());
if (idx >= 0 && idx < vertexCount)
m.vertexOffsets.push_back({static_cast<uint32_t>(idx), d});
}
break;
case 2: // bone
m.type = MorphType::Bone;
for (int32_t i = 0; i < offsets; ++i) {
int idx = boneIndex();
osg::Vec3f t = toRH(r_.vec3());
osg::Vec4f q = r_.vec4();
if (idx >= 0 && idx < static_cast<int>(model_.bones.size()))
m.boneOffsets.push_back({idx, t, toRH(osg::Quat(q.x(), q.y(), q.z(), q.w()))});
}
break;
case 3: case 4: case 5: case 6: case 7: // UV / additional UV
m.type = MorphType::UV;
for (int32_t i = 0; i < offsets; ++i) {
r_.vertexIndex(h_.vertexIndexSize);
r_.skip(16);
}
break;
case 8: // material
m.type = MorphType::Material;
for (int32_t i = 0; i < offsets; ++i) {
r_.signedIndex(h_.materialIndexSize);
r_.skip(1 + 16 + 12 + 4 + 12 + 16 + 4 + 16 + 16 + 16);
}
break;
case 10: // impulse
m.type = MorphType::Impulse;
for (int32_t i = 0; i < offsets; ++i) {
r_.signedIndex(h_.rigidBodyIndexSize);
r_.skip(1 + 12 + 12);
}
break;
default: throw std::runtime_error("unknown PMX morph type");
}
}
}
BinaryReader r_;
Model& model_;
PmxHeader h_;
};
} // namespace
void loadPmx(const std::vector<uint8_t>& data, const std::string& sourcePath, Model& model) {
PmxParser(data, model).parse(sourcePath);
}
} // namespace mr
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "model/Model.h"
#include <cstdint>
#include <string>
#include <vector>
namespace mr {
// Parses PMX 2.0 / 2.1 data. Throws std::runtime_error on malformed input.
void loadPmx(const std::vector<uint8_t>& data, const std::string& sourcePath, Model& model);
} // namespace mr
+178
View File
@@ -0,0 +1,178 @@
#include "model/Poser.h"
#include <algorithm>
#include <cmath>
#include <numeric>
namespace mr {
namespace {
osg::Quat eulerToQuat(const osg::Vec3f& deg) {
const double k = osg::PI / 180.0;
return osg::Quat(deg.x() * k, osg::X_AXIS, deg.y() * k, osg::Y_AXIS, deg.z() * k, osg::Z_AXIS);
}
osg::Quat scaledRotation(const osg::Quat& q, float w) {
osg::Quat result;
if (w >= 0.f) result.slerp(w, osg::Quat(), q);
else result.slerp(-w, osg::Quat(), q.inverse());
return result;
}
} // namespace
Poser::Poser(std::shared_ptr<const Model> model) : model_(std::move(model)) {
const size_t boneCount = model_->bones.size();
poses_.resize(boneCount);
weights_.assign(model_->morphs.size(), 0.f);
effective_.assign(model_->morphs.size(), 0.f);
morphTranslation_.resize(boneCount);
morphRotation_.resize(boneCount);
animRotation_.resize(boneCount);
animTranslation_.resize(boneCount);
globals_.resize(boneCount);
skin_.resize(boneCount);
computeEvaluationOrder();
bindRotation_.resize(boneCount);
std::vector<osg::Matrixf> rest(boneCount);
for (int b : order_) {
const Bone& bone = model_->bones[b];
rest[b] = bone.parent >= 0 ? bone.localBind * rest[bone.parent] : bone.localBind;
osg::Vec3f t, s;
osg::Quat r, so;
rest[b].decompose(t, r, s, so);
bindRotation_[b] = r;
}
}
void Poser::resetPose() { std::fill(poses_.begin(), poses_.end(), BonePose()); }
void Poser::resetMorphs() { std::fill(weights_.begin(), weights_.end(), 0.f); }
void Poser::computeEvaluationOrder() {
const auto& bones = model_->bones;
const int n = static_cast<int>(bones.size());
std::vector<int> candidates(n);
std::iota(candidates.begin(), candidates.end(), 0);
std::stable_sort(candidates.begin(), candidates.end(), [&](int a, int b) {
if (bones[a].afterPhysics != bones[b].afterPhysics) return !bones[a].afterPhysics;
return bones[a].layer < bones[b].layer;
});
// Depth-first so parents and inheritance sources are always evaluated first.
std::vector<int> state(n, 0); // 0 = new, 1 = visiting, 2 = done
order_.clear();
order_.reserve(n);
std::vector<std::pair<int, int>> stack;
for (int start : candidates) {
if (state[start]) continue;
stack.push_back({start, 0});
state[start] = 1;
while (!stack.empty()) {
auto& [bone, step] = stack.back();
int dep = -1;
if (step == 0) dep = bones[bone].parent;
else if (step == 1) dep = bones[bone].inheritParent;
if (step < 2) {
++step;
if (dep >= 0 && state[dep] == 0) {
state[dep] = 1;
stack.push_back({dep, 0});
}
continue;
}
state[bone] = 2;
order_.push_back(bone);
stack.pop_back();
}
}
}
void Poser::accumulateMorph(int morph, float weight, int depth) {
if (depth > 8 || morph < 0 || morph >= static_cast<int>(effective_.size())) return;
const Morph& m = model_->morphs[morph];
if (m.type == MorphType::Group || m.type == MorphType::Flip) {
for (const auto& g : m.groupOffsets) accumulateMorph(g.morph, weight * g.weight, depth + 1);
} else {
effective_[morph] += weight;
}
}
bool Poser::update() {
if (!firstUpdate_ && poses_ == lastPoses_ && weights_ == lastWeights_) return false;
firstUpdate_ = false;
lastPoses_ = poses_;
lastWeights_ = weights_;
const Model& model = *model_;
const auto& bones = model.bones;
std::fill(effective_.begin(), effective_.end(), 0.f);
for (size_t i = 0; i < weights_.size(); ++i)
if (weights_[i] != 0.f) accumulateMorph(static_cast<int>(i), weights_[i], 0);
std::fill(morphTranslation_.begin(), morphTranslation_.end(), osg::Vec3f());
std::fill(morphRotation_.begin(), morphRotation_.end(), osg::Quat());
for (size_t i = 0; i < effective_.size(); ++i) {
const float w = effective_[i];
if (w == 0.f || model.morphs[i].type != MorphType::Bone) continue;
for (const auto& b : model.morphs[i].boneOffsets) {
morphTranslation_[b.bone] += b.translation * w;
morphRotation_[b.bone] = morphRotation_[b.bone] * scaledRotation(b.rotation, w);
}
}
for (int b : order_) {
const Bone& bone = bones[b];
// Convert the model-space pose into the bone's own frame.
const osg::Quat& g = bindRotation_[b];
const osg::Quat poseRotation = g * eulerToQuat(poses_[b].eulerDegrees) * g.inverse();
osg::Quat rotation = morphRotation_[b] * poseRotation;
osg::Vec3f translation = g.inverse() * poses_[b].translation + morphTranslation_[b];
if (bone.inheritParent >= 0) {
if (bone.inheritRotation)
rotation = rotation * scaledRotation(animRotation_[bone.inheritParent], bone.inheritWeight);
if (bone.inheritTranslation) translation += animTranslation_[bone.inheritParent] * bone.inheritWeight;
}
animRotation_[b] = rotation;
animTranslation_[b] = translation;
osg::Matrixf local = osg::Matrixf::rotate(rotation) * osg::Matrixf::translate(translation) * bone.localBind;
globals_[b] = bone.parent >= 0 ? local * globals_[bone.parent] : local;
skin_[b] = bone.inverseBind * globals_[b];
}
const size_t vertexCount = model.vertices.size();
morphed_.resize(vertexCount);
for (size_t i = 0; i < vertexCount; ++i) morphed_[i] = model.vertices[i].position;
for (size_t i = 0; i < effective_.size(); ++i) {
const float w = effective_[i];
if (w == 0.f || model.morphs[i].type != MorphType::Vertex) continue;
for (const auto& o : model.morphs[i].vertexOffsets) morphed_[o.vertex] += o.offset * w;
}
positions_.resize(vertexCount);
normals_.resize(vertexCount);
for (size_t i = 0; i < vertexCount; ++i) {
const Vertex& v = model.vertices[i];
if (v.bones[0] < 0) {
positions_[i] = morphed_[i];
normals_[i] = v.normal;
continue;
}
osg::Vec3f p, n;
for (int k = 0; k < 4; ++k) {
if (v.bones[k] < 0) continue;
const osg::Matrixf& m = skin_[v.bones[k]];
p += (morphed_[i] * m) * v.weights[k];
n += osg::Matrixf::transform3x3(v.normal, m) * v.weights[k];
}
n.normalize();
positions_[i] = p;
normals_[i] = n;
}
return true;
}
} // namespace mr
+60
View File
@@ -0,0 +1,60 @@
#pragma once
#include "model/Model.h"
#include <memory>
#include <vector>
namespace mr {
struct BonePose {
// Both are expressed in model-space axes (X right, Y up, Z toward the viewer) at the bone's pivot,
// so posing behaves the same regardless of how a format orients its bone frames.
osg::Vec3f translation;
osg::Vec3f eulerDegrees; // applied X, then Y, then Z
bool operator==(const BonePose& o) const { return translation == o.translation && eulerDegrees == o.eulerDegrees; }
bool operator!=(const BonePose& o) const { return !(*this == o); }
};
// Applies morph weights and bone poses to a model (CPU morphing + linear blend skinning).
class Poser {
public:
explicit Poser(std::shared_ptr<const Model> model);
const Model& model() const { return *model_; }
std::vector<BonePose>& bonePoses() { return poses_; }
std::vector<float>& morphWeights() { return weights_; }
void resetPose();
void resetMorphs();
// Recomputes the deformed mesh if anything changed. Returns true when it did.
bool update();
const std::vector<osg::Vec3f>& positions() const { return positions_; }
const std::vector<osg::Vec3f>& normals() const { return normals_; }
const std::vector<osg::Matrixf>& boneGlobals() const { return globals_; }
const std::vector<float>& effectiveMorphWeights() const { return effective_; }
private:
void computeEvaluationOrder();
void accumulateMorph(int morph, float weight, int depth);
std::shared_ptr<const Model> model_;
std::vector<BonePose> poses_, lastPoses_;
std::vector<float> weights_, lastWeights_;
bool firstUpdate_ = true;
std::vector<int> order_;
std::vector<osg::Quat> bindRotation_; // rest-pose global rotation of each bone
std::vector<float> effective_;
std::vector<osg::Vec3f> morphTranslation_;
std::vector<osg::Quat> morphRotation_;
std::vector<osg::Quat> animRotation_;
std::vector<osg::Vec3f> animTranslation_;
std::vector<osg::Matrixf> globals_, skin_;
std::vector<osg::Vec3f> morphed_, positions_, normals_;
};
} // namespace mr
+96
View File
@@ -0,0 +1,96 @@
#include "model/TextEncoding.h"
#include <cstdint>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#else
#include <iconv.h>
#endif
namespace mr {
namespace {
void appendUtf8(std::string& out, uint32_t cp) {
if (cp < 0x80) {
out += static_cast<char>(cp);
} else if (cp < 0x800) {
out += static_cast<char>(0xC0 | (cp >> 6));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else if (cp < 0x10000) {
out += static_cast<char>(0xE0 | (cp >> 12));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else {
out += static_cast<char>(0xF0 | (cp >> 18));
out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
}
}
bool isAscii(const std::string& s) {
for (unsigned char c : s)
if (c >= 0x80) return false;
return true;
}
} // namespace
std::string utf16leToUtf8(const char* data, size_t byteCount) {
std::string out;
out.reserve(byteCount);
const auto* p = reinterpret_cast<const uint8_t*>(data);
size_t n = byteCount / 2;
for (size_t i = 0; i < n; ++i) {
uint32_t c = p[2 * i] | (p[2 * i + 1] << 8);
if (c >= 0xD800 && c <= 0xDBFF && i + 1 < n) {
uint32_t lo = p[2 * (i + 1)] | (p[2 * (i + 1) + 1] << 8);
if (lo >= 0xDC00 && lo <= 0xDFFF) {
c = 0x10000 + ((c - 0xD800) << 10) + (lo - 0xDC00);
++i;
}
}
appendUtf8(out, c);
}
return out;
}
std::string shiftJisToUtf8(const std::string& sjis) {
if (sjis.empty() || isAscii(sjis)) return sjis;
#ifdef _WIN32
int wlen = MultiByteToWideChar(932, 0, sjis.data(), static_cast<int>(sjis.size()), nullptr, 0);
if (wlen <= 0) return sjis;
std::wstring wide(wlen, L'\0');
MultiByteToWideChar(932, 0, sjis.data(), static_cast<int>(sjis.size()), wide.data(), wlen);
int len = WideCharToMultiByte(CP_UTF8, 0, wide.data(), wlen, nullptr, 0, nullptr, nullptr);
std::string out(len, '\0');
WideCharToMultiByte(CP_UTF8, 0, wide.data(), wlen, out.data(), len, nullptr, nullptr);
return out;
#else
iconv_t cd = iconv_open("UTF-8", "CP932");
if (cd == reinterpret_cast<iconv_t>(-1)) cd = iconv_open("UTF-8", "SHIFT_JIS");
if (cd == reinterpret_cast<iconv_t>(-1)) return sjis;
std::vector<char> in(sjis.begin(), sjis.end());
std::vector<char> out(sjis.size() * 4 + 4);
char* inPtr = in.data();
size_t inLeft = in.size();
char* outPtr = out.data();
size_t outLeft = out.size();
while (inLeft > 0) {
if (iconv(cd, &inPtr, &inLeft, &outPtr, &outLeft) == static_cast<size_t>(-1)) {
if (outLeft < 4) break;
*outPtr++ = '?'; // skip an invalid byte
--outLeft;
++inPtr;
--inLeft;
}
}
iconv_close(cd);
return std::string(out.data(), outPtr - out.data());
#endif
}
} // namespace mr
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include <string>
namespace mr {
std::string utf16leToUtf8(const char* data, size_t byteCount);
std::string shiftJisToUtf8(const std::string& sjis);
} // namespace mr
+271
View File
@@ -0,0 +1,271 @@
#include "render/ModelNode.h"
#include "render/Shaders.h"
#include "render/TextureLoader.h"
#include <osg/BlendFunc>
#include <osg/CullFace>
#include <osg/Depth>
#include <osg/Geode>
#include <osg/LineWidth>
#include <osg/Point>
#include <osg/PolygonMode>
namespace mr {
namespace {
// MMD's default light: direction (-0.5, -1, 0.5) in its left-handed space.
const osg::Vec3f kMmdLightDirection(-0.5f, -1.0f, -0.5f);
class DeformCallback : public osg::NodeCallback {
public:
void operator()(osg::Node* node, osg::NodeVisitor* nv) override {
static_cast<ModelNode*>(node)->updateDeformation();
traverse(node, nv);
}
};
} // namespace
ModelNode::ModelNode(std::shared_ptr<Model> model) : model_(std::move(model)), poser_(model_) {
setMatrix(osg::Matrix::rotate(osg::PI_2, osg::X_AXIS)); // Y-up model -> Z-up world
setDataVariance(osg::Object::DYNAMIC);
osg::StateSet* ss = getOrCreateStateSet();
ss->setAttributeAndModes(createModelProgram(), osg::StateAttribute::ON);
ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
ss->addUniform(new osg::Uniform("u_texture", 0));
ss->addUniform(new osg::Uniform("u_sphere", 1));
ss->addUniform(new osg::Uniform("u_toon", 2));
ss->addUniform(new osg::Uniform("u_lightColor", osg::Vec3f(0.6f, 0.6f, 0.6f)));
const bool isMmd = model_->format != SourceFormat::Assimp;
lightingUniform_ = new osg::Uniform("u_lightingModel", isMmd ? 0 : 1);
lightFollowUniform_ = new osg::Uniform("u_lightFollowsCamera", 0);
osg::Vec3f worldLight = osg::Matrixf::transform3x3(kMmdLightDirection, osg::Matrixf(getMatrix()));
lightDirUniform_ = new osg::Uniform("u_lightDirection", worldLight);
ss->addUniform(lightingUniform_);
ss->addUniform(lightFollowUniform_);
ss->addUniform(lightDirUniform_);
textures_.resize(model_->textures.size());
textureTried_.assign(model_->textures.size(), false);
buildMesh();
buildSkeleton();
setShowSkeleton(false);
updateDeformation();
setUpdateCallback(new DeformCallback);
}
osg::Texture2D* ModelNode::texture(int index, bool clamp) {
if (index < 0 || index >= static_cast<int>(textures_.size())) return nullptr;
if (!textureTried_[index]) {
textureTried_[index] = true;
if (osg::ref_ptr<osg::Image> image = loadTextureImage(model_->textures[index]))
textures_[index] = makeTexture(image.get(), clamp);
}
return textures_[index].get();
}
osg::StateSet* ModelNode::buildMaterialState(const Material& m, int order) {
auto* ss = new osg::StateSet;
ss->addUniform(new osg::Uniform("u_diffuse", m.diffuse));
ss->addUniform(new osg::Uniform("u_ambient", m.ambient));
ss->addUniform(new osg::Uniform("u_specular", m.specular));
ss->addUniform(new osg::Uniform("u_shininess", m.shininess));
osg::Texture2D* main = texture(m.texture, false);
if (main) ss->setTextureAttributeAndModes(0, main, osg::StateAttribute::ON);
ss->addUniform(new osg::Uniform("u_useTexture", main ? 1 : 0));
osg::Texture2D* sphere = nullptr;
if (m.sphereMode == SphereMode::Multiply || m.sphereMode == SphereMode::Add)
sphere = texture(m.sphereTexture, true);
if (sphere) ss->setTextureAttributeAndModes(1, sphere, osg::StateAttribute::ON);
ss->addUniform(new osg::Uniform("u_sphereMode", !sphere ? 0 : m.sphereMode == SphereMode::Add ? 2 : 1));
osg::Texture2D* toon = texture(m.toonTexture, true);
if (!toon && m.sharedToon >= 0 && m.sharedToon <= 9) {
if (!sharedToons_[m.sharedToon]) sharedToons_[m.sharedToon] = makeTexture(makeSharedToonImage(m.sharedToon), true);
toon = sharedToons_[m.sharedToon].get();
}
if (toon) ss->setTextureAttributeAndModes(2, toon, osg::StateAttribute::ON);
ss->addUniform(new osg::Uniform("u_useToon", toon ? 1 : 0));
osg::ref_ptr<osg::CullFace> cull = new osg::CullFace(osg::CullFace::BACK);
ss->setAttributeAndModes(cull, m.doubleSided ? osg::StateAttribute::OFF : osg::StateAttribute::ON);
// MMD draws materials in file order with alpha blending always enabled.
ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg::StateAttribute::ON);
ss->setRenderBinDetails(10 + order, "RenderBin");
return ss;
}
void ModelNode::buildMesh() {
const Model& model = *model_;
positions_ = new osg::Vec3Array(model.vertices.size());
normals_ = new osg::Vec3Array(model.vertices.size());
osg::ref_ptr<osg::Vec2Array> uvs = new osg::Vec2Array(model.vertices.size());
for (size_t i = 0; i < model.vertices.size(); ++i) {
(*positions_)[i] = model.vertices[i].position;
(*normals_)[i] = model.vertices[i].normal;
(*uvs)[i] = model.vertices[i].uv;
}
positions_->setDataVariance(osg::Object::DYNAMIC);
normals_->setDataVariance(osg::Object::DYNAMIC);
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
for (size_t i = 0; i < model.materials.size(); ++i) {
const Material& m = model.materials[i];
if (m.indexCount == 0) continue;
osg::ref_ptr<osg::Geometry> geom = new osg::Geometry;
geom->setName(m.name);
geom->setDataVariance(osg::Object::DYNAMIC);
geom->setUseDisplayList(false);
geom->setUseVertexBufferObjects(true);
geom->setVertexArray(positions_);
geom->setNormalArray(normals_, osg::Array::BIND_PER_VERTEX);
geom->setTexCoordArray(0, uvs, osg::Array::BIND_PER_VERTEX);
osg::ref_ptr<osg::DrawElementsUInt> elements = new osg::DrawElementsUInt(
GL_TRIANGLES, model.indices.begin() + m.indexOffset, model.indices.begin() + m.indexOffset + m.indexCount);
geom->addPrimitiveSet(elements);
geom->setStateSet(buildMaterialState(m, static_cast<int>(i)));
geode->addDrawable(geom);
geometries_.push_back(geom);
}
meshGroup_ = geode;
addChild(meshGroup_);
}
void ModelNode::buildSkeleton() {
const Model& model = *model_;
for (size_t i = 0; i < model.bones.size(); ++i)
if (model.bones[i].visible || model.bones[i].isSkinBone) skeletonBones_.push_back(static_cast<int>(i));
skeletonGeode_ = new osg::Geode;
osg::StateSet* ss = skeletonGeode_->getOrCreateStateSet();
ss->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON); // fixed function
ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
ss->setMode(GL_BLEND, osg::StateAttribute::OFF);
ss->setAttributeAndModes(new osg::PolygonMode(), osg::StateAttribute::ON | osg::StateAttribute::PROTECTED);
ss->setAttribute(new osg::LineWidth(2.f));
ss->setAttribute(new osg::Point(6.f));
ss->setRenderBinDetails(100000, "RenderBin");
auto makeGeom = [](GLenum mode) {
osg::ref_ptr<osg::Geometry> g = new osg::Geometry;
g->setDataVariance(osg::Object::DYNAMIC);
g->setUseDisplayList(false);
g->setUseVertexBufferObjects(true);
g->setVertexArray(new osg::Vec3Array);
g->setColorArray(new osg::Vec4Array, osg::Array::BIND_PER_VERTEX);
g->addPrimitiveSet(new osg::DrawArrays(mode, 0, 0));
return g;
};
skeletonLines_ = makeGeom(GL_LINES);
skeletonPoints_ = makeGeom(GL_POINTS);
skeletonGeode_->addDrawable(skeletonLines_);
skeletonGeode_->addDrawable(skeletonPoints_);
addChild(skeletonGeode_);
}
void ModelNode::updateSkeleton() {
const auto& globals = poser_.boneGlobals();
const auto& bones = model_->bones;
auto* lineVerts = static_cast<osg::Vec3Array*>(skeletonLines_->getVertexArray());
auto* lineColors = static_cast<osg::Vec4Array*>(skeletonLines_->getColorArray());
auto* pointVerts = static_cast<osg::Vec3Array*>(skeletonPoints_->getVertexArray());
auto* pointColors = static_cast<osg::Vec4Array*>(skeletonPoints_->getColorArray());
lineVerts->clear();
lineColors->clear();
pointVerts->clear();
pointColors->clear();
const osg::Vec4 normal(0.3f, 0.8f, 1.f, 1.f), selected(1.f, 0.85f, 0.1f, 1.f);
for (int b : skeletonBones_) {
const osg::Vec4& color = b == selectedBone_ ? selected : normal;
osg::Vec3 head = globals[b].getTrans();
pointVerts->push_back(head);
pointColors->push_back(color);
int parent = bones[b].parent;
if (parent >= 0) {
lineVerts->push_back(globals[parent].getTrans());
lineVerts->push_back(head);
lineColors->push_back(color);
lineColors->push_back(color);
}
}
static_cast<osg::DrawArrays*>(skeletonLines_->getPrimitiveSet(0))->setCount(lineVerts->size());
static_cast<osg::DrawArrays*>(skeletonPoints_->getPrimitiveSet(0))->setCount(pointVerts->size());
for (osg::Array* a : {static_cast<osg::Array*>(lineVerts), static_cast<osg::Array*>(lineColors),
static_cast<osg::Array*>(pointVerts), static_cast<osg::Array*>(pointColors)})
a->dirty();
skeletonLines_->dirtyBound();
skeletonPoints_->dirtyBound();
}
void ModelNode::updateDeformation() {
if (poser_.update()) {
const auto& p = poser_.positions();
const auto& n = poser_.normals();
std::copy(p.begin(), p.end(), positions_->begin());
std::copy(n.begin(), n.end(), normals_->begin());
positions_->dirty();
normals_->dirty();
for (auto& g : geometries_) g->dirtyBound();
skeletonDirty_ = true;
}
if (skeletonDirty_ && skeletonGeode_->getNodeMask() != 0) {
updateSkeleton();
skeletonDirty_ = false;
}
}
void ModelNode::setShowSkeleton(bool show) {
skeletonGeode_->setNodeMask(show ? ~0u : 0u);
skeletonDirty_ = true;
}
void ModelNode::setSelectedBone(int bone) {
if (bone == selectedBone_) return;
selectedBone_ = bone;
skeletonDirty_ = true;
}
void ModelNode::setBackfaceCulling(bool enabled) {
osg::StateSet* ss = meshGroup_->getOrCreateStateSet();
if (enabled) ss->removeMode(GL_CULL_FACE);
else ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
}
void ModelNode::setWireframe(bool enabled) {
osg::StateSet* ss = meshGroup_->getOrCreateStateSet();
if (enabled)
ss->setAttributeAndModes(new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
else ss->removeAttribute(osg::StateAttribute::POLYGONMODE);
}
void ModelNode::setLightingModel(LightingModel lighting) { lightingUniform_->set(static_cast<int>(lighting)); }
void ModelNode::setLightFollowsCamera(bool follow) {
lightFollowUniform_->set(follow ? 1 : 0);
// In view space a light from the upper left, slightly in front of the camera.
osg::Vec3f dir = follow ? osg::Vec3f(0.3f, -0.5f, -1.f)
: osg::Matrixf::transform3x3(kMmdLightDirection, osg::Matrixf(getMatrix()));
lightDirUniform_->set(dir);
}
osg::BoundingSphere ModelNode::restBound() const {
osg::Vec3f lo, hi;
model_->computeBounds(lo, hi);
osg::BoundingBox box(lo, hi);
osg::BoundingSphere sphere(box);
sphere.center() = sphere.center() * getMatrix();
return sphere;
}
} // namespace mr
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include "model/Model.h"
#include "model/Poser.h"
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/Texture2D>
#include <osg/Uniform>
#include <memory>
namespace mr {
enum class LightingModel { MmdToon = 0, Lambert = 1 };
// Scene graph for one model. Converts the model's Y-up space to OSG's Z-up world
// and re-uploads deformed vertices whenever the pose or morph weights change.
class ModelNode : public osg::MatrixTransform {
public:
explicit ModelNode(std::shared_ptr<Model> model);
const Model& model() const { return *model_; }
Poser& poser() { return poser_; }
void setShowSkeleton(bool show);
void setSelectedBone(int bone);
void setBackfaceCulling(bool enabled);
void setWireframe(bool enabled);
void setLightingModel(LightingModel lighting);
void setLightFollowsCamera(bool follow);
// World-space bounding sphere of the rest pose.
osg::BoundingSphere restBound() const;
void updateDeformation();
private:
void buildMesh();
osg::StateSet* buildMaterialState(const Material& material, int order);
osg::Texture2D* texture(int index, bool clamp);
void buildSkeleton();
void updateSkeleton();
std::shared_ptr<Model> model_;
Poser poser_;
osg::ref_ptr<osg::Group> meshGroup_;
osg::ref_ptr<osg::Vec3Array> positions_;
osg::ref_ptr<osg::Vec3Array> normals_;
std::vector<osg::ref_ptr<osg::Geometry>> geometries_;
std::vector<osg::ref_ptr<osg::Texture2D>> textures_;
std::vector<bool> textureTried_;
osg::ref_ptr<osg::Texture2D> sharedToons_[10];
osg::ref_ptr<osg::Geode> skeletonGeode_;
osg::ref_ptr<osg::Geometry> skeletonLines_;
osg::ref_ptr<osg::Geometry> skeletonPoints_;
std::vector<int> skeletonBones_;
int selectedBone_ = -1;
bool skeletonDirty_ = true;
osg::ref_ptr<osg::Uniform> lightingUniform_;
osg::ref_ptr<osg::Uniform> lightFollowUniform_;
osg::ref_ptr<osg::Uniform> lightDirUniform_;
};
} // namespace mr
+89
View File
@@ -0,0 +1,89 @@
#include "render/Shaders.h"
namespace mr {
namespace {
// GLSL 1.20 so the same shaders run on macOS legacy contexts, Windows and Linux.
const char* kVertexShader = R"(#version 120
varying vec3 v_normal;
varying vec3 v_viewPos;
varying vec2 v_uv;
void main() {
vec4 viewPos = gl_ModelViewMatrix * gl_Vertex;
v_viewPos = viewPos.xyz;
v_normal = gl_NormalMatrix * gl_Normal;
v_uv = gl_MultiTexCoord0.xy;
gl_Position = gl_ProjectionMatrix * viewPos;
}
)";
const char* kFragmentShader = R"(#version 120
uniform mat4 osg_ViewMatrix;
uniform sampler2D u_texture;
uniform sampler2D u_sphere;
uniform sampler2D u_toon;
uniform int u_useTexture;
uniform int u_sphereMode; // 0 none, 1 multiply, 2 add
uniform int u_useToon;
uniform int u_lightingModel; // 0 MMD toon, 1 Lambert
uniform int u_lightFollowsCamera;
uniform vec4 u_diffuse;
uniform vec3 u_ambient;
uniform vec3 u_specular;
uniform float u_shininess;
uniform vec3 u_lightDirection; // direction the light travels (world space)
uniform vec3 u_lightColor;
varying vec3 v_normal;
varying vec3 v_viewPos;
varying vec2 v_uv;
void main() {
vec3 n = normalize(v_normal);
if (!gl_FrontFacing) n = -n;
vec3 lightDir = u_lightFollowsCamera == 1 ? normalize(u_lightDirection)
: normalize(mat3(osg_ViewMatrix) * u_lightDirection);
vec3 toLight = -lightDir;
vec3 toEye = normalize(-v_viewPos);
float ndl = dot(n, toLight);
vec3 color;
float alpha = u_diffuse.a;
if (u_lightingModel == 0) {
color = clamp(u_diffuse.rgb * u_lightColor + u_ambient, 0.0, 1.0);
} else {
color = u_diffuse.rgb * (0.35 + 0.65 * max(ndl, 0.0));
}
if (u_useTexture == 1) {
vec4 t = texture2D(u_texture, v_uv);
color *= t.rgb;
alpha *= t.a;
}
if (alpha < 0.004) discard;
if (u_sphereMode != 0) {
vec3 s = texture2D(u_sphere, n.xy * 0.5 + 0.5).rgb;
if (u_sphereMode == 1) color *= s;
else color += s;
}
if (u_lightingModel == 0 && u_useToon == 1) {
color *= texture2D(u_toon, vec2(0.5, clamp(ndl + 0.5, 0.0, 1.0))).rgb;
}
if (u_shininess > 0.0) {
vec3 h = normalize(toLight + toEye);
color += u_specular * u_lightColor * pow(max(dot(n, h), 0.0), u_shininess);
}
gl_FragColor = vec4(clamp(color, 0.0, 1.0), alpha);
}
)";
} // namespace
osg::ref_ptr<osg::Program> createModelProgram() {
osg::ref_ptr<osg::Program> program = new osg::Program;
program->setName("ModelProgram");
program->addShader(new osg::Shader(osg::Shader::VERTEX, kVertexShader));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, kFragmentShader));
return program;
}
} // namespace mr
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include <osg/Program>
namespace mr {
osg::ref_ptr<osg::Program> createModelProgram();
} // namespace mr
+100
View File
@@ -0,0 +1,100 @@
#include "render/TextureLoader.h"
#include "model/PathUtil.h"
#include <osgDB/ReaderWriter>
#include <osgDB/Registry>
#include <algorithm>
#include <iostream>
#include <sstream>
namespace mr {
namespace {
std::string sniffExtension(const std::vector<uint8_t>& d, const std::string& fallbackName) {
auto starts = [&](std::initializer_list<uint8_t> magic) {
if (d.size() < magic.size()) return false;
return std::equal(magic.begin(), magic.end(), d.begin());
};
if (starts({0x89, 'P', 'N', 'G'})) return "png";
if (starts({0xFF, 0xD8})) return "jpg";
if (starts({'B', 'M'})) return "bmp";
if (starts({'D', 'D', 'S', ' '})) return "dds";
if (starts({'G', 'I', 'F'})) return "gif";
std::string lower = toLowerAscii(fallbackName);
size_t dot = lower.find_last_of('.');
std::string ext = dot == std::string::npos ? lower : lower.substr(dot + 1);
if (ext.empty() || ext == "sph" || ext == "spa") return "bmp";
return ext;
}
osg::ref_ptr<osg::Image> decode(const std::vector<uint8_t>& bytes, const std::string& nameHint) {
const std::string ext = sniffExtension(bytes, nameHint);
osgDB::ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(ext);
if (!rw) {
std::cerr << "No OSG image plugin for '" << ext << "' (" << nameHint << ")\n";
return nullptr;
}
std::istringstream in(std::string(bytes.begin(), bytes.end()), std::ios::binary);
osgDB::ReaderWriter::ReadResult rr = rw->readImage(in);
if (!rr.validImage()) {
std::cerr << "Failed to decode texture " << nameHint << "\n";
return nullptr;
}
osg::ref_ptr<osg::Image> image = rr.getImage();
if (image->getOrigin() == osg::Image::TOP_LEFT) {
image->flipVertical();
image->setOrigin(osg::Image::BOTTOM_LEFT);
}
return image;
}
} // namespace
osg::ref_ptr<osg::Image> loadTextureImage(const Texture& texture) {
if (texture.rawWidth > 0 && texture.rawHeight > 0) {
osg::ref_ptr<osg::Image> image = new osg::Image;
image->allocateImage(texture.rawWidth, texture.rawHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE);
std::copy(texture.rawRGBA.begin(), texture.rawRGBA.end(), image->data());
image->flipVertical(); // Assimp stores rows top-down
return image;
}
if (!texture.encodedData.empty()) return decode(texture.encodedData, "embedded." + texture.formatHint);
std::vector<uint8_t> bytes;
if (texture.path.empty() || !readFileBytes(texture.path, bytes)) return nullptr;
return decode(bytes, texture.path);
}
osg::ref_ptr<osg::Texture2D> makeTexture(osg::Image* image, bool clampToEdge) {
osg::ref_ptr<osg::Texture2D> tex = new osg::Texture2D(image);
tex->setResizeNonPowerOfTwoHint(false);
tex->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR);
tex->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
const auto wrap = clampToEdge ? osg::Texture::CLAMP_TO_EDGE : osg::Texture::REPEAT;
tex->setWrap(osg::Texture::WRAP_S, wrap);
tex->setWrap(osg::Texture::WRAP_T, wrap);
return tex;
}
osg::ref_ptr<osg::Image> makeSharedToonImage(int index) {
// Approximate shadow tints of MMD's default toon01..toon10 ramps.
static const float tints[10][3] = {
{0.80f, 0.80f, 0.80f}, {0.95f, 0.85f, 0.80f}, {0.75f, 0.75f, 0.75f}, {0.95f, 0.88f, 0.80f},
{0.90f, 0.80f, 0.80f}, {0.75f, 0.80f, 0.90f}, {0.85f, 0.85f, 0.85f}, {0.90f, 0.85f, 0.75f},
{0.95f, 0.95f, 0.95f}, {0.85f, 0.80f, 0.85f}};
const float* tint = tints[std::clamp(index, 0, 9)];
const int height = 32;
osg::ref_ptr<osg::Image> image = new osg::Image;
image->allocateImage(1, height, 1, GL_RGB, GL_UNSIGNED_BYTE);
for (int y = 0; y < height; ++y) {
// Row 0 is the bottom (unlit side); the top half is fully lit.
float t = std::clamp((y / float(height - 1) - 0.40f) / 0.15f, 0.f, 1.f);
unsigned char* px = image->data(0, y);
for (int c = 0; c < 3; ++c) px[c] = static_cast<unsigned char>(255.f * (tint[c] + (1.f - tint[c]) * t));
}
return image;
}
} // namespace mr
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include "model/Model.h"
#include <osg/Image>
#include <osg/Texture2D>
namespace mr {
// Decodes a model texture (file or embedded). Detects the real format from the
// file header, since MMD models often ship .sph/.spa files that are BMPs.
osg::ref_ptr<osg::Image> loadTextureImage(const Texture& texture);
osg::ref_ptr<osg::Texture2D> makeTexture(osg::Image* image, bool clampToEdge);
// Procedural stand-in for MMD's built-in toon01.bmp .. toon10.bmp (index 0..9).
osg::ref_ptr<osg::Image> makeSharedToonImage(int index);
} // namespace mr
+326
View File
@@ -0,0 +1,326 @@
#include "ui/ImGuiOsg.h"
#include <imgui.h>
#include <imgui_impl_opengl2.h>
#include <osg/GLExtensions>
#include <osg/Timer>
#include <osgDB/WriteFile>
#include <osgGA/GUIEventHandler>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <iostream>
namespace mr {
namespace {
ImGuiKey mapKey(int key) {
using K = osgGA::GUIEventAdapter::KeySymbol;
switch (key) {
case K::KEY_Tab: return ImGuiKey_Tab;
case K::KEY_Left: return ImGuiKey_LeftArrow;
case K::KEY_Right: return ImGuiKey_RightArrow;
case K::KEY_Up: return ImGuiKey_UpArrow;
case K::KEY_Down: return ImGuiKey_DownArrow;
case K::KEY_Page_Up: return ImGuiKey_PageUp;
case K::KEY_Page_Down: return ImGuiKey_PageDown;
case K::KEY_Home: return ImGuiKey_Home;
case K::KEY_End: return ImGuiKey_End;
case K::KEY_Insert: return ImGuiKey_Insert;
case K::KEY_Delete: return ImGuiKey_Delete;
case K::KEY_BackSpace: return ImGuiKey_Backspace;
case K::KEY_Space: return ImGuiKey_Space;
case K::KEY_Return: return ImGuiKey_Enter;
case K::KEY_KP_Enter: return ImGuiKey_KeypadEnter;
case K::KEY_Escape: return ImGuiKey_Escape;
default: break;
}
if (key >= 'a' && key <= 'z') return static_cast<ImGuiKey>(ImGuiKey_A + (key - 'a'));
if (key >= 'A' && key <= 'Z') return static_cast<ImGuiKey>(ImGuiKey_A + (key - 'A'));
if (key >= '0' && key <= '9') return static_cast<ImGuiKey>(ImGuiKey_0 + (key - '0'));
return ImGuiKey_None;
}
#if !defined(_WIN32) && !defined(__APPLE__)
// ImGui only has native clipboard support on Windows and macOS; on Linux use the standard CLI tools.
std::string g_clipboard;
const char* const* clipboardCommands(bool paste) {
static const char* const waylandPaste[] = {"wl-paste -n 2>/dev/null", nullptr};
static const char* const waylandCopy[] = {"wl-copy 2>/dev/null", nullptr};
static const char* const x11Paste[] = {"xclip -selection clipboard -o 2>/dev/null", "xsel -bo 2>/dev/null", nullptr};
static const char* const x11Copy[] = {"xclip -selection clipboard -i 2>/dev/null", "xsel -bi 2>/dev/null", nullptr};
const bool wayland = std::getenv("WAYLAND_DISPLAY") != nullptr;
return paste ? (wayland ? waylandPaste : x11Paste) : (wayland ? waylandCopy : x11Copy);
}
const char* getClipboardText(ImGuiContext*) {
for (const char* const* cmd = clipboardCommands(true); *cmd; ++cmd) {
FILE* pipe = popen(*cmd, "r");
if (!pipe) continue;
std::string text;
char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), pipe)) > 0) text.append(buf, n);
if (pclose(pipe) == 0) {
g_clipboard = text;
break;
}
}
return g_clipboard.c_str();
}
void setClipboardText(ImGuiContext*, const char* text) {
g_clipboard = text ? text : "";
for (const char* const* cmd = clipboardCommands(false); *cmd; ++cmd) {
FILE* pipe = popen(*cmd, "w");
if (!pipe) continue;
fwrite(g_clipboard.data(), 1, g_clipboard.size(), pipe);
if (pclose(pipe) == 0) break;
}
}
#endif
class InitOperation : public osg::Operation {
public:
explicit InitOperation(ImGuiOsg* owner) : osg::Operation("ImGuiInit", false), owner_(owner) {}
void operator()(osg::Object*) override { owner_->initGL(); }
private:
osg::observer_ptr<ImGuiOsg> owner_;
};
class DrawCallback : public osg::Camera::DrawCallback {
public:
explicit DrawCallback(ImGuiOsg* owner) : owner_(owner) {}
void operator()(osg::RenderInfo& renderInfo) const override {
osg::ref_ptr<ImGuiOsg> owner;
if (owner_.lock(owner)) owner->render(renderInfo);
}
private:
osg::observer_ptr<ImGuiOsg> owner_;
};
class EventHandler : public osgGA::GUIEventHandler {
public:
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&) override {
if (!ImGui::GetCurrentContext()) return false;
ImGuiIO& io = ImGui::GetIO();
using E = osgGA::GUIEventAdapter;
auto updateMods = [&]() {
unsigned mask = ea.getModKeyMask();
io.AddKeyEvent(ImGuiMod_Ctrl, (mask & E::MODKEY_CTRL) != 0);
io.AddKeyEvent(ImGuiMod_Shift, (mask & E::MODKEY_SHIFT) != 0);
io.AddKeyEvent(ImGuiMod_Alt, (mask & E::MODKEY_ALT) != 0);
io.AddKeyEvent(ImGuiMod_Super, (mask & E::MODKEY_SUPER) != 0);
};
auto mousePos = [&]() {
float w = ea.getXmax() - ea.getXmin(), h = ea.getYmax() - ea.getYmin();
float nx = w > 0 ? (ea.getX() - ea.getXmin()) / w : 0.f;
float ny = h > 0 ? (ea.getY() - ea.getYmin()) / h : 0.f;
if (ea.getMouseYOrientation() == E::Y_INCREASING_UPWARDS) ny = 1.f - ny;
io.AddMousePosEvent(nx * io.DisplaySize.x, ny * io.DisplaySize.y);
};
auto button = [&]() -> int {
switch (ea.getButton()) {
case E::LEFT_MOUSE_BUTTON: return 0;
case E::RIGHT_MOUSE_BUTTON: return 1;
case E::MIDDLE_MOUSE_BUTTON: return 2;
default: return -1;
}
};
switch (ea.getEventType()) {
case E::PUSH:
case E::RELEASE: {
mousePos();
updateMods();
int b = button();
if (b >= 0) io.AddMouseButtonEvent(b, ea.getEventType() == E::PUSH);
return io.WantCaptureMouse;
}
case E::DOUBLECLICK:
mousePos();
return io.WantCaptureMouse;
case E::DRAG:
case E::MOVE:
mousePos();
return io.WantCaptureMouse;
case E::SCROLL: {
float dx = 0.f, dy = 0.f;
switch (ea.getScrollingMotion()) {
case E::SCROLL_UP: dy = 1.f; break;
case E::SCROLL_DOWN: dy = -1.f; break;
case E::SCROLL_LEFT: dx = 1.f; break;
case E::SCROLL_RIGHT: dx = -1.f; break;
case E::SCROLL_2D:
dx = ea.getScrollingDeltaX() * 0.1f;
dy = ea.getScrollingDeltaY() * 0.1f;
break;
default: break;
}
io.AddMouseWheelEvent(dx, dy);
return io.WantCaptureMouse;
}
case E::KEYDOWN:
case E::KEYUP: {
updateMods();
const bool down = ea.getEventType() == E::KEYDOWN;
int key = ea.getUnmodifiedKey() ? ea.getUnmodifiedKey() : ea.getKey();
ImGuiKey imguiKey = mapKey(key);
if (imguiKey != ImGuiKey_None) io.AddKeyEvent(imguiKey, down);
// OSG reports special keys as X11-style keysyms in 0xFF00-0xFFFF; everything else is a character.
int ch = ea.getKey();
const bool ctrlOrSuper = (ea.getModKeyMask() & (E::MODKEY_CTRL | E::MODKEY_SUPER)) != 0;
if (down && !ctrlOrSuper && ch >= 32 && ch != 127 && !(ch >= 0xFF00 && ch <= 0xFFFF))
io.AddInputCharacter(static_cast<unsigned>(ch));
return io.WantCaptureKeyboard;
}
default: return false;
}
}
};
} // namespace
ImGuiOsg::ImGuiOsg(DrawFunction draw) : draw_(std::move(draw)) {
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = nullptr;
#if !defined(_WIN32) && !defined(__APPLE__)
ImGuiPlatformIO& platformIo = ImGui::GetPlatformIO();
platformIo.Platform_GetClipboardTextFn = getClipboardText;
platformIo.Platform_SetClipboardTextFn = setClipboardText;
#endif
ImGui::StyleColorsDark();
ImGui::GetStyle().WindowRounding = 4.f;
loadFonts();
}
void ImGuiOsg::loadFonts() {
ImGuiIO& io = ImGui::GetIO();
const float size = 16.f;
io.Fonts->Clear();
static const ImWchar symbolRanges[] = {0x0370, 0x03FF, 0x2000, 0x27BF, 0x2E80, 0x2FDF, 0x3000, 0x30FF,
0xFF00, 0xFFEF, 0};
ImFontGlyphRangesBuilder builder;
builder.AddRanges(io.Fonts->GetGlyphRangesJapanese());
builder.AddRanges(symbolRanges);
builder.AddText(extraGlyphs_.c_str());
glyphRanges_.clear();
builder.BuildRanges(&glyphRanges_);
// A CJK font is needed to show MMD bone and morph names (Japanese).
const char* candidates[] = {
"/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc",
"/System/Library/Fonts/Hiragino Sans GB.ttc",
"/Library/Fonts/Arial Unicode.ttf",
"C:/Windows/Fonts/meiryo.ttc",
"C:/Windows/Fonts/YuGothM.ttc",
"C:/Windows/Fonts/msgothic.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/truetype/fonts-japanese-gothic.ttf",
};
for (const char* path : candidates) {
std::error_code ec;
if (!std::filesystem::exists(std::filesystem::u8path(path), ec)) continue;
ImFontConfig config;
config.OversampleH = 1;
if (io.Fonts->AddFontFromFileTTF(path, size, &config, glyphRanges_.Data)) return;
}
std::cerr << "No Japanese font found; MMD names may show as '?'\n";
ImFontConfig config;
config.SizePixels = size;
io.Fonts->AddFontDefault(&config);
}
void ImGuiOsg::addGlyphs(const std::string& utf8Text) {
extraGlyphs_ += utf8Text;
fontsDirty_ = true;
}
void ImGuiOsg::setUiScale(float scale) {
ImGuiStyle& style = ImGui::GetStyle();
style.ScaleAllSizes(scale / uiScale_);
ImGui::GetIO().FontGlobalScale = scale;
uiScale_ = scale;
}
void ImGuiOsg::attach(osgViewer::Viewer& viewer) {
camera_ = viewer.getCamera();
viewer.setRealizeOperation(new InitOperation(this));
viewer.addEventHandler(new EventHandler);
viewer.getCamera()->setFinalDrawCallback(new DrawCallback(this));
}
void ImGuiOsg::initGL() {
if (initialized_) return;
ImGui_ImplOpenGL2_Init();
initialized_ = true;
}
void ImGuiOsg::render(osg::RenderInfo& renderInfo) {
if (!initialized_) initGL();
osg::State* state = renderInfo.getState();
osg::Camera* camera = renderInfo.getCurrentCamera();
const osg::Viewport* vp = camera ? camera->getViewport() : nullptr;
if (!vp) return;
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2(static_cast<float>(vp->width()), static_cast<float>(vp->height()));
const double now = osg::Timer::instance()->time_s();
io.DeltaTime = lastTime_ > 0.0 ? static_cast<float>(std::max(now - lastTime_, 1e-4)) : 1.f / 60.f;
lastTime_ = now;
// Hand OpenGL back in a neutral state so the fixed-function ImGui backend works.
state->unbindVertexBufferObject();
state->unbindElementBufferObject();
state->disableAllVertexArrays();
const osg::GLExtensions* ext = state->get<osg::GLExtensions>();
if (ext->isGlslSupported) ext->glUseProgram(0);
state->setLastAppliedProgramObject(nullptr);
state->setActiveTextureUnit(0);
state->setClientActiveTextureUnit(0);
if (ext->isMultiTexturingSupported) {
ext->glActiveTexture(GL_TEXTURE0);
ext->glClientActiveTexture(GL_TEXTURE0);
}
if (ext->isBufferObjectSupported) {
ext->glBindBuffer(GL_ARRAY_BUFFER_ARB, 0);
ext->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
}
if (ext->isVAOSupported) ext->glBindVertexArray(0);
if (fontsDirty_) {
fontsDirty_ = false;
loadFonts();
ImGui_ImplOpenGL2_DestroyFontsTexture();
}
ImGui_ImplOpenGL2_NewFrame();
ImGui::NewFrame();
if (uiVisible_ && draw_) draw_();
ImGui::Render();
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
if (!screenshotPath_.empty()) {
osg::ref_ptr<osg::Image> image = new osg::Image;
image->readPixels(static_cast<int>(vp->x()), static_cast<int>(vp->y()), static_cast<int>(vp->width()),
static_cast<int>(vp->height()), GL_RGB, GL_UNSIGNED_BYTE);
if (osgDB::writeImageFile(*image, screenshotPath_)) std::cout << "Saved screenshot " << screenshotPath_ << "\n";
else std::cerr << "Failed to write screenshot " << screenshotPath_ << "\n";
screenshotPath_.clear();
}
state->dirtyAllModes();
state->dirtyAllAttributes();
state->dirtyAllVertexArrays();
}
} // namespace mr
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <imgui.h>
#include <osgViewer/Viewer>
#include <functional>
#include <string>
namespace mr {
// Renders Dear ImGui on top of an osgViewer::Viewer (single-threaded) and feeds it OSG input events.
class ImGuiOsg : public osg::Referenced {
public:
using DrawFunction = std::function<void()>;
explicit ImGuiOsg(DrawFunction draw);
// Call before viewer.realize().
void attach(osgViewer::Viewer& viewer);
void setUiVisible(bool visible) { uiVisible_ = visible; }
bool uiVisible() const { return uiVisible_; }
void setUiScale(float scale);
float uiScale() const { return uiScale_; }
// Saves the next rendered frame (including the UI) to a PNG/JPG file.
// Ensures every character in the text (e.g. model bone/morph names) is in the font atlas.
void addGlyphs(const std::string& utf8Text);
void requestScreenshot(const std::string& path) { screenshotPath_ = path; }
bool screenshotPending() const { return !screenshotPath_.empty(); }
// Called from the camera draw callback.
void render(osg::RenderInfo& renderInfo);
bool initialized() const { return initialized_; }
void initGL();
private:
void loadFonts();
DrawFunction draw_;
std::string extraGlyphs_;
bool fontsDirty_ = false;
ImVector<ImWchar> glyphRanges_;
bool initialized_ = false;
bool uiVisible_ = true;
float uiScale_ = 1.f;
double lastTime_ = 0.0;
std::string screenshotPath_;
osg::observer_ptr<osg::Camera> camera_;
};
} // namespace mr
Binary file not shown.

After

Width:  |  Height:  |  Size: 91 B

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 91 B

+166
View File
@@ -0,0 +1,166 @@
// Loader and posing tests. Test models are generated by tools/make_test_models.py.
#include "model/ModelLoader.h"
#include "model/Poser.h"
#include <cmath>
#include <cstdio>
#include <string>
namespace {
int g_failures = 0;
#define CHECK(cond) \
do { \
if (!(cond)) { \
std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
++g_failures; \
} \
} while (0)
bool near(float a, float b, float eps = 1e-4f) { return std::fabs(a - b) <= eps; }
bool near(const osg::Vec3f& a, const osg::Vec3f& b, float eps = 1e-4f) {
return near(a.x(), b.x(), eps) && near(a.y(), b.y(), eps) && near(a.z(), b.z(), eps);
}
std::shared_ptr<mr::Model> load(const char* name) {
std::string error;
auto model = mr::loadModel(std::string(MR_TEST_DATA_DIR) + "/" + name, error);
if (!model) std::printf("load %s failed: %s\n", name, error.c_str());
return model;
}
// File vertex 16 is (1, 10, 1) in right-handed space, stored as (1, 10, -1) in the file.
void testPmx() {
auto model = load("column.pmx");
CHECK(model);
if (!model) return;
CHECK(model->format == mr::SourceFormat::PMX);
CHECK(model->name == "テストモデル");
CHECK(model->vertices.size() == 20);
CHECK(model->indices.size() == 96);
CHECK(near(model->vertices[16].position, osg::Vec3f(1, 10, 1)));
CHECK(near(model->vertices[0].uv.y(), 1.0f)); // v flipped to OpenGL convention
CHECK(model->indices[0] == 0 && model->indices[1] == 4 && model->indices[2] == 1);
CHECK(model->textures.size() == 1 && model->textures[0].path.find("checker.png") != std::string::npos);
CHECK(model->warnings.empty());
CHECK(model->materials.size() == 1 && model->materials[0].sharedToon == 0 && model->materials[0].drawEdge);
CHECK(model->bones.size() == 4);
CHECK(model->findBone("上半身") == 1 && model->findBone("upper") == 1);
CHECK(model->bones[2].inheritRotation && model->bones[2].inheritParent == 1);
CHECK(model->bones[3].isIK);
CHECK(model->morphs.size() == 5);
CHECK(model->morphs[0].panel == mr::MorphPanel::Mouth && model->morphs[0].vertexOffsets.size() == 4);
CHECK(model->morphs[1].type == mr::MorphType::Group);
CHECK(model->morphs[2].type == mr::MorphType::Bone);
CHECK(model->morphs[4].type == mr::MorphType::Material);
// Middle ring is BDEF2 0.5/0.5 between center and upper.
CHECK(model->vertices[8].bones[0] == 0 && near(model->vertices[8].weights[0], 0.5f));
mr::Poser poser(model);
CHECK(poser.update());
CHECK(near(poser.positions()[16], osg::Vec3f(1, 10, 1)));
CHECK(!poser.update()); // nothing changed
poser.morphWeights()[0] = 1.f;
CHECK(poser.update());
CHECK(near(poser.positions()[16], osg::Vec3f(2, 10, 1.5f)));
poser.resetMorphs();
poser.morphWeights()[1] = 1.f; // group -> 0.5 * mouth
poser.update();
CHECK(near(poser.positions()[16], osg::Vec3f(1.5f, 10, 1.25f)));
poser.resetMorphs();
poser.morphWeights()[2] = 1.f; // bone morph lifts the upper body
poser.update();
CHECK(near(poser.positions()[16], osg::Vec3f(1, 11, 1)));
CHECK(near(poser.positions()[0], osg::Vec3f(1, 0, 1)));
poser.resetMorphs();
// Rotate the upper body 90 degrees about +Z around its head (0, 5, 0).
poser.bonePoses()[1].eulerDegrees.set(0, 0, 90);
poser.update();
CHECK(near(poser.positions()[16], osg::Vec3f(-5, 6, 1), 1e-3f));
CHECK(near(poser.positions()[0], osg::Vec3f(1, 0, 1)));
// Eye inherits half of the upper-body rotation on top of its parent's: 135 degrees total.
osg::Quat q = poser.boneGlobals()[2].getRotate();
double angle;
osg::Vec3d axis;
q.getRotate(angle, axis);
CHECK(near(static_cast<float>(angle), static_cast<float>(osg::PI * 0.75), 1e-3f));
CHECK(near(static_cast<float>(axis.z()), 1.f, 1e-3f));
}
void testPmd() {
auto model = load("column.pmd");
CHECK(model);
if (!model) return;
CHECK(model->format == mr::SourceFormat::PMD);
CHECK(model->name == "テストPMD");
CHECK(model->vertices.size() == 20 && model->indices.size() == 96);
CHECK(near(model->vertices[16].position, osg::Vec3f(1, 10, 1)));
CHECK(model->bones.size() == 2 && model->bones[1].name == "上半身");
CHECK(model->bones[0].translatable);
CHECK(model->morphs.size() == 1 && model->morphs[0].name == "あ");
CHECK(model->morphs[0].panel == mr::MorphPanel::Mouth);
CHECK(model->morphs[0].vertexOffsets.size() == 4 && model->morphs[0].vertexOffsets[0].vertex == 16);
CHECK(model->materials.size() == 1 && model->materials[0].texture == 0);
CHECK(model->materials[0].sharedToon == 0);
CHECK(!model->textures[0].path.empty());
// A zero weight on the first bone must leave the second bone as the only influence.
CHECK(model->vertices[16].bones[0] == 1 && near(model->vertices[16].weights[0], 1.f));
CHECK(model->vertices[16].bones[1] == -1);
mr::Poser poser(model);
poser.morphWeights()[0] = 1.f;
poser.update();
CHECK(near(poser.positions()[16], osg::Vec3f(2, 10, 1.5f)));
poser.resetMorphs();
poser.bonePoses()[1].eulerDegrees.set(0, 0, 90);
poser.update();
CHECK(near(poser.positions()[16], osg::Vec3f(-5, 6, 1), 1e-3f));
}
void testFbx() {
auto model = load("rigged_box.fbx");
CHECK(model);
if (!model) return;
CHECK(model->format == mr::SourceFormat::Assimp);
int lower = model->findBone("Lower"), upper = model->findBone("Upper");
CHECK(lower >= 0 && upper >= 0);
CHECK(model->findMorph("MouthOpen") >= 0);
if (upper < 0 || model->findMorph("MouthOpen") < 0) return;
mr::Poser poser(model);
poser.update();
// Rest pose must reproduce the bind-pose mesh exactly.
float maxErr = 0.f;
for (size_t i = 0; i < model->vertices.size(); ++i)
maxErr = std::max(maxErr, (poser.positions()[i] - model->vertices[i].position).length());
CHECK(maxErr < 1e-3f);
poser.morphWeights()[model->findMorph("MouthOpen")] = 1.f;
poser.update();
float moved = 0.f;
for (size_t i = 0; i < model->vertices.size(); ++i)
moved = std::max(moved, (poser.positions()[i] - model->vertices[i].position).length());
CHECK(moved > 0.1f);
poser.resetMorphs();
poser.bonePoses()[upper].eulerDegrees.set(45, 0, 0);
poser.update();
moved = 0.f;
for (size_t i = 0; i < model->vertices.size(); ++i)
moved = std::max(moved, (poser.positions()[i] - model->vertices[i].position).length());
CHECK(moved > 0.1f);
}
} // namespace
int main() {
testPmx();
testPmd();
testFbx();
if (g_failures == 0) std::printf("All tests passed\n");
return g_failures == 0 ? 0 : 1;
}
+43
View File
@@ -0,0 +1,43 @@
# Run with: blender -b -P tools/make_test_fbx.py
# Writes tests/data/rigged_box.fbx: a tall box with a two-bone armature and a shape key.
import os
import bpy
out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tests", "data", "rigged_box.fbx")
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 1))
mesh = bpy.context.active_object
mesh.name = "Body"
mesh.scale = (0.5, 0.5, 2.0)
bpy.ops.object.transform_apply(scale=True)
bpy.ops.object.mode_set(mode="EDIT")
bpy.ops.mesh.subdivide(number_cuts=6)
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.armature_add(location=(0, 0, 0))
arm = bpy.context.active_object
arm.name = "Armature"
bpy.ops.object.mode_set(mode="EDIT")
lower = arm.data.edit_bones[0]
lower.name = "Lower"
lower.head, lower.tail = (0, 0, 0), (0, 0, 1)
upper = arm.data.edit_bones.new("Upper")
upper.head, upper.tail = (0, 0, 1), (0, 0, 2)
upper.parent = lower
bpy.ops.object.mode_set(mode="OBJECT")
mesh.select_set(True)
arm.select_set(True)
bpy.context.view_layer.objects.active = arm
bpy.ops.object.parent_set(type="ARMATURE_AUTO")
mesh.shape_key_add(name="Basis")
key = mesh.shape_key_add(name="MouthOpen")
for i, v in enumerate(mesh.data.vertices):
if v.co.z > 1.6:
key.data[i].co.x += 0.3
bpy.ops.object.select_all(action="SELECT")
bpy.ops.export_scene.fbx(filepath=out, use_selection=True, add_leaf_bones=False, bake_anim=False)
print("wrote", out)
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Writes small PMX/PMD test models (and a checker texture) into tests/data.
Geometry is authored in the viewer's right-handed space and converted to
MMD's left-handed convention (z mirrored, triangle winding reversed) on write.
"""
import os
import struct
import zlib
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tests", "data")
RINGS = [0.0, 2.5, 5.0, 7.5, 10.0]
CORNERS = [(1, 1), (-1, 1), (-1, -1), (1, -1)] # (x, z) counter-clockwise seen from +Y
def column():
"""Square column: 5 rings x 4 corners, outward faces CCW (right-handed)."""
verts = []
for y in RINGS:
for i, (x, z) in enumerate(CORNERS):
verts.append(((x, y, z), (x * 0.7071, 0.0, z * 0.7071), (i / 4.0, y / 10.0)))
tris = []
for r in range(len(RINGS) - 1):
for i in range(4):
a = r * 4 + i
b = r * 4 + (i + 1) % 4
c = a + 4
d = b + 4
# Seen from outside: a (bottom), b (bottom, next corner), d, c (top)
tris.append((a, c, b))
tris.append((b, c, d))
return verts, tris
def lh(v):
return (v[0], v[1], -v[2])
def write_png(path, size=8):
rows = b""
for y in range(size):
rows += b"\x00"
for x in range(size):
on = ((x // 2) + (y // 2)) % 2 == 0
rows += bytes((230, 60, 60, 255) if on else (240, 240, 240, 255))
def chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0))
png += chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")
with open(path, "wb") as f:
f.write(png)
def pmx_text(s):
b = s.encode("utf-16-le")
return struct.pack("<i", len(b)) + b
def write_pmx(path):
verts, tris = column()
out = b"PMX " + struct.pack("<f", 2.0) + bytes([8, 0, 0, 2, 1, 1, 1, 1, 1])
out += pmx_text("テストモデル") + pmx_text("TestModel") + pmx_text("comment") + pmx_text("")
out += struct.pack("<i", len(verts))
for idx, (p, n, uv) in enumerate(verts):
y = p[1]
out += struct.pack("<3f", *lh(p)) + struct.pack("<3f", *lh(n)) + struct.pack("<2f", *uv)
if y < 4:
out += bytes([0]) + struct.pack("<b", 0) # BDEF1 center
elif y < 6:
out += bytes([1]) + struct.pack("<bbf", 0, 1, 0.5) # BDEF2
elif y < 9:
out += bytes([3]) + struct.pack("<bbf", 1, 0, 1.0) + struct.pack("<9f", *([0.0] * 9)) # SDEF
else:
out += bytes([2]) + struct.pack("<bbbb", 1, -1, -1, -1) + struct.pack("<4f", 1, 0, 0, 0) # BDEF4
out += struct.pack("<f", 1.0)
out += struct.pack("<i", len(tris) * 3)
for a, b, c in tris:
out += struct.pack("<3H", a, c, b) # reverse winding for left-handed
out += struct.pack("<i", 1) + pmx_text("tex\\Checker.PNG")
out += struct.pack("<i", 1)
out += pmx_text("材質") + pmx_text("material")
out += struct.pack("<4f", 1, 1, 1, 1) + struct.pack("<3f", 0, 0, 0) + struct.pack("<f", 0)
out += struct.pack("<3f", 0.5, 0.5, 0.5) + bytes([0x10]) + struct.pack("<4f", 0, 0, 0, 1) + struct.pack("<f", 1)
out += struct.pack("<bb", 0, -1) + bytes([0]) + bytes([1, 0]) + pmx_text("") + struct.pack("<i", len(tris) * 3)
def bone(name, en, pos, parent, flags, extra):
return pmx_text(name) + pmx_text(en) + struct.pack("<3f", *lh(pos)) + struct.pack("<b", parent) + \
struct.pack("<i", 0) + struct.pack("<H", flags) + extra
base = 0x0002 | 0x0008 | 0x0010
out += struct.pack("<i", 4)
out += bone("センター", "center", (0, 0, 0), -1, base | 0x0001 | 0x0004, struct.pack("<b", 1))
out += bone("上半身", "upper", (0, 5, 0), 0, base, struct.pack("<3f", 0, 5, 0))
out += bone("目", "eye", (0, 9, 0), 1, base | 0x0100, struct.pack("<3f", 0, 1, 0) + struct.pack("<bf", 1, 0.5))
ik = struct.pack("<3f", 0, 0, 0) + struct.pack("<bif", 2, 10, 1.0) + struct.pack("<i", 1)
ik += struct.pack("<b", 1) + bytes([1]) + struct.pack("<6f", -1, 0, 0, 1, 0, 0)
out += bone("IK", "ik", (0, 10, 0), -1, base | 0x0004 | 0x0020, ik)
out += struct.pack("<i", 5)
out += pmx_text("あ") + pmx_text("mouth_a") + bytes([3, 1]) + struct.pack("<i", 4)
for i in range(16, 20):
out += struct.pack("<H", i) + struct.pack("<3f", *lh((1.0, 0.0, 0.5)))
out += pmx_text("グループ") + pmx_text("group") + bytes([4, 0]) + struct.pack("<i", 1) + struct.pack("<bf", 0, 0.5)
out += pmx_text("ボーン") + pmx_text("bone_morph") + bytes([4, 2]) + struct.pack("<i", 1)
out += struct.pack("<b", 1) + struct.pack("<3f", 0, 1, 0) + struct.pack("<4f", 0, 0, 0, 1)
out += pmx_text("UV") + pmx_text("uv_morph") + bytes([4, 3]) + struct.pack("<i", 1)
out += struct.pack("<H", 0) + struct.pack("<4f", 0.1, 0, 0, 0)
out += pmx_text("材質モーフ") + pmx_text("material_morph") + bytes([4, 8]) + struct.pack("<i", 1)
out += struct.pack("<b", 0) + bytes([0]) + struct.pack("<28f", *([0.0] * 28))
out += struct.pack("<i", 0) * 3 # display frames, rigid bodies, joints
with open(path, "wb") as f:
f.write(out)
def sjis(s, n):
b = s.encode("cp932")
assert len(b) <= n
return b + b"\x00" * (n - len(b))
def write_pmd(path):
verts, tris = column()
out = b"Pmd" + struct.pack("<f", 1.0) + sjis("テストPMD", 20) + sjis("comment", 256)
out += struct.pack("<I", len(verts))
for p, n, uv in verts:
y = p[1]
b0, b1, w = (0, 0, 100) if y < 4 else (0, 1, 50) if y < 6 else (0, 1, 0) # top: all weight on 2nd bone
out += struct.pack("<3f", *lh(p)) + struct.pack("<3f", *lh(n)) + struct.pack("<2f", *uv)
out += struct.pack("<HHBB", b0, b1, w, 0)
out += struct.pack("<I", len(tris) * 3)
for a, b, c in tris:
out += struct.pack("<3H", a, c, b)
out += struct.pack("<I", 1)
out += struct.pack("<4f", 1, 1, 1, 1) + struct.pack("<f", 5) + struct.pack("<3f", 0, 0, 0)
out += struct.pack("<3f", 0.5, 0.5, 0.5) + bytes([0, 1]) + struct.pack("<I", len(tris) * 3)
out += sjis("checker.png", 20)
out += struct.pack("<H", 2)
out += sjis("センター", 20) + struct.pack("<HHBH", 0xFFFF, 1, 1, 0) + struct.pack("<3f", 0, 0, 0)
out += sjis("上半身", 20) + struct.pack("<HHBH", 0, 0, 0, 0) + struct.pack("<3f", *lh((0, 5, 0)))
out += struct.pack("<H", 0) # IK
out += struct.pack("<H", 2) # morphs: base + one
top = list(range(16, 20))
out += sjis("base", 20) + struct.pack("<IB", len(top), 0)
for i in top:
out += struct.pack("<I", i) + struct.pack("<3f", *lh(verts[i][0]))
out += sjis("あ", 20) + struct.pack("<IB", len(top), 3)
for k in range(len(top)):
out += struct.pack("<I", k) + struct.pack("<3f", *lh((1.0, 0.0, 0.5)))
out += bytes([0]) + bytes([0]) + struct.pack("<I", 0) # display lists
out += bytes([0]) # no English names
for i in range(10):
out += sjis("toon%02d.bmp" % (i + 1), 100)
with open(path, "wb") as f:
f.write(out)
if __name__ == "__main__":
os.makedirs(os.path.join(OUT, "tex"), exist_ok=True)
write_png(os.path.join(OUT, "tex", "checker.png"))
write_png(os.path.join(OUT, "checker.png"))
write_pmx(os.path.join(OUT, "column.pmx"))
write_pmd(os.path.join(OUT, "column.pmd"))
print("wrote test models to", os.path.normpath(OUT))