Compare commits

Author SHA1 Message Date
dev 21d0910e8e Merge pull request 'Camera fit: made-for height, distance and offset for camera motions' (#11) from devin/1796110078-camera-fit into main
Merge PR #11: camera fit
2026-12-01 08:35:43 -05:00
dev 73834b8c70 Merge pull request 'Post-processing: bloom, ambient occlusion, colour grading, FXAA' (#10) from devin/1796106677-postfx into main
Merge PR #10: bloom, colour grading, AO, FXAA; UV and material morphs
2026-12-01 08:35:31 -05:00
gs5579andDevin AI dc9d9fa46e Camera fit: made-for height, height scale, distance, offset; camera follows model placement
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 07:29:56 +00:00
gs5579andDevin AI 302e7c4f20 UV and material morphs; FXAA-only path skips composite, 8-bit post targets
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 07:03:56 +00:00
gs5579andDevin AI 799c4ac344 Grid: no depth writes so AO ignores it
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:48:44 +00:00
gs5579andDevin AI e786a88dec AO: distance-scaled bias against flat-ground self-occlusion
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:47:37 +00:00
gs5579andDevin AI 637a2c12f2 Post-FX: fit near/far for big stages, explicit grid shader, fade AO with distance
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:42:48 +00:00
gs5579andDevin AI 4b33a676eb Bloom: luminance threshold, gentler defaults; README
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:35:26 +00:00
gs5579andDevin AI 5be372d773 Post-processing: bloom, ambient occlusion, filmic tone mapping, colour grading, FXAA
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:34:45 +00:00
dev fd6f56826e Merge pull request 'Look panel: outlines, shadows, cel/studio shading, rim light' (#9) from devin/1796104981-shaders into main 2026-12-01 01:31:13 -05:00
gs5579andDevin AI bb6f154d60 Outlines: keep thin edges about a pixel wide; tone down cel highlight
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:21:59 +00:00
gs5579andDevin AI 2c625254f3 Shadow lookup: early-out with 4 taps outside penumbras
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:19:36 +00:00
gs5579andDevin AI 33458062ff Keep outlines and (by default) stages out of the shadow pass for speed
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:16:54 +00:00
gs5579andDevin AI 3154e4fab9 Add Look panel: edge outlines, shadow mapping, anime cel and soft studio shading, rim light
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-12-01 06:08:50 +00:00
dev 30d8c98891 Merge pull request 'Scene save/load (.mrscene)' (#8) from devin/1795937342-scene-files into main 2026-12-01 00:57:47 -05:00
dev 6a1c1e409f Merge pull request 'Multi-model scenes, stages and floor grid' (#7) from devin/1795876546-grid-multimodel into main 2026-12-01 00:57:38 -05:00
gs5579andDevin AI 269e107b70 Keep the pop-out viewport window alive when docking so the main view keeps its GL objects
Closing the pop-out's graphics context made OSG delete GL objects shared with the main window
(textures lose their CPU images after upload, so models came back black). Docking now hides the
window and reuses it; the window's close button docks instead of closing.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-29 09:34:32 +00:00
gs5579andDevin AI a48caace28 Return freed memory to macOS after New scene; report phys_footprint on macOS
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-29 08:37:36 +00:00
gs5579andDevin AI 2e2551c0ec Fix double-click on macOS, add Open scene menu item and file browser Open button, free memory on New scene, --reload-test
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-29 08:34:21 +00:00
gs5579andDevin AI 2ab57412ca Scene save/load (.mrscene) with relative paths, poses, motions, audio, view and settings
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-29 07:31:34 +00:00
gs5579andDevin AI ba6fafc344 Per-model Scale for models and stages (UI, --scale, --stage-scale)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-29 07:16:38 +00:00
gs5579andDevin AI 0d44e05fe9 Use diffuse alpha from imported materials (DirectX .x transparency)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-29 07:12:52 +00:00
gs5579andDevin AI 637b8ef220 Enable Assimp's DirectX .x importer for MMD stages
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-29 07:05:15 +00:00
gs5579andDevin AI 9d22dc687b Multi-model scenes, stages and a floor grid with XYZ axes
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 14:37:32 +00:00
dev 935203f11a Merge pull request 'MMD rigid-body physics (Bullet)' (#6) from devin/1795875194-physics into main 2026-11-28 09:35:43 -05:00
gs5579andDevin AI becfb7b7e8 Document physics
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 14:16:33 +00:00
gs5579andDevin AI b3d0afdd24 MMD rigid-body physics with Bullet: PMX/PMD rigid bodies and joints, Poser integration, UI toggle
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 14:16:22 +00:00
gs5579andDevin AI 22e3977fa0 Document the editor layout, timeline, pop-out viewport and rendering
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 14:02:41 +00:00
gs5579andDevin AI 5e14086a59 Render dialog: PNG frame sequence, optional ffmpeg MP4, --render batch mode
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 14:00:22 +00:00
gs5579andDevin AI e9ab4a5b12 Dockable editor layout, keyframe timeline and pop-out viewport
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 13:59:11 +00:00
gs5579andDevin AI 0658940348 Document camera and audio playback
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 06:27:58 +00:00
gs5579andDevin AI fa76cab6aa Fix structured binding capture for clang
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 06:27:26 +00:00
gs5579andDevin AI 95383f8353 Add VMD camera playback and synced audio via miniaudio
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 06:26:44 +00:00
gs5579andDevin AI 3d75165ce4 Add IK solving and VMD motion playback with timeline
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 06:14:40 +00:00
dev 77a6ff4550 Merge pull request 'GPU (hardware) skinning with CPU fallback' (#3) from devin/1795845494-gpu-skinning into main 2026-11-28 01:11:17 -05:00
gs5579andDevin AI e6f388ecdb Fix hardware skinning test build
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 06:01:39 +00:00
gs5579andDevin AI f415f4a4c3 Test hardware skinning math; document skinning modes
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 06:01:33 +00:00
gs5579andDevin AI c3cb854875 Add GPU (hardware) skinning path with CPU fallback
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-11-28 05:59:55 +00:00
dev 091c036d7b Merge pull request 'Parallel skinning and texture decoding, --bench option' (#2) from devin/1795844914-render-perf into main 2026-11-28 00:58:07 -05:00
47 changed files with 5674 additions and 188 deletions

No files matched your search

+72 -7
View File
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.16)
project(ModelRenderer VERSION 0.1.0 LANGUAGES CXX)
project(ModelRenderer VERSION 0.1.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -15,7 +15,7 @@ option(MR_FETCH_ASSIMP "Download and build Assimp if it is not installed" ON)
include(FetchContent)
# --- OpenSceneGraph -----------------------------------------------------------
find_package(OpenSceneGraph 3.6 REQUIRED COMPONENTS osgDB osgGA osgViewer osgUtil)
find_package(OpenSceneGraph 3.6 REQUIRED COMPONENTS osgDB osgGA osgViewer osgUtil osgText)
find_package(OpenGL REQUIRED)
# --- Assimp --------------------------------------------------------------------
@@ -31,6 +31,7 @@ if(NOT assimp_FOUND)
set(ASSIMP_BUILD_FBX_IMPORTER ON CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_OBJ_IMPORTER ON CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_GLTF_IMPORTER ON CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_X_IMPORTER ON CACHE BOOL "" FORCE) # DirectX .x: MMD accessories and stages
set(ASSIMP_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(ASSIMP_BUILD_ASSIMP_TOOLS OFF CACHE BOOL "" FORCE)
set(ASSIMP_INSTALL OFF CACHE BOOL "" FORCE)
@@ -44,8 +45,8 @@ endif()
# --- Dear ImGui ----------------------------------------------------------------
FetchContent_Declare(imgui
URL https://github.com/ocornut/imgui/archive/refs/tags/v1.91.5.tar.gz
URL_HASH SHA256=2aa2d169c569368439e5d5667e0796d09ca5cc6432965ce082e516937d7db254)
URL https://github.com/ocornut/imgui/archive/refs/tags/v1.91.5-docking.tar.gz
URL_HASH SHA256=f66c5d1b28fed044bd8dffa3882b4d1b29b2dbd1167fabe3d9d2219081e81cd8)
FetchContent_MakeAvailable(imgui)
add_library(imgui STATIC
@@ -68,6 +69,32 @@ if(NOT WIN32)
endif()
# --- Core library: model formats + posing (no rendering) -------------------------
# --- Bullet (MMD rigid-body physics) -----------------------------------------
set(BUILD_BULLET2_DEMOS OFF CACHE BOOL "" FORCE)
set(BUILD_CPU_DEMOS OFF CACHE BOOL "" FORCE)
set(BUILD_OPENGL3_DEMOS OFF CACHE BOOL "" FORCE)
set(BUILD_EXTRAS OFF CACHE BOOL "" FORCE)
set(BUILD_UNIT_TESTS OFF CACHE BOOL "" FORCE)
set(BUILD_PYBULLET OFF CACHE BOOL "" FORCE)
set(BUILD_BULLET3 OFF CACHE BOOL "" FORCE)
set(USE_GRAPHICAL_BENCHMARK OFF CACHE BOOL "" FORCE)
set(INSTALL_LIBS OFF CACHE BOOL "" FORCE)
set(USE_MSVC_RUNTIME_LIBRARY_DLL ON CACHE BOOL "" FORCE)
set(CMAKE_POLICY_VERSION_MINIMUM 3.5 CACHE STRING "")
FetchContent_Declare(bullet
URL https://github.com/bulletphysics/bullet3/archive/refs/tags/3.25.tar.gz
URL_HASH SHA256=c45afb6399e3f68036ddb641c6bf6f552bf332d5ab6be62f7e6c54eda05ceb77)
FetchContent_GetProperties(bullet)
if(NOT bullet_POPULATED)
FetchContent_Populate(bullet)
add_subdirectory(${bullet_SOURCE_DIR} ${bullet_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()
FetchContent_Declare(nlohmann_json
URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz
URL_HASH SHA256=d6c65aca6b1ed68e7a182f4757257b107ae403032760ed6ef121c9d55e81757d)
FetchContent_MakeAvailable(nlohmann_json)
add_library(mr_core STATIC
src/model/Model.cpp
src/model/TextEncoding.cpp
@@ -76,24 +103,62 @@ add_library(mr_core STATIC
src/model/PmdLoader.cpp
src/model/AssimpLoader.cpp
src/model/ModelLoader.cpp
src/model/Poser.cpp)
src/model/Poser.cpp
src/model/Motion.cpp
src/physics/PhysicsWorld.cpp
src/scene/SceneFile.cpp)
target_include_directories(mr_core PUBLIC src ${OPENSCENEGRAPH_INCLUDE_DIRS})
find_package(Threads REQUIRED)
target_link_libraries(mr_core PUBLIC ${OPENSCENEGRAPH_LIBRARIES} assimp::assimp Threads::Threads)
target_include_directories(mr_core PRIVATE ${bullet_SOURCE_DIR}/src)
target_link_libraries(mr_core PRIVATE BulletDynamics BulletCollision LinearMath nlohmann_json::nlohmann_json)
if(NOT WIN32)
target_link_libraries(mr_core PRIVATE Iconv::Iconv)
endif()
# --- miniaudio (audio playback) ---------------------------------------------------
FetchContent_Declare(miniaudio
URL https://github.com/mackron/miniaudio/archive/refs/tags/0.11.21.tar.gz
URL_HASH SHA256=6afb5c231613d2fab4f1c668b7243ff9a7d6d78a7f5a2692c133f026fe508506)
FetchContent_GetProperties(miniaudio)
if(NOT miniaudio_POPULATED)
FetchContent_Populate(miniaudio)
endif()
add_library(mr_audio STATIC src/audio/AudioPlayer.cpp src/audio/miniaudio_impl.c)
target_include_directories(mr_audio PUBLIC src SYSTEM PRIVATE ${miniaudio_SOURCE_DIR})
target_link_libraries(mr_audio PRIVATE Threads::Threads ${CMAKE_DL_LIBS})
if(UNIX AND NOT APPLE)
target_link_libraries(mr_audio PRIVATE m)
endif()
# --- Viewer application ----------------------------------------------------------
add_executable(model_renderer
src/app/main.cpp
src/app/AppUi.cpp
src/app/FileBrowser.cpp
src/app/Timeline.cpp
src/app/Render.cpp
src/app/SceneIo.cpp
src/render/Grid.cpp
src/render/ModelNode.cpp
src/render/Look.cpp
src/render/PostFx.cpp
src/render/TextureLoader.cpp
src/render/Shaders.cpp
src/render/GpuCaps.cpp
src/ui/ImGuiOsg.cpp)
target_link_libraries(model_renderer PRIVATE mr_core imgui OpenGL::GL)
target_link_libraries(model_renderer PRIVATE mr_core mr_audio imgui OpenGL::GL)
if(APPLE)
enable_language(OBJCXX)
target_sources(model_renderer PRIVATE src/app/WindowVisibility.mm)
target_link_libraries(model_renderer PRIVATE "-framework Cocoa")
else()
target_sources(model_renderer PRIVATE src/app/WindowVisibility.cpp)
if(NOT WIN32)
find_package(X11 REQUIRED)
target_link_libraries(model_renderer PRIVATE X11::X11)
endif()
endif()
if(MSVC)
target_compile_options(mr_core PRIVATE /W3 /utf-8)
@@ -107,7 +172,7 @@ endif()
if(MR_BUILD_TESTS)
enable_testing()
add_executable(mr_tests tests/test_main.cpp)
target_link_libraries(mr_tests PRIVATE mr_core)
target_link_libraries(mr_tests PRIVATE mr_core mr_audio)
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()
+75 -5
View File
@@ -12,7 +12,7 @@ Built with C++17, [OpenSceneGraph](https://github.com/openscenegraph/OpenSceneGr
.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)
CPU or GPU skinning)
```
* PMX and PMD use their own loaders because Assimp cannot read PMD and drops PMX morphs.
@@ -21,10 +21,16 @@ Built with C++17, [OpenSceneGraph](https://github.com/openscenegraph/OpenSceneGr
* 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.
* Skinning has two paths, switchable under **View**: hardware (default; bone matrices go to the
vertex shader in a float texture) and software (`Poser` skins every vertex on the CPU, using all
cores). Hardware falls back to software if the GPU lacks vertex texture fetch or float textures.
Morphs are applied on the CPU in both modes and only re-uploaded when morph weights change.
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).
BDEF1/2/4 weights (SDEF/QDEF approximated as linear blend), IK (CCD with MMD-style knee limits),
VMD bone/morph/IK-switch and camera playback with MMD's Bezier easing, and song playback
(.wav/.mp3/.flac via [miniaudio](https://miniaud.io)) kept in sync with the timeline. Not yet:
VMD light/self-shadow keys, UV and material morphs.
## Building
@@ -101,10 +107,65 @@ 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.
The window is a dockable editor: **Scene** and **Bones** on the left, **Morphs** on the right,
the **Timeline** at the bottom and the 3D view in the middle. Drag a panel's tab to move, tab or
float it; the layout is saved to `~/.model_renderer_layout.ini` (**View > Reset panel layout**
restores the default).
* **Scenes**: **File > Save scene** (Ctrl+S, Cmd+S on macOS) writes a `.mrscene` file with every
model and stage (Position, Rotation, Scale, Stage, visibility), each model's dance, bone pose
and morph edits, the camera motion, the song, the timeline frame, the 3D view's camera, the
View settings and the Render size. **File > Open scene...** (Ctrl+O) opens it again, and **New scene**
clears everything. Paths are stored relative to the scene file, so keep the scene next to (or
above) its `models/` folder and the whole folder can be moved or shared. The file is plain JSON.
* **File > Add model, motion or audio...** (or **Add media...** in the Timeline) picks a model,
a dance `.vmd`, a camera `.vmd` or a song (`.wav`/`.mp3`/`.flac`); camera files are detected
automatically. A dance `.vmd` applies to the model selected in the Scene panel.
* **Scene**: several models can be loaded at once. The list selects which one the Bones, Morphs
and Timeline panels edit, with a visibility checkbox and `x` to remove each one. **Position**,
**Rotation** and **Scale** place the selected model.
* **Stages** (**Add stage...**) are environment models such as a room or beach, as PMX, PMD or
DirectX `.x` (the format most classic MMD stages and accessories use). They get no
physics and don't move the camera when added. Files with "stage" or "ステージ" in the name, or
very large models, are marked as stages automatically; the **Stage** checkbox changes it.
* **Bones**: select a bone, then use the rotation sliders / move fields. `*` marks posed bones.
Bones the motion drives can still be offset. Bones in an IK chain follow their IK bone while
**View > Solve IK** is on.
* **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).
* **Timeline**: transport (play/pause, step, jump, frame field, loop, volume), a ruler to scrub
and one row of keyframes per camera, song, bone and morph track. Click a bone row to select
that bone. Ctrl+wheel zooms, Shift+wheel or middle drag pans. While the song plays its clock
drives the timeline. Untick **Camera follow** to orbit freely.
**Camera fit...** adapts a camera motion made for a different model: set **Made for height** (about
20 for standard MMD models, or **Measure model...** to read it from the model the motion came
with), then **Fit to model** scales the camera's heights to the selected model. **Distance** moves
every shot closer or farther and **Offset X/Y/Z** shifts the whole camera. With **Follow model
placement** on, moving, turning or scaling the model carries the camera with it. Saved in the scene;
`--camera-made-for H --camera-fit`, `--camera-height S`, `--camera-distance S` and
`--camera-offset x,y,z` do the same from the command line.
* **Pop out** (top-left of the 3D view, or **View > Viewport in separate window**) moves the 3D
view into its own OS window, e.g. for a second monitor; close it or press **Dock viewport back**.
* **File > Render...** writes a PNG frame sequence at any resolution (presets up to 4K and
vertical), optionally with a transparent background. If `ffmpeg` is on the `PATH` it also
encodes `render.mp4` with the song.
* **Physics**: models with rigid bodies and joints (hair, skirts, tails) are simulated with
Bullet, as in MMD. Toggle it in the Scene panel or **View > Physics** (`--physics off` on the
command line); **Reset physics** snaps everything back to the pose. Physics resets and settles
when you jump on the timeline, and renders step it exactly one frame at a time.
* **Look** panel (tabbed with Morphs): material style (MMD toon, Lambert, anime cel, soft
studio), light colour and direction, MMD edge outlines (from each PMX/PMD material's edge colour
and size), soft shadow mapping (self-shadows, shadows on stages, and a shadow-only floor when no
stage is visible), rim light, and one-click presets. Saved in `.mrscene` files and used in final
renders. Command line: `--shading toon|lambert|cel|soft`, `--shadows on|off`,
`--outlines on|off`, `--rim S`.
* **Post-processing** (Look panel): bloom, ambient occlusion, FXAA anti-aliasing, filmic tone
mapping and colour grading (exposure, contrast, saturation, temperature, vignette). All off by
default, so older GPUs pay nothing; the Anime and Studio presets turn some on. Also applied to
the pop-out window and final renders. Command line: `--bloom S`, `--ao on|off`,
`--fxaa on|off`, `--filmic on|off`.
* **View**: floor grid with labelled X (red), Y (green) and Z (blue) axes (hidden in renders),
skeleton overlay, wireframe, culling, shading style, outlines, shadows, GPU vs CPU skinning,
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.
@@ -114,6 +175,15 @@ Command-line options (`--help`) allow scripted renders, e.g.
--orbit 20,10 --hide-ui --screenshot out.png
```
`--motion dance.vmd --camera camera.vmd --audio song.wav --play` plays a full MMD scene
(`--frame N` jumps to a frame, `--pop-out` opens the separate viewport window);
`--add model.pmx` and `--stage stage.pmx` add more models (motions apply to the first);
`--scale S` and `--stage-scale S` resize the first model and the stages;
`--no-grid` hides the floor grid; `model_renderer scene.mrscene` opens a scene and
`--save-scene FILE` saves one after loading (`--reload-test N` reopens it N times and prints memory use);
`--render DIR [--range A,B] [--render-size WxH]` renders PNG frames without opening the UI flow;
`tools/make_test_vmd.py --demo out.vmd` writes a short demo motion. `--skinning gpu|cpu` picks the skinning path; `--bench N` prints load, frame and deformation times.
## Tests
```sh
+799 -41
View File
@@ -1,10 +1,18 @@
#include "app/AppUi.h"
#include "app/WindowVisibility.h"
#include "model/ModelLoader.h"
#include "render/GpuCaps.h"
#include "render/Grid.h"
#include "render/Shaders.h"
#include <imgui.h>
#include <imgui_internal.h>
#include <osg/NodeCallback>
#include <osgViewer/Renderer>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
@@ -34,15 +42,92 @@ const char* panelName(MorphPanel p) {
}
}
bool looksLikeStage(const std::string& path, const Model& model) {
for (const std::string& s : {path, model.name})
if (containsCaseInsensitive(s, "stage") || s.find("ステージ") != std::string::npos) return true;
osg::Vec3f lo, hi;
model.computeBounds(lo, hi);
return (hi - lo).length() > 120.f; // a character is about 20 units tall
}
} // namespace
namespace {
class TickCallback : public osg::NodeCallback {
public:
explicit TickCallback(App* app) : app_(app) {}
void operator()(osg::Node* node, osg::NodeVisitor* nv) override {
if (nv->getFrameStamp()) app_->tick(nv->getFrameStamp()->getReferenceTime());
traverse(node, nv);
}
private:
App* app_;
};
} // namespace
App::App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulator* manipulator)
: viewer_(viewer), root_(root), manipulator_(manipulator) {
imgui_ = new ImGuiOsg([this]() { drawUi(); });
root_->addUpdateCallback(new TickCallback(this));
viewer_.getCamera()->setProjectionResizePolicy(osg::Camera::FIXED);
imgui_->attach(viewer_);
sceneRoot_ = new osg::Group;
grid_ = createGrid(50.f, 5.f);
sceneRoot_->addChild(grid_);
sceneGroup_ = new osg::Group;
sceneRoot_->addChild(sceneGroup_);
sceneLook_ = std::make_unique<SceneLook>(sceneRoot_.get(), sceneGroup_.get());
// One post-processing chain per output camera; each camera's cull mask picks its own.
mainChain_ = new PostChain(sceneRoot_.get(), kMainViewMask);
popChain_ = new PostChain(sceneRoot_.get(), kPopViewMask);
renderChain_ = new PostChain(sceneRoot_.get(), kRenderViewMask);
for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()}) root_->addChild(chain);
viewer_.getCamera()->setCullMask(kMainViewMask | kGridNodeMask);
}
bool App::loadModel(const std::string& path) {
void App::setLook(const LookSettings& look) {
look_ = look;
applyViewSettings();
}
void App::updateLook() {
if (gpuCaps().probed) {
sceneLook_->setShadowsSupported(gpuCaps().shadows);
for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()})
chain->setSupported(gpuCaps().framebufferObjects, gpuCaps().floatTextures);
}
osg::Camera* master = viewer_.getCamera();
if (const osg::Viewport* vp = master->getViewport())
mainChain_->setSize(static_cast<int>(vp->width()), static_cast<int>(vp->height()));
mainChain_->setClearColor(master->getClearColor());
if (popCamera_ && popCamera_->getViewport()) {
popChain_->setSize(static_cast<int>(popCamera_->getViewport()->width()),
static_cast<int>(popCamera_->getViewport()->height()));
popChain_->setClearColor(popCamera_->getClearColor());
}
// Shadows cover the characters; with only stages visible they cover a capped part of the stage.
osg::BoundingSphere characters, stages;
for (const auto& item : items_) {
if (!item->visible) continue;
(item->stage ? stages : characters).expandBy(item->node->getBound());
}
const bool stageVisible = stages.valid();
if (!characters.valid() && stages.valid()) {
characters = stages;
characters.radius() = std::min(characters.radius(), 30.f);
}
sceneLook_->update(manipulator_->getInverseMatrix(), characters, !stageVisible);
}
void App::setShowGrid(bool show) {
showGrid_ = show;
grid_->setNodeMask(show ? kGridNodeMask : 0u);
}
bool App::loadModel(const std::string& path, bool stage) {
std::string error;
auto model = mr::loadModel(path, error);
if (!model) {
@@ -50,31 +135,449 @@ bool App::loadModel(const std::string& path) {
return false;
}
loadError_.clear();
if (modelNode_) root_->removeChild(modelNode_);
std::string glyphs = model->name + model->comment;
for (const auto& b : model->bones) glyphs += b.name + b.nameEn;
for (const auto& mo : model->morphs) glyphs += mo.name + mo.nameEn;
for (const auto& ma : model->materials) glyphs += ma.name;
imgui_->addGlyphs(glyphs);
modelNode_ = new ModelNode(model);
root_->addChild(modelNode_);
selectedBone_ = -1;
boneFilter_[0] = '\0';
morphFilter_[0] = '\0';
lightingModel_ = model->format == SourceFormat::Assimp ? 1 : 0;
applyViewSettings();
frameModel();
auto item = std::make_unique<SceneItem>();
item->node = new ModelNode(model);
item->base = item->node->getMatrix();
item->path = path;
item->stage = stage || looksLikeStage(path, *model);
item->name = model->name.empty() ? path.substr(path.find_last_of("/\\") + 1) : model->name;
sceneGroup_->addChild(item->node);
const bool firstCharacter =
!item->stage && std::none_of(items_.begin(), items_.end(), [](const auto& i) { return !i->stage; });
const bool frame = items_.empty() || !item->stage;
items_.push_back(std::move(item));
if (firstCharacter) look_.shading = model->format == SourceFormat::Assimp ? 1 : 0;
selectModel(static_cast<int>(items_.size()) - 1);
if (frame) frameModel();
return true;
}
void App::selectModel(int index) {
if (modelNode_) modelNode_->setSelectedBone(-1);
active_ = index >= 0 && index < static_cast<int>(items_.size()) ? index : -1;
SceneItem* item = activeItem();
modelNode_ = item ? item->node.get() : nullptr;
player_ = item ? item->player.get() : nullptr;
selectedBone_ = -1;
boneFilter_[0] = '\0';
morphFilter_[0] = '\0';
applyViewSettings();
}
void App::removeModel(int index) {
if (index < 0 || index >= static_cast<int>(items_.size())) return;
sceneGroup_->removeChild(items_[index]->node);
items_.erase(items_.begin() + index);
modelNode_ = nullptr;
player_ = nullptr;
selectModel(items_.empty() ? -1 : std::min(index, static_cast<int>(items_.size()) - 1));
}
void App::setModelScale(int index, float scale) {
if (index < 0 || index >= static_cast<int>(items_.size()) || scale <= 0.f) return;
items_[index]->scale = scale;
updatePlacement(*items_[index]);
}
void App::updatePlacement(SceneItem& item) {
item.node->setMatrix(osg::Matrix::scale(item.scale, item.scale, item.scale) *
osg::Matrix::rotate(osg::DegreesToRadians(item.rotationY), osg::Y_AXIS) *
osg::Matrix::translate(item.position) * item.base);
if (camera_ && useMotionCamera_ && cameraFit_.followModel) applyCamera();
}
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_);
for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()}) chain->apply(look_);
sceneLook_->apply(look_);
for (auto& item : items_) {
ModelNode* node = item->node.get();
const bool active = node == modelNode_;
node->setShowSkeleton(showSkeleton_ && active);
node->setBackfaceCulling(backfaceCulling_);
node->setWireframe(wireframe_);
node->setLightingModel(static_cast<LightingModel>(look_.shading));
node->setShowOutlines(look_.outlines);
node->setOutlineWidth(look_.outlineWidth);
node->setSelectedBone(active ? selectedBone_ : -1);
node->poser().setPhysicsEnabled(physicsEnabled_ && !item->stage);
node->setSkinningMode(skinning_ == 1 ? SkinningMode::Hardware : SkinningMode::Software);
const bool casts = !item->stage || look_.stageShadows;
node->setNodeMask(!item->visible ? 0u : casts ? ~0u : ~kShadowCasterMask);
}
}
void App::setGpuSkinning(bool enabled) {
skinning_ = enabled ? 1 : 0;
applyViewSettings();
}
bool App::loadMotion(const std::string& path) {
std::string error;
auto motion = loadVmd(path, error);
if (!motion) {
loadError_ = "Failed to load motion " + path + ": " + error;
return false;
}
const std::string name = path.substr(path.find_last_of("/\\") + 1);
if (!motion->cameraKeys.empty()) {
camera_ = motion;
cameraName_ = name;
cameraPath_ = path;
}
if (!motion->boneTracks.empty() || !motion->morphTracks.empty() || motion->cameraKeys.empty()) {
if (SceneItem* item = activeItem()) {
item->motion = motion;
item->motionName = name;
item->motionPath = path;
item->node->poser().resetMotion();
item->player.reset(new MotionPlayer(motion, item->node->model()));
player_ = item->player.get();
} else {
loadError_ = "Load a model before its motion: " + name;
}
}
setPlaying(false);
setMotionFrame(0.f);
return true;
}
bool App::loadAudio(const std::string& path) {
std::string error;
if (!audio_.load(path, error)) {
loadError_ = "Failed to load audio " + path + ": " + error;
return false;
}
audio_.setVolume(volume_);
audioName_ = path.substr(path.find_last_of("/\\") + 1);
audioPath_ = path;
setPlaying(false);
setMotionFrame(0.f);
return true;
}
void App::unloadMotion() {
setPlaying(false);
for (auto& item : items_) {
item->player.reset();
item->motion.reset();
item->motionName.clear();
item->motionPath.clear();
item->node->poser().resetMotion();
}
player_ = nullptr;
camera_.reset();
cameraPath_.clear();
restoreCamera();
audio_.unload();
audioPath_.clear();
audioName_.clear();
motionFrame_ = 0.f;
}
float App::timelineEnd() const {
float end = 0.f;
for (const auto& item : items_)
if (item->motion) end = std::max(end, static_cast<float>(item->motion->lastFrame));
if (camera_) end = std::max(end, static_cast<float>(camera_->lastFrame));
if (audio_.loaded()) end = std::max(end, static_cast<float>(audio_.length()) * kMotionFps);
return end;
}
void App::setPlaying(bool playing) {
playing_ = playing;
if (playing && motionFrame_ / kMotionFps < audio_.length()) {
audio_.seek(motionFrame_ / kMotionFps);
audio_.play();
} else {
audio_.pause();
}
}
void App::setPhysicsEnabled(bool enabled) {
physicsEnabled_ = enabled;
applyViewSettings();
}
void App::setMotionFrame(float frame) {
if (std::fabs(frame - motionFrame_) > 2.f)
for (auto& item : items_) item->node->poser().resetPhysics();
motionFrame_ = std::max(0.f, frame);
if (playing_) setPlaying(true);
else audio_.seek(motionFrame_ / kMotionFps);
applyFrame();
}
void App::applyFrame() {
for (auto& item : items_)
if (item->player) item->player->apply(motionFrame_, item->node->poser());
if (camera_ && useMotionCamera_) applyCamera();
}
void App::applyCamera() {
CameraPose pose = evaluateCamera(camera_->cameraKeys, motionFrame_);
const auto fit = [&](osg::Vec3f p) { return osg::Vec3f(p.x(), p.y() * cameraFit_.heightScale, p.z()); };
const osg::Vec3f center = fit(pose.center);
const osg::Vec3f eye = center + (fit(pose.eye) - center) * cameraFit_.distance + cameraFit_.offset;
// Camera motions are relative to the dancer: moving, turning or scaling the model carries the camera along.
osg::Matrixd toWorld = osg::Matrixd::rotate(osg::PI_2, osg::X_AXIS); // as ModelNode
if (const SceneItem* item = cameraFit_.followModel ? followedItem() : nullptr) toWorld = item->node->getMatrix();
const osg::Vec3d worldEye = osg::Vec3d(eye) * toWorld, worldCenter = osg::Vec3d(center + cameraFit_.offset) * toWorld;
const osg::Vec3d worldUp = osg::Vec3d(pose.up + center) * toWorld - osg::Vec3d(center) * toWorld;
manipulator_->setTransformation(worldEye, worldCenter, worldUp);
fov_ = pose.fov;
}
void App::setCameraFit(const CameraFit& fit) {
cameraFit_ = fit;
if (camera_ && useMotionCamera_) applyCamera();
}
// The selected model, or the first visible non-stage model when a stage is selected.
const App::SceneItem* App::followedItem() const {
if (active_ >= 0 && active_ < static_cast<int>(items_.size()) && !items_[active_]->stage) return items_[active_].get();
for (const auto& item : items_)
if (!item->stage && item->visible) return item.get();
return nullptr;
}
// In the model's own units: its Scale already scales the camera through followModel.
float App::followedModelHeight() const {
const SceneItem* item = followedItem();
if (!item) return 0.f;
osg::Vec3f lo, hi;
item->node->model().computeBounds(lo, hi);
return hi.y() - lo.y();
}
void App::fitCameraToModel() {
const float height = followedModelHeight();
if (height > 0.f && cameraFit_.madeFor > 0.f) cameraFit_.heightScale = height / cameraFit_.madeFor;
if (camera_ && useMotionCamera_) applyCamera();
}
void App::drawCameraFit() {
bool changed = false;
ImGui::TextUnformatted("Fit the camera motion to your model");
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8.f);
ImGui::DragFloat("Made for height", &cameraFit_.madeFor, 0.1f, 1.f, 1000.f, "%.1f");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Height of the model the camera motion was made for.\nStandard MMD models are about 20.");
ImGui::SameLine();
if (ImGui::Button("Measure model...")) {
measuringModel_ = true;
fileBrowser_.open();
}
const float height = followedModelHeight();
ImGui::BeginDisabled(height <= 0.f);
if (ImGui::Button("Fit to model")) fitCameraToModel();
ImGui::EndDisabled();
ImGui::SameLine();
ImGui::TextDisabled(height > 0.f ? "your model: %.1f" : "no model", height);
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8.f);
changed |= ImGui::DragFloat("Height scale", &cameraFit_.heightScale, 0.005f, 0.05f, 20.f, "%.3fx");
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8.f);
changed |= ImGui::DragFloat("Distance", &cameraFit_.distance, 0.005f, 0.05f, 20.f, "%.3fx");
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12.f);
changed |= ImGui::DragFloat3("Offset X/Y/Z", cameraFit_.offset.ptr(), 0.05f);
changed |= ImGui::Checkbox("Follow model placement", &cameraFit_.followModel);
if (ImGui::IsItemHovered())
ImGui::SetTooltip("Moving, turning or scaling the model moves the camera with it.");
if (ImGui::Button("Reset")) {
cameraFit_ = CameraFit();
changed = true;
}
if (changed && camera_ && useMotionCamera_) applyCamera();
}
void App::restoreCamera() {
fov_ = 30.0;
}
// Pop-out: a slave camera with its own OS window that shares GL objects with the editor window.
// The editor window then draws only the UI.
void App::updatePopOut() {
osg::Camera* master = viewer_.getCamera();
if (popCamera_ && !(popCamera_->getGraphicsContext() && popCamera_->getGraphicsContext()->valid()))
wantPopOut_ = false; // the window was closed
if (wantPopOut_ && !popCamera_ && parkedPopCamera_) {
osg::GraphicsContext* gc = parkedPopCamera_->getGraphicsContext();
if (gc && gc->valid()) {
// Drop events queued while hidden, such as repeated close requests.
if (auto* window = dynamic_cast<osgViewer::GraphicsWindow*>(gc)) window->getEventQueue()->clear();
popCamera_ = parkedPopCamera_;
setWindowVisible(gc, true);
viewer_.addSlave(popCamera_.get(), true);
master->setCullMask(0);
}
parkedPopCamera_ = nullptr;
}
if (wantPopOut_ && !popCamera_) {
osg::GraphicsContext* mainGc = master->getGraphicsContext();
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
if (mainGc && mainGc->getTraits()) {
traits->hostName = mainGc->getTraits()->hostName;
traits->displayNum = mainGc->getTraits()->displayNum;
traits->screenNum = mainGc->getTraits()->screenNum;
}
traits->x = 140;
traits->y = 140;
traits->width = 1280;
traits->height = 720;
traits->windowName = "Model Renderer - Viewport";
traits->windowDecoration = true;
traits->doubleBuffer = true;
traits->sharedContext = mainGc;
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
if (!gc) {
loadError_ = "Could not open a separate viewport window.";
wantPopOut_ = false;
return;
}
gc->realize();
prepareReusableWindow(gc.get());
popCamera_ = new osg::Camera;
popCamera_->setGraphicsContext(gc.get());
popCamera_->setViewport(0, 0, traits->width, traits->height);
popCamera_->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
popCamera_->setProjectionResizePolicy(osg::Camera::FIXED);
popCamera_->setClearColor(master->getClearColor());
popCamera_->setClearMask(master->getClearMask());
// Slaves inherit the master's cull settings; the master's cull mask hides the scene.
popCamera_->setInheritanceMask(popCamera_->getInheritanceMask() & ~osg::CullSettings::CULL_MASK);
popCamera_->setCullMask(kPopViewMask | kGridNodeMask);
popCamera_->setDrawBuffer(GL_BACK);
popCamera_->setReadBuffer(GL_BACK);
viewer_.addSlave(popCamera_.get(), true);
if (!popCamera_->getRenderer()) popCamera_->setRenderer(new osgViewer::Renderer(popCamera_.get()));
master->setCullMask(0);
} else if (!wantPopOut_ && popCamera_) {
const unsigned index = viewer_.findSlaveIndexForCamera(popCamera_.get());
if (index < viewer_.getNumSlaves()) viewer_.removeSlave(index);
osg::GraphicsContext* gc = popCamera_->getGraphicsContext();
if (gc && gc->valid()) {
setWindowVisible(gc, false);
parkedPopCamera_ = popCamera_;
} else {
popCamera_->setGraphicsContext(nullptr);
}
popCamera_ = nullptr;
master->setCullMask(kMainViewMask | kGridNodeMask);
}
if (!popCamera_) return;
const osg::GraphicsContext::Traits* traits = popCamera_->getGraphicsContext()->getTraits();
const int w = std::max(traits->width, 1), h = std::max(traits->height, 1);
popCamera_->setViewport(0, 0, w, h);
popCamera_->setProjectionMatrixAsPerspective(fov_, double(w) / h, 0.1, 1000.0);
popCamera_->setViewMatrix(manipulator_->getInverseMatrix());
}
void App::catchPopOutClose() {
auto* window = popCamera_ ? dynamic_cast<osgViewer::GraphicsWindow*>(popCamera_->getGraphicsContext()) : nullptr;
if (!window || !window->valid()) return;
window->checkEvents();
osgGA::EventQueue::Events events;
window->getEventQueue()->takeEvents(events);
for (const auto& event : events) {
const osgGA::GUIEventAdapter* ea = event->asGUIEventAdapter();
if (ea && ea->getEventType() == osgGA::GUIEventAdapter::CLOSE_WINDOW) wantPopOut_ = false;
else window->getEventQueue()->addEvent(event.get());
}
}
void App::drawViewportOverlay() {
if (viewRect_.z() < 8.f) return;
ImGui::SetNextWindowPos(ImVec2(viewRect_.x() + 8.f, viewRect_.y() + 8.f));
ImGui::SetNextWindowBgAlpha(0.45f);
const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoDocking |
ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav |
ImGuiWindowFlags_NoMove;
ImGui::Begin("##viewport-tools", nullptr, flags);
if (popCamera_) {
ImGui::TextUnformatted("The 3D view is in its own window.");
if (ImGui::Button("Dock viewport back")) setViewportPoppedOut(false);
} else {
if (ImGui::Button("Pop out")) setViewportPoppedOut(true);
ImGui::SameLine();
if (ImGui::Button("Frame model")) frameModel();
}
ImGui::End();
}
// The 3D view fills the window behind the panels; this squeezes the projection into the
// dockspace's free central area, so no extra render target is needed.
void App::updateProjection() {
osg::Camera* camera = viewer_.getCamera();
const osg::Viewport* vp = camera->getViewport();
if (!vp || vp->width() <= 0 || vp->height() <= 0) return;
const double W = vp->width(), H = vp->height();
double x = 0, y = 0, w = W, h = H;
if (imgui_->uiVisible() && viewRect_.z() > 8.f && viewRect_.w() > 8.f) {
x = viewRect_.x();
y = viewRect_.y();
w = viewRect_.z();
h = viewRect_.w();
}
const osg::Matrixd offset = osg::Matrixd::scale(w / W, h / H, 1.0) *
osg::Matrixd::translate((2.0 * x + w) / W - 1.0, 1.0 - (2.0 * y + h) / H, 0.0);
camera->setProjectionMatrix(osg::Matrixd::perspective(fov_, w / h, 0.1, 1000.0) * offset);
}
void App::tick(double time) {
const double dt = lastTick_ < 0.0 ? 0.0 : time - lastTick_;
const double realDt = lastTick_ < 0.0 ? 0.0 : std::clamp(time - lastTick_, 0.0, 0.1);
lastTick_ = time;
updateRender();
// Renders advance exactly one frame per update, so physics is stepped by the frame time.
for (auto& item : items_) {
item->node->poser().stepPhysics(render_.active ? 1.f / 30.f : float(realDt));
item->node->poser().setIkEnabled(ikEnabled_);
}
updatePopOut();
updateProjection();
updateLook();
const bool anyMotion = std::any_of(items_.begin(), items_.end(), [](const auto& i) { return i->player != nullptr; });
if (!anyMotion && !camera_ && !audio_.loaded()) return;
if (playing_) {
// The sound card's clock drives playback while the song plays, so motion stays in sync.
if (audio_.playing()) motionFrame_ = static_cast<float>(audio_.position()) * kMotionFps;
else motionFrame_ += static_cast<float>(dt) * kMotionFps;
const float end = timelineEnd();
if (motionFrame_ >= end) {
if (loopMotion_ && end > 0.f) {
motionFrame_ = 0.f;
setPlaying(true);
} else {
motionFrame_ = end;
setPlaying(false);
}
}
}
applyFrame();
}
void App::openFile(const std::string& path) {
std::string lower = path;
std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return std::tolower(c); });
auto endsWith = [&](const char* ext) {
const size_t n = std::strlen(ext);
return lower.size() > n && lower.compare(lower.size() - n, n, ext) == 0;
};
if (endsWith(".mrscene")) {
openScene(path);
} else if (endsWith(".vmd")) {
loadMotion(path);
} else if (endsWith(".wav") || endsWith(".mp3") || endsWith(".flac")) {
loadAudio(path);
} else {
loadModel(path, openAsStage_);
}
openAsStage_ = false;
}
void App::setShowSkeleton(bool show) {
@@ -97,6 +600,11 @@ void App::frameModel(float azimuthDeg, float elevationDeg) {
void App::drawUi() {
drawMenuBar();
const ImGuiID dockspace = ImGui::DockSpaceOverViewport(0, nullptr, ImGuiDockNodeFlags_PassthruCentralNode);
buildLayout(dockspace);
if (ImGuiDockNode* central = ImGui::DockBuilderGetCentralNode(dockspace))
viewRect_.set(central->Pos.x, central->Pos.y, central->Size.x, central->Size.y);
drawViewportOverlay();
if (!loadError_.empty()) {
ImGui::SetNextWindowPos(ImVec2(10, 40), ImGuiCond_Always);
ImGui::Begin("Error", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse);
@@ -104,41 +612,116 @@ void App::drawUi() {
if (ImGui::Button("Dismiss")) loadError_.clear();
ImGui::End();
}
if (fileBrowser_.draw()) loadModel(fileBrowser_.selectedPath());
if (!ImGui::GetIO().WantTextInput) {
if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_S)) requestSaveScene(true);
else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_S)) requestSaveScene(false);
else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_O)) fileBrowser_.open(FileBrowser::Mode::Open, {}, ".mrscene");
}
if (!fileBrowser_.isOpen()) measuringModel_ = false;
if (fileBrowser_.draw()) {
if (fileBrowser_.mode() == FileBrowser::Mode::Save) saveScene(fileBrowser_.selectedPath());
else if (measuringModel_) {
std::string error;
auto model = mr::loadModel(fileBrowser_.selectedPath(), error);
if (model) {
osg::Vec3f lo, hi;
model->computeBounds(lo, hi);
cameraFit_.madeFor = hi.y() - lo.y();
fitCameraToModel();
} else {
loadError_ = error;
}
} else openFile(fileBrowser_.selectedPath());
}
drawModelWindow();
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();
for (const char* name : {"Bones", "Morphs"}) {
ImGui::Begin(name);
ImGui::TextDisabled("No model selected.");
ImGui::End();
}
}
drawLookWindow();
drawTimelineWindow();
drawRenderDialog();
if (showDemo_) ImGui::ShowDemoWindow(&showDemo_);
}
void App::buildLayout(unsigned dockspace) {
ImGuiDockNode* node = ImGui::DockBuilderGetNode(dockspace);
if (!resetLayout_ && node && node->IsSplitNode()) return; // restored from the saved layout
resetLayout_ = false;
ImGui::DockBuilderRemoveNode(dockspace);
ImGui::DockBuilderAddNode(dockspace, ImGuiDockNodeFlags_DockSpace | ImGuiDockNodeFlags_PassthruCentralNode);
ImGui::DockBuilderSetNodeSize(dockspace, ImGui::GetMainViewport()->WorkSize);
ImGuiID center = dockspace;
const ImGuiID bottom = ImGui::DockBuilderSplitNode(center, ImGuiDir_Down, 0.30f, nullptr, &center);
ImGuiID left = ImGui::DockBuilderSplitNode(center, ImGuiDir_Left, 0.22f, nullptr, &center);
const ImGuiID right = ImGui::DockBuilderSplitNode(center, ImGuiDir_Right, 0.26f, nullptr, &center);
const ImGuiID leftBottom = ImGui::DockBuilderSplitNode(left, ImGuiDir_Down, 0.62f, nullptr, &left);
ImGui::DockBuilderDockWindow("Scene", left);
ImGui::DockBuilderDockWindow("Bones", leftBottom);
ImGui::DockBuilderDockWindow("Morphs", right);
ImGui::DockBuilderDockWindow("Look", right);
ImGui::DockBuilderDockWindow("Timeline", bottom);
ImGui::DockBuilderFinish(dockspace);
}
void App::drawMenuBar() {
if (!ImGui::BeginMainMenuBar()) return;
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("Open...")) fileBrowser_.open();
if (ImGui::MenuItem("New scene")) newScene();
if (ImGui::MenuItem("Open scene...", "Ctrl+O")) fileBrowser_.open(FileBrowser::Mode::Open, {}, ".mrscene");
if (ImGui::MenuItem("Save scene", "Ctrl+S")) requestSaveScene(false);
if (ImGui::MenuItem("Save scene as...", "Ctrl+Shift+S")) requestSaveScene(true);
ImGui::Separator();
if (ImGui::MenuItem("Add model, motion or audio...")) fileBrowser_.open();
if (ImGui::MenuItem("Add stage...")) {
openAsStage_ = true;
fileBrowser_.open();
}
if (ImGui::MenuItem("Remove selected model", nullptr, false, active_ >= 0)) removeModel(active_);
if (ImGui::MenuItem("Render...", nullptr, false, modelNode_ != nullptr)) openRenderDialog();
ImGui::Separator();
if (ImGui::MenuItem("Quit")) viewer_.setDone(true);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("View")) {
bool changed = false;
if (ImGui::MenuItem("Floor grid", nullptr, &showGrid_)) setShowGrid(showGrid_);
changed |= ImGui::MenuItem("Skeleton", nullptr, &showSkeleton_);
changed |= ImGui::MenuItem("Wireframe", nullptr, &wireframe_);
changed |= ImGui::MenuItem("Backface culling", nullptr, &backfaceCulling_);
changed |= ImGui::MenuItem("Light follows camera", nullptr, &lightFollowsCamera_);
changed |= ImGui::MenuItem("Light follows camera", nullptr, &look_.lightFollowsCamera);
changed |= ImGui::MenuItem("Outlines", nullptr, &look_.outlines);
changed |= ImGui::MenuItem("Shadows", nullptr, &look_.shadows, sceneLook_->shadowsSupported());
ImGui::MenuItem("Solve IK", nullptr, &ikEnabled_);
const bool hasPhysics = modelNode_ && modelNode_->poser().hasPhysics();
if (ImGui::MenuItem("Physics", nullptr, &physicsEnabled_, hasPhysics)) setPhysicsEnabled(physicsEnabled_);
if (ImGui::MenuItem("Reset physics", nullptr, false, hasPhysics && physicsEnabled_))
modelNode_->poser().resetPhysics();
ImGui::Separator();
changed |= ImGui::RadioButton("MMD toon shading", &lightingModel_, 0);
changed |= ImGui::RadioButton("Lambert shading", &lightingModel_, 1);
changed |= ImGui::RadioButton("MMD toon shading", &look_.shading, 0);
changed |= ImGui::RadioButton("Lambert shading", &look_.shading, 1);
changed |= ImGui::RadioButton("Anime cel shading", &look_.shading, 2);
changed |= ImGui::RadioButton("Soft studio shading", &look_.shading, 3);
ImGui::Separator();
const bool gpuOk = gpuCaps().skinning;
ImGui::BeginDisabled(!gpuOk);
changed |= ImGui::RadioButton("GPU skinning (hardware)", &skinning_, 1);
ImGui::EndDisabled();
changed |= ImGui::RadioButton("CPU skinning (software)", &skinning_, 0);
if (!gpuOk && gpuCaps().probed) ImGui::TextDisabled("This GPU cannot do hardware skinning");
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();
if (ImGui::MenuItem("Reset panel layout")) resetLayout_ = true;
if (ImGui::MenuItem("Viewport in separate window", nullptr, viewportPoppedOut()))
setViewportPoppedOut(!viewportPoppedOut());
ImGui::MenuItem("ImGui demo", nullptr, &showDemo_);
if (changed) applyViewSettings();
ImGui::EndMenu();
@@ -148,21 +731,85 @@ void App::drawMenuBar() {
ImGui::Text("Space: reset camera");
ImGui::EndMenu();
}
{
const bool recent = ImGui::GetTime() - sceneStatusTime_ < 4.0;
const std::string title = recent ? sceneStatus_
: scenePath_.empty() ? std::string("Untitled scene")
: scenePath_.substr(scenePath_.find_last_of("/\\") + 1);
ImGui::SameLine(0.f, 24.f * imgui_->uiScale());
ImGui::TextDisabled("%s", title.c_str());
}
ImGui::SameLine(ImGui::GetWindowWidth() - 90 * imgui_->uiScale());
ImGui::TextDisabled("%.0f FPS", ImGui::GetIO().Framerate);
ImGui::EndMainMenuBar();
}
void App::drawSceneList() {
int remove = -1;
const float scale = imgui_->uiScale();
for (size_t i = 0; i < items_.size(); ++i) {
SceneItem& item = *items_[i];
ImGui::PushID(static_cast<int>(i));
if (ImGui::Checkbox("##visible", &item.visible)) applyViewSettings();
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Show / hide");
ImGui::SameLine();
const std::string label = (item.stage ? "[Stage] " : "") + item.name +
(item.motion ? " (" + item.motionName + ")" : std::string());
if (ImGui::Selectable(label.c_str(), static_cast<int>(i) == active_, 0,
ImVec2(ImGui::GetContentRegionAvail().x - 28.f * scale, 0)))
selectModel(static_cast<int>(i));
ImGui::SameLine();
if (ImGui::SmallButton("x")) remove = static_cast<int>(i);
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Remove from scene");
ImGui::PopID();
}
if (items_.empty()) ImGui::TextDisabled("No models in the scene.");
if (ImGui::Button("Add model...")) fileBrowser_.open();
ImGui::SameLine();
if (ImGui::Button("Add stage...")) {
openAsStage_ = true;
fileBrowser_.open();
}
if (remove >= 0) removeModel(remove);
}
void App::drawModelWindow() {
ImGui::Begin("Scene");
drawSceneList();
if (!modelNode_) {
ImGui::End();
return;
}
SceneItem& item = *activeItem();
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::SeparatorText(item.name.c_str());
if (ImGui::Checkbox("Stage", &item.stage)) applyViewSettings();
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Environment model: physics off, camera not reframed on load");
bool moved = ImGui::DragFloat3("Position", item.position.ptr(), 0.05f, 0.f, 0.f, "%.2f");
moved |= ImGui::DragFloat("Rotation", &item.rotationY, 0.5f, -180.f, 180.f, "%.1f deg");
moved |= ImGui::DragFloat("Scale", &item.scale, 0.005f, 0.01f, 100.f, "%.3fx",
ImGuiSliderFlags_Logarithmic | ImGuiSliderFlags_AlwaysClamp);
if (moved) updatePlacement(item);
ImGui::SameLine();
if (ImGui::SmallButton("Reset##placement")) {
item.position = osg::Vec3f();
item.rotationY = 0.f;
item.scale = 1.f;
updatePlacement(item);
}
ImGui::TextDisabled("%s", m.format == SourceFormat::PMX ? "PMX" : m.format == SourceFormat::PMD ? "PMD" : "Assimp");
ImGui::Text("Vertices %zu Triangles %zu", m.vertices.size(), m.indices.size() / 3);
ImGui::Text("Materials %zu Textures %zu", m.materials.size(), m.textures.size());
ImGui::Text("Bones %zu Morphs %zu", m.bones.size(), m.morphs.size());
if (!m.rigidBodies.empty() && !item.stage) {
ImGui::Text("Rigid bodies %zu Joints %zu", m.rigidBodies.size(), m.joints.size());
bool physics = physicsEnabled_;
if (ImGui::Checkbox("Physics", &physics)) setPhysicsEnabled(physics);
ImGui::SameLine();
if (ImGui::SmallButton("Reset##physics")) modelNode_->poser().resetPhysics();
}
ImGui::TextDisabled("Skinning: %s",
modelNode_->activeSkinningMode() == SkinningMode::Hardware ? "GPU" : "CPU");
if (ImGui::Button("Reset pose")) modelNode_->poser().resetPose();
ImGui::SameLine();
if (ImGui::Button("Reset morphs")) modelNode_->poser().resetMorphs();
@@ -195,9 +842,6 @@ void App::drawBoneEditor() {
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();
@@ -227,12 +871,127 @@ void App::drawBonesWindow() {
ImGui::End();
}
void App::drawLookWindow() {
ImGui::Begin("Look");
bool changed = false;
ImGui::TextDisabled("Presets");
struct Preset {
const char* name;
int shading;
bool outlines;
float rim;
osg::Vec3f light;
bool bloom, ao, fxaa;
int toneMapping;
float saturation, vignette;
};
const Preset presets[] = {
{"MMD classic", 0, true, 0.f, {0.6f, 0.6f, 0.6f}, false, false, false, 0, 1.f, 0.f},
{"Anime", 2, true, 0.6f, {0.85f, 0.82f, 0.8f}, true, false, true, 0, 1.1f, 0.f},
{"Studio", 3, false, 0.35f, {0.95f, 0.9f, 0.82f}, true, true, true, 1, 1.f, 0.3f}};
for (const Preset& p : presets) {
if (&p != presets) ImGui::SameLine();
if (ImGui::Button(p.name)) {
look_.shading = p.shading;
look_.outlines = p.outlines;
look_.rimStrength = p.rim;
look_.lightColor = p.light;
look_.shadows = true;
look_.bloom = p.bloom;
look_.ambientOcclusion = p.ao;
look_.fxaa = p.fxaa;
look_.toneMapping = p.toneMapping;
look_.saturation = p.saturation;
look_.vignette = p.vignette;
changed = true;
}
}
ImGui::SeparatorText("Shading");
const char* styles[] = {"MMD toon", "Lambert", "Anime cel", "Soft studio"};
changed |= ImGui::Combo("Style", &look_.shading, styles, IM_ARRAYSIZE(styles));
ImGui::SeparatorText("Light");
changed |= ImGui::ColorEdit3("Light color", look_.lightColor.ptr(), ImGuiColorEditFlags_Float);
changed |= ImGui::Checkbox("Follow camera", &look_.lightFollowsCamera);
ImGui::BeginDisabled(look_.lightFollowsCamera);
changed |= ImGui::SliderFloat("Direction", &look_.lightAzimuth, -180.f, 180.f, "%.0f deg");
changed |= ImGui::SliderFloat("Height", &look_.lightElevation, 5.f, 90.f, "%.0f deg");
ImGui::EndDisabled();
ImGui::SeparatorText("Outlines");
changed |= ImGui::Checkbox("Show outlines", &look_.outlines);
ImGui::BeginDisabled(!look_.outlines);
changed |= ImGui::SliderFloat("Outline width", &look_.outlineWidth, 0.1f, 4.f, "%.2fx");
ImGui::EndDisabled();
if (modelNode_ && !modelNode_->hasOutlines()) ImGui::TextDisabled("The selected model has no outline data.");
ImGui::SeparatorText("Shadows");
const bool shadowsOk = sceneLook_->shadowsSupported();
ImGui::BeginDisabled(!shadowsOk);
changed |= ImGui::Checkbox("Cast shadows", &look_.shadows);
ImGui::BeginDisabled(!look_.shadows);
const char* qualities[] = {"Low (1024)", "Medium (2048)", "High (4096)"};
changed |= ImGui::Combo("Quality", &look_.shadowQuality, qualities, IM_ARRAYSIZE(qualities));
changed |= ImGui::SliderFloat("Softness", &look_.shadowSoftness, 0.f, 6.f, "%.1f");
changed |= ImGui::SliderFloat("Darkness", &look_.shadowStrength, 0.f, 1.f, "%.2f");
changed |= ImGui::Checkbox("Stages cast shadows", &look_.stageShadows);
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Trees and buildings cast shadows too. Slower on older graphics cards.");
changed |= ImGui::Checkbox("Floor shadow when there is no stage", &look_.groundShadow);
ImGui::BeginDisabled(!look_.groundShadow);
changed |= ImGui::SliderFloat("Floor shadow opacity", &look_.groundShadowOpacity, 0.f, 1.f, "%.2f");
ImGui::EndDisabled();
ImGui::EndDisabled();
ImGui::EndDisabled();
if (!shadowsOk) ImGui::TextDisabled("This GPU cannot render shadows.");
ImGui::SeparatorText("Rim light");
changed |= ImGui::SliderFloat("Rim strength", &look_.rimStrength, 0.f, 1.5f, "%.2f");
changed |= ImGui::ColorEdit3("Rim color", look_.rimColor.ptr(), ImGuiColorEditFlags_Float);
ImGui::SeparatorText("Post-processing");
const bool postOk = mainChain_->supported() || !gpuCaps().probed;
ImGui::BeginDisabled(!postOk);
changed |= ImGui::Checkbox("Bloom", &look_.bloom);
ImGui::BeginDisabled(!look_.bloom);
changed |= ImGui::SliderFloat("Bloom strength", &look_.bloomStrength, 0.f, 2.f, "%.2f");
changed |= ImGui::SliderFloat("Bloom threshold", &look_.bloomThreshold, 0.f, 1.5f, "%.2f");
changed |= ImGui::SliderFloat("Bloom size", &look_.bloomRadius, 0.25f, 4.f, "%.2f");
ImGui::EndDisabled();
changed |= ImGui::Checkbox("Ambient occlusion", &look_.ambientOcclusion);
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Soft darkening in creases and where objects meet.");
ImGui::BeginDisabled(!look_.ambientOcclusion);
changed |= ImGui::SliderFloat("AO strength", &look_.aoStrength, 0.f, 3.f, "%.2f");
changed |= ImGui::SliderFloat("AO radius", &look_.aoRadius, 0.2f, 6.f, "%.1f");
ImGui::EndDisabled();
changed |= ImGui::Checkbox("Anti-aliasing (FXAA)", &look_.fxaa);
ImGui::SeparatorText("Colour grading");
const char* toneMaps[] = {"Off", "Filmic"};
changed |= ImGui::Combo("Tone mapping", &look_.toneMapping, toneMaps, IM_ARRAYSIZE(toneMaps));
changed |= ImGui::SliderFloat("Exposure", &look_.exposure, 0.25f, 3.f, "%.2f");
changed |= ImGui::SliderFloat("Contrast", &look_.contrast, 0.5f, 1.5f, "%.2f");
changed |= ImGui::SliderFloat("Saturation", &look_.saturation, 0.f, 2.f, "%.2f");
changed |= ImGui::SliderFloat("Temperature", &look_.temperature, -1.f, 1.f, "%.2f");
if (ImGui::IsItemHovered()) ImGui::SetTooltip("Negative is cooler (blue), positive warmer (orange).");
changed |= ImGui::SliderFloat("Vignette", &look_.vignette, 0.f, 1.f, "%.2f");
ImGui::EndDisabled();
if (!postOk) ImGui::TextDisabled("This GPU cannot run post-processing.");
ImGui::Separator();
if (ImGui::Button("Reset look")) {
const int shading = look_.shading;
look_ = LookSettings();
look_.shading = shading;
changed = true;
}
if (changed) applyViewSettings();
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_));
@@ -255,8 +1014,7 @@ void App::drawMorphsWindow() {
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;
const bool supported = morph.type != MorphType::Impulse;
ImGui::BeginDisabled(!supported);
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.5f);
std::string label = morph.name + "##m" + std::to_string(i);
@@ -264,7 +1022,7 @@ void App::drawMorphsWindow() {
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)");
supported ? "" : " (impulse morphs are not supported yet)");
}
}
ImGui::End();
+142 -5
View File
@@ -1,13 +1,21 @@
#pragma once
#include <atomic>
#include <memory>
#include <osg/Image>
#include "app/FileBrowser.h"
#include "audio/AudioPlayer.h"
#include "model/Motion.h"
#include "render/Look.h"
#include "render/ModelNode.h"
#include "render/PostFx.h"
#include "ui/ImGuiOsg.h"
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
#include <string>
#include <vector>
namespace mr {
@@ -15,11 +23,54 @@ class App {
public:
App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulator* manipulator);
bool loadModel(const std::string& path);
// Adds a model to the scene and makes it the active one. Stages are environments:
// no physics, and the camera is not reframed when they are added.
bool loadModel(const std::string& path, bool stage = false);
void selectModel(int index);
void setModelScale(int index, float scale);
// Scene files (.mrscene): models, placement, poses, motions, audio, view and settings.
void newScene();
bool openScene(const std::string& path);
bool saveScene(const std::string& path);
const std::string& scenePath() const { return scenePath_; }
void removeModel(int index);
size_t modelCount() const { return items_.size(); }
void setShowGrid(bool show);
const std::string& loadError() const { return loadError_; }
ModelNode* modelNode() { return modelNode_.get(); }
ModelNode* modelNode() { return modelNode_; }
void frameModel(float azimuthDeg = 0.f, float elevationDeg = 0.f);
void setShowSkeleton(bool show);
void setGpuSkinning(bool enabled);
void setPhysicsEnabled(bool enabled);
const LookSettings& look() const { return look_; }
void setLook(const LookSettings& look);
// Adapts a camera motion made for another model: see Scene::cameraHeightScale.
struct CameraFit {
float madeFor = 20.f; // height of the model the camera motion was made for
float heightScale = 1.f, distance = 1.f;
osg::Vec3f offset;
bool followModel = true; // apply the followed model's position, rotation and scale
};
const CameraFit& cameraFit() const { return cameraFit_; }
void setCameraFit(const CameraFit& fit);
// Sets the height scale from the followed model's height and madeFor.
void fitCameraToModel();
float followedModelHeight() const;
bool loadMotion(const std::string& path);
void unloadMotion();
void setMotionFrame(float frame);
bool loadAudio(const std::string& path);
void setPlaying(bool playing);
// Advances playback; called once per frame from the update traversal.
void tick(double time);
void setViewportPoppedOut(bool popped) { wantPopOut_ = popped; }
bool viewportPoppedOut() const { return popCamera_.valid(); }
// Call before the viewer's event traversal: turns closing the pop-out window into docking it back.
void catchPopOutClose();
// Batch render (command line): renders frames [start, end] into dir, then quits.
void renderToFolder(const std::string& dir, int start, int end, int width, int height);
ImGuiOsg* imgui() { return imgui_.get(); }
void drawUi();
@@ -30,21 +81,107 @@ private:
void drawBonesWindow();
void drawBoneEditor();
void drawMorphsWindow();
void drawLookWindow();
void updateLook();
void applyViewSettings();
void drawTimelineWindow();
void drawTimelineTracks(float end);
void buildLayout(unsigned dockspace);
void updateProjection();
void updatePopOut();
void openRenderDialog();
void startRender();
void updateRender();
void finishRender(const std::string& status);
void drawRenderDialog();
void drawViewportOverlay();
void openFile(const std::string& path);
float timelineEnd() const;
void applyFrame();
void applyCamera();
void restoreCamera();
osgViewer::Viewer& viewer_;
osg::ref_ptr<osg::Group> root_;
osg::ref_ptr<osg::Group> sceneRoot_; // everything 3D; drawn through a post-processing chain
osg::ref_ptr<osg::Group> sceneGroup_; // models and stages
osg::ref_ptr<PostChain> mainChain_, popChain_, renderChain_;
std::unique_ptr<SceneLook> sceneLook_;
osg::ref_ptr<osgGA::TrackballManipulator> manipulator_;
osg::ref_ptr<ImGuiOsg> imgui_;
osg::ref_ptr<ModelNode> modelNode_;
struct SceneItem {
osg::ref_ptr<ModelNode> node;
std::string name, path, motionPath;
bool stage = false, visible = true;
osg::Vec3f position; // model space, Y up
float rotationY = 0.f; // degrees
float scale = 1.f;
osg::Matrix base; // ModelNode's model-to-world matrix
std::shared_ptr<Motion> motion;
std::unique_ptr<MotionPlayer> player;
std::string motionName;
};
const SceneItem* followedItem() const;
SceneItem* activeItem() { return active_ >= 0 ? items_[active_].get() : nullptr; }
void updatePlacement(SceneItem& item);
void drawSceneList();
void requestSaveScene(bool saveAs);
std::string scenePath_, cameraPath_, sceneStatus_;
double sceneStatusTime_ = -10.0;
std::vector<std::unique_ptr<SceneItem>> items_;
int active_ = -1;
ModelNode* modelNode_ = nullptr; // active model
MotionPlayer* player_ = nullptr; // active model's motion
osg::ref_ptr<osg::Node> grid_;
bool showGrid_ = true;
bool openAsStage_ = false;
FileBrowser fileBrowser_;
std::string loadError_;
bool showSkeleton_ = false;
bool backfaceCulling_ = true;
bool wireframe_ = false;
bool lightFollowsCamera_ = false;
int lightingModel_ = 0;
LookSettings look_;
int skinning_ = 1; // 1 hardware (GPU), 0 software (CPU)
bool ikEnabled_ = true;
float motionFrame_ = 0.f;
bool playing_ = false;
bool loopMotion_ = true;
double lastTick_ = -1.0;
std::shared_ptr<Motion> camera_;
std::string cameraName_;
bool useMotionCamera_ = true;
CameraFit cameraFit_;
bool measuringModel_ = false; // the file browser picks a model to read madeFor from
void drawCameraFit();
double fov_ = 30.0;
osg::Vec4f viewRect_; // 3D view area in UI pixels (x, y from top-left, w, h)
bool resetLayout_ = false;
bool wantPopOut_ = false;
bool showRenderDialog_ = false;
bool physicsEnabled_ = true;
bool quitAfterRender_ = false;
std::string audioPath_;
struct RenderJob {
char dir[512] = {};
int width = 1920, height = 1080;
int start = 0, end = 0, current = 0, pending = -1;
bool transparent = false, mp4 = true, withAudio = true;
bool active = false, cancel = false;
std::string status;
osg::ref_ptr<osg::Camera> camera;
osg::ref_ptr<osg::Image> image;
std::shared_ptr<std::atomic<int>> encodeResult;
} render_;
osg::ref_ptr<osg::Camera> popCamera_; // renders the scene into the separate viewport window
// Hidden pop-out kept for reuse: closing its context would also delete GL objects shared with the main window.
osg::ref_ptr<osg::Camera> parkedPopCamera_;
float timelineZoom_ = 4.f; // pixels per frame
float timelineScroll_ = 0.f; // frame at the left edge
AudioPlayer audio_;
std::string audioName_;
float volume_ = 1.f;
bool showDemo_ = false;
bool onlyVisibleBones_ = true;
int selectedBone_ = -1;
+53 -11
View File
@@ -15,7 +15,7 @@ namespace mr {
namespace {
bool isModelFile(const std::string& name) {
std::string lower = toLowerAscii(name);
for (const char* ext : {".pmx", ".pmd", ".fbx", ".obj", ".gltf", ".glb", ".dae"})
for (const char* ext : {".mrscene", ".pmx", ".pmd", ".fbx", ".x", ".vmd", ".wav", ".mp3", ".flac", ".obj", ".gltf", ".glb", ".dae"})
if (lower.size() >= std::strlen(ext) && lower.compare(lower.size() - std::strlen(ext), std::string::npos, ext) == 0)
return true;
return false;
@@ -27,7 +27,16 @@ FileBrowser::FileBrowser() {
currentDir_ = pathToUtf8(fs::current_path(ec));
}
void FileBrowser::open() {
void FileBrowser::open(Mode mode, const std::string& defaultPath, const std::string& extension) {
mode_ = mode;
extension_ = extension;
nameBuffer_[0] = '\0';
if (mode == Mode::Save && !defaultPath.empty()) {
const fs::path p = pathFromUtf8(defaultPath);
std::error_code ec;
if (p.has_parent_path() && fs::is_directory(p.parent_path(), ec)) currentDir_ = pathToUtf8(p.parent_path());
std::snprintf(nameBuffer_, sizeof(nameBuffer_), "%s", pathToUtf8(p.filename()).c_str());
}
openRequested_ = true;
refresh();
}
@@ -35,13 +44,16 @@ void FileBrowser::open() {
void FileBrowser::refresh() {
entries_.clear();
error_.clear();
highlighted_.clear();
std::snprintf(pathBuffer_, sizeof(pathBuffer_), "%s", currentDir_.c_str());
std::error_code ec;
for (const auto& e : fs::directory_iterator(pathFromUtf8(currentDir_), fs::directory_options::skip_permission_denied, ec)) {
std::string name = pathToUtf8(e.path().filename());
if (name.empty() || name[0] == '.') continue;
bool dir = e.is_directory(ec);
if (dir || isModelFile(name)) entries_.push_back({name, dir});
const bool listed = extension_.empty() ? isModelFile(name)
: toLowerAscii(e.path().extension().string()) == extension_;
if (dir || listed) entries_.push_back({name, dir});
}
if (ec) error_ = ec.message();
std::sort(entries_.begin(), entries_.end(), [](const auto& a, const auto& b) {
@@ -52,12 +64,15 @@ void FileBrowser::refresh() {
bool FileBrowser::draw() {
if (openRequested_) {
ImGui::OpenPopup("Open model");
ImGui::OpenPopup("###filebrowser");
openRequested_ = false;
}
bool chosen = false;
ImGui::SetNextWindowSize(ImVec2(640, 460), ImGuiCond_FirstUseEver);
if (ImGui::BeginPopupModal("Open model", nullptr)) {
const bool saving = mode_ == Mode::Save;
visible_ = ImGui::BeginPopupModal(
saving ? "Save scene###filebrowser" : extension_ == ".mrscene" ? "Open scene###filebrowser" : "Open###filebrowser", nullptr);
if (visible_) {
if (ImGui::Button("Up")) {
currentDir_ = pathToUtf8(pathFromUtf8(currentDir_).parent_path());
refresh();
@@ -70,21 +85,39 @@ bool FileBrowser::draw() {
if (fs::is_directory(p, ec)) {
currentDir_ = pathBuffer_;
refresh();
} else if (fs::is_regular_file(p, ec)) {
} else if (!saving && fs::is_regular_file(p, ec)) {
selected_ = pathBuffer_;
chosen = true;
}
}
ImGui::TextDisabled("Supported: .pmx .pmd .fbx (also .obj .gltf .glb .dae)");
if (saving) {
ImGui::SetNextItemWidth(-80.f);
const bool enter = ImGui::InputText("##name", nameBuffer_, sizeof(nameBuffer_), ImGuiInputTextFlags_EnterReturnsTrue);
ImGui::SameLine();
if ((ImGui::Button("Save") || enter) && nameBuffer_[0]) {
std::string name = nameBuffer_;
if (!extension_.empty() && toLowerAscii(fs::path(name).extension().string()) != extension_)
name += extension_;
selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name));
chosen = true;
}
} else if (extension_.empty()) {
ImGui::TextDisabled("Scenes: .mrscene Models: .pmx .pmd .fbx .x (also .obj .gltf .glb .dae) Motions: .vmd Audio: .wav .mp3 .flac");
}
if (!error_.empty()) ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "%s", error_.c_str());
ImGui::BeginChild("entries", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), ImGuiChildFlags_Borders);
std::string enterDir;
for (const auto& [name, dir] : entries_) {
std::string label = dir ? "[dir] " + name : name;
if (ImGui::Selectable(label.c_str(), false, ImGuiSelectableFlags_AllowDoubleClick) &&
(dir || ImGui::IsMouseDoubleClicked(0))) {
if (dir) enterDir = name;
else {
if (!ImGui::Selectable(label.c_str(), !dir && name == highlighted_, ImGuiSelectableFlags_AllowDoubleClick))
continue;
if (dir) {
enterDir = name;
} else if (saving) {
std::snprintf(nameBuffer_, sizeof(nameBuffer_), "%s", name.c_str());
} else {
highlighted_ = name;
if (ImGui::IsMouseDoubleClicked(0)) {
selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name));
chosen = true;
}
@@ -95,6 +128,15 @@ bool FileBrowser::draw() {
currentDir_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(enterDir));
refresh();
}
if (!saving) {
ImGui::BeginDisabled(highlighted_.empty());
if (ImGui::Button("Open")) {
selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(highlighted_));
chosen = true;
}
ImGui::EndDisabled();
ImGui::SameLine();
}
if (ImGui::Button("Cancel") || chosen) ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
+10 -2
View File
@@ -8,11 +8,16 @@ namespace mr {
// Minimal ImGui file picker (ImGui has no native file dialog).
class FileBrowser {
public:
enum class Mode { Open, Save };
FileBrowser();
void open();
// Save mode asks for a file name (defaultPath may include a folder) and returns it with saveExtension.
// extension: the file type saved (Save mode) or the only type listed (Open mode); empty lists everything.
void open(Mode mode = Mode::Open, const std::string& defaultPath = {}, const std::string& extension = {});
Mode mode() const { return mode_; }
// Draws the popup; returns true when a file was chosen (see selectedPath()).
bool draw();
const std::string& selectedPath() const { return selected_; }
bool isOpen() const { return openRequested_ || visible_; }
private:
void refresh();
@@ -22,7 +27,10 @@ private:
std::vector<std::pair<std::string, bool>> entries_; // name, isDirectory
std::string selected_;
std::string error_;
bool openRequested_ = false;
bool openRequested_ = false, visible_ = false;
Mode mode_ = Mode::Open;
char nameBuffer_[256] = {};
std::string extension_, highlighted_;
};
} // namespace mr
+218
View File
@@ -0,0 +1,218 @@
#include "app/AppUi.h"
#include "render/Grid.h"
#include <imgui.h>
#include <osgDB/WriteFile>
#include <osgViewer/Renderer>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <thread>
namespace mr {
namespace {
bool ffmpegAvailable() {
static int found = -1;
if (found < 0) {
#ifdef _WIN32
found = std::system("ffmpeg -version > NUL 2>&1") == 0;
#else
found = std::system("ffmpeg -version > /dev/null 2>&1") == 0;
#endif
}
return found == 1;
}
std::string quotePath(const std::string& s) { return "\"" + s + "\""; }
} // namespace
void App::openRenderDialog() {
if (render_.dir[0] == '\0') {
std::error_code ec;
const std::string dir = (std::filesystem::current_path(ec) / "render").string();
std::snprintf(render_.dir, sizeof(render_.dir), "%s", dir.c_str());
}
render_.start = 0;
render_.end = static_cast<int>(timelineEnd());
showRenderDialog_ = true;
}
void App::renderToFolder(const std::string& dir, int start, int end, int width, int height) {
std::snprintf(render_.dir, sizeof(render_.dir), "%s", dir.c_str());
render_.start = start;
render_.end = end >= 0 ? end : static_cast<int>(timelineEnd());
render_.width = width;
render_.height = height;
quitAfterRender_ = true;
startRender();
if (!render_.active) {
std::fprintf(stderr, "%s\n", render_.status.c_str());
viewer_.setDone(true);
}
}
void App::startRender() {
std::error_code ec;
std::filesystem::create_directories(render_.dir, ec);
if (ec) {
render_.status = "Cannot create " + std::string(render_.dir) + ": " + ec.message();
return;
}
setPlaying(false);
render_.start = std::max(0, render_.start);
render_.end = std::max(render_.start, render_.end);
render_.current = render_.start;
render_.pending = -1;
render_.active = true;
render_.status.clear();
osg::Camera* master = viewer_.getCamera();
render_.image = new osg::Image;
render_.image->allocateImage(render_.width, render_.height, 1, GL_RGBA, GL_UNSIGNED_BYTE);
osg::ref_ptr<osg::Camera> cam = new osg::Camera;
cam->setGraphicsContext(master->getGraphicsContext());
cam->setViewport(0, 0, render_.width, render_.height);
cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
cam->setRenderOrder(osg::Camera::PRE_RENDER);
cam->attach(osg::Camera::COLOR_BUFFER, render_.image.get(), 4, 0);
cam->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
cam->setInheritanceMask(cam->getInheritanceMask() & ~osg::CullSettings::CULL_MASK);
cam->setCullMask(kRenderViewMask);
osg::Vec4 clear = master->getClearColor();
if (render_.transparent) clear.a() = 0.f;
cam->setClearColor(clear);
renderChain_->setSize(render_.width, render_.height);
renderChain_->setClearColor(clear);
cam->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
viewer_.addSlave(cam.get(), true);
if (!cam->getRenderer()) cam->setRenderer(new osgViewer::Renderer(cam.get()));
render_.camera = cam;
}
void App::finishRender(const std::string& status) {
if (render_.camera) {
const unsigned index = viewer_.findSlaveIndexForCamera(render_.camera.get());
if (index < viewer_.getNumSlaves()) viewer_.removeSlave(index);
render_.camera = nullptr;
}
render_.image = nullptr;
render_.active = false;
render_.status = status;
if (quitAfterRender_) {
std::printf("%s\n", status.c_str());
render_.mp4 = false;
viewer_.setDone(true);
}
if (status.rfind("Done", 0) != 0 || !render_.mp4 || !ffmpegAvailable()) return;
const std::string dir = render_.dir;
std::string cmd = "ffmpeg -y -loglevel error -framerate 30 -i " +
quotePath((std::filesystem::path(dir) / "frame_%05d.png").string());
if (render_.withAudio && !audioPath_.empty()) {
char offset[32];
std::snprintf(offset, sizeof(offset), "%.3f", render_.start / 30.0);
cmd += " -ss " + std::string(offset) + " -i " + quotePath(audioPath_) + " -map 0:v -map 1:a -c:a aac -shortest";
}
cmd += " -c:v libx264 -pix_fmt yuv420p -crf 18 " + quotePath((std::filesystem::path(dir) / "render.mp4").string());
render_.status = "Encoding render.mp4 with ffmpeg...";
std::shared_ptr<std::atomic<int>> result = render_.encodeResult = std::make_shared<std::atomic<int>>(-1);
std::thread([cmd, result] { result->store(std::system(cmd.c_str()) == 0 ? 1 : 0); }).detach();
}
// Called every update: saves the frame drawn last time, then poses the next one.
void App::updateRender() {
if (render_.encodeResult && render_.encodeResult->load() >= 0) {
render_.status = render_.encodeResult->load() == 1 ? "Done: wrote render.mp4 and the PNG frames."
: "ffmpeg failed; the PNG frames are still there.";
render_.encodeResult.reset();
}
if (!render_.active) return;
if (render_.pending >= 0) {
char name[32];
std::snprintf(name, sizeof(name), "frame_%05d.png", render_.pending - render_.start);
const std::string file = (std::filesystem::path(render_.dir) / name).string();
if (!osgDB::writeImageFile(*render_.image, file)) {
finishRender("Could not write " + file);
return;
}
render_.pending = -1;
if (++render_.current > render_.end) {
finishRender("Done: wrote " + std::to_string(render_.end - render_.start + 1) + " frames to " + render_.dir);
return;
}
}
if (render_.cancel) {
render_.cancel = false;
finishRender("Cancelled.");
return;
}
setMotionFrame(static_cast<float>(render_.current));
render_.camera->setProjectionMatrixAsPerspective(fov_, double(render_.width) / render_.height, 0.1, 1000.0);
render_.camera->setViewMatrix(manipulator_->getInverseMatrix());
render_.pending = render_.current;
}
void App::drawRenderDialog() {
if (!showRenderDialog_) return;
ImGui::SetNextWindowSize(ImVec2(ImGui::GetFontSize() * 28.f, 0.f), ImGuiCond_Appearing);
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
if (!ImGui::Begin("Render", &showRenderDialog_, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoCollapse)) {
ImGui::End();
return;
}
ImGui::BeginDisabled(render_.active);
ImGui::InputText("Output folder", render_.dir, sizeof(render_.dir));
static const int presets[][2] = {{1280, 720}, {1920, 1080}, {2560, 1440}, {3840, 2160}, {1080, 1920}};
static const char* presetNames[] = {"720p", "1080p", "1440p", "4K", "Vertical 1080x1920"};
for (int i = 0; i < 5; ++i) {
if (i) ImGui::SameLine();
if (ImGui::SmallButton(presetNames[i])) {
render_.width = presets[i][0];
render_.height = presets[i][1];
}
}
int size[2] = {render_.width, render_.height};
if (ImGui::InputInt2("Resolution", size)) {
render_.width = std::clamp(size[0], 16, 8192);
render_.height = std::clamp(size[1], 16, 8192);
}
int range[2] = {render_.start, render_.end};
if (ImGui::InputInt2("Frames", range)) {
render_.start = std::max(0, range[0]);
render_.end = std::max(render_.start, range[1]);
}
ImGui::TextDisabled("%d frames, %.1f s at 30 fps", render_.end - render_.start + 1,
(render_.end - render_.start + 1) / 30.f);
ImGui::Checkbox("Transparent background", &render_.transparent);
const bool ffmpeg = ffmpegAvailable();
ImGui::BeginDisabled(!ffmpeg);
ImGui::Checkbox("Also encode render.mp4 (ffmpeg)", &render_.mp4);
if (render_.mp4 && !audioPath_.empty()) {
ImGui::SameLine();
ImGui::Checkbox("with song", &render_.withAudio);
}
ImGui::EndDisabled();
if (!ffmpeg) ImGui::TextDisabled("Install ffmpeg to get a video file; PNG frames always work.");
ImGui::EndDisabled();
ImGui::Separator();
if (render_.active) {
const float total = float(render_.end - render_.start + 1);
const float done = float(render_.current - render_.start);
char label[64];
std::snprintf(label, sizeof(label), "Frame %d of %d", render_.current - render_.start + 1, int(total));
ImGui::ProgressBar(done / total, ImVec2(-1.f, 0.f), label);
if (ImGui::Button("Cancel")) render_.cancel = true;
} else {
ImGui::BeginDisabled(!modelNode_ || render_.encodeResult != nullptr);
if (ImGui::Button("Render PNG frames", ImVec2(-1.f, 0.f))) startRender();
ImGui::EndDisabled();
ImGui::TextDisabled("Uses the motion camera when Camera follow is on, otherwise the current view.");
}
if (!render_.status.empty()) ImGui::TextWrapped("%s", render_.status.c_str());
ImGui::End();
}
} // namespace mr
+175
View File
@@ -0,0 +1,175 @@
// Scene save/load: converts between the editor's state and mr::Scene (scene/SceneFile.h).
#include "app/AppUi.h"
#include "scene/SceneFile.h"
#include <imgui.h>
#include <algorithm>
#if defined(__GLIBC__)
#include <malloc.h>
#elif defined(__APPLE__)
#include <malloc/malloc.h>
#endif
namespace mr {
void App::newScene() {
unloadMotion();
while (!items_.empty()) removeModel(static_cast<int>(items_.size()) - 1);
scenePath_.clear();
loadError_.clear();
// Hand the freed model data back to the OS; the allocators otherwise keep it for reuse.
#if defined(__GLIBC__)
malloc_trim(0);
#elif defined(__APPLE__)
malloc_zone_pressure_relief(nullptr, 0);
#endif
}
void App::requestSaveScene(bool saveAs) {
if (!saveAs && !scenePath_.empty()) saveScene(scenePath_);
else fileBrowser_.open(FileBrowser::Mode::Save, scenePath_.empty() ? "scene.mrscene" : scenePath_, ".mrscene");
}
bool App::saveScene(const std::string& path) {
Scene scene;
for (const auto& item : items_) {
SceneModel m;
m.path = item->path;
m.stage = item->stage;
m.visible = item->visible;
m.position = item->position;
m.rotationY = item->rotationY;
m.scale = item->scale;
if (item->motion) m.motionPath = item->motionPath;
const Model& model = item->node->model();
Poser& poser = item->node->poser();
const auto& poses = poser.bonePoses();
for (size_t b = 0; b < model.bones.size() && b < poses.size(); ++b)
if (poses[b] != BonePose()) m.bonePoses.emplace_back(model.bones[b].name, poses[b]);
// Morphs keyed by the motion are overwritten every frame, so only manual weights are kept.
std::vector<uint8_t> keyed(model.morphs.size(), 0);
if (item->player)
for (const auto& binding : item->player->morphBindings()) keyed[binding.first] = 1;
const auto& weights = poser.morphWeights();
for (size_t i = 0; i < model.morphs.size() && i < weights.size(); ++i)
if (!keyed[i] && weights[i] != 0.f) m.morphWeights.emplace_back(model.morphs[i].name, weights[i]);
scene.models.push_back(std::move(m));
}
scene.activeModel = active_;
scene.cameraMotionPath = camera_ ? cameraPath_ : std::string();
scene.audioPath = audio_.loaded() ? audioPath_ : std::string();
scene.frame = motionFrame_;
scene.loop = loopMotion_;
scene.followCamera = useMotionCamera_;
scene.cameraMadeFor = cameraFit_.madeFor;
scene.cameraHeightScale = cameraFit_.heightScale;
scene.cameraDistance = cameraFit_.distance;
scene.cameraOffset = cameraFit_.offset;
scene.cameraFollowModel = cameraFit_.followModel;
scene.volume = volume_;
scene.view.valid = true;
manipulator_->getTransformation(scene.view.eye, scene.view.center, scene.view.up);
scene.showGrid = showGrid_;
scene.physics = physicsEnabled_;
scene.ik = ikEnabled_;
scene.gpuSkinning = skinning_ == 1;
scene.skeleton = showSkeleton_;
scene.wireframe = wireframe_;
scene.backfaceCulling = backfaceCulling_;
scene.look = look_;
scene.renderWidth = render_.width;
scene.renderHeight = render_.height;
scene.renderTransparent = render_.transparent;
scene.renderMp4 = render_.mp4;
scene.renderAudio = render_.withAudio;
std::string error;
if (!mr::saveScene(scene, path, error)) {
loadError_ = "Failed to save scene: " + error;
return false;
}
scenePath_ = path;
sceneStatus_ = "Saved " + path.substr(path.find_last_of("/\\") + 1);
sceneStatusTime_ = ImGui::GetCurrentContext() ? ImGui::GetTime() : 0.0;
return true;
}
bool App::openScene(const std::string& path) {
Scene scene;
std::string error;
if (!mr::loadScene(path, scene, error)) {
loadError_ = "Failed to open scene: " + error;
return false;
}
newScene();
std::string problems;
auto note = [&](const std::string& message) { problems += (problems.empty() ? "" : "\n") + message; };
for (const SceneModel& m : scene.models) {
if (!loadModel(m.path, m.stage)) {
note(loadError_);
continue;
}
SceneItem& item = *items_.back();
item.stage = m.stage;
item.visible = m.visible;
item.position = m.position;
item.rotationY = m.rotationY;
item.scale = m.scale;
updatePlacement(item);
const Model& model = item.node->model();
Poser& poser = item.node->poser();
for (const auto& [name, pose] : m.bonePoses) {
const int bone = model.findBone(name);
if (bone >= 0) poser.bonePoses()[bone] = pose;
}
for (const auto& [name, weight] : m.morphWeights) {
const int morph = model.findMorph(name);
if (morph >= 0) poser.morphWeights()[morph] = weight;
}
if (!m.motionPath.empty() && !loadMotion(m.motionPath)) note(loadError_);
}
// A dance .vmd that also holds camera keys has already set the camera.
if (!scene.cameraMotionPath.empty() && scene.cameraMotionPath != cameraPath_ && !loadMotion(scene.cameraMotionPath))
note(loadError_);
if (!scene.audioPath.empty() && !loadAudio(scene.audioPath)) note(loadError_);
showGrid_ = scene.showGrid;
setShowGrid(showGrid_);
physicsEnabled_ = scene.physics;
ikEnabled_ = scene.ik;
skinning_ = scene.gpuSkinning ? 1 : 0;
showSkeleton_ = scene.skeleton;
wireframe_ = scene.wireframe;
backfaceCulling_ = scene.backfaceCulling;
look_ = scene.look;
loopMotion_ = scene.loop;
useMotionCamera_ = scene.followCamera;
cameraFit_.madeFor = scene.cameraMadeFor;
cameraFit_.heightScale = scene.cameraHeightScale;
cameraFit_.distance = scene.cameraDistance;
cameraFit_.offset = scene.cameraOffset;
cameraFit_.followModel = scene.cameraFollowModel;
volume_ = scene.volume;
audio_.setVolume(volume_);
render_.width = scene.renderWidth;
render_.height = scene.renderHeight;
render_.transparent = scene.renderTransparent;
render_.mp4 = scene.renderMp4;
render_.withAudio = scene.renderAudio;
if (!items_.empty()) selectModel(std::clamp(scene.activeModel, 0, static_cast<int>(items_.size()) - 1));
applyViewSettings();
for (auto& item : items_) item->node->poser().resetPhysics();
setMotionFrame(scene.frame);
if (scene.view.valid && !(camera_ && useMotionCamera_))
manipulator_->setTransformation(scene.view.eye, scene.view.center, scene.view.up);
scenePath_ = path;
if (!problems.empty()) loadError_ = "Some parts of the scene could not be loaded:\n" + problems;
return true;
}
} // namespace mr
+247
View File
@@ -0,0 +1,247 @@
#include "app/AppUi.h"
#include <imgui.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
namespace mr {
namespace {
const ImU32 kKeyColor = IM_COL32(255, 196, 92, 255);
const ImU32 kCameraKeyColor = IM_COL32(120, 200, 255, 255);
const ImU32 kMorphKeyColor = IM_COL32(220, 130, 255, 255);
const ImU32 kPlayheadColor = IM_COL32(255, 80, 90, 255);
void drawDiamond(ImDrawList* dl, float x, float y, float r, ImU32 color) {
dl->AddQuadFilled(ImVec2(x, y - r), ImVec2(x + r, y), ImVec2(x, y + r), ImVec2(x - r, y), color);
}
// Draws the keys of one track that fall inside [first, last] frames.
template <typename Key>
void drawKeys(ImDrawList* dl, const std::vector<Key>& keys, float first, float last, float x0, float zoom,
float y, float r, ImU32 color) {
auto it = std::lower_bound(keys.begin(), keys.end(), first,
[](const Key& k, float f) { return static_cast<float>(k.frame) < f; });
float lastX = -1e9f;
for (; it != keys.end() && static_cast<float>(it->frame) <= last; ++it) {
const float x = x0 + (static_cast<float>(it->frame) - first) * zoom;
if (x - lastX < 1.f) continue; // skip overdraw when zoomed far out
drawDiamond(dl, x, y, r, color);
lastX = x;
}
}
float niceStep(float zoom) {
static const float steps[] = {1, 2, 5, 10, 15, 30, 60, 150, 300, 600, 1800, 3600};
for (float s : steps)
if (s * zoom >= 56.f) return s;
return 7200.f;
}
} // namespace
void App::drawTimelineWindow() {
ImGui::Begin("Timeline");
const float end = std::max(timelineEnd(), 1.f);
const bool hasMedia = player_ || camera_ || audio_.loaded();
ImGui::BeginDisabled(!hasMedia);
if (ImGui::Button("|<")) setMotionFrame(0.f);
ImGui::SameLine();
if (ImGui::ArrowButton("##prev", ImGuiDir_Left)) setMotionFrame(std::max(0.f, std::ceil(motionFrame_) - 1.f));
ImGui::SameLine();
if (ImGui::Button(playing_ ? "Pause" : "Play", ImVec2(ImGui::GetFontSize() * 4.f, 0.f))) setPlaying(!playing_);
ImGui::SameLine();
if (ImGui::ArrowButton("##next", ImGuiDir_Right)) setMotionFrame(std::min(end, std::floor(motionFrame_) + 1.f));
ImGui::SameLine();
if (ImGui::Button(">|")) setMotionFrame(end);
ImGui::SameLine();
int frame = static_cast<int>(motionFrame_ + 0.5f);
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 4.5f);
if (ImGui::InputInt("##frame", &frame, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue))
setMotionFrame(std::clamp(static_cast<float>(frame), 0.f, end));
ImGui::SameLine();
const float seconds = motionFrame_ / 30.f;
ImGui::Text("/ %.0f %d:%05.2f", end, static_cast<int>(seconds) / 60, std::fmod(seconds, 60.f));
ImGui::SameLine();
ImGui::Checkbox("Loop", &loopMotion_);
ImGui::EndDisabled();
if (camera_) {
ImGui::SameLine();
if (ImGui::Checkbox("Camera follow", &useMotionCamera_)) {
if (useMotionCamera_) applyCamera();
else restoreCamera();
}
ImGui::SameLine();
if (ImGui::Button("Camera fit...")) ImGui::OpenPopup("Camera fit");
if (ImGui::BeginPopup("Camera fit")) {
drawCameraFit();
ImGui::EndPopup();
}
}
if (audio_.loaded() && audio_.hasDevice()) {
ImGui::SameLine();
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 6.f);
if (ImGui::SliderFloat("Volume", &volume_, 0.f, 1.f, "%.2f")) audio_.setVolume(volume_);
}
ImGui::SameLine();
if (ImGui::Button("Add media...")) fileBrowser_.open();
ImGui::SameLine();
ImGui::BeginDisabled(!modelNode_);
if (ImGui::Button("Render...")) openRenderDialog();
ImGui::EndDisabled();
if (hasMedia) {
ImGui::SameLine();
if (ImGui::Button("Clear")) unloadMotion();
}
if (!hasMedia) {
ImGui::Spacing();
ImGui::TextDisabled("Open a dance .vmd, a camera .vmd or a song (.wav/.mp3/.flac) to fill the timeline.");
} else {
drawTimelineTracks(end);
}
ImGui::End();
}
void App::drawTimelineTracks(float end) {
ImGuiIO& io = ImGui::GetIO();
ImDrawList* dl = ImGui::GetWindowDrawList();
const float labelW = ImGui::GetFontSize() * 13.f;
const float rowH = ImGui::GetFrameHeight();
const float rulerH = ImGui::GetFontSize() * 1.4f;
const ImVec2 origin = ImGui::GetCursorScreenPos();
const float availW = ImGui::GetContentRegionAvail().x;
const float x0 = origin.x + labelW;
const float canvasW = std::max(availW - labelW, 10.f);
// Keep the playhead in view while playing.
const float visibleFrames = canvasW / timelineZoom_;
if (playing_ && (motionFrame_ < timelineScroll_ || motionFrame_ > timelineScroll_ + visibleFrames * 0.95f))
timelineScroll_ = motionFrame_ - visibleFrames * 0.05f;
timelineScroll_ = std::clamp(timelineScroll_, 0.f, std::max(0.f, end - visibleFrames * 0.5f));
const float first = timelineScroll_, last = timelineScroll_ + visibleFrames;
auto xToFrame = [&](float x) { return std::clamp(first + (x - x0) / timelineZoom_, 0.f, end); };
// Ruler: click or drag to scrub.
ImGui::SetCursorScreenPos(ImVec2(x0, origin.y));
ImGui::InvisibleButton("##ruler", ImVec2(canvasW, rulerH));
if (ImGui::IsItemActive()) setMotionFrame(xToFrame(io.MousePos.x));
const bool rulerHovered = ImGui::IsItemHovered();
dl->AddRectFilled(ImVec2(x0, origin.y), ImVec2(x0 + canvasW, origin.y + rulerH), IM_COL32(32, 34, 42, 255));
dl->PushClipRect(ImVec2(x0, origin.y), ImVec2(x0 + canvasW, origin.y + rulerH), true);
const float step = niceStep(timelineZoom_);
for (float f = std::floor(first / step) * step; f <= last; f += step) {
const float x = x0 + (f - first) * timelineZoom_;
dl->AddLine(ImVec2(x, origin.y + rulerH * 0.45f), ImVec2(x, origin.y + rulerH), IM_COL32(120, 125, 140, 255));
char label[32];
std::snprintf(label, sizeof(label), "%.0f", f);
dl->AddText(ImVec2(x + 3.f, origin.y), IM_COL32(170, 175, 190, 255), label);
}
dl->PopClipRect();
ImGui::SetCursorScreenPos(ImVec2(origin.x, origin.y));
ImGui::TextDisabled("frame");
// Rows.
struct Row {
std::string label;
int kind; // 0 camera, 1 audio, 2 bone, 3 morph
int index;
};
std::vector<Row> rows;
if (camera_) rows.push_back({"Camera " + cameraName_, 0, 0});
if (audio_.loaded()) rows.push_back({"Audio " + audioName_, 1, 0});
if (player_ && modelNode_) {
const Model& model = modelNode_->model();
const auto& bones = player_->boneBindings();
for (size_t i = 0; i < bones.size(); ++i) rows.push_back({model.bones[bones[i].first].name, 2, int(i)});
const auto& morphs = player_->morphBindings();
for (size_t i = 0; i < morphs.size(); ++i) rows.push_back({model.morphs[morphs[i].first].name, 3, int(i)});
}
ImGui::SetCursorScreenPos(ImVec2(origin.x, origin.y + rulerH + 2.f));
const ImGuiWindowFlags childFlags = (io.KeyCtrl || io.KeyShift) ? ImGuiWindowFlags_NoScrollWithMouse : 0;
ImGui::BeginChild("##tracks", ImVec2(availW, 0.f), ImGuiChildFlags_None, childFlags);
ImDrawList* cdl = ImGui::GetWindowDrawList();
const float tracksTop = ImGui::GetWindowPos().y;
const float tracksBottom = tracksTop + ImGui::GetWindowHeight();
bool canvasHovered = false;
ImGuiListClipper clipper;
clipper.Begin(static_cast<int>(rows.size()), rowH);
while (clipper.Step()) {
for (int r = clipper.DisplayStart; r < clipper.DisplayEnd; ++r) {
const Row& row = rows[r];
ImGui::PushID(r);
const ImVec2 p = ImGui::GetCursorScreenPos();
if (r % 2) cdl->AddRectFilled(p, ImVec2(p.x + availW, p.y + rowH), IM_COL32(255, 255, 255, 8));
bool selected = false;
int boneIndex = -1;
if (row.kind == 2) {
boneIndex = player_->boneBindings()[row.index].first;
selected = boneIndex == selectedBone_;
}
if (ImGui::Selectable(row.label.c_str(), selected, 0, ImVec2(labelW - 8.f, rowH)) && boneIndex >= 0) {
selectedBone_ = boneIndex;
modelNode_->setSelectedBone(selectedBone_);
}
if (ImGui::IsItemHovered() && ImGui::CalcTextSize(row.label.c_str()).x > labelW - 8.f)
ImGui::SetTooltip("%s", row.label.c_str());
ImGui::SameLine(labelW);
ImGui::InvisibleButton("##canvas", ImVec2(canvasW, rowH));
if (ImGui::IsItemActive()) setMotionFrame(xToFrame(io.MousePos.x));
canvasHovered |= ImGui::IsItemHovered();
const float cy = p.y + rowH * 0.5f, rad = rowH * 0.28f;
cdl->PushClipRect(ImVec2(x0, p.y), ImVec2(x0 + canvasW, p.y + rowH), true);
switch (row.kind) {
case 0: drawKeys(cdl, camera_->cameraKeys, first, last, x0, timelineZoom_, cy, rad, kCameraKeyColor); break;
case 1: {
const float len = static_cast<float>(audio_.length()) * 30.f;
cdl->AddRectFilled(ImVec2(x0 + (0.f - first) * timelineZoom_, p.y + 3.f),
ImVec2(x0 + (len - first) * timelineZoom_, p.y + rowH - 3.f),
IM_COL32(80, 170, 120, 150), 3.f);
break;
}
case 2:
drawKeys(cdl, *player_->boneBindings()[row.index].second, first, last, x0, timelineZoom_, cy, rad,
selected ? IM_COL32(255, 255, 255, 255) : kKeyColor);
break;
case 3:
drawKeys(cdl, *player_->morphBindings()[row.index].second, first, last, x0, timelineZoom_, cy, rad,
kMorphKeyColor);
break;
}
cdl->PopClipRect();
ImGui::PopID();
}
}
ImGui::EndChild();
// Zoom (Ctrl+wheel), pan (Shift+wheel or middle drag).
if (canvasHovered || rulerHovered) {
if (io.KeyCtrl && io.MouseWheel != 0.f) {
const float anchor = first + (io.MousePos.x - x0) / timelineZoom_;
timelineZoom_ = std::clamp(timelineZoom_ * std::pow(1.2f, io.MouseWheel), 0.05f, 40.f);
timelineScroll_ = anchor - (io.MousePos.x - x0) / timelineZoom_;
} else if (io.KeyShift && io.MouseWheel != 0.f) {
timelineScroll_ -= io.MouseWheel * 60.f / timelineZoom_;
}
if (io.MouseWheelH != 0.f) timelineScroll_ -= io.MouseWheelH * 60.f / timelineZoom_;
if (ImGui::IsMouseDragging(ImGuiMouseButton_Middle, 0.f)) timelineScroll_ -= io.MouseDelta.x / timelineZoom_;
}
// Playhead across ruler and tracks.
const float px = x0 + (motionFrame_ - first) * timelineZoom_;
if (px >= x0 && px <= x0 + canvasW) {
ImDrawList* fg = ImGui::GetWindowDrawList();
fg->PushClipRect(ImVec2(x0, origin.y), ImVec2(x0 + canvasW, tracksBottom), true);
fg->AddLine(ImVec2(px, origin.y), ImVec2(px, tracksBottom), kPlayheadColor, 2.f);
fg->AddTriangleFilled(ImVec2(px - 5.f, origin.y), ImVec2(px + 5.f, origin.y), ImVec2(px, origin.y + 7.f),
kPlayheadColor);
fg->PopClipRect();
}
}
} // namespace mr
+28
View File
@@ -0,0 +1,28 @@
#include "app/WindowVisibility.h"
#include <osg/GraphicsContext>
#if defined(_WIN32)
#include <osgViewer/api/Win32/GraphicsWindowWin32>
#else
#include <osgViewer/api/X11/GraphicsWindowX11>
#endif
namespace mr {
void setWindowVisible(osg::GraphicsContext* gc, bool visible) {
#if defined(_WIN32)
if (auto* window = dynamic_cast<osgViewer::GraphicsWindowWin32*>(gc))
ShowWindow(window->getHWND(), visible ? SW_SHOW : SW_HIDE);
#else
if (auto* window = dynamic_cast<osgViewer::GraphicsWindowX11*>(gc)) {
if (visible) XMapRaised(window->getDisplay(), window->getWindow());
else XUnmapWindow(window->getDisplay(), window->getWindow());
XFlush(window->getDisplay());
}
#endif
}
void prepareReusableWindow(osg::GraphicsContext*) {}
} // namespace mr
+15
View File
@@ -0,0 +1,15 @@
#pragma once
namespace osg {
class GraphicsContext;
}
namespace mr {
// Shows or hides an OSG window without closing its graphics context.
void setWindowVisible(osg::GraphicsContext* gc, bool visible);
// Makes the window's close button send one close event, so the window can be hidden and shown again.
void prepareReusableWindow(osg::GraphicsContext* gc);
} // namespace mr
+66
View File
@@ -0,0 +1,66 @@
#include "app/WindowVisibility.h"
#import <Cocoa/Cocoa.h>
#import <objc/runtime.h>
#include <osgViewer/api/Cocoa/GraphicsWindowCocoa>
// OSG's Cocoa window keeps reporting a close request on every frame once its close button is clicked, until the
// context is closed. This target reports a single close event instead.
@interface MrCloseButtonTarget : NSObject {
osgViewer::GraphicsWindowCocoa* window_;
}
- (instancetype)initWithWindow:(osgViewer::GraphicsWindowCocoa*)window;
- (void)closeClicked:(id)sender;
@end
@implementation MrCloseButtonTarget
- (instancetype)initWithWindow:(osgViewer::GraphicsWindowCocoa*)window {
if ((self = [super init])) window_ = window;
return self;
}
- (void)closeClicked:(id)sender {
(void)sender;
window_->getEventQueue()->closeWindow();
}
@end
namespace mr {
namespace {
char closeTargetKey;
NSWindow* nsWindowOf(osg::GraphicsContext* gc) {
auto* window = dynamic_cast<osgViewer::GraphicsWindowCocoa*>(gc);
return window ? (NSWindow*)window->getWindow() : nil;
}
} // namespace
void setWindowVisible(osg::GraphicsContext* gc, bool visible) {
NSWindow* nsWindow = nsWindowOf(gc);
if (!nsWindow) return;
if (visible) {
[nsWindow makeKeyAndOrderFront:nil];
return;
}
[nsWindow orderOut:nil];
for (NSWindow* other in [NSApp orderedWindows]) {
if (other != nsWindow && [other isVisible]) {
[other makeKeyAndOrderFront:nil];
break;
}
}
}
void prepareReusableWindow(osg::GraphicsContext* gc) {
NSWindow* nsWindow = nsWindowOf(gc);
if (!nsWindow) return;
MrCloseButtonTarget* target =
[[MrCloseButtonTarget alloc] initWithWindow:static_cast<osgViewer::GraphicsWindowCocoa*>(gc)];
objc_setAssociatedObject(nsWindow, &closeTargetKey, target, OBJC_ASSOCIATION_RETAIN);
[target release];
NSButton* closeButton = [nsWindow standardWindowButton:NSWindowCloseButton];
[closeButton setTarget:target];
[closeButton setAction:@selector(closeClicked:)];
}
} // namespace mr
+238 -7
View File
@@ -1,5 +1,7 @@
#include "app/AppUi.h"
#include "model/PathUtil.h"
#include "render/GpuCaps.h"
#include "render/ModelNode.h"
#include <osg/Group>
@@ -8,14 +10,36 @@
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <functional>
#include <cstdlib>
#include <iostream>
#include <optional>
#if defined(_WIN32)
#define NOMINMAX
#include <windows.h>
#include <psapi.h>
#elif defined(__APPLE__)
#include <mach/mach.h>
#else
#include <unistd.h>
#endif
#include <sstream>
#include <string>
#include <vector>
namespace {
// Runs a hook before each event traversal, ahead of the viewer's own handling of window events.
class EditorViewer : public osgViewer::Viewer {
public:
std::function<void()> beforeEvents;
void eventTraversal() override {
if (beforeEvents) beforeEvents();
osgViewer::Viewer::eventTraversal();
}
};
// Ignores mouse/keyboard events that ImGui already consumed.
class GuiAwareManipulator : public osgGA::TrackballManipulator {
public:
@@ -27,7 +51,7 @@ public:
};
void printUsage() {
std::cout << "Usage: model_renderer [model.pmx|.pmd|.fbx] [options]\n"
std::cout << "Usage: model_renderer [model.pmx|.pmd|.fbx|scene.mrscene] [options]\n"
" --size WxH window size (default 1280x800)\n"
" --morph NAME=WEIGHT set a morph weight (repeatable)\n"
" --bone NAME=RX,RY,RZ[,TX,TY,TZ] pose a bone, degrees (repeatable)\n"
@@ -38,6 +62,32 @@ void printUsage() {
" --screenshot FILE render, save a PNG and exit\n"
" --frames N frames to render before the screenshot (default 5)\n"
" --list print bone and morph names after loading\n"
" --skinning gpu|cpu hardware or software skinning (default gpu)\n"
" --motion FILE.vmd load an MMD motion\n"
" --frame N motion frame to show (30 per second)\n"
" --camera FILE.vmd load an MMD camera motion\n"
" --audio FILE load a song (.wav .mp3 .flac)\n"
" --play start playback\n"
" --add FILE add another model to the scene (repeatable)\n"
" --stage FILE add a stage/environment model (repeatable)\n"
" --scale S scale the first model\n"
" --stage-scale S scale every --stage model\n"
" --no-grid hide the floor grid\n"
" --save-scene FILE save the scene (.mrscene) after loading\n"
" --reload-test N reopen the scene N times and print memory use, then exit\n"
" --physics on|off rigid-body physics (default on)\n"
" --shading toon|lambert|cel|soft material style\n"
" --shadows on|off shadow mapping (default on)\n"
" --outlines on|off MMD edge outlines (default on)\n"
" --rim S rim light strength (0 = off)\n"
" --bloom S bloom strength (0 = off)\n"
" --ao on|off ambient occlusion\n"
" --fxaa on|off FXAA anti-aliasing\n"
" --filmic on|off filmic tone mapping\n"
" --pop-out show the 3D view in its own window\n"
" --render DIR render PNG frames into DIR and exit\n"
" --range A,B frames to render (default: whole timeline)\n"
" --render-size WxH render resolution (default 1920x1080)\n"
" --bench N time N idle and N animated frames, then exit\n";
}
@@ -49,6 +99,28 @@ std::vector<float> parseFloats(const std::string& s) {
return out;
}
// Resident memory of this process, for leak checks.
double residentBytes() {
#if defined(_WIN32)
PROCESS_MEMORY_COUNTERS pmc{};
return K32GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)) ? double(pmc.WorkingSetSize) : 0.0;
#elif defined(__APPLE__)
// phys_footprint is what Activity Monitor reports as Memory; resident_size also counts freed pages
// the system hasn't reclaimed yet.
task_vm_info_data_t info{};
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
return task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast<task_info_t>(&info), &count) == KERN_SUCCESS
? double(info.phys_footprint) : 0.0;
#else
long pages = 0, resident = 0;
if (std::FILE* f = std::fopen("/proc/self/statm", "r")) {
if (std::fscanf(f, "%ld %ld", &pages, &resident) != 2) resident = 0;
std::fclose(f);
}
return double(resident) * double(sysconf(_SC_PAGESIZE));
#endif
}
// Times idle frames, frames that re-pose the model, and the CPU deformation alone.
void runBenchmark(osgViewer::Viewer& viewer, mr::ModelNode* node, int frames) {
using Clock = std::chrono::steady_clock;
@@ -61,6 +133,10 @@ void runBenchmark(osgViewer::Viewer& viewer, mr::ModelNode* node, int frames) {
for (int f = 0; f < frames; ++f) viewer.frame();
const double idle = ms(Clock::now() - start) / frames;
std::printf("idle frame: %.2f ms\n", idle);
if (node)
std::printf("skinning: %s (%s)\n",
node->activeSkinningMode() == mr::SkinningMode::Hardware ? "GPU" : "CPU",
mr::gpuCaps().renderer.c_str());
if (!node) return;
mr::Poser& poser = node->poser();
@@ -96,11 +172,29 @@ void runBenchmark(osgViewer::Viewer& viewer, mr::ModelNode* node, int frames) {
} // namespace
int main(int argc, char** argv) {
std::string modelPath, screenshot;
std::string modelPath, screenshot, motionPath, cameraPath, audioPath;
float motionFrame = 0.f;
bool play = false;
bool popOut = false;
bool physics = true, grid = true;
std::vector<std::string> stagePaths, extraModels;
float modelScale = 1.f, stageScale = 1.f;
std::optional<float> cameraMadeFor, cameraHeight, cameraDistance;
std::optional<osg::Vec3f> cameraOffset;
bool cameraFitToModel = false;
std::string saveScenePath;
bool orbitSet = false, physicsSet = false;
int shading = -1, shadows = -1, outlines = -1;
float bloom = -1.f;
int ao = -1, fxaa = -1, filmic = -1;
float rim = -1.f;
int reloadTest = 0;
std::string renderDir;
int renderStart = 0, renderEnd = -1, renderW = 1920, renderH = 1080;
std::vector<std::pair<std::string, std::string>> morphArgs, boneArgs;
int width = 1280, height = 800, frames = 5, benchFrames = 0;
float azimuth = 0.f, elevation = 0.f, uiScale = 1.f;
bool skeleton = false, hideUi = false, listNames = false;
bool skeleton = false, hideUi = false, listNames = false, gpuSkinning = true;
for (int i = 1; i < argc; ++i) {
std::string a = argv[i];
@@ -129,6 +223,7 @@ int main(int argc, char** argv) {
auto v = parseFloats(next());
if (v.size() >= 1) azimuth = v[0];
if (v.size() >= 2) elevation = v[1];
orbitSet = true;
} else if (a == "--skeleton") {
skeleton = true;
} else if (a == "--hide-ui") {
@@ -139,6 +234,72 @@ int main(int argc, char** argv) {
screenshot = next();
} else if (a == "--list") {
listNames = true;
} else if (a == "--skinning") {
gpuSkinning = next() != "cpu";
} else if (a == "--motion") {
motionPath = next();
} else if (a == "--camera") {
cameraPath = next();
} else if (a == "--audio") {
audioPath = next();
} else if (a == "--frame") {
motionFrame = std::strtof(next().c_str(), nullptr);
} else if (a == "--play") {
play = true;
} else if (a == "--stage") {
stagePaths.push_back(next());
} else if (a == "--add") {
extraModels.push_back(next());
} else if (a == "--scale") {
modelScale = std::strtof(next().c_str(), nullptr);
} else if (a == "--camera-made-for") {
cameraMadeFor = std::strtof(next().c_str(), nullptr);
} else if (a == "--camera-fit") {
cameraFitToModel = true;
} else if (a == "--camera-height") {
cameraHeight = std::strtof(next().c_str(), nullptr);
} else if (a == "--camera-distance") {
cameraDistance = std::strtof(next().c_str(), nullptr);
} else if (a == "--camera-offset") {
osg::Vec3f o;
std::sscanf(next().c_str(), "%f,%f,%f", &o.x(), &o.y(), &o.z());
cameraOffset = o;
} else if (a == "--stage-scale") {
stageScale = std::strtof(next().c_str(), nullptr);
} else if (a == "--no-grid") {
grid = false;
} else if (a == "--physics") {
physics = next() != "off";
physicsSet = true;
} else if (a == "--shading") {
const std::string s = next();
shading = s == "lambert" ? 1 : s == "cel" ? 2 : s == "soft" ? 3 : 0;
} else if (a == "--shadows") {
shadows = next() != "off" ? 1 : 0;
} else if (a == "--outlines") {
outlines = next() != "off" ? 1 : 0;
} else if (a == "--bloom") {
bloom = std::stof(next());
} else if (a == "--ao") {
ao = next() != "off";
} else if (a == "--fxaa") {
fxaa = next() != "off";
} else if (a == "--filmic") {
filmic = next() != "off";
} else if (a == "--rim") {
rim = std::strtof(next().c_str(), nullptr);
} else if (a == "--reload-test") {
reloadTest = std::max(1, std::atoi(next().c_str()));
} else if (a == "--save-scene") {
saveScenePath = next();
} else if (a == "--pop-out") {
popOut = true;
} else if (a == "--render") {
renderDir = next();
} else if (a == "--range") {
std::sscanf(next().c_str(), "%d,%d", &renderStart, &renderEnd);
} else if (a == "--render-size") {
std::sscanf(next().c_str(), "%dx%d", &renderW, &renderH);
} else if (a == "--bench") {
benchFrames = std::max(1, std::atoi(next().c_str()));
} else if (a == "--frames") {
@@ -152,7 +313,7 @@ int main(int argc, char** argv) {
}
}
osgViewer::Viewer viewer;
EditorViewer viewer;
viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
viewer.setUpViewInWindow(80, 80, width, height);
viewer.getCamera()->setClearColor(osg::Vec4(0.22f, 0.24f, 0.28f, 1.f));
@@ -164,8 +325,42 @@ int main(int argc, char** argv) {
viewer.setCameraManipulator(manipulator);
mr::App app(viewer, root, manipulator);
viewer.beforeEvents = [&app] { app.catchPopOutClose(); };
viewer.setRealizeOperation(new mr::GpuCapsProbe(viewer.getRealizeOperation()));
app.setGpuSkinning(gpuSkinning);
const auto loadStart = std::chrono::steady_clock::now();
if (!modelPath.empty() && !app.loadModel(modelPath)) std::cerr << app.loadError() << "\n";
const bool isScene = modelPath.size() > 8 && mr::toLowerAscii(modelPath.substr(modelPath.size() - 8)) == ".mrscene";
if (isScene) {
app.openScene(modelPath);
if (!app.loadError().empty()) std::cerr << app.loadError() << "\n";
} else if (!modelPath.empty() && !app.loadModel(modelPath)) {
std::cerr << app.loadError() << "\n";
}
for (const auto& path : extraModels)
if (!app.loadModel(path)) std::cerr << app.loadError() << "\n";
for (const auto& path : stagePaths) {
if (app.loadModel(path, true)) app.setModelScale(static_cast<int>(app.modelCount()) - 1, stageScale);
else std::cerr << app.loadError() << "\n";
}
if (modelScale != 1.f) app.setModelScale(0, modelScale);
// Motions and --bone/--morph apply to the first model (or the scene's selected one).
if (app.modelCount() > 0 && !isScene) app.selectModel(0);
if (!grid) app.setShowGrid(false);
{
mr::LookSettings look = app.look();
if (shading >= 0) look.shading = shading;
if (bloom >= 0.f) {
look.bloom = bloom > 0.f;
look.bloomStrength = bloom > 0.f ? bloom : look.bloomStrength;
}
if (ao >= 0) look.ambientOcclusion = ao == 1;
if (fxaa >= 0) look.fxaa = fxaa == 1;
if (filmic >= 0) look.toneMapping = filmic;
if (shadows >= 0) look.shadows = shadows == 1;
if (outlines >= 0) look.outlines = outlines == 1;
if (rim >= 0.f) look.rimStrength = rim;
app.setLook(look);
}
const double loadMs =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - loadStart).count();
@@ -196,13 +391,49 @@ int main(int argc, char** argv) {
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);
for (const std::string& path : {motionPath, cameraPath})
if (!path.empty() && !app.loadMotion(path)) std::cerr << app.loadError() << "\n";
if (!audioPath.empty() && !app.loadAudio(audioPath)) std::cerr << app.loadError() << "\n";
if (!motionPath.empty() || !cameraPath.empty() || !audioPath.empty()) {
app.setMotionFrame(motionFrame);
app.setPlaying(play);
}
if (skeleton || !isScene) app.setShowSkeleton(skeleton);
if (orbitSet || !isScene) app.frameModel(azimuth, elevation);
}
if (cameraMadeFor || cameraHeight || cameraDistance || cameraOffset || cameraFitToModel) {
mr::App::CameraFit fit = app.cameraFit();
if (cameraMadeFor) fit.madeFor = *cameraMadeFor;
if (cameraHeight) fit.heightScale = *cameraHeight;
if (cameraDistance) fit.distance = *cameraDistance;
if (cameraOffset) fit.offset = *cameraOffset;
app.setCameraFit(fit);
if (cameraFitToModel) app.fitCameraToModel();
}
app.setViewportPoppedOut(popOut);
if (physicsSet || !isScene) app.setPhysicsEnabled(physics);
if (!saveScenePath.empty() && !app.saveScene(saveScenePath)) std::cerr << app.loadError() << "\n";
if (!renderDir.empty()) app.renderToFolder(renderDir, renderStart, renderEnd, renderW, renderH);
app.imgui()->setUiVisible(!hideUi);
if (uiScale != 1.f) app.imgui()->setUiScale(uiScale);
viewer.realize();
if (reloadTest > 0) {
// Reopens the scene (or clears it with New scene) repeatedly; memory should level off.
const std::string scene = app.scenePath();
for (int r = 0; r <= reloadTest && !viewer.done(); ++r) {
if (r > 0) {
if (scene.empty()) app.newScene();
else app.openScene(scene);
}
for (int f = 0; f < 30; ++f) viewer.frame();
std::printf("reload %d: %zu models, %.0f MB in use\n", r, app.modelCount(), residentBytes() / 1048576.0);
}
app.newScene();
for (int f = 0; f < 30; ++f) viewer.frame();
std::printf("after New scene: %.0f MB in use\n", residentBytes() / 1048576.0);
return 0;
}
if (benchFrames > 0) {
runBenchmark(viewer, app.modelNode(), benchFrames);
return 0;
+90
View File
@@ -0,0 +1,90 @@
#include "audio/AudioPlayer.h"
#include <miniaudio.h>
#include <algorithm>
namespace mr {
struct AudioPlayer::Impl {
ma_engine engine;
ma_sound sound;
bool engineReady = false, device = false, soundReady = false;
Impl() {
device = engineReady = ma_engine_init(nullptr, &engine) == MA_SUCCESS;
if (!engineReady) {
ma_engine_config config = ma_engine_config_init();
config.noDevice = MA_TRUE;
config.channels = 2;
config.sampleRate = 48000;
engineReady = ma_engine_init(&config, &engine) == MA_SUCCESS;
}
}
~Impl() {
if (soundReady) ma_sound_uninit(&sound);
if (engineReady) ma_engine_uninit(&engine);
}
};
AudioPlayer::AudioPlayer() : impl_(new Impl) {}
AudioPlayer::~AudioPlayer() = default;
bool AudioPlayer::load(const std::string& path, std::string& error) {
unload();
if (!impl_->engineReady) {
error = "audio engine unavailable";
return false;
}
const ma_uint32 flags = MA_SOUND_FLAG_STREAM | MA_SOUND_FLAG_NO_SPATIALIZATION;
const ma_result result = ma_sound_init_from_file(&impl_->engine, path.c_str(), flags, nullptr, nullptr, &impl_->sound);
if (result != MA_SUCCESS) {
error = ma_result_description(result);
return false;
}
impl_->soundReady = true;
return true;
}
void AudioPlayer::unload() {
if (!impl_->soundReady) return;
ma_sound_uninit(&impl_->sound);
impl_->soundReady = false;
}
bool AudioPlayer::loaded() const { return impl_->soundReady; }
bool AudioPlayer::hasDevice() const { return impl_->device; }
double AudioPlayer::length() const {
float seconds = 0.f;
if (impl_->soundReady) ma_sound_get_length_in_seconds(&impl_->sound, &seconds);
return seconds;
}
double AudioPlayer::position() const {
float seconds = 0.f;
if (impl_->soundReady) ma_sound_get_cursor_in_seconds(&impl_->sound, &seconds);
return seconds;
}
void AudioPlayer::play() {
if (impl_->soundReady && impl_->device) ma_sound_start(&impl_->sound);
}
void AudioPlayer::pause() {
if (impl_->soundReady) ma_sound_stop(&impl_->sound);
}
bool AudioPlayer::playing() const { return impl_->soundReady && ma_sound_is_playing(&impl_->sound); }
void AudioPlayer::seek(double seconds) {
if (!impl_->soundReady) return;
const ma_uint32 rate = ma_engine_get_sample_rate(&impl_->engine);
ma_sound_seek_to_pcm_frame(&impl_->sound, static_cast<ma_uint64>(std::max(0.0, seconds) * rate));
}
void AudioPlayer::setVolume(float volume) {
if (impl_->soundReady) ma_sound_set_volume(&impl_->sound, volume);
}
} // namespace mr
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include <memory>
#include <string>
namespace mr {
// Streams one sound file (.wav, .mp3, .flac) to the default output device via miniaudio.
// Without an output device the file still loads, so its length is known, but it stays silent.
class AudioPlayer {
public:
AudioPlayer();
~AudioPlayer();
AudioPlayer(const AudioPlayer&) = delete;
AudioPlayer& operator=(const AudioPlayer&) = delete;
bool load(const std::string& path, std::string& error);
void unload();
bool loaded() const;
bool hasDevice() const;
double length() const; // seconds
double position() const; // seconds
void play();
void pause();
bool playing() const;
void seek(double seconds);
void setVolume(float volume);
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace mr
+4
View File
@@ -0,0 +1,4 @@
#define MINIAUDIO_IMPLEMENTATION
#define MA_NO_GENERATION
#define MA_NO_ENCODING
#include <miniaudio.h>
+3 -1
View File
@@ -222,7 +222,9 @@ private:
aiString name;
if (src->Get(AI_MATKEY_NAME, name) == AI_SUCCESS) m.name = name.C_Str();
aiColor4D c;
if (src->Get(AI_MATKEY_COLOR_DIFFUSE, c) == AI_SUCCESS) m.diffuse.set(c.r, c.g, c.b, 1.f);
// DirectX .x keeps material alpha in the diffuse colour rather than in an opacity key.
if (src->Get(AI_MATKEY_COLOR_DIFFUSE, c) == AI_SUCCESS)
m.diffuse.set(c.r, c.g, c.b, c.a > 0.01f ? std::min(c.a, 1.f) : 1.f);
if (src->Get(AI_MATKEY_COLOR_SPECULAR, c) == AI_SUCCESS) m.specular.set(c.r, c.g, c.b);
if (src->Get(AI_MATKEY_COLOR_AMBIENT, c) == AI_SUCCESS) m.ambient.set(c.r, c.g, c.b);
float f = 0.f;
+38
View File
@@ -61,4 +61,42 @@ void Model::normalizeWeights() {
}
}
void validateIk(Bone& bone, int index, int boneCount) {
auto valid = [&](int b) { return b >= 0 && b < boneCount && b != index; };
bool ok = bone.isIK && valid(bone.ikTarget) && !bone.ikLinks.empty();
for (const auto& link : bone.ikLinks) ok = ok && valid(link.bone);
if (!ok) {
bone.isIK = false;
bone.ikTarget = -1;
bone.ikLinks.clear();
}
bone.ikIterations = std::min(std::max(bone.ikIterations, 0), 256);
}
namespace {
// MMD applies Euler angles as Y * X * Z (column vectors); mirroring Z negates the X and Y angles.
osg::Quat mmdRotation(const osg::Vec3f& e) {
return osg::Quat(e.z(), osg::Z_AXIS) * osg::Quat(-e.x(), osg::X_AXIS) * osg::Quat(-e.y(), osg::Y_AXIS);
}
osg::Vec3f mirrorZ(const osg::Vec3f& v) { return {v.x(), v.y(), -v.z()}; }
} // namespace
void setRigidBodyFromMmd(RigidBody& body, const osg::Vec3f& position, const osg::Vec3f& euler) {
body.position = mirrorZ(position);
body.rotation = mmdRotation(euler);
}
void setJointFromMmd(Joint& joint, const osg::Vec3f& position, const osg::Vec3f& euler, const osg::Vec3f& linearLower,
const osg::Vec3f& linearUpper, const osg::Vec3f& angularLower, const osg::Vec3f& angularUpper) {
joint.position = mirrorZ(position);
joint.rotation = mmdRotation(euler);
joint.linearLower = {linearLower.x(), linearLower.y(), -linearUpper.z()};
joint.linearUpper = {linearUpper.x(), linearUpper.y(), -linearLower.z()};
joint.angularLower = {-angularUpper.x(), -angularUpper.y(), angularLower.z()};
joint.angularUpper = {-angularLower.x(), -angularLower.y(), angularUpper.z()};
}
} // namespace mr
+92
View File
@@ -24,6 +24,7 @@ struct Vertex {
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};
float edgeScale = 1.f; // PMX per-vertex outline width multiplier
};
enum class SphereMode { None, Multiply, Add, SubTexture };
@@ -51,10 +52,29 @@ struct Material {
bool drawEdge = false;
osg::Vec4f edgeColor{0.f, 0.f, 0.f, 1.f};
float edgeSize = 1.f;
bool castShadow = true; // drawn into the shadow map
bool receiveShadow = true; // darkened by the shadow map
uint32_t indexOffset = 0; // into Model::indices
uint32_t indexCount = 0;
};
// One joint of an IK chain. Limits are Euler angles in radians (model axes, applied X, Y, Z).
struct IkLink {
int bone = -1;
bool limited = false;
osg::Vec3f lower, upper;
};
// Mirroring Z negates rotations about X and Y, so the limits swap and change sign.
inline void mmdLimitsToRightHanded(const osg::Vec3f& lowerLH, const osg::Vec3f& upperLH, osg::Vec3f& lower,
osg::Vec3f& upper) {
lower.set(-upperLH.x(), -upperLH.y(), lowerLH.z());
upper.set(-lowerLH.x(), -lowerLH.y(), upperLH.z());
}
struct Bone;
void validateIk(Bone& bone, int index, int boneCount);
struct Bone {
std::string name;
std::string nameEn;
@@ -71,6 +91,10 @@ struct Bone {
bool inheritRotation = false;
bool inheritTranslation = false;
bool isIK = false;
int ikTarget = -1; // bone the chain tries to bring to this bone's position
int ikIterations = 0;
float ikLimitAngle = 0.f; // max rotation per link per iteration, radians
std::vector<IkLink> ikLinks; // ordered from the target outward
int layer = 0;
bool afterPhysics = false;
};
@@ -96,6 +120,38 @@ struct BoneMorphOffset {
osg::Quat rotation;
};
struct UvMorphOffset {
uint32_t vertex;
osg::Vec2f offset; // in the OpenGL UV convention (V up)
};
enum class MaterialMorphOp : uint8_t { Multiply = 0, Add = 1 };
struct MaterialMorphOffset {
int material = -1; // -1: every material
MaterialMorphOp op = MaterialMorphOp::Multiply;
osg::Vec4f diffuse;
osg::Vec3f specular;
float shininess = 0.f;
osg::Vec3f ambient;
osg::Vec4f edgeColor;
float edgeSize = 0.f;
osg::Vec4f textureTint, sphereTint, toonTint;
};
// Material values after material morphs. Texture tints apply as texel * mul + add.
struct MaterialState {
osg::Vec4f diffuse;
osg::Vec3f specular;
float shininess = 0.f;
osg::Vec3f ambient;
osg::Vec4f edgeColor;
float edgeSize = 0.f;
osg::Vec4f textureMul{1.f, 1.f, 1.f, 1.f}, textureAdd;
osg::Vec4f sphereMul{1.f, 1.f, 1.f, 1.f}, sphereAdd;
osg::Vec4f toonMul{1.f, 1.f, 1.f, 1.f}, toonAdd;
};
struct Morph {
std::string name;
std::string nameEn;
@@ -104,8 +160,42 @@ struct Morph {
std::vector<VertexMorphOffset> vertexOffsets;
std::vector<GroupMorphOffset> groupOffsets; // Group and Flip
std::vector<BoneMorphOffset> boneOffsets;
std::vector<UvMorphOffset> uvOffsets; // main UV channel only
std::vector<MaterialMorphOffset> materialOffsets;
};
enum class RigidShape : uint8_t { Sphere = 0, Box = 1, Capsule = 2 };
// 0: follows its bone, 1: simulated and drives the bone, 2: simulated rotation, bone position.
enum class RigidMode : uint8_t { FollowBone = 0, Physics = 1, PhysicsWithBone = 2 };
struct RigidBody {
std::string name;
int bone = -1;
int group = 0; // 0..15
uint16_t collisionMask = 0xFFFF; // groups this body collides with
RigidShape shape = RigidShape::Sphere;
osg::Vec3f size; // sphere: radius; box: half extents; capsule: radius, height
osg::Vec3f position; // model space at rest
osg::Quat rotation;
float mass = 0.f, linearDamping = 0.f, angularDamping = 0.f, restitution = 0.f, friction = 0.5f;
RigidMode mode = RigidMode::FollowBone;
};
// 6DOF spring joint between two rigid bodies (limits in the joint frame).
struct Joint {
std::string name;
int bodyA = -1, bodyB = -1;
osg::Vec3f position;
osg::Quat rotation;
osg::Vec3f linearLower, linearUpper, angularLower, angularUpper;
osg::Vec3f linearSpring, angularSpring;
};
// Convert MMD's left-handed rigid body / joint values (Euler angles in radians) to internal axes.
void setRigidBodyFromMmd(RigidBody& body, const osg::Vec3f& position, const osg::Vec3f& euler);
void setJointFromMmd(Joint& joint, const osg::Vec3f& position, const osg::Vec3f& euler, const osg::Vec3f& linearLower,
const osg::Vec3f& linearUpper, const osg::Vec3f& angularLower, const osg::Vec3f& angularUpper);
struct Model {
SourceFormat format = SourceFormat::Assimp;
std::string sourcePath;
@@ -117,6 +207,8 @@ struct Model {
std::vector<Material> materials;
std::vector<Bone> bones;
std::vector<Morph> morphs;
std::vector<RigidBody> rigidBodies;
std::vector<Joint> joints;
std::vector<std::string> warnings;
int findBone(const std::string& boneName) const;
+269
View File
@@ -0,0 +1,269 @@
#include "model/Motion.h"
#include "model/BinaryReader.h"
#include "model/TextEncoding.h"
#include <algorithm>
#include <fstream>
#include <iterator>
#include <stdexcept>
namespace mr {
float BezierCurve::eval(float x) const {
if (x <= 0.f) return 0.f;
if (x >= 1.f) return 1.f;
auto bezier = [](float t, float p1, float p2) {
const float s = 1.f - t;
return 3.f * s * s * t * p1 + 3.f * s * t * t * p2 + t * t * t;
};
// x(t) is monotonic because both control x values lie in [0, 1].
float lo = 0.f, hi = 1.f, t = x;
for (int i = 0; i < 32; ++i) {
t = 0.5f * (lo + hi);
if (bezier(t, x1, x2) < x) lo = t;
else hi = t;
}
return bezier(t, y1, y2);
}
namespace {
// Fixed-size Shift-JIS field: stop at NUL and drop a lead byte cut off by truncation.
std::string fixedSjis(BinaryReader& r, size_t size) {
const std::string raw(reinterpret_cast<const char*>(r.bytes(size)), size);
size_t end = raw.find('\0');
if (end == std::string::npos) end = raw.size();
size_t i = 0, valid = 0;
while (i < end) {
const auto c = static_cast<unsigned char>(raw[i]);
const size_t len = (c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC) ? 2 : 1;
if (i + len > end) break;
i += len;
valid = i;
}
return shiftJisToUtf8(raw.substr(0, valid));
}
osg::Vec3f vmdPosition(BinaryReader& r) {
const osg::Vec3f p = r.vec3();
return osg::Vec3f(p.x(), p.y(), -p.z());
}
// Mirroring Z turns a left-handed rotation (x, y, z, w) into (-x, -y, z, w).
osg::Quat vmdRotation(BinaryReader& r) {
const float x = r.f32(), y = r.f32(), z = r.f32(), w = r.f32();
return osg::Quat(-x, -y, z, w);
}
} // namespace
std::shared_ptr<Motion> loadVmd(const std::string& path, std::string& error) {
std::ifstream in(path, std::ios::binary);
if (!in) {
error = "cannot open file";
return nullptr;
}
const std::vector<uint8_t> data((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
try {
BinaryReader r(data);
const std::string magic(reinterpret_cast<const char*>(r.bytes(30)), 30);
size_t nameSize;
if (magic.compare(0, 25, "Vocaloid Motion Data 0002") == 0) nameSize = 20;
else if (magic.compare(0, 25, "Vocaloid Motion Data file") == 0) nameSize = 10;
else throw std::runtime_error("not a VMD motion file");
auto motion = std::make_shared<Motion>();
motion->modelName = fixedSjis(r, nameSize);
const uint32_t boneKeys = r.u32();
if (static_cast<size_t>(boneKeys) * 111 > r.remaining()) throw std::runtime_error("truncated bone keyframes");
for (uint32_t i = 0; i < boneKeys; ++i) {
const std::string name = fixedSjis(r, 15);
BoneKeyframe key;
key.frame = r.u32();
key.translation = vmdPosition(r);
key.rotation = vmdRotation(r);
const uint8_t* interp = r.bytes(64);
auto at = [&](int i) { return interp[i] / 127.f; };
for (int c = 0; c < 4; ++c) key.curves[c] = BezierCurve{at(c), at(c + 4), at(c + 8), at(c + 12)};
motion->boneTracks[name].push_back(key);
motion->lastFrame = std::max(motion->lastFrame, key.frame);
}
if (r.remaining() >= 4) {
const uint32_t morphKeys = r.u32();
if (static_cast<size_t>(morphKeys) * 23 > r.remaining()) throw std::runtime_error("truncated morph keyframes");
for (uint32_t i = 0; i < morphKeys; ++i) {
const std::string name = fixedSjis(r, 15);
MorphKeyframe key;
key.frame = r.u32();
key.weight = r.f32();
motion->morphTracks[name].push_back(key);
motion->lastFrame = std::max(motion->lastFrame, key.frame);
}
}
bool more = r.remaining() >= 4;
if (more) {
const uint32_t count = r.u32();
if (static_cast<size_t>(count) * 61 > r.remaining()) throw std::runtime_error("truncated camera keyframes");
for (uint32_t i = 0; i < count; ++i) {
CameraKeyframe key;
key.frame = r.u32();
key.distance = r.f32();
key.target = vmdPosition(r);
key.rotation = r.vec3();
const uint8_t* interp = r.bytes(24);
auto at = [&](int i) { return interp[i] / 127.f; };
for (int c = 0; c < 6; ++c)
key.curves[c] = BezierCurve{at(4 * c), at(4 * c + 2), at(4 * c + 1), at(4 * c + 3)};
key.fov = static_cast<float>(r.u32());
r.u8(); // perspective flag
motion->cameraKeys.push_back(key);
motion->lastFrame = std::max(motion->lastFrame, key.frame);
}
}
// Light and self-shadow sections are skipped for now; IK on/off keys follow them.
for (size_t recordSize : {size_t(28), size_t(9)}) {
if (!more || r.remaining() < 4) {
more = false;
break;
}
const uint32_t count = r.u32();
if (static_cast<size_t>(count) * recordSize > r.remaining()) throw std::runtime_error("truncated VMD section");
r.skip(count * recordSize);
}
if (more && r.remaining() >= 4) {
const uint32_t count = r.u32();
for (uint32_t i = 0; i < count; ++i) {
IkKeyframe key;
key.frame = r.u32();
r.u8(); // model visible
const uint32_t iks = r.u32();
if (static_cast<size_t>(iks) * 21 > r.remaining()) throw std::runtime_error("truncated IK keyframes");
for (uint32_t k = 0; k < iks; ++k) {
std::string name = fixedSjis(r, 20);
key.enabled.emplace_back(std::move(name), r.u8() != 0);
}
motion->ikKeyframes.push_back(std::move(key));
}
}
auto byFrame = [](const auto& a, const auto& b) { return a.frame < b.frame; };
for (auto& [name, keys] : motion->boneTracks) std::stable_sort(keys.begin(), keys.end(), byFrame);
for (auto& [name, keys] : motion->morphTracks) std::stable_sort(keys.begin(), keys.end(), byFrame);
std::stable_sort(motion->ikKeyframes.begin(), motion->ikKeyframes.end(), byFrame);
std::stable_sort(motion->cameraKeys.begin(), motion->cameraKeys.end(), byFrame);
return motion;
} catch (const std::exception& e) {
error = e.what();
return nullptr;
}
}
namespace {
// VMD names are cut to 15 bytes of Shift-JIS, so a truncated track name matches as a prefix.
template <typename Items>
int findByName(const Items& items, const std::string& name) {
int prefix = -1;
for (size_t i = 0; i < items.size(); ++i) {
if (items[i].name == name) return static_cast<int>(i);
if (prefix < 0 && name.size() >= 6 && items[i].name.compare(0, name.size(), name) == 0)
prefix = static_cast<int>(i);
}
return prefix;
}
template <typename Key>
std::pair<const Key*, const Key*> segment(const std::vector<Key>& keys, float frame, float& t) {
auto next = std::upper_bound(keys.begin(), keys.end(), frame,
[](float f, const Key& k) { return f < static_cast<float>(k.frame); });
if (next == keys.begin()) {
t = 0.f;
return {&keys.front(), &keys.front()};
}
if (next == keys.end()) {
t = 0.f;
return {&keys.back(), &keys.back()};
}
const Key* prev = &*(next - 1);
t = (frame - prev->frame) / static_cast<float>(next->frame - prev->frame);
return {prev, &*next};
}
} // namespace
CameraPose evaluateCamera(const std::vector<CameraKeyframe>& keys, float frame) {
CameraPose pose;
if (keys.empty()) return pose;
float t;
const auto ends = segment(keys, frame, t);
const CameraKeyframe* a = ends.first;
const CameraKeyframe* b = ends.second->frame - a->frame <= 1 ? a : ends.second;
auto lerp = [&](float x, float y, int curve) { return x + (y - x) * b->curves[curve].eval(t); };
osg::Vec3f target, rotation;
for (int k = 0; k < 3; ++k) {
target[k] = lerp(a->target[k], b->target[k], k);
rotation[k] = lerp(a->rotation[k], b->rotation[k], 3);
}
const float distance = lerp(a->distance, b->distance, 4);
pose.fov = lerp(a->fov, b->fov, 5);
// Mirroring Z keeps the X and Y angles and negates Z; MMD pitches, then rolls, then yaws.
const osg::Matrixf rotate = osg::Matrixf::rotate(rotation.x(), osg::X_AXIS) *
osg::Matrixf::rotate(-rotation.z(), osg::Z_AXIS) *
osg::Matrixf::rotate(rotation.y(), osg::Y_AXIS);
pose.center = target;
pose.eye = target + osg::Vec3f(0.f, 0.f, -distance) * rotate;
pose.up = osg::Matrixf::transform3x3(osg::Vec3f(0.f, 1.f, 0.f), rotate);
return pose;
}
MotionPlayer::MotionPlayer(std::shared_ptr<const Motion> motion, const Model& model) : motion_(std::move(motion)) {
for (const auto& [name, keys] : motion_->boneTracks) {
const int bone = findByName(model.bones, name);
if (bone >= 0 && !keys.empty()) bones_.emplace_back(bone, &keys);
}
for (const auto& [name, keys] : motion_->morphTracks) {
const int morph = findByName(model.morphs, name);
if (morph >= 0 && !keys.empty()) morphs_.emplace_back(morph, &keys);
}
for (const auto& key : motion_->ikKeyframes) {
ik_.emplace_back();
for (const auto& [name, on] : key.enabled) {
const int bone = findByName(model.bones, name);
if (bone >= 0) ik_.back().emplace_back(bone, on);
}
}
}
void MotionPlayer::apply(float frame, Poser& poser) const {
auto& motion = poser.motionPoses();
for (const auto& [bone, keys] : bones_) {
float t;
auto [a, b] = segment(*keys, frame, t);
osg::Vec3f translation;
for (int k = 0; k < 3; ++k) {
const float s = b->curves[k].eval(t);
translation[k] = a->translation[k] + (b->translation[k] - a->translation[k]) * s;
}
osg::Quat rotation;
rotation.slerp(b->curves[3].eval(t), a->rotation, b->rotation);
motion[bone].translation = translation;
motion[bone].rotation = rotation;
}
auto& weights = poser.morphWeights();
for (const auto& [morph, keys] : morphs_) {
float t;
auto [a, b] = segment(*keys, frame, t);
weights[morph] = a->weight + (b->weight - a->weight) * t;
}
auto& ikEnabled = poser.ikBoneEnabled();
std::fill(ikEnabled.begin(), ikEnabled.end(), 1);
const auto& ikKeys = motion_->ikKeyframes;
for (size_t i = 0; i < ikKeys.size() && static_cast<float>(ikKeys[i].frame) <= frame; ++i)
for (const auto& [bone, on] : ik_[i]) ikEnabled[bone] = on ? 1 : 0;
}
} // namespace mr
+91
View File
@@ -0,0 +1,91 @@
#pragma once
#include "model/Model.h"
#include "model/Poser.h"
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace mr {
// MMD keyframe easing: cubic Bezier from (0,0) to (1,1) with two control points in [0,1].
struct BezierCurve {
float x1 = 20.f / 127.f, y1 = 20.f / 127.f, x2 = 107.f / 127.f, y2 = 107.f / 127.f;
float eval(float t) const;
};
struct BoneKeyframe {
uint32_t frame = 0;
osg::Vec3f translation; // internal right-handed space
osg::Quat rotation;
BezierCurve curves[4]; // X, Y, Z translation, rotation; ease the segment ending at this key
};
struct MorphKeyframe {
uint32_t frame = 0;
float weight = 0.f;
};
struct IkKeyframe {
uint32_t frame = 0;
std::vector<std::pair<std::string, bool>> enabled; // IK bone name -> on/off
};
struct CameraKeyframe {
uint32_t frame = 0;
float distance = 0.f; // MMD convention: negative puts the camera in front of the target
osg::Vec3f target; // internal right-handed space
osg::Vec3f rotation; // radians, as stored in the VMD (left-handed)
float fov = 30.f; // vertical, degrees
BezierCurve curves[6]; // target X, Y, Z, rotation, distance, fov
};
// Camera in model space (Y up).
struct CameraPose {
osg::Vec3f eye, center, up;
float fov = 30.f;
};
struct Motion {
std::string modelName;
std::map<std::string, std::vector<BoneKeyframe>> boneTracks; // sorted by frame
std::map<std::string, std::vector<MorphKeyframe>> morphTracks;
std::vector<IkKeyframe> ikKeyframes;
std::vector<CameraKeyframe> cameraKeys;
uint32_t lastFrame = 0;
};
// MMD motion files run at 30 frames per second.
constexpr float kMotionFps = 30.f;
std::shared_ptr<Motion> loadVmd(const std::string& path, std::string& error);
// Keys one frame apart are a cut, as in MMD: the camera jumps instead of interpolating.
CameraPose evaluateCamera(const std::vector<CameraKeyframe>& keys, float frame);
// Binds a motion's tracks to a model by name and writes the pose at a frame into a Poser.
class MotionPlayer {
public:
MotionPlayer(std::shared_ptr<const Motion> motion, const Model& model);
const Motion& motion() const { return *motion_; }
size_t boundBones() const { return bones_.size(); }
size_t boundMorphs() const { return morphs_.size(); }
size_t boneTrackCount() const { return motion_->boneTracks.size(); }
size_t morphTrackCount() const { return motion_->morphTracks.size(); }
void apply(float frame, Poser& poser) const;
const std::vector<std::pair<int, const std::vector<BoneKeyframe>*>>& boneBindings() const { return bones_; }
const std::vector<std::pair<int, const std::vector<MorphKeyframe>*>>& morphBindings() const { return morphs_; }
private:
std::shared_ptr<const Motion> motion_;
std::vector<std::pair<int, const std::vector<BoneKeyframe>*>> bones_;
std::vector<std::pair<int, const std::vector<MorphKeyframe>*>> morphs_;
std::vector<std::vector<std::pair<int, bool>>> ik_; // per IkKeyframe, resolved bone indices
};
} // namespace mr
+74 -6
View File
@@ -174,15 +174,35 @@ private:
}
}
static bool isKnee(const std::string& name) { return name.find("ひざ") != std::string::npos; }
void parseIK() {
uint16_t count = r_.u16();
const int n = static_cast<int>(model_.bones.size());
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);
const int ikBone = r_.u16();
const int target = r_.u16();
const uint8_t chain = r_.u8();
const int iterations = r_.u16();
const float limit = r_.f32();
std::vector<IkLink> links(chain);
for (auto& link : links) link.bone = r_.u16();
if (ikBone >= n) continue;
Bone& b = model_.bones[ikBone];
b.isIK = true;
b.ikTarget = target;
b.ikIterations = iterations;
b.ikLimitAngle = limit * 4.f; // PMD stores a quarter of the per-iteration limit (radians)
for (auto& link : links) {
// PMD has no limits; MMD restricts knees to bend one way, like PMX's usual knee limits.
if (link.bone < n && isKnee(model_.bones[link.bone].name)) {
link.limited = true;
mmdLimitsToRightHanded(osg::Vec3f(-osg::PIf, 0, 0), osg::Vec3f(-osg::DegreesToRadians(0.5f), 0, 0),
link.lower, link.upper);
}
}
b.ikLinks = std::move(links);
validateIk(b, ikBone, n);
}
}
@@ -235,11 +255,59 @@ private:
if (r_.remaining() >= 1000) {
for (int i = 0; i < 10; ++i) toonNames_[i] = sjis(r_, 100);
}
if (r_.remaining() >= 4) parsePhysics();
} catch (const std::runtime_error&) {
model_.warnings.push_back("PMD optional sections are truncated");
}
}
void parsePhysics() {
const uint32_t bodyCount = r_.u32();
std::vector<RigidBody> bodies;
for (uint32_t i = 0; i < bodyCount; ++i) {
RigidBody b;
b.name = sjis(r_, 20);
const uint16_t bone = r_.u16();
b.bone = bone < model_.bones.size() ? bone : -1;
b.group = r_.u8();
b.collisionMask = r_.u16();
b.shape = static_cast<RigidShape>(std::min<int>(r_.u8(), 2));
b.size = r_.vec3();
// PMD stores the position relative to the bone (or the first bone).
osg::Vec3f position = r_.vec3();
const int anchor = b.bone >= 0 ? b.bone : (model_.bones.empty() ? -1 : 0);
if (anchor >= 0) {
const osg::Vec3f bonePos = model_.bones[anchor].restPosition;
position += osg::Vec3f(bonePos.x(), bonePos.y(), -bonePos.z());
}
const osg::Vec3f rotation = r_.vec3();
setRigidBodyFromMmd(b, position, rotation);
b.mass = r_.f32();
b.linearDamping = r_.f32();
b.angularDamping = r_.f32();
b.restitution = r_.f32();
b.friction = r_.f32();
b.mode = static_cast<RigidMode>(std::min<int>(r_.u8(), 2));
bodies.push_back(std::move(b));
}
const uint32_t jointCount = r_.u32();
std::vector<Joint> joints;
for (uint32_t i = 0; i < jointCount; ++i) {
Joint j;
j.name = sjis(r_, 20);
j.bodyA = static_cast<int>(r_.u32());
j.bodyB = static_cast<int>(r_.u32());
const osg::Vec3f position = r_.vec3(), rotation = r_.vec3();
const osg::Vec3f linLo = r_.vec3(), linHi = r_.vec3(), angLo = r_.vec3(), angHi = r_.vec3();
setJointFromMmd(j, position, rotation, linLo, linHi, angLo, angHi);
j.linearSpring = r_.vec3();
j.angularSpring = r_.vec3();
joints.push_back(std::move(j));
}
model_.rigidBodies = std::move(bodies);
model_.joints = std::move(joints);
}
void resolveToons() {
for (size_t i = 0; i < model_.materials.size(); ++i) {
int toon = toonIndices_[i];
+89 -15
View File
@@ -46,7 +46,8 @@ public:
parseMaterials();
parseBones();
parseMorphs();
// Display frames, rigid bodies and joints are not needed for rendering/posing.
parseDisplayFrames();
parsePhysics();
model_.normalizeWeights();
}
@@ -111,7 +112,7 @@ private:
break;
default: throw std::runtime_error("unknown PMX weight type");
}
r_.f32(); // edge scale
v.edgeScale = r_.f32();
}
}
@@ -167,6 +168,8 @@ private:
uint8_t flags = r_.u8();
m.doubleSided = (flags & 0x01) != 0;
m.drawEdge = (flags & 0x10) != 0;
m.castShadow = (flags & 0x04) != 0;
m.receiveShadow = (flags & 0x08) != 0;
m.edgeColor = r_.vec4();
m.edgeSize = r_.f32();
m.texture = textureIndex();
@@ -226,16 +229,18 @@ private:
}
if (flags & 0x2000) r_.i32(); // external parent key
if (flags & 0x0020) {
boneIndex(); // IK target
r_.i32(); // loop count
r_.f32(); // limit angle
b.ikTarget = boneIndex();
b.ikIterations = r_.i32();
b.ikLimitAngle = r_.f32();
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();
b.ikLinks.resize(static_cast<size_t>(links));
for (auto& link : b.ikLinks) {
link.bone = boneIndex();
link.limited = r_.u8() != 0;
if (link.limited) {
const osg::Vec3f lower = r_.vec3(), upper = r_.vec3();
mmdLimitsToRightHanded(lower, upper, link.lower, link.upper);
}
}
}
@@ -248,6 +253,7 @@ private:
b.inheritParent = -1;
b.inheritRotation = b.inheritTranslation = false;
}
validateIk(b, i, n);
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);
@@ -297,18 +303,32 @@ private:
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
case 3: case 4: case 5: case 6: case 7: // UV / additional UV (only the main UV is used)
m.type = MorphType::UV;
for (int32_t i = 0; i < offsets; ++i) {
r_.vertexIndex(h_.vertexIndexSize);
r_.skip(16);
int64_t idx = r_.vertexIndex(h_.vertexIndexSize);
osg::Vec4f d = r_.vec4();
if (type == 3 && idx >= 0 && idx < vertexCount)
m.uvOffsets.push_back({static_cast<uint32_t>(idx), osg::Vec2f(d.x(), -d.y())});
}
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);
MaterialMorphOffset o;
o.material = r_.signedIndex(h_.materialIndexSize);
o.op = r_.u8() == 1 ? MaterialMorphOp::Add : MaterialMorphOp::Multiply;
o.diffuse = r_.vec4();
o.specular = r_.vec3();
o.shininess = r_.f32();
o.ambient = r_.vec3();
o.edgeColor = r_.vec4();
o.edgeSize = r_.f32();
o.textureTint = r_.vec4();
o.sphereTint = r_.vec4();
o.toonTint = r_.vec4();
if (o.material >= -1 && o.material < static_cast<int>(model_.materials.size()))
m.materialOffsets.push_back(o);
}
break;
case 10: // impulse
@@ -323,6 +343,60 @@ private:
}
}
void parseDisplayFrames() {
const int32_t count = r_.i32();
for (int32_t i = 0; i < count; ++i) {
text();
text();
r_.u8();
const int32_t elements = r_.i32();
for (int32_t e = 0; e < elements; ++e)
r_.signedIndex(r_.u8() == 0 ? h_.boneIndexSize : h_.morphIndexSize);
}
}
void parsePhysics() {
const int boneCount = static_cast<int>(model_.bones.size());
const int32_t bodyCount = r_.i32();
model_.rigidBodies.reserve(static_cast<size_t>(std::max(bodyCount, 0)));
for (int32_t i = 0; i < bodyCount; ++i) {
RigidBody b;
b.name = text();
text();
b.bone = boneIndex();
if (b.bone >= boneCount) b.bone = -1;
b.group = r_.u8();
b.collisionMask = r_.u16();
b.shape = static_cast<RigidShape>(std::min<int>(r_.u8(), 2));
b.size = r_.vec3();
const osg::Vec3f position = r_.vec3();
const osg::Vec3f rotation = r_.vec3();
setRigidBodyFromMmd(b, position, rotation);
b.mass = r_.f32();
b.linearDamping = r_.f32();
b.angularDamping = r_.f32();
b.restitution = r_.f32();
b.friction = r_.f32();
b.mode = static_cast<RigidMode>(std::min<int>(r_.u8(), 2));
model_.rigidBodies.push_back(std::move(b));
}
const int32_t jointCount = r_.i32();
for (int32_t i = 0; i < jointCount; ++i) {
Joint j;
j.name = text();
text();
const uint8_t type = r_.u8();
j.bodyA = static_cast<int>(r_.signedIndex(h_.rigidBodyIndexSize));
j.bodyB = static_cast<int>(r_.signedIndex(h_.rigidBodyIndexSize));
const osg::Vec3f position = r_.vec3(), rotation = r_.vec3();
const osg::Vec3f linLo = r_.vec3(), linHi = r_.vec3(), angLo = r_.vec3(), angHi = r_.vec3();
setJointFromMmd(j, position, rotation, linLo, linHi, angLo, angHi);
j.linearSpring = r_.vec3();
j.angularSpring = r_.vec3();
if (type == 0) model_.joints.push_back(std::move(j));
}
}
BinaryReader r_;
Model& model_;
PmxHeader h_;
+254 -19
View File
@@ -1,4 +1,5 @@
#include "model/Poser.h"
#include "physics/PhysicsWorld.h"
#include "model/Parallel.h"
@@ -31,13 +32,42 @@ Poser::Poser(std::shared_ptr<const Model> model) : model_(std::move(model)) {
poses_.resize(boneCount);
weights_.assign(model_->morphs.size(), 0.f);
effective_.assign(model_->morphs.size(), 0.f);
for (const Morph& m : model_->morphs) {
hasUvMorphs_ |= !m.uvOffsets.empty();
hasMaterialMorphs_ |= !m.materialOffsets.empty();
}
morphTranslation_.resize(boneCount);
morphRotation_.resize(boneCount);
animRotation_.resize(boneCount);
animTranslation_.resize(boneCount);
globals_.resize(boneCount);
skin_.resize(boneCount);
motion_.resize(boneCount);
ikBoneEnabled_.assign(boneCount, 1);
computeEvaluationOrder();
if (!model_->rigidBodies.empty()) {
physics_ = std::make_unique<PhysicsWorld>(*model_);
const auto& driven = physics_->drivenBones();
physicsChild_.assign(boneCount, 0);
for (int b : order_) {
const int p = model_->bones[b].parent;
physicsChild_[b] = !driven[b] && p >= 0 && (driven[p] || physicsChild_[p]);
}
}
isIkLink_.assign(boneCount, 0);
ikAffected_.resize(boneCount);
for (size_t b = 0; b < boneCount; ++b) {
const Bone& bone = model_->bones[b];
if (!bone.isIK) continue;
std::vector<uint8_t> moved(boneCount, 0);
for (const auto& link : bone.ikLinks) moved[link.bone] = isIkLink_[link.bone] = 1;
for (int o : order_) {
const int parent = model_->bones[o].parent;
if (parent >= 0 && moved[parent]) moved[o] = 1;
if (moved[o]) ikAffected_[b].push_back(o);
}
}
bindRotation_.resize(boneCount);
std::vector<osg::Matrixf> rest(boneCount);
@@ -55,6 +85,11 @@ void Poser::resetPose() { std::fill(poses_.begin(), poses_.end(), BonePose()); }
void Poser::resetMorphs() { std::fill(weights_.begin(), weights_.end(), 0.f); }
void Poser::resetMotion() {
std::fill(motion_.begin(), motion_.end(), MotionPose());
std::fill(ikBoneEnabled_.begin(), ikBoneEnabled_.end(), 1);
}
void Poser::computeEvaluationOrder() {
const auto& bones = model_->bones;
const int n = static_cast<int>(bones.size());
@@ -65,7 +100,14 @@ void Poser::computeEvaluationOrder() {
return bones[a].layer < bones[b].layer;
});
// Depth-first so parents and inheritance sources are always evaluated first.
// Depth-first so parents, inheritance sources and IK chains are always evaluated first.
auto dependency = [&](int bone, int step) {
const Bone& b = bones[bone];
if (step == 0) return b.parent;
if (step == 1) return b.inheritParent;
if (step == 2) return b.ikTarget;
return b.ikLinks[step - 3].bone;
};
std::vector<int> state(n, 0); // 0 = new, 1 = visiting, 2 = done
order_.clear();
order_.reserve(n);
@@ -76,10 +118,9 @@ void Poser::computeEvaluationOrder() {
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) {
const int steps = 3 + static_cast<int>(bones[bone].ikLinks.size());
if (step < steps) {
const int dep = dependency(bone, step);
++step;
if (dep >= 0 && state[dep] == 0) {
state[dep] = 1;
@@ -104,11 +145,189 @@ void Poser::accumulateMorph(int morph, float weight, int depth) {
}
}
namespace {
template <typename T>
T towardOne(const T& offset, float w, const T& one) {
return one + (offset - one) * w;
}
} // namespace
// Like MMD, multiply offsets and add offsets accumulate separately: value = base * mul + add.
void Poser::applyUvAndMaterialMorphs() {
const Model& model = *model_;
if (hasUvMorphs_) {
uvs_.resize(model.vertices.size());
for (size_t i = 0; i < model.vertices.size(); ++i) uvs_[i] = model.vertices[i].uv;
for (size_t i = 0; i < effective_.size(); ++i) {
const float w = effective_[i];
if (w == 0.f) continue;
for (const auto& o : model.morphs[i].uvOffsets) uvs_[o.vertex] += o.offset * w;
}
}
const size_t count = model.materials.size();
const osg::Vec4f one4(1.f, 1.f, 1.f, 1.f);
const osg::Vec3f one3(1.f, 1.f, 1.f);
std::vector<MaterialMorphOffset> mul(count), add(count);
for (auto& m : mul) {
m.diffuse = m.edgeColor = m.textureTint = m.sphereTint = m.toonTint = one4;
m.specular = m.ambient = one3;
m.shininess = m.edgeSize = 1.f;
}
for (size_t i = 0; hasMaterialMorphs_ && i < effective_.size(); ++i) {
const float w = effective_[i];
if (w == 0.f) continue;
for (const auto& o : model.morphs[i].materialOffsets) {
const size_t first = o.material < 0 ? 0 : static_cast<size_t>(o.material);
const size_t last = o.material < 0 ? count : first + 1;
for (size_t k = first; k < last && k < count; ++k) {
if (o.op == MaterialMorphOp::Multiply) {
MaterialMorphOffset& a = mul[k];
a.diffuse = osg::componentMultiply(a.diffuse, towardOne(o.diffuse, w, one4));
a.specular = osg::componentMultiply(a.specular, towardOne(o.specular, w, one3));
a.shininess *= towardOne(o.shininess, w, 1.f);
a.ambient = osg::componentMultiply(a.ambient, towardOne(o.ambient, w, one3));
a.edgeColor = osg::componentMultiply(a.edgeColor, towardOne(o.edgeColor, w, one4));
a.edgeSize *= towardOne(o.edgeSize, w, 1.f);
a.textureTint = osg::componentMultiply(a.textureTint, towardOne(o.textureTint, w, one4));
a.sphereTint = osg::componentMultiply(a.sphereTint, towardOne(o.sphereTint, w, one4));
a.toonTint = osg::componentMultiply(a.toonTint, towardOne(o.toonTint, w, one4));
} else {
MaterialMorphOffset& a = add[k];
a.diffuse += o.diffuse * w;
a.specular += o.specular * w;
a.shininess += o.shininess * w;
a.ambient += o.ambient * w;
a.edgeColor += o.edgeColor * w;
a.edgeSize += o.edgeSize * w;
a.textureTint += o.textureTint * w;
a.sphereTint += o.sphereTint * w;
a.toonTint += o.toonTint * w;
}
}
}
}
materials_.resize(count);
for (size_t k = 0; k < count; ++k) {
const Material& base = model.materials[k];
const MaterialMorphOffset &m = mul[k], &a = add[k];
MaterialState& s = materials_[k];
s.diffuse = osg::componentMultiply(base.diffuse, m.diffuse) + a.diffuse;
s.specular = osg::componentMultiply(base.specular, m.specular) + a.specular;
s.shininess = base.shininess * m.shininess + a.shininess;
s.ambient = osg::componentMultiply(base.ambient, m.ambient) + a.ambient;
s.edgeColor = osg::componentMultiply(base.edgeColor, m.edgeColor) + a.edgeColor;
s.edgeSize = base.edgeSize * m.edgeSize + a.edgeSize;
s.textureMul = m.textureTint;
s.textureAdd = a.textureTint;
s.sphereMul = m.sphereTint;
s.sphereAdd = a.sphereTint;
s.toonMul = m.toonTint;
s.toonAdd = a.toonTint;
}
}
void Poser::setSkinningMode(SkinningMode mode) {
if (mode == mode_) return;
mode_ = mode;
firstUpdate_ = true;
}
void Poser::updateGlobal(int b) {
const Bone& bone = model_->bones[b];
const osg::Matrixf local =
osg::Matrixf::rotate(animRotation_[b]) * osg::Matrixf::translate(animTranslation_[b]) * bone.localBind;
globals_[b] = bone.parent >= 0 ? local * globals_[bone.parent] : local;
}
namespace {
// Euler angles (X, then Y, then Z, as in eulerToQuat) of a rotation, in radians.
osg::Vec3f quatToEuler(const osg::Quat& q) {
const osg::Matrixf m = osg::Matrixf::rotate(q);
const float sy = std::min(1.f, std::max(-1.f, -m(0, 2)));
return osg::Vec3f(std::atan2(m(1, 2), m(2, 2)), std::asin(sy), std::atan2(m(0, 1), m(0, 0)));
}
// Axis index when a limit allows rotation about exactly one axis, otherwise -1.
int singleLimitAxis(const IkLink& link) {
int axis = -1;
for (int k = 0; k < 3; ++k) {
if (link.lower[k] == 0.f && link.upper[k] == 0.f) continue;
if (axis >= 0) return -1;
axis = k;
}
return axis;
}
} // namespace
// Cyclic coordinate descent, as MMD does: each link in turn rotates to point the target at the IK bone.
void Poser::solveIk(int ikBone) {
const Bone& ik = model_->bones[ikBone];
const osg::Vec3f goal = globals_[ikBone].getTrans();
for (int iter = 0; iter < ik.ikIterations; ++iter) {
if ((globals_[ik.ikTarget].getTrans() - goal).length2() < 1e-10f) break;
for (const IkLink& link : ik.ikLinks) {
const int b = link.bone;
const osg::Matrixf inv = osg::Matrixf::inverse(globals_[b]);
osg::Vec3f toTarget = globals_[ik.ikTarget].getTrans() * inv;
osg::Vec3f toGoal = goal * inv;
if (toTarget.normalize() < 1e-6f || toGoal.normalize() < 1e-6f) continue;
const int axisIndex = link.limited ? singleLimitAxis(link) : -1;
if (axisIndex >= 0) {
osg::Vec3f axis;
axis[axisIndex] = 1.f;
osg::Vec3f u = toTarget - axis * (toTarget * axis), v = toGoal - axis * (toGoal * axis);
if (u.normalize() < 1e-6f || v.normalize() < 1e-6f) continue;
float delta = std::atan2(axis * (u ^ v), u * v);
delta = std::min(ik.ikLimitAngle, std::max(-ik.ikLimitAngle, delta));
const osg::Quat& q = animRotation_[b];
const float current = 2.f * std::atan2(osg::Vec3f(q.x(), q.y(), q.z()) * axis, float(q.w()));
const float angle =
std::min(link.upper[axisIndex], std::max(link.lower[axisIndex], current + delta));
animRotation_[b] = osg::Quat(angle, axis);
} else {
const float angle = std::min(ik.ikLimitAngle, std::acos(std::min(1.f, std::max(-1.f, toTarget * toGoal))));
osg::Vec3f axis = toTarget ^ toGoal;
if (angle < 1e-6f || axis.normalize() < 1e-6f) continue;
osg::Quat rotation = osg::Quat(angle, axis) * animRotation_[b];
if (link.limited) {
osg::Vec3f e = quatToEuler(rotation);
for (int k = 0; k < 3; ++k) e[k] = std::min(link.upper[k], std::max(link.lower[k], e[k]));
rotation = osg::Quat(e.x(), osg::X_AXIS, e.y(), osg::Y_AXIS, e.z(), osg::Z_AXIS);
}
animRotation_[b] = rotation;
}
for (int a : ikAffected_[ikBone]) updateGlobal(a);
}
}
}
Poser::~Poser() = default;
void Poser::setPhysicsEnabled(bool enabled) {
if (enabled == physicsEnabled_) return;
physicsEnabled_ = enabled;
physicsReset_ = true;
firstUpdate_ = true;
}
bool Poser::update() {
if (!firstUpdate_ && poses_ == lastPoses_ && weights_ == lastWeights_) return false;
const bool simulate = physics_ && physicsEnabled_;
if (!simulate) physicsDt_ = 0.f;
if (!firstUpdate_ && !(simulate && (physicsDt_ > 0.f || physicsReset_)) && poses_ == lastPoses_ && weights_ == lastWeights_ && motion_ == lastMotion_ &&
ikEnabled_ == lastIkEnabled_ && ikBoneEnabled_ == lastIkBoneEnabled_)
return false;
morphsChanged_ = firstUpdate_ || weights_ != lastWeights_;
firstUpdate_ = false;
lastPoses_ = poses_;
lastWeights_ = weights_;
lastMotion_ = motion_;
lastIkEnabled_ = ikEnabled_;
lastIkBoneEnabled_ = ikBoneEnabled_;
const Model& model = *model_;
const auto& bones = model.bones;
@@ -133,8 +352,8 @@ bool Poser::update() {
// 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];
osg::Quat rotation = morphRotation_[b] * motion_[b].rotation * poseRotation;
osg::Vec3f translation = g.inverse() * poses_[b].translation + morphTranslation_[b] + motion_[b].translation;
if (bone.inheritParent >= 0) {
if (bone.inheritRotation)
rotation = rotation * scaledRotation(animRotation_[bone.inheritParent], bone.inheritWeight);
@@ -142,21 +361,37 @@ bool Poser::update() {
}
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];
updateGlobal(b);
if (bone.isIK && ikEnabled_ && ikBoneEnabled_[b]) solveIk(b);
}
if (simulate) {
if (physicsReset_) {
physics_->reset(globals_);
for (int i = 0; i < 30; ++i) physics_->step(1.f / 60.f, globals_);
physicsReset_ = false;
}
if (physicsDt_ > 0.f) physics_->step(std::min(physicsDt_, 0.1f), globals_);
physicsDt_ = 0.f;
physics_->apply(globals_);
for (int b : order_)
if (physicsChild_[b]) updateGlobal(b);
}
for (size_t b = 0; b < bones.size(); ++b) skin_[b] = bones[b].inverseBind * globals_[b];
const size_t vertexCount = model.vertices.size();
morphed_.resize(vertexCount);
parallelFor(vertexCount, kMinVerticesPerThread, [&](size_t begin, size_t end) {
for (size_t i = begin; i < end; ++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;
if (morphsChanged_) {
morphed_.resize(vertexCount);
parallelFor(vertexCount, kMinVerticesPerThread, [&](size_t begin, size_t end) {
for (size_t i = begin; i < end; ++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;
}
applyUvAndMaterialMorphs();
}
if (mode_ == SkinningMode::Hardware) return true;
positions_.resize(vertexCount);
normals_.resize(vertexCount);
+64 -1
View File
@@ -7,6 +7,12 @@
namespace mr {
class PhysicsWorld;
// Software: the CPU skins every vertex. Hardware: the CPU only computes bone matrices and
// morphed rest positions; the vertex shader does the skinning.
enum class SkinningMode { Software, Hardware };
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.
@@ -17,34 +23,88 @@ struct BonePose {
bool operator!=(const BonePose& o) const { return !(*this == o); }
};
// Keyframed bone transform from a motion (e.g. VMD): parent-aligned offset from rest + rotation.
struct MotionPose {
osg::Vec3f translation;
osg::Quat rotation;
bool operator==(const MotionPose& o) const { return translation == o.translation && rotation == o.rotation; }
};
// 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);
~Poser();
const Model& model() const { return *model_; }
std::vector<BonePose>& bonePoses() { return poses_; }
std::vector<float>& morphWeights() { return weights_; }
// Motion transforms are applied before the user pose, which acts as an offset on top.
std::vector<MotionPose>& motionPoses() { return motion_; }
// IK chains are solved after posing; per-bone flags come from motion files.
void setIkEnabled(bool enabled) { ikEnabled_ = enabled; }
// Rigid-body physics (only for models with rigid bodies).
bool hasPhysics() const { return physics_ != nullptr; }
const PhysicsWorld* physics() const { return physics_.get(); }
void setPhysicsEnabled(bool enabled);
bool physicsEnabled() const { return physicsEnabled_; }
void stepPhysics(float seconds) { physicsDt_ += seconds; }
// Snap bodies back to the current pose (e.g. after jumping on the timeline) and let them settle.
void resetPhysics() { physicsReset_ = true; }
bool ikEnabled() const { return ikEnabled_; }
std::vector<uint8_t>& ikBoneEnabled() { return ikBoneEnabled_; }
bool isIkLink(int bone) const { return bone >= 0 && bone < int(isIkLink_.size()) && isIkLink_[bone]; }
void resetPose();
void resetMorphs();
void resetMotion();
// Recomputes the deformed mesh if anything changed. Returns true when it did.
void setSkinningMode(SkinningMode mode);
SkinningMode skinningMode() const { return mode_; }
// Returns false when nothing changed since the last call.
bool update();
bool morphsChangedInLastUpdate() const { return morphsChanged_; }
// Skinned vertices; only maintained in Software mode.
const std::vector<osg::Vec3f>& positions() const { return positions_; }
const std::vector<osg::Vec3f>& morphedPositions() const { return morphed_; }
// Per-bone rest-space -> posed-space matrices (row-vector convention: p' = p * M).
const std::vector<osg::Matrixf>& skinMatrices() const { return skin_; }
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_; }
// Main UVs after UV morphs; empty when the model has no UV morphs.
const std::vector<osg::Vec2f>& morphedUvs() const { return uvs_; }
// Per-material values after material morphs.
const std::vector<MaterialState>& materialStates() const { return materials_; }
bool hasMaterialMorphs() const { return hasMaterialMorphs_; }
private:
void computeEvaluationOrder();
void accumulateMorph(int morph, float weight, int depth);
void applyUvAndMaterialMorphs();
void updateGlobal(int bone);
void solveIk(int ikBone);
std::shared_ptr<const Model> model_;
std::vector<BonePose> poses_, lastPoses_;
std::vector<float> weights_, lastWeights_;
std::vector<MotionPose> motion_, lastMotion_;
std::vector<uint8_t> ikBoneEnabled_, lastIkBoneEnabled_;
bool ikEnabled_ = true, lastIkEnabled_ = true;
std::vector<std::vector<int>> ikAffected_; // per IK bone: bones whose globals the chain moves, in order
std::vector<uint8_t> isIkLink_;
bool firstUpdate_ = true;
std::unique_ptr<PhysicsWorld> physics_;
bool physicsEnabled_ = true, physicsReset_ = true;
float physicsDt_ = 0.f;
std::vector<uint8_t> physicsChild_; // not simulated but below a simulated bone
bool morphsChanged_ = true;
SkinningMode mode_ = SkinningMode::Software;
std::vector<int> order_;
std::vector<osg::Quat> bindRotation_; // rest-pose global rotation of each bone
@@ -55,6 +115,9 @@ private:
std::vector<osg::Vec3f> animTranslation_;
std::vector<osg::Matrixf> globals_, skin_;
std::vector<osg::Vec3f> morphed_, positions_, normals_;
std::vector<osg::Vec2f> uvs_;
std::vector<MaterialState> materials_;
bool hasUvMorphs_ = false, hasMaterialMorphs_ = false;
};
} // namespace mr
+175
View File
@@ -0,0 +1,175 @@
#include "physics/PhysicsWorld.h"
#include <btBulletDynamicsCommon.h>
#include <algorithm>
namespace mr {
namespace {
btTransform toBt(const osg::Matrixf& m) {
const osg::Quat q = m.getRotate();
const osg::Vec3f t = m.getTrans();
return btTransform(btQuaternion(btScalar(q.x()), btScalar(q.y()), btScalar(q.z()), btScalar(q.w())),
btVector3(t.x(), t.y(), t.z()));
}
osg::Matrixf toOsg(const btTransform& t) {
const btQuaternion q = t.getRotation();
const btVector3& o = t.getOrigin();
return osg::Matrixf::rotate(osg::Quat(q.x(), q.y(), q.z(), q.w())) * osg::Matrixf::translate(o.x(), o.y(), o.z());
}
btVector3 bt(const osg::Vec3f& v) { return btVector3(v.x(), v.y(), v.z()); }
constexpr float kFixedStep = 1.f / 120.f;
constexpr int kMaxSubSteps = 12;
} // namespace
struct PhysicsWorld::Impl {
struct Body {
std::unique_ptr<btCollisionShape> shape;
std::unique_ptr<btDefaultMotionState> motion;
std::unique_ptr<btRigidBody> body;
osg::Matrixf offset; // body transform in its bone's space
osg::Matrixf invOffset;
osg::Matrixf rest; // model-space rest transform
int bone = -1;
RigidMode mode = RigidMode::FollowBone;
bool kinematic = true;
};
btDefaultCollisionConfiguration config;
btCollisionDispatcher dispatcher{&config};
btDbvtBroadphase broadphase;
btSequentialImpulseConstraintSolver solver;
btDiscreteDynamicsWorld world{&dispatcher, &broadphase, &solver, &config};
std::vector<Body> bodies;
std::vector<std::unique_ptr<btTypedConstraint>> joints;
std::vector<uint8_t> driven;
osg::Matrixf target(const Body& b, const std::vector<osg::Matrixf>& globals) const {
return b.bone >= 0 && b.bone < int(globals.size()) ? b.offset * globals[b.bone] : b.rest;
}
~Impl() {
for (auto& j : joints) world.removeConstraint(j.get());
for (auto& b : bodies) world.removeRigidBody(b.body.get());
}
};
PhysicsWorld::PhysicsWorld(const Model& model) : impl_(std::make_unique<Impl>()) {
Impl& w = *impl_;
w.world.setGravity(btVector3(0, -9.8f * 10.f, 0)); // MMD units: 1 unit is about 8 cm
w.driven.assign(model.bones.size(), 0);
w.bodies.reserve(model.rigidBodies.size());
for (const RigidBody& rb : model.rigidBodies) {
Impl::Body b;
const osg::Vec3f s(std::max(rb.size.x(), 1e-3f), std::max(rb.size.y(), 1e-3f), std::max(rb.size.z(), 1e-3f));
switch (rb.shape) {
case RigidShape::Sphere: b.shape = std::make_unique<btSphereShape>(s.x()); break;
case RigidShape::Box: b.shape = std::make_unique<btBoxShape>(bt(s)); break;
case RigidShape::Capsule: b.shape = std::make_unique<btCapsuleShape>(s.x(), s.y()); break;
}
b.bone = rb.bone >= 0 && rb.bone < int(model.bones.size()) ? rb.bone : -1;
b.mode = rb.mode;
b.rest = osg::Matrixf::rotate(rb.rotation) * osg::Matrixf::translate(rb.position);
const osg::Matrixf boneRest = b.bone >= 0 ? osg::Matrixf::inverse(model.bones[b.bone].inverseBind) : osg::Matrixf();
b.offset = b.rest * osg::Matrixf::inverse(boneRest);
b.invOffset = osg::Matrixf::inverse(b.offset);
b.kinematic = rb.mode == RigidMode::FollowBone || rb.mass <= 0.f;
const btScalar mass = b.kinematic ? 0.f : rb.mass;
btVector3 inertia(0, 0, 0);
if (mass > 0.f) b.shape->calculateLocalInertia(mass, inertia);
b.motion = std::make_unique<btDefaultMotionState>(toBt(b.rest));
btRigidBody::btRigidBodyConstructionInfo info(mass, b.motion.get(), b.shape.get(), inertia);
info.m_linearDamping = rb.linearDamping;
info.m_angularDamping = rb.angularDamping;
info.m_restitution = rb.restitution;
info.m_friction = rb.friction;
info.m_additionalDamping = true;
b.body = std::make_unique<btRigidBody>(info);
if (b.kinematic) b.body->setCollisionFlags(b.body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
b.body->setActivationState(DISABLE_DEACTIVATION);
const int group = 1 << std::clamp(rb.group, 0, 15);
w.world.addRigidBody(b.body.get(), group, rb.collisionMask);
if (!b.kinematic && b.bone >= 0) w.driven[b.bone] = 1;
w.bodies.push_back(std::move(b));
}
for (const Joint& j : model.joints) {
if (j.bodyA < 0 || j.bodyB < 0 || j.bodyA >= int(w.bodies.size()) || j.bodyB >= int(w.bodies.size()) ||
j.bodyA == j.bodyB)
continue;
btRigidBody& a = *w.bodies[j.bodyA].body;
btRigidBody& b = *w.bodies[j.bodyB].body;
const btTransform frame = toBt(osg::Matrixf::rotate(j.rotation) * osg::Matrixf::translate(j.position));
auto c = std::make_unique<btGeneric6DofSpringConstraint>(a, b, a.getWorldTransform().inverse() * frame,
b.getWorldTransform().inverse() * frame, true);
c->setLinearLowerLimit(bt(j.linearLower));
c->setLinearUpperLimit(bt(j.linearUpper));
c->setAngularLowerLimit(bt(j.angularLower));
c->setAngularUpperLimit(bt(j.angularUpper));
for (int i = 0; i < 3; ++i) {
if (j.linearSpring[i] != 0.f) {
c->enableSpring(i, true);
c->setStiffness(i, j.linearSpring[i]);
}
if (j.angularSpring[i] != 0.f) {
c->enableSpring(i + 3, true);
c->setStiffness(i + 3, j.angularSpring[i]);
}
}
w.world.addConstraint(c.get(), true);
w.joints.push_back(std::move(c));
}
}
PhysicsWorld::~PhysicsWorld() = default;
size_t PhysicsWorld::bodyCount() const { return impl_->bodies.size(); }
size_t PhysicsWorld::jointCount() const { return impl_->joints.size(); }
const std::vector<uint8_t>& PhysicsWorld::drivenBones() const { return impl_->driven; }
void PhysicsWorld::reset(const std::vector<osg::Matrixf>& globals) {
Impl& w = *impl_;
for (auto& b : w.bodies) {
const btTransform t = toBt(w.target(b, globals));
b.body->setWorldTransform(t);
b.body->setInterpolationWorldTransform(t);
b.motion->setWorldTransform(t);
b.body->setLinearVelocity(btVector3(0, 0, 0));
b.body->setAngularVelocity(btVector3(0, 0, 0));
b.body->setInterpolationLinearVelocity(btVector3(0, 0, 0));
b.body->setInterpolationAngularVelocity(btVector3(0, 0, 0));
b.body->clearForces();
}
}
void PhysicsWorld::step(float dt, const std::vector<osg::Matrixf>& globals) {
Impl& w = *impl_;
for (auto& b : w.bodies)
if (b.kinematic) b.motion->setWorldTransform(toBt(w.target(b, globals)));
w.world.stepSimulation(dt, kMaxSubSteps, kFixedStep);
// Mode 2 bodies rotate freely but stay pinned to their bone's position.
for (auto& b : w.bodies) {
if (b.kinematic || b.mode != RigidMode::PhysicsWithBone) continue;
btTransform t = b.body->getWorldTransform();
t.setOrigin(toBt(w.target(b, globals)).getOrigin());
b.body->setWorldTransform(t);
b.motion->setWorldTransform(t);
}
}
void PhysicsWorld::apply(std::vector<osg::Matrixf>& globals) const {
const Impl& w = *impl_;
for (const auto& b : w.bodies) {
if (b.kinematic || b.bone < 0 || b.bone >= int(globals.size())) continue;
osg::Matrixf g = b.invOffset * toOsg(b.body->getWorldTransform());
if (b.mode == RigidMode::PhysicsWithBone) g.setTrans(globals[b.bone].getTrans());
globals[b.bone] = g;
}
}
} // namespace mr
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "model/Model.h"
#include <memory>
#include <vector>
namespace mr {
// MMD rigid-body physics (hair, skirts, tails) on top of Bullet. Works in model space:
// bodies that follow bones are driven from the animated bone globals, and dynamic bodies
// write their simulated transforms back into the bones they are attached to.
class PhysicsWorld {
public:
explicit PhysicsWorld(const Model& model);
~PhysicsWorld();
PhysicsWorld(const PhysicsWorld&) = delete;
PhysicsWorld& operator=(const PhysicsWorld&) = delete;
size_t bodyCount() const;
size_t jointCount() const;
// Bones whose global transform comes from the simulation.
const std::vector<uint8_t>& drivenBones() const;
// Teleports every body to its bone and clears velocities.
void reset(const std::vector<osg::Matrixf>& boneGlobals);
// Moves bone-following bodies to the animated pose and advances the simulation by dt seconds.
void step(float dt, const std::vector<osg::Matrixf>& boneGlobals);
// Overwrites the globals of physics-driven bones with the simulated result.
void apply(std::vector<osg::Matrixf>& boneGlobals) const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace mr
+36
View File
@@ -0,0 +1,36 @@
#include "render/GpuCaps.h"
#include <osg/GL>
#include <osg/GLExtensions>
#include <osg/GraphicsContext>
#include <osg/State>
#ifndef GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS
#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C
#endif
namespace mr {
namespace {
GpuCaps caps;
}
const GpuCaps& gpuCaps() { return caps; }
void GpuCapsProbe::operator()(osg::GraphicsContext* gc) {
const unsigned contextID = gc->getState()->getContextID();
GLint vertexUnits = 0;
glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vertexUnits);
const bool floatTextures = osg::isGLExtensionOrVersionSupported(contextID, "GL_ARB_texture_float", 3.0f);
const GLubyte* renderer = glGetString(GL_RENDERER);
caps.renderer = renderer ? reinterpret_cast<const char*>(renderer) : "";
caps.skinning = vertexUnits > 0 && floatTextures;
caps.shadows = osg::isGLExtensionOrVersionSupported(contextID, "GL_ARB_depth_texture", 1.4f) &&
osg::isGLExtensionOrVersionSupported(contextID, "GL_EXT_framebuffer_object", 3.0f);
caps.framebufferObjects = osg::isGLExtensionOrVersionSupported(contextID, "GL_EXT_framebuffer_object", 3.0f);
caps.floatTextures = floatTextures;
caps.probed = true;
if (next_) (*next_)(gc);
}
} // namespace mr
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <osg/GraphicsThread>
#include <string>
namespace mr {
struct GpuCaps {
bool probed = false;
bool skinning = false; // vertex texture fetch + float textures
bool shadows = false; // depth textures + framebuffer objects
bool framebufferObjects = false;
bool floatTextures = false;
std::string renderer;
};
const GpuCaps& gpuCaps();
// Realize operation that queries the GL context once it exists, then runs `next` (if any).
class GpuCapsProbe : public osg::GraphicsOperation {
public:
explicit GpuCapsProbe(osg::Operation* next = nullptr)
: osg::GraphicsOperation("GpuCapsProbe", false), next_(next) {}
void operator()(osg::GraphicsContext* gc) override;
private:
osg::ref_ptr<osg::Operation> next_;
};
} // namespace mr
+93
View File
@@ -0,0 +1,93 @@
#include "render/Grid.h"
#include <osg/BlendFunc>
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/LineWidth>
#include <osg/Program>
#include <osgText/Text>
namespace mr {
namespace {
osg::Geometry* lineGeometry(osg::Vec3Array* verts, osg::Vec4Array* colors, float width) {
auto* geom = new osg::Geometry;
geom->setVertexArray(verts);
geom->setColorArray(colors, osg::Array::BIND_PER_VERTEX);
geom->addPrimitiveSet(new osg::DrawArrays(GL_LINES, 0, static_cast<GLsizei>(verts->size())));
geom->getOrCreateStateSet()->setAttributeAndModes(new osg::LineWidth(width));
return geom;
}
void addLine(osg::Vec3Array* v, osg::Vec4Array* c, const osg::Vec3& a, const osg::Vec3& b, const osg::Vec4& color) {
v->push_back(a);
v->push_back(b);
c->push_back(color);
c->push_back(color);
}
osgText::Text* label(const char* text, const osg::Vec3& pos, const osg::Vec4& color) {
auto* t = new osgText::Text;
t->setText(text);
t->setPosition(pos);
t->setColor(color);
t->setCharacterSizeMode(osgText::Text::SCREEN_COORDS);
t->setCharacterSize(18.f);
t->setAxisAlignment(osgText::Text::SCREEN);
t->setAlignment(osgText::Text::CENTER_CENTER);
return t;
}
} // namespace
osg::Node* createGrid(float halfExtent, float spacing) {
// World is Z-up: MMD X = world X, MMD Y = world Z, MMD +Z (away from the model's front) = world +Y.
const float h = halfExtent, z = 0.01f; // lifted slightly to avoid fighting with stage floors
const int n = static_cast<int>(halfExtent / spacing);
const osg::Vec4 minor(0.42f, 0.45f, 0.50f, 0.45f), major(0.55f, 0.58f, 0.64f, 0.7f);
auto* gv = new osg::Vec3Array;
auto* gc = new osg::Vec4Array;
for (int i = -n; i <= n; ++i) {
if (i == 0) continue;
const float c = static_cast<float>(i) * spacing;
const osg::Vec4& color = i % 2 == 0 ? major : minor;
addLine(gv, gc, {-h, c, z}, {h, c, z}, color);
addLine(gv, gc, {c, -h, z}, {c, h, z}, color);
}
const osg::Vec4 red(0.95f, 0.30f, 0.30f, 1.f), green(0.40f, 0.90f, 0.35f, 1.f), blue(0.35f, 0.55f, 1.f, 1.f);
const float up = spacing * 3.f;
auto* av = new osg::Vec3Array;
auto* ac = new osg::Vec4Array;
addLine(av, ac, {-h, 0, z}, {h, 0, z}, red);
addLine(av, ac, {0, -h, z}, {0, h, z}, blue);
addLine(av, ac, {0, 0, z}, {0, 0, up}, green);
auto* geode = new osg::Geode;
osg::Geometry* gridLines = lineGeometry(gv, gc, 1.f);
osg::Geometry* axisLines = lineGeometry(av, ac, 2.f);
geode->addDrawable(gridLines);
geode->addDrawable(axisLines);
geode->addDrawable(label("X", {h + spacing * 0.4f, 0, z}, red));
geode->addDrawable(label("Y", {0, 0, up + spacing * 0.3f}, green));
geode->addDrawable(label("Z", {0, h + spacing * 0.4f, z}, blue));
osg::StateSet* ss = geode->getOrCreateStateSet();
ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
ss->setMode(GL_BLEND, osg::StateAttribute::ON);
ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
ss->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
// No depth writes: thin lines would otherwise show up as occluders in ambient occlusion.
ss->setAttributeAndModes(new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false));
// Explicit vertex-colour program so no model shader state can leak onto the lines.
auto* program = new osg::Program;
program->addShader(new osg::Shader(osg::Shader::VERTEX,
"#version 120\nvoid main() { gl_FrontColor = gl_Color;"
" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }\n"));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, "#version 120\nvoid main() { gl_FragColor = gl_Color; }\n"));
for (osg::Geometry* lines : {gridLines, axisLines}) lines->getOrCreateStateSet()->setAttributeAndModes(program);
geode->setNodeMask(kGridNodeMask);
return geode;
}
} // namespace mr
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <osg/Node>
namespace mr {
// Node mask of the floor grid; final renders cull it.
constexpr unsigned kGridNodeMask = 0x2;
// Floor grid on the MMD ground plane (world z = 0) with labelled X (red), Y (green, up) and Z (blue) axes.
osg::Node* createGrid(float halfExtent, float spacing);
} // namespace mr
+175
View File
@@ -0,0 +1,175 @@
#include "render/Look.h"
#include "render/Shaders.h"
#include <osg/BlendFunc>
#include <osg/ColorMask>
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <algorithm>
#include <cmath>
namespace mr {
namespace {
constexpr float kGroundExtent = 50.f;
osg::ref_ptr<osg::Node> createGroundShadow() {
osg::ref_ptr<osg::Geometry> quad = osg::createTexturedQuadGeometry(
osg::Vec3(-kGroundExtent, -kGroundExtent, 0.f), osg::Vec3(2.f * kGroundExtent, 0.f, 0.f),
osg::Vec3(0.f, 2.f * kGroundExtent, 0.f));
quad->setUseDisplayList(false);
quad->setUseVertexBufferObjects(true);
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(quad);
osg::StateSet* ss = geode->getOrCreateStateSet();
ss->setAttributeAndModes(createGroundShadowProgram(), osg::StateAttribute::ON);
ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg::StateAttribute::ON);
ss->setAttributeAndModes(new osg::Depth(osg::Depth::LEQUAL, 0.0, 1.0, false), osg::StateAttribute::ON);
ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
ss->setRenderBinDetails(5, "RenderBin");
return geode;
}
} // namespace
SceneLook::SceneLook(osg::Group* root, osg::Group* casters) : root_(root) {
osg::StateSet* ss = root_->getOrCreateStateSet();
lightDir_ = new osg::Uniform("u_lightDirection", osg::Vec3f(-0.5f, 0.5f, -1.f));
lightColor_ = new osg::Uniform("u_lightColor", settings_.lightColor);
shadowEnabled_ = new osg::Uniform("u_shadowEnabled", 0);
shadowMatrix_ = new osg::Uniform("u_shadowMatrix", osg::Matrixf());
shadowTexel_ = new osg::Uniform("u_shadowTexel", 1.f / 2048.f);
shadowSoftness_ = new osg::Uniform("u_shadowSoftness", 1.5f);
shadowBias_ = new osg::Uniform("u_shadowBias", 0.001f);
shadowStrength_ = new osg::Uniform("u_shadowStrength", 0.f);
groundOpacity_ = new osg::Uniform("u_groundShadowOpacity", 0.45f);
rimStrength_ = new osg::Uniform("u_rimStrength", 0.f);
rimColor_ = new osg::Uniform("u_rimColor", settings_.rimColor);
for (osg::Uniform* u : {lightDir_.get(), lightColor_.get(), shadowEnabled_.get(), shadowMatrix_.get(),
shadowTexel_.get(), shadowSoftness_.get(), shadowBias_.get(), shadowStrength_.get(),
groundOpacity_.get(), rimStrength_.get(), rimColor_.get()})
ss->addUniform(u);
ss->addUniform(new osg::Uniform("u_shadowMap", static_cast<int>(kShadowTextureUnit)));
{
shadowMap_ = new osg::Texture2D;
shadowMap_->setInternalFormat(GL_DEPTH_COMPONENT);
shadowMap_->setSourceFormat(GL_DEPTH_COMPONENT);
shadowMap_->setSourceType(GL_FLOAT);
shadowMap_->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
shadowMap_->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
shadowMap_->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
shadowMap_->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
ss->setTextureAttribute(kShadowTextureUnit, shadowMap_);
shadowCamera_ = new osg::Camera;
shadowCamera_->setName("ShadowCamera");
shadowCamera_->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
shadowCamera_->setRenderOrder(osg::Camera::PRE_RENDER);
shadowCamera_->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
shadowCamera_->setClearMask(GL_DEPTH_BUFFER_BIT);
shadowCamera_->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
shadowCamera_->setCullingMode(osg::CullSettings::VIEW_FRUSTUM_CULLING);
shadowCamera_->setCullMask(kShadowCasterMask);
shadowCamera_->setDrawBuffer(GL_NONE);
shadowCamera_->setReadBuffer(GL_NONE);
osg::StateSet* cs = shadowCamera_->getOrCreateStateSet();
cs->setAttributeAndModes(createShadowDepthProgram(),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
cs->setAttribute(new osg::ColorMask(false, false, false, false),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
cs->setMode(GL_BLEND, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
// The depth map must not be bound for sampling while it is being rendered.
cs->setTextureAttribute(kShadowTextureUnit, new osg::Texture2D,
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
shadowCamera_->addChild(casters);
root_->addChild(shadowCamera_);
resizeShadowMap(2048);
ground_ = createGroundShadow();
root_->addChild(ground_);
}
apply(settings_);
}
void SceneLook::setShadowsSupported(bool supported) {
if (supported == shadowsSupported_) return;
shadowsSupported_ = supported;
apply(settings_);
}
void SceneLook::resizeShadowMap(int size) {
if (size == shadowSize_) return;
shadowSize_ = size;
shadowMap_->setTextureSize(size, size);
shadowMap_->dirtyTextureObject();
shadowCamera_->setViewport(0, 0, size, size);
shadowCamera_->detach(osg::Camera::DEPTH_BUFFER);
shadowCamera_->attach(osg::Camera::DEPTH_BUFFER, shadowMap_.get());
shadowCamera_->setRenderingCache(nullptr); // rebuild the FBO at the new size
shadowTexel_->set(1.f / static_cast<float>(size));
}
void SceneLook::apply(const LookSettings& settings) {
settings_ = settings;
lightColor_->set(settings.lightColor);
rimStrength_->set(settings.rimStrength);
rimColor_->set(settings.rimColor);
shadowSoftness_->set(settings.shadowSoftness);
groundOpacity_->set(settings.groundShadowOpacity);
const bool shadows = shadowsSupported_ && settings.shadows;
shadowEnabled_->set(shadows ? 1 : 0);
shadowStrength_->set(shadows ? settings.shadowStrength : 0.f);
resizeShadowMap(1024 << std::clamp(settings.shadowQuality, 0, 2));
shadowCamera_->setNodeMask(shadows ? ~0u : 0u);
if (!shadows) ground_->setNodeMask(0u);
}
osg::Vec3f SceneLook::lightDirection(const osg::Matrixd& view) const {
if (settings_.lightFollowsCamera) {
// Light from the upper left, slightly in front of the camera.
osg::Vec3d viewDir(0.3, -0.5, -1.0);
osg::Vec3d world = osg::Matrixd::transform3x3(viewDir, osg::Matrixd::inverse(view));
world.normalize();
return osg::Vec3f(world);
}
const double az = osg::DegreesToRadians(double(settings_.lightAzimuth));
const double el = osg::DegreesToRadians(double(settings_.lightElevation));
osg::Vec3d from(std::cos(el) * std::cos(az), std::cos(el) * std::sin(az), std::sin(el));
return osg::Vec3f(-from);
}
void SceneLook::update(const osg::Matrixd& view, const osg::BoundingSphere& focus, bool groundVisible) {
const osg::Vec3f dir = lightDirection(view);
lightDir_->set(dir);
const bool shadows = shadowsSupported_ && settings_.shadows && focus.valid();
shadowCamera_->setNodeMask(shadows ? ~0u : 0u);
shadowEnabled_->set(shadows ? 1 : 0);
ground_->setNodeMask(shadows && settings_.groundShadow && groundVisible ? ~0u : 0u);
if (!shadows) return;
const double radius = std::max(focus.radius() * 1.1, 0.1);
const osg::Vec3d center = focus.center();
const osg::Vec3d d(dir);
const osg::Vec3d up = std::abs(d.z()) > 0.99 ? osg::Vec3d(0.0, 1.0, 0.0) : osg::Vec3d(0.0, 0.0, 1.0);
const double distance = radius * 4.0;
osg::Matrixd lightView = osg::Matrixd::lookAt(center - d * distance, center, up);
// Snap the light-space origin to whole texels so shadow edges do not shimmer as the camera moves.
const double texel = 2.0 * radius / shadowSize_;
osg::Vec3d origin = osg::Vec3d(0.0, 0.0, 0.0) * lightView;
lightView.postMultTranslate(osg::Vec3d(std::floor(origin.x() / texel) * texel - origin.x(),
std::floor(origin.y() / texel) * texel - origin.y(), 0.0));
osg::Matrixd lightProj = osg::Matrixd::ortho(-radius, radius, -radius, radius, 0.05, distance + radius * 4.0);
shadowCamera_->setViewMatrix(lightView);
shadowCamera_->setProjectionMatrix(lightProj);
const osg::Matrixd bias = osg::Matrixd::translate(1.0, 1.0, 1.0) * osg::Matrixd::scale(0.5, 0.5, 0.5);
shadowMatrix_->set(osg::Matrixf(lightView * lightProj * bias));
// Depth bias in shadow-map units: about one texel of world-space slope.
shadowBias_->set(static_cast<float>(1.5 * texel / (distance + radius * 4.0)));
}
} // namespace mr
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <osg/BoundingSphere>
#include <osg/Camera>
#include <osg/Group>
#include <osg/Texture2D>
#include <osg/Uniform>
#include "scene/LookSettings.h"
namespace mr {
// Owns the global lighting uniforms, the shadow map pass and the ground shadow floor.
class SceneLook {
public:
// Uniforms go on root's state set; the shadow pass renders `casters`.
SceneLook(osg::Group* root, osg::Group* casters);
void apply(const LookSettings& settings);
// Per frame: view is the active camera's view matrix, focus the region shadows must cover.
void update(const osg::Matrixd& view, const osg::BoundingSphere& focus, bool groundVisible);
bool shadowsSupported() const { return shadowsSupported_; }
void setShadowsSupported(bool supported);
osg::Vec3f lightDirection(const osg::Matrixd& view) const; // world space, direction of travel
private:
void resizeShadowMap(int size);
osg::ref_ptr<osg::Group> root_;
osg::ref_ptr<osg::Camera> shadowCamera_;
osg::ref_ptr<osg::Texture2D> shadowMap_;
osg::ref_ptr<osg::Node> ground_;
bool shadowsSupported_ = true;
int shadowSize_ = 0;
LookSettings settings_;
osg::ref_ptr<osg::Uniform> lightDir_, lightColor_, shadowEnabled_, shadowMatrix_, shadowTexel_, shadowSoftness_,
shadowBias_, shadowStrength_, groundOpacity_, rimStrength_, rimColor_;
};
} // namespace mr
+248 -28
View File
@@ -1,9 +1,11 @@
#include "render/ModelNode.h"
#include "model/Parallel.h"
#include "render/GpuCaps.h"
#include "render/Shaders.h"
#include "render/TextureLoader.h"
#include <algorithm>
#include <osg/BlendFunc>
#include <osg/CullFace>
#include <osg/Depth>
@@ -16,9 +18,6 @@ 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 {
@@ -27,6 +26,20 @@ public:
}
};
// In hardware mode the vertex arrays hold rest positions, so bounds come from the posed skeleton.
class PosedBoundsCallback : public osg::Drawable::ComputeBoundingBoxCallback {
public:
explicit PosedBoundsCallback(const ModelNode* node) : node_(node) {}
osg::BoundingBox computeBound(const osg::Drawable& drawable) const override {
if (node_->activeSkinningMode() == SkinningMode::Hardware && node_->posedBounds().valid())
return node_->posedBounds();
return drawable.computeBoundingBox();
}
private:
const ModelNode* node_;
};
} // namespace
ModelNode::ModelNode(std::shared_ptr<Model> model) : model_(std::move(model)), poser_(model_) {
@@ -39,21 +52,18 @@ ModelNode::ModelNode(std::shared_ptr<Model> model) : model_(std::move(model)), p
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)));
for (const char* name : {"u_texMul", "u_sphereMul", "u_toonMul"}) ss->addUniform(new osg::Uniform(name, osg::Vec4f(1, 1, 1, 1)));
for (const char* name : {"u_texAdd", "u_sphereAdd", "u_toonAdd"}) ss->addUniform(new osg::Uniform(name, osg::Vec4f()));
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);
preloadTextureImages();
buildMesh();
buildSkinning();
buildSkeleton();
setShowSkeleton(false);
updateDeformation();
@@ -81,10 +91,20 @@ osg::Texture2D* ModelNode::texture(int index, bool clamp) {
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));
MaterialUniforms& u = materialUniforms_[order];
u.diffuse = new osg::Uniform("u_diffuse", m.diffuse);
u.ambient = new osg::Uniform("u_ambient", m.ambient);
u.specular = new osg::Uniform("u_specular", m.specular);
u.shininess = new osg::Uniform("u_shininess", m.shininess);
u.textureMul = new osg::Uniform("u_texMul", osg::Vec4f(1, 1, 1, 1));
u.textureAdd = new osg::Uniform("u_texAdd", osg::Vec4f());
u.sphereMul = new osg::Uniform("u_sphereMul", osg::Vec4f(1, 1, 1, 1));
u.sphereAdd = new osg::Uniform("u_sphereAdd", osg::Vec4f());
u.toonMul = new osg::Uniform("u_toonMul", osg::Vec4f(1, 1, 1, 1));
u.toonAdd = new osg::Uniform("u_toonAdd", osg::Vec4f());
for (osg::Uniform* uniform : {u.diffuse.get(), u.ambient.get(), u.specular.get(), u.shininess.get(), u.textureMul.get(),
u.textureAdd.get(), u.sphereMul.get(), u.sphereAdd.get(), u.toonMul.get(), u.toonAdd.get()})
ss->addUniform(uniform);
osg::Texture2D* main = texture(m.texture, false);
if (main) ss->setTextureAttributeAndModes(0, main, osg::StateAttribute::ON);
@@ -103,6 +123,8 @@ osg::StateSet* ModelNode::buildMaterialState(const Material& m, int order) {
}
if (toon) ss->setTextureAttributeAndModes(2, toon, osg::StateAttribute::ON);
ss->addUniform(new osg::Uniform("u_useToon", toon ? 1 : 0));
ss->addUniform(new osg::Uniform("u_castShadow", m.castShadow ? 1 : 0));
ss->addUniform(new osg::Uniform("u_receiveShadow", m.receiveShadow ? 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);
@@ -117,7 +139,9 @@ 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());
uvs_ = new osg::Vec2Array(model.vertices.size());
osg::Vec2Array* uvs = uvs_.get();
materialUniforms_.assign(model.materials.size(), MaterialUniforms());
for (size_t i = 0; i < model.vertices.size(); ++i) {
(*positions_)[i] = model.vertices[i].position;
(*normals_)[i] = model.vertices[i].normal;
@@ -125,6 +149,7 @@ void ModelNode::buildMesh() {
}
positions_->setDataVariance(osg::Object::DYNAMIC);
normals_->setDataVariance(osg::Object::DYNAMIC);
uvs_->setDataVariance(osg::Object::DYNAMIC);
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
for (size_t i = 0; i < model.materials.size(); ++i) {
@@ -142,13 +167,158 @@ void ModelNode::buildMesh() {
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)));
geom->setComputeBoundingBoxCallback(new PosedBoundsCallback(this));
geode->addDrawable(geom);
geometries_.push_back(geom);
}
meshGroup_ = geode;
addChild(meshGroup_);
buildEdges(uvs);
}
void ModelNode::buildEdges(osg::Vec2Array* uvs) {
const Model& model = *model_;
edgeGroup_ = new osg::Geode;
osg::StateSet* ss = edgeGroup_->getOrCreateStateSet();
ss->setAttributeAndModes(createEdgeProgram(), osg::StateAttribute::ON);
ss->setAttributeAndModes(new osg::CullFace(osg::CullFace::FRONT),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg::StateAttribute::ON);
ss->addUniform(new osg::Uniform("u_castShadow", 0));
ss->addUniform(new osg::Uniform("u_useTexture", 0));
edgeWidthUniform_ = new osg::Uniform("u_edgeWidth", 1.f);
ss->addUniform(edgeWidthUniform_);
osg::ref_ptr<osg::FloatArray> scales = new osg::FloatArray(model.vertices.size());
for (size_t i = 0; i < model.vertices.size(); ++i) (*scales)[i] = model.vertices[i].edgeScale;
const int materialCount = static_cast<int>(model.materials.size());
for (size_t i = 0; i < model.materials.size(); ++i) {
const Material& m = model.materials[i];
if (m.indexCount == 0 || !m.drawEdge || m.edgeSize <= 0.f || m.edgeColor.a() <= 0.f) continue;
osg::ref_ptr<osg::Geometry> geom = new osg::Geometry;
geom->setName(m.name + " (edge)");
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);
geom->setVertexAttribArray(kEdgeScaleAttrib, scales, osg::Array::BIND_PER_VERTEX);
geom->addPrimitiveSet(new osg::DrawElementsUInt(GL_TRIANGLES, model.indices.begin() + m.indexOffset,
model.indices.begin() + m.indexOffset + m.indexCount));
osg::StateSet* es = geom->getOrCreateStateSet();
materialUniforms_[i].edgeColor = new osg::Uniform("u_edgeColor", m.edgeColor);
materialUniforms_[i].edgeSize = new osg::Uniform("u_edgeSize", m.edgeSize);
es->addUniform(materialUniforms_[i].edgeColor);
es->addUniform(materialUniforms_[i].edgeSize);
// Drawn after every material of the model, like MMD's edge pass.
es->setRenderBinDetails(10 + materialCount + static_cast<int>(i), "RenderBin");
geom->setComputeBoundingBoxCallback(new PosedBoundsCallback(this));
edgeGroup_->addDrawable(geom);
geometries_.push_back(geom);
}
addChild(edgeGroup_);
}
bool ModelNode::hasOutlines() const { return edgeGroup_->getNumDrawables() > 0; }
void ModelNode::setShowOutlines(bool show) {
showOutlines_ = show;
edgeGroup_->setNodeMask(show && !wireframe_ ? ~kShadowCasterMask : 0u);
}
void ModelNode::setOutlineWidth(float width) { edgeWidthUniform_->set(width); }
void ModelNode::buildSkinning() {
const Model& model = *model_;
const size_t boneCount = model.bones.size();
osg::StateSet* ss = getOrCreateStateSet();
skinningUniform_ = new osg::Uniform("u_skinning", 0);
ss->addUniform(skinningUniform_);
osg::ref_ptr<osg::Vec4Array> indices = new osg::Vec4Array(model.vertices.size());
osg::ref_ptr<osg::Vec4Array> weights = new osg::Vec4Array(model.vertices.size());
for (size_t i = 0; i < model.vertices.size(); ++i) {
const Vertex& v = model.vertices[i];
for (int k = 0; k < 4; ++k) {
const bool used = v.bones[k] >= 0 && v.weights[k] > 0.f;
(*indices)[i][k] = used ? float(v.bones[k]) : 0.f;
(*weights)[i][k] = used ? v.weights[k] : 0.f;
}
}
for (auto& g : geometries_) {
g->setVertexAttribArray(kBoneIndexAttrib, indices, osg::Array::BIND_PER_VERTEX);
g->setVertexAttribArray(kBoneWeightAttrib, weights, osg::Array::BIND_PER_VERTEX);
}
boneRestPositions_.resize(boneCount);
for (size_t b = 0; b < boneCount; ++b)
boneRestPositions_[b] = osg::Matrixf::inverse(model.bones[b].inverseBind).getTrans();
float morphReach = 0.f;
for (const auto& m : model.morphs)
for (const auto& o : m.vertexOffsets) morphReach = std::max(morphReach, o.offset.length());
for (const auto& v : model.vertices) {
if (v.bones[0] < 0) {
unskinnedBounds_.expandBy(v.position);
continue;
}
int main = 0;
for (int k = 1; k < 4; ++k)
if (v.bones[k] >= 0 && v.weights[k] > v.weights[main]) main = k;
boneReach_ = std::max(boneReach_, (v.position - boneRestPositions_[v.bones[main]]).length());
}
boneReach_ += morphReach;
if (unskinnedBounds_.valid()) {
const osg::Vec3f pad(morphReach, morphReach, morphReach);
unskinnedBounds_.expandBy(unskinnedBounds_._max + pad);
unskinnedBounds_.expandBy(unskinnedBounds_._min - pad);
}
if (boneCount == 0) return;
const int columns = static_cast<int>(std::min<size_t>(boneCount, kBonesPerTextureRow));
const int rows = static_cast<int>((boneCount + kBonesPerTextureRow - 1) / kBonesPerTextureRow);
boneImage_ = new osg::Image;
boneImage_->allocateImage(columns * 3, rows, 1, GL_RGBA, GL_FLOAT);
boneImage_->setInternalTextureFormat(GL_RGBA32F_ARB);
std::fill(reinterpret_cast<float*>(boneImage_->data()),
reinterpret_cast<float*>(boneImage_->data()) + columns * 3 * rows * 4, 0.f);
boneImage_->setDataVariance(osg::Object::DYNAMIC);
boneTexture_ = new osg::Texture2D(boneImage_);
boneTexture_->setDataVariance(osg::Object::DYNAMIC);
boneTexture_->setResizeNonPowerOfTwoHint(false);
boneTexture_->setUseHardwareMipMapGeneration(false);
boneTexture_->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
boneTexture_->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
boneTexture_->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
boneTexture_->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
ss->setTextureAttribute(kBoneTextureUnit, boneTexture_);
ss->addUniform(new osg::Uniform("u_boneTexture", static_cast<int>(kBoneTextureUnit)));
ss->addUniform(new osg::Uniform("u_boneTexSize", osg::Vec2f(float(columns * 3), float(rows))));
}
void ModelNode::uploadBoneMatrices() {
const auto& skin = poser_.skinMatrices();
const auto& bones = model_->bones;
float* data = reinterpret_cast<float*>(boneImage_->data());
const int width = boneImage_->s();
posedBounds_ = unskinnedBounds_;
const osg::Vec3f reach(boneReach_, boneReach_, boneReach_);
for (size_t b = 0; b < skin.size(); ++b) {
const osg::Matrixf& m = skin[b];
float* texel = data + ((b / kBonesPerTextureRow) * width + (b % kBonesPerTextureRow) * 3) * 4;
for (int k = 0; k < 3; ++k)
for (int r = 0; r < 4; ++r) texel[k * 4 + r] = m(r, k);
if (bones[b].isSkinBone) {
const osg::Vec3f p = boneRestPositions_[b] * m;
posedBounds_.expandBy(p - reach);
posedBounds_.expandBy(p + reach);
}
}
boneImage_->dirty();
}
void ModelNode::setSkinningMode(SkinningMode mode) { requestedSkinning_ = mode; }
void ModelNode::buildSkeleton() {
const Model& model = *model_;
for (size_t i = 0; i < model.bones.size(); ++i)
@@ -165,6 +335,7 @@ void ModelNode::buildSkeleton() {
ss->setAttribute(new osg::LineWidth(2.f));
ss->setAttribute(new osg::Point(6.f));
ss->setRenderBinDetails(100000, "RenderBin");
ss->addUniform(new osg::Uniform("u_castShadow", 0));
auto makeGeom = [](GLenum mode) {
osg::ref_ptr<osg::Geometry> g = new osg::Geometry;
@@ -219,13 +390,35 @@ void ModelNode::updateSkeleton() {
}
void ModelNode::updateDeformation() {
const bool hardware =
requestedSkinning_ == SkinningMode::Hardware && gpuCaps().skinning && boneImage_.valid();
const SkinningMode wanted = hardware ? SkinningMode::Hardware : SkinningMode::Software;
if (wanted != activeSkinning_) {
activeSkinning_ = wanted;
poser_.setSkinningMode(wanted);
skinningUniform_->set(hardware ? 1 : 0);
if (hardware) {
for (size_t i = 0; i < model_->vertices.size(); ++i) (*normals_)[i] = model_->vertices[i].normal;
normals_->dirty();
}
}
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();
if (poser_.morphsChangedInLastUpdate()) applyMorphedMaterials();
if (activeSkinning_ == SkinningMode::Software) {
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();
} else {
uploadBoneMatrices();
if (poser_.morphsChangedInLastUpdate()) {
const auto& p = poser_.morphedPositions();
std::copy(p.begin(), p.end(), positions_->begin());
positions_->dirty();
}
}
for (auto& g : geometries_) g->dirtyBound();
skeletonDirty_ = true;
}
@@ -235,6 +428,39 @@ void ModelNode::updateDeformation() {
}
}
void ModelNode::applyMorphedMaterials() {
const auto& uvs = poser_.morphedUvs();
if (!uvs.empty()) {
std::copy(uvs.begin(), uvs.end(), uvs_->begin());
uvs_->dirty();
}
if (!poser_.hasMaterialMorphs()) return;
const auto& states = poser_.materialStates();
for (size_t i = 0; i < states.size() && i < materialUniforms_.size(); ++i) {
const MaterialState& s = states[i];
MaterialUniforms& u = materialUniforms_[i];
if (!u.diffuse) continue;
u.diffuse->set(s.diffuse);
u.ambient->set(s.ambient);
u.specular->set(s.specular);
u.shininess->set(s.shininess);
u.textureMul->set(s.textureMul);
u.textureAdd->set(s.textureAdd);
u.sphereMul->set(s.sphereMul);
u.sphereAdd->set(s.sphereAdd);
u.toonMul->set(s.toonMul);
u.toonAdd->set(s.toonAdd);
if (u.edgeColor) {
// Fading a material out (a common morph) fades its outline with it.
osg::Vec4f edge = s.edgeColor;
const float baseAlpha = model_->materials[i].diffuse.a();
if (baseAlpha > 0.f) edge.a() *= std::clamp(s.diffuse.a() / baseAlpha, 0.f, 1.f);
u.edgeColor->set(edge);
u.edgeSize->set(s.edgeSize);
}
}
}
void ModelNode::setShowSkeleton(bool show) {
skeletonGeode_->setNodeMask(show ? ~0u : 0u);
skeletonDirty_ = true;
@@ -253,6 +479,8 @@ void ModelNode::setBackfaceCulling(bool enabled) {
}
void ModelNode::setWireframe(bool enabled) {
wireframe_ = enabled;
setShowOutlines(showOutlines_);
osg::StateSet* ss = meshGroup_->getOrCreateStateSet();
if (enabled)
ss->setAttributeAndModes(new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE),
@@ -262,14 +490,6 @@ void ModelNode::setWireframe(bool enabled) {
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);
+33 -4
View File
@@ -12,7 +12,7 @@
namespace mr {
enum class LightingModel { MmdToon = 0, Lambert = 1 };
enum class LightingModel { MmdToon = 0, Lambert = 1, AnimeCel = 2, SoftStudio = 3 };
// 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.
@@ -28,7 +28,14 @@ public:
void setBackfaceCulling(bool enabled);
void setWireframe(bool enabled);
void setLightingModel(LightingModel lighting);
void setLightFollowsCamera(bool follow);
// MMD edge lines for materials that have them; width multiplies every material's edge size.
void setShowOutlines(bool show);
void setOutlineWidth(float width);
bool hasOutlines() const;
// Hardware falls back to Software when the GPU cannot do it.
void setSkinningMode(SkinningMode mode);
SkinningMode activeSkinningMode() const { return activeSkinning_; }
const osg::BoundingBox& posedBounds() const { return posedBounds_; }
// World-space bounding sphere of the rest pose.
osg::BoundingSphere restBound() const;
@@ -40,6 +47,10 @@ private:
osg::StateSet* buildMaterialState(const Material& material, int order);
void preloadTextureImages();
osg::Texture2D* texture(int index, bool clamp);
void buildEdges(osg::Vec2Array* uvs);
void applyMorphedMaterials();
void buildSkinning();
void uploadBoneMatrices();
void buildSkeleton();
void updateSkeleton();
@@ -48,6 +59,13 @@ private:
osg::ref_ptr<osg::Group> meshGroup_;
osg::ref_ptr<osg::Vec3Array> positions_;
osg::ref_ptr<osg::Vec3Array> normals_;
osg::ref_ptr<osg::Vec2Array> uvs_;
// Per-material uniforms that UV/material morphs update.
struct MaterialUniforms {
osg::ref_ptr<osg::Uniform> diffuse, ambient, specular, shininess, textureMul, textureAdd, sphereMul, sphereAdd,
toonMul, toonAdd, edgeColor, edgeSize;
};
std::vector<MaterialUniforms> materialUniforms_;
std::vector<osg::ref_ptr<osg::Geometry>> geometries_;
std::vector<osg::ref_ptr<osg::Texture2D>> textures_;
std::vector<bool> textureTried_;
@@ -61,9 +79,20 @@ private:
int selectedBone_ = -1;
bool skeletonDirty_ = true;
SkinningMode requestedSkinning_ = SkinningMode::Hardware;
SkinningMode activeSkinning_ = SkinningMode::Software;
osg::ref_ptr<osg::Image> boneImage_;
osg::ref_ptr<osg::Texture2D> boneTexture_;
osg::ref_ptr<osg::Uniform> skinningUniform_;
std::vector<osg::Vec3f> boneRestPositions_;
float boneReach_ = 0.f; // max distance of a vertex (incl. morphs) from its main bone
osg::BoundingBox unskinnedBounds_; // vertices without bones
osg::BoundingBox posedBounds_;
osg::ref_ptr<osg::Uniform> lightingUniform_;
osg::ref_ptr<osg::Uniform> lightFollowUniform_;
osg::ref_ptr<osg::Uniform> lightDirUniform_;
osg::ref_ptr<osg::Geode> edgeGroup_;
osg::ref_ptr<osg::Uniform> edgeWidthUniform_;
bool showOutlines_ = true, wireframe_ = false;
};
} // namespace mr
+443
View File
@@ -0,0 +1,443 @@
#include "render/PostFx.h"
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Program>
#include <osgUtil/CullVisitor>
#include <algorithm>
#include <cmath>
#ifndef GL_RGBA16F_ARB
#define GL_RGBA16F_ARB 0x881A
#endif
#ifndef GL_DEPTH_COMPONENT24
#define GL_DEPTH_COMPONENT24 0x81A6
#endif
namespace mr {
namespace {
// GLSL 1.20 throughout, for macOS's legacy OpenGL profile.
const char* kQuadVertex = R"(#version 120
varying vec2 v_uv;
void main() {
v_uv = gl_MultiTexCoord0.xy;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
)";
// Downsample with a soft-knee threshold: only bright areas glow.
const char* kBrightFragment = R"(#version 120
uniform sampler2D u_color;
uniform vec2 u_texel;
uniform float u_threshold;
varying vec2 v_uv;
void main() {
vec3 c = 0.25 * (texture2D(u_color, v_uv + u_texel * vec2(-1.0, -1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(1.0, -1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(-1.0, 1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(1.0, 1.0)).rgb);
float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
float knee = 0.5 * u_threshold + 1e-4;
float soft = clamp(l - u_threshold + knee, 0.0, 2.0 * knee);
soft = soft * soft / (4.0 * knee);
gl_FragColor = vec4(c * (max(soft, l - u_threshold) / max(l, 1e-4)), 1.0);
}
)";
// 9-tap Gaussian using bilinear taps.
const char* kBlurFragment = R"(#version 120
uniform sampler2D u_src;
uniform vec2 u_dir;
varying vec2 v_uv;
void main() {
vec3 c = texture2D(u_src, v_uv).rgb * 0.227027;
c += (texture2D(u_src, v_uv + u_dir * 1.384615).rgb + texture2D(u_src, v_uv - u_dir * 1.384615).rgb) * 0.316216;
c += (texture2D(u_src, v_uv + u_dir * 3.230769).rgb + texture2D(u_src, v_uv - u_dir * 3.230769).rgb) * 0.070270;
gl_FragColor = vec4(c, 1.0);
}
)";
// Screen-space ambient occlusion from the depth buffer (normals from depth derivatives).
const char* kAoFragment = R"(#version 120
uniform sampler2D u_depth;
uniform vec4 u_proj; // projection m00, m11, m20, m21
uniform vec2 u_projZ; // projection m22, m32
uniform float u_radius;
uniform float u_strength;
varying vec2 v_uv;
vec3 viewPos(vec2 uv) {
float zn = texture2D(u_depth, uv).r * 2.0 - 1.0;
float z = u_projZ.y / (zn + u_projZ.x);
vec2 ndc = uv * 2.0 - 1.0;
return vec3(z * (ndc.x + u_proj.z) / u_proj.x, z * (ndc.y + u_proj.w) / u_proj.y, z);
}
void main() {
if (texture2D(u_depth, v_uv).r >= 1.0) { gl_FragColor = vec4(1.0); return; }
vec3 p = viewPos(v_uv);
vec3 n = normalize(cross(dFdx(p), dFdy(p)));
if (n.z > 0.0) n = -n;
vec2 r = vec2(u_proj.x, u_proj.y) * (0.5 * u_radius / p.z);
float angle = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
float occlusion = 0.0;
for (int i = 0; i < 12; ++i) {
float t = (float(i) + 0.5) / 12.0;
float a = angle + float(i) * 2.3999632;
vec3 v = viewPos(v_uv + vec2(cos(a), sin(a)) * t * r) - p;
float vv = dot(v, v);
float falloff = max(0.0, 1.0 - vv / (u_radius * u_radius));
// The distance-scaled bias stops flat ground self-occluding as depth precision drops.
occlusion += falloff * max(0.0, (dot(v, n) - 0.004 * p.z) * inversesqrt(vv + 1e-6) - 0.15);
}
float ao = clamp(1.0 - u_strength * occlusion / 4.0, 0.0, 1.0);
// Depth precision runs out far away (sky domes, distant terrain): fade out instead of banding.
ao = mix(ao, 1.0, smoothstep(60.0 * u_radius, 120.0 * u_radius, p.z));
gl_FragColor = vec4(ao, ao, ao, 1.0);
}
)";
const char* kCompositeFragment = R"(#version 120
uniform sampler2D u_color;
uniform sampler2D u_bloom;
uniform sampler2D u_ao;
uniform vec2 u_aoTexel;
uniform int u_bloomOn;
uniform int u_aoOn;
uniform int u_toneMap;
uniform float u_bloomStrength;
uniform float u_exposure;
uniform float u_contrast;
uniform float u_saturation;
uniform vec3 u_tint;
uniform float u_vignette;
varying vec2 v_uv;
vec3 aces(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); }
void main() {
vec4 src = texture2D(u_color, v_uv);
vec3 c = src.rgb;
if (u_aoOn == 1) {
float ao = 0.25 * (texture2D(u_ao, v_uv + u_aoTexel * vec2(-0.75, -0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(0.75, -0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(-0.75, 0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(0.75, 0.75)).r);
c *= ao;
}
if (u_bloomOn == 1) c += texture2D(u_bloom, v_uv).rgb * u_bloomStrength;
c *= u_exposure * u_tint;
// Filmic: ACES fit, scaled so white lands near 0.85 and highlights roll off instead of clipping.
if (u_toneMap == 1) c = pow(aces(max(c, 0.0) * 0.8) / 0.886, vec3(1.15));
c = (c - 0.5) * u_contrast + 0.5;
float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
c = mix(vec3(l), c, u_saturation);
vec2 d = v_uv - 0.5;
c *= 1.0 - u_vignette * smoothstep(0.25, 0.75, dot(d, d) * 2.0);
gl_FragColor = vec4(clamp(c, 0.0, 1.0), src.a);
}
)";
// FXAA (the compact "console" variant) or a plain copy.
const char* kFinalFragment = R"(#version 120
uniform sampler2D u_src;
uniform vec2 u_texel;
uniform int u_fxaa;
varying vec2 v_uv;
float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); }
void main() {
vec4 m = texture2D(u_src, v_uv);
if (u_fxaa == 0) { gl_FragColor = m; return; }
float lNW = luma(texture2D(u_src, v_uv + vec2(-1.0, -1.0) * u_texel).rgb);
float lNE = luma(texture2D(u_src, v_uv + vec2(1.0, -1.0) * u_texel).rgb);
float lSW = luma(texture2D(u_src, v_uv + vec2(-1.0, 1.0) * u_texel).rgb);
float lSE = luma(texture2D(u_src, v_uv + vec2(1.0, 1.0) * u_texel).rgb);
float lM = luma(m.rgb);
float lMin = min(lM, min(min(lNW, lNE), min(lSW, lSE)));
float lMax = max(lM, max(max(lNW, lNE), max(lSW, lSE)));
vec2 dir = vec2(-((lNW + lNE) - (lSW + lSE)), (lNW + lSW) - (lNE + lSE));
float reduce = max((lNW + lNE + lSW + lSE) * 0.03125, 1.0 / 128.0);
float rcp = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce);
dir = clamp(dir * rcp, vec2(-8.0), vec2(8.0)) * u_texel;
vec3 a = 0.5 * (texture2D(u_src, v_uv - dir / 6.0).rgb + texture2D(u_src, v_uv + dir / 6.0).rgb);
vec3 b = a * 0.5 + 0.25 * (texture2D(u_src, v_uv - dir * 0.5).rgb + texture2D(u_src, v_uv + dir * 0.5).rgb);
float lB = luma(b);
gl_FragColor = vec4((lB < lMin || lB > lMax) ? a : b, m.a);
}
)";
osg::ref_ptr<osg::Texture2D> makeTexture(GLint internalFormat, GLenum format, GLenum type, bool linear) {
osg::ref_ptr<osg::Texture2D> t = new osg::Texture2D;
t->setInternalFormat(internalFormat);
t->setSourceFormat(format);
t->setSourceType(type);
const osg::Texture::FilterMode f = linear ? osg::Texture::LINEAR : osg::Texture::NEAREST;
t->setFilter(osg::Texture::MIN_FILTER, f);
t->setFilter(osg::Texture::MAG_FILTER, f);
t->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
t->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
t->setResizeNonPowerOfTwoHint(false);
t->setTextureSize(4, 4);
return t;
}
// A pass that draws one fullscreen quad with `fragment` into `target` (or into the parent camera).
osg::ref_ptr<osg::Camera> makePass(const char* name, const char* fragment, osg::Texture2D* target, int order) {
osg::ref_ptr<osg::Camera> cam = new osg::Camera;
cam->setName(name);
cam->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
cam->setProjectionMatrix(osg::Matrixd::ortho2D(0.0, 1.0, 0.0, 1.0));
cam->setViewMatrix(osg::Matrixd::identity());
cam->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
cam->setInheritanceMask(cam->getInheritanceMask() & ~osg::CullSettings::CULL_MASK);
cam->setCullMask(~0u);
if (target) {
cam->setRenderOrder(osg::Camera::PRE_RENDER, order);
cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
cam->setClearMask(0);
cam->attach(osg::Camera::COLOR_BUFFER, target);
} else {
cam->setRenderOrder(osg::Camera::NESTED_RENDER);
cam->setClearMask(0);
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0, 0, 0), osg::Vec3(1, 0, 0), osg::Vec3(0, 1, 0)));
geode->setCullingActive(false);
osg::StateSet* ss = geode->getOrCreateStateSet();
osg::ref_ptr<osg::Program> program = new osg::Program;
program->setName(name);
program->addShader(new osg::Shader(osg::Shader::VERTEX, kQuadVertex));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragment));
ss->setAttributeAndModes(program, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_BLEND, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setAttributeAndModes(new osg::Depth(osg::Depth::ALWAYS, 0.0, 1.0, false),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
cam->addChild(geode);
return cam;
}
void bind(osg::Camera* pass, unsigned unit, osg::Texture2D* tex, const char* sampler) {
osg::StateSet* ss = pass->getChild(0)->getOrCreateStateSet();
ss->setTextureAttribute(unit, tex, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
ss->addUniform(new osg::Uniform(sampler, static_cast<int>(unit)));
}
osg::Uniform* uniform(osg::Camera* pass, osg::Uniform* u) {
pass->getChild(0)->getOrCreateStateSet()->addUniform(u);
return u;
}
void resizeTarget(osg::Camera* cam, osg::Camera::BufferComponent buffer, osg::Texture2D* tex, int w, int h) {
tex->setTextureSize(w, h);
tex->dirtyTextureObject();
cam->setViewport(0, 0, w, h);
cam->detach(buffer);
cam->attach(buffer, tex);
cam->setRenderingCache(nullptr);
}
class ProjectionCallback : public osg::NodeCallback {
public:
void operator()(osg::Node* node, osg::NodeVisitor* nv) override {
if (auto* cv = nv->asCullVisitor())
if (cv->getProjectionMatrix() && cv->getModelViewMatrix())
static_cast<PostChain*>(node)->cullUpdate(*cv->getProjectionMatrix(), *cv->getModelViewMatrix());
traverse(node, nv);
}
};
} // namespace
bool postFxActive(const LookSettings& s) {
return s.bloom || s.ambientOcclusion || s.toneMapping != 0 || s.fxaa || s.exposure != 1.f || s.contrast != 1.f ||
s.saturation != 1.f || s.temperature != 0.f || s.vignette > 0.f;
}
PostChain::PostChain(osg::Node* scene, unsigned viewMask) : scene_(scene) {
setNodeMask(viewMask);
setCullCallback(new ProjectionCallback);
addChild(scene_);
}
void PostChain::setSupported(bool framebufferObjects, bool floatTextures) {
if (framebufferObjects == supported_ && floatTextures == floatColor_) return;
supported_ = framebufferObjects;
if (!built_) floatColor_ = floatTextures;
refresh();
}
void PostChain::apply(const LookSettings& settings) {
settings_ = settings;
refresh();
}
void PostChain::setClearColor(const osg::Vec4& color) {
clearColor_ = color;
if (sceneCam_) sceneCam_->setClearColor(color);
}
void PostChain::cullUpdate(const osg::Matrixd& p, const osg::Matrixd& view) {
if (!active_) return;
osg::Matrixd fitted = p;
const osg::BoundingSphere bs = scene_->getBound();
if (p(2, 3) != 0.0 && p(3, 2) != 0.0 && bs.valid()) {
// Perspective: re-fit near/far around the scene, as OSG does for the output camera itself,
// so large stages and sky domes are not clipped.
const double dist = -(bs.center() * view).z(), r = bs.radius();
const double f = std::max(dist + r, 1.0);
// Same near/far ratio OSG uses for the window, which keeps depth precision for sky domes.
const double n = std::max(std::max(dist - r, f * 0.0005), 0.1);
const double m22 = -(f + n) / (f - n), m32 = -2.0 * f * n / (f - n);
osg::Matrixd correction; // remaps clip-space z only
correction(2, 2) = m32 / p(3, 2);
correction(3, 2) = p(2, 2) * m32 / p(3, 2) - m22;
fitted = p * correction;
}
sceneCam_->setViewMatrix(view);
sceneCam_->setProjectionMatrix(fitted);
proj_->set(osg::Vec4f(fitted(0, 0), fitted(1, 1), fitted(2, 0), fitted(2, 1)));
projZ_->set(osg::Vec2f(fitted(2, 2), fitted(3, 2)));
}
void PostChain::build() {
// Model shaders clamp to [0, 1], so 8-bit targets lose nothing and halve the bandwidth of float ones.
const GLint colorFormat = GL_RGBA8;
const GLenum colorType = GL_UNSIGNED_BYTE;
color_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
depth_ = makeTexture(GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false);
bloomA_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
bloomB_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
ao_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true);
ldr_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true);
// Uses the output camera's view and projection (set each cull) and inherits its cull mask.
sceneCam_ = new osg::Camera;
sceneCam_->setName("PostSceneCamera");
sceneCam_->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
sceneCam_->setRenderOrder(osg::Camera::PRE_RENDER, 0);
sceneCam_->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
sceneCam_->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
sceneCam_->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
sceneCam_->setClearColor(clearColor_);
sceneCam_->attach(osg::Camera::COLOR_BUFFER, color_.get());
sceneCam_->attach(osg::Camera::DEPTH_BUFFER, depth_.get());
sceneCam_->addChild(scene_);
brightCam_ = makePass("PostBright", kBrightFragment, bloomA_.get(), 1);
bind(brightCam_, 0, color_.get(), "u_color");
brightTexel_ = uniform(brightCam_, new osg::Uniform("u_texel", osg::Vec2f()));
threshold_ = uniform(brightCam_, new osg::Uniform("u_threshold", 0.75f));
blurHCam_ = makePass("PostBlurH", kBlurFragment, bloomB_.get(), 2);
bind(blurHCam_, 0, bloomA_.get(), "u_src");
blurHDir_ = uniform(blurHCam_, new osg::Uniform("u_dir", osg::Vec2f()));
blurVCam_ = makePass("PostBlurV", kBlurFragment, bloomA_.get(), 3);
bind(blurVCam_, 0, bloomB_.get(), "u_src");
blurVDir_ = uniform(blurVCam_, new osg::Uniform("u_dir", osg::Vec2f()));
aoCam_ = makePass("PostAo", kAoFragment, ao_.get(), 4);
bind(aoCam_, 0, depth_.get(), "u_depth");
proj_ = uniform(aoCam_, new osg::Uniform("u_proj", osg::Vec4f(1, 1, 0, 0)));
projZ_ = uniform(aoCam_, new osg::Uniform("u_projZ", osg::Vec2f(-1, -0.2f)));
aoRadius_ = uniform(aoCam_, new osg::Uniform("u_radius", 1.5f));
aoStrength_ = uniform(aoCam_, new osg::Uniform("u_strength", 1.f));
compositeCam_ = makePass("PostComposite", kCompositeFragment, ldr_.get(), 5);
bind(compositeCam_, 0, color_.get(), "u_color");
bind(compositeCam_, 1, bloomA_.get(), "u_bloom");
bind(compositeCam_, 2, ao_.get(), "u_ao");
compositeAoTexel_ = uniform(compositeCam_, new osg::Uniform("u_aoTexel", osg::Vec2f()));
bloomOn_ = uniform(compositeCam_, new osg::Uniform("u_bloomOn", 0));
aoOn_ = uniform(compositeCam_, new osg::Uniform("u_aoOn", 0));
toneMap_ = uniform(compositeCam_, new osg::Uniform("u_toneMap", 0));
bloomStrength_ = uniform(compositeCam_, new osg::Uniform("u_bloomStrength", 0.5f));
exposure_ = uniform(compositeCam_, new osg::Uniform("u_exposure", 1.f));
contrast_ = uniform(compositeCam_, new osg::Uniform("u_contrast", 1.f));
saturation_ = uniform(compositeCam_, new osg::Uniform("u_saturation", 1.f));
tint_ = uniform(compositeCam_, new osg::Uniform("u_tint", osg::Vec3f(1, 1, 1)));
vignette_ = uniform(compositeCam_, new osg::Uniform("u_vignette", 0.f));
finalCam_ = makePass("PostFinal", kFinalFragment, nullptr, 0);
bind(finalCam_, 0, ldr_.get(), "u_src");
fxaaOn_ = uniform(finalCam_, new osg::Uniform("u_fxaa", 0));
fxaaTexel_ = uniform(finalCam_, new osg::Uniform("u_texel", osg::Vec2f()));
built_ = true;
const int w = width_, h = height_;
width_ = height_ = 0;
setSize(std::max(w, 1), std::max(h, 1));
}
void PostChain::setSize(int width, int height) {
width = std::max(width, 1);
height = std::max(height, 1);
if (width == width_ && height == height_) return;
width_ = width;
height_ = height;
if (!built_) return;
const int bw = std::max(width / 4, 1), bh = std::max(height / 4, 1);
const int aw = std::max(width / 2, 1), ah = std::max(height / 2, 1);
resizeTarget(sceneCam_, osg::Camera::COLOR_BUFFER, color_, width, height);
resizeTarget(sceneCam_, osg::Camera::DEPTH_BUFFER, depth_, width, height);
resizeTarget(brightCam_, osg::Camera::COLOR_BUFFER, bloomA_, bw, bh);
resizeTarget(blurHCam_, osg::Camera::COLOR_BUFFER, bloomB_, bw, bh);
blurVCam_->setViewport(0, 0, bw, bh);
blurVCam_->setRenderingCache(nullptr);
resizeTarget(aoCam_, osg::Camera::COLOR_BUFFER, ao_, aw, ah);
resizeTarget(compositeCam_, osg::Camera::COLOR_BUFFER, ldr_, width, height);
brightTexel_->set(osg::Vec2f(1.f / width, 1.f / height));
compositeAoTexel_->set(osg::Vec2f(1.f / aw, 1.f / ah));
fxaaTexel_->set(osg::Vec2f(1.f / width, 1.f / height));
refresh();
}
void PostChain::refresh() {
const bool active = supported_ && postFxActive(settings_);
if (active && !built_) build();
if (active != active_) {
active_ = active;
removeChildren(0, getNumChildren());
if (active) {
for (osg::Camera* cam : {sceneCam_.get(), brightCam_.get(), blurHCam_.get(), blurVCam_.get(), aoCam_.get(),
compositeCam_.get(), finalCam_.get()})
addChild(cam);
} else {
addChild(scene_);
}
}
if (!built_) return;
const LookSettings& s = settings_;
const unsigned bloomMask = s.bloom ? ~0u : 0u;
brightCam_->setNodeMask(bloomMask);
blurHCam_->setNodeMask(bloomMask);
blurVCam_->setNodeMask(bloomMask);
aoCam_->setNodeMask(s.ambientOcclusion ? ~0u : 0u);
// FXAA alone reads the scene directly and skips the full-screen composite pass.
const bool composite = s.bloom || s.ambientOcclusion || s.toneMapping != 0 || s.exposure != 1.f ||
s.contrast != 1.f || s.saturation != 1.f || s.temperature != 0.f || s.vignette > 0.f;
compositeCam_->setNodeMask(composite ? ~0u : 0u);
finalCam_->getChild(0)->getOrCreateStateSet()->setTextureAttribute(
0, composite ? ldr_.get() : color_.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
const float bw = static_cast<float>(std::max(width_ / 4, 1)), bh = static_cast<float>(std::max(height_ / 4, 1));
// Blur radius scales with the image height so the glow looks the same at any resolution.
const float spread = s.bloomRadius * std::max(height_, 1) / 540.f;
blurHDir_->set(osg::Vec2f(spread / bw, 0.f));
blurVDir_->set(osg::Vec2f(0.f, spread / bh));
threshold_->set(s.bloomThreshold);
bloomOn_->set(s.bloom ? 1 : 0);
bloomStrength_->set(s.bloomStrength);
aoOn_->set(s.ambientOcclusion ? 1 : 0);
aoRadius_->set(s.aoRadius);
aoStrength_->set(s.aoStrength);
toneMap_->set(s.toneMapping);
exposure_->set(s.exposure);
contrast_->set(s.contrast);
saturation_->set(s.saturation);
const float t = std::clamp(s.temperature, -1.f, 1.f);
tint_->set(osg::Vec3f(1.f + 0.12f * t, 1.f + 0.02f * t, 1.f - 0.15f * t));
vignette_->set(s.vignette);
fxaaOn_->set(s.fxaa ? 1 : 0);
}
} // namespace mr
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <osg/Camera>
#include <osg/Group>
#include <osg/Texture2D>
#include <osg/Uniform>
#include "scene/LookSettings.h"
namespace mr {
// Node-mask bits that pick which output camera draws which post-processing chain.
constexpr unsigned kMainViewMask = 0x10;
constexpr unsigned kPopViewMask = 0x20;
constexpr unsigned kRenderViewMask = 0x40;
// True when any post-processing effect is switched on.
bool postFxActive(const LookSettings& settings);
// Post-processing for one output camera. Nested cameras render the scene into textures with the
// output camera's view and projection, then bloom, ambient occlusion, tone mapping, colour grading
// and FXAA are composited onto a fullscreen quad. With every effect off the scene is drawn directly.
class PostChain : public osg::Group {
public:
PostChain(osg::Node* scene, unsigned viewMask);
void setSupported(bool framebufferObjects, bool floatTextures);
bool supported() const { return supported_; }
void apply(const LookSettings& settings);
void setSize(int width, int height);
void setClearColor(const osg::Vec4& color);
// Called while culling: fits near/far to the scene (the output camera's are fixed) and
// passes the resulting projection to the ambient-occlusion pass.
void cullUpdate(const osg::Matrixd& projection, const osg::Matrixd& view);
private:
void build();
void refresh();
osg::ref_ptr<osg::Node> scene_;
LookSettings settings_;
bool supported_ = false, floatColor_ = false, built_ = false, active_ = false;
int width_ = 0, height_ = 0;
osg::Vec4 clearColor_{0.f, 0.f, 0.f, 1.f};
osg::ref_ptr<osg::Texture2D> color_, depth_, bloomA_, bloomB_, ao_, ldr_;
osg::ref_ptr<osg::Camera> sceneCam_, brightCam_, blurHCam_, blurVCam_, aoCam_, compositeCam_, finalCam_;
osg::ref_ptr<osg::Uniform> brightTexel_, threshold_, blurHDir_, blurVDir_, aoTexel_, aoRadius_, aoStrength_,
proj_, projZ_, bloomOn_, aoOn_, bloomStrength_, toneMap_, exposure_, contrast_, saturation_, tint_,
vignette_, compositeAoTexel_, fxaaOn_, fxaaTexel_;
};
} // namespace mr
+250 -30
View File
@@ -1,24 +1,105 @@
#include "render/Shaders.h"
#include <string>
namespace mr {
namespace {
// GLSL 1.20 so the same shaders run on macOS legacy contexts, Windows and Linux.
const char* kVertexShader = R"(#version 120
// Hardware skinning reads bone matrices from a float texture: bone b occupies texels
// (b % 1024) * 3 + k, row b / 1024, where texel k holds column k of its 4x3 matrix.
const char* kSkinning = R"(
uniform int u_skinning;
uniform sampler2D u_boneTexture;
uniform vec2 u_boneTexSize;
attribute vec4 a_boneIndices;
attribute vec4 a_boneWeights;
vec4 boneColumn(float bone, float k) {
vec2 texel = vec2(mod(bone, 1024.0) * 3.0 + k, floor(bone / 1024.0));
return texture2DLod(u_boneTexture, (texel + 0.5) / u_boneTexSize, 0.0);
}
void skin(float bone, float weight, vec4 pos, vec3 nrm, inout vec3 outPos, inout vec3 outNrm) {
vec4 c0 = boneColumn(bone, 0.0);
vec4 c1 = boneColumn(bone, 1.0);
vec4 c2 = boneColumn(bone, 2.0);
outPos += weight * vec3(dot(pos, c0), dot(pos, c1), dot(pos, c2));
outNrm += weight * vec3(dot(nrm, c0.xyz), dot(nrm, c1.xyz), dot(nrm, c2.xyz));
}
void skinnedVertex(out vec4 pos, out vec3 nrm) {
pos = gl_Vertex;
nrm = gl_Normal;
if (u_skinning == 1 && a_boneWeights.x > 0.0) {
vec3 p = vec3(0.0);
vec3 n = vec3(0.0);
skin(a_boneIndices.x, a_boneWeights.x, pos, nrm, p, n);
if (a_boneWeights.y > 0.0) skin(a_boneIndices.y, a_boneWeights.y, pos, nrm, p, n);
if (a_boneWeights.z > 0.0) skin(a_boneIndices.z, a_boneWeights.z, pos, nrm, p, n);
if (a_boneWeights.w > 0.0) skin(a_boneIndices.w, a_boneWeights.w, pos, nrm, p, n);
pos = vec4(p, 1.0);
nrm = n;
}
}
)";
const char* kModelVertex = R"(
varying vec3 v_normal;
varying vec3 v_viewPos;
varying vec2 v_uv;
void main() {
vec4 viewPos = gl_ModelViewMatrix * gl_Vertex;
vec4 pos;
vec3 nrm;
skinnedVertex(pos, nrm);
vec4 viewPos = gl_ModelViewMatrix * pos;
v_viewPos = viewPos.xyz;
v_normal = gl_NormalMatrix * gl_Normal;
v_normal = gl_NormalMatrix * nrm;
v_uv = gl_MultiTexCoord0.xy;
gl_Position = gl_ProjectionMatrix * viewPos;
}
)";
const char* kFragmentShader = R"(#version 120
// Shadow map lookup with percentage-closer filtering over a Poisson disc.
// Returns 1 when lit, 0 when fully in shadow.
const char* kShadowLookup = R"(
uniform mat4 osg_ViewMatrixInverse;
uniform sampler2D u_shadowMap;
uniform int u_shadowEnabled;
uniform mat4 u_shadowMatrix; // world -> shadow map texture coordinates
uniform float u_shadowTexel; // 1 / shadow map size
uniform float u_shadowSoftness;
uniform float u_shadowBias;
const vec2 kPoisson[12] = vec2[12](
vec2(-0.326, -0.406), vec2(-0.840, -0.074), vec2(-0.696, 0.457), vec2(-0.203, 0.621),
vec2(0.962, -0.195), vec2(0.473, -0.480), vec2(0.519, 0.767), vec2(0.185, -0.893),
vec2(0.507, 0.064), vec2(0.896, 0.412), vec2(-0.322, -0.933), vec2(-0.792, -0.598));
float shadowFactor(vec3 viewPos, float ndl) {
if (u_shadowEnabled == 0) return 1.0;
vec4 sc = u_shadowMatrix * (osg_ViewMatrixInverse * vec4(viewPos, 1.0));
sc.xyz /= sc.w;
if (sc.x <= 0.0 || sc.x >= 1.0 || sc.y <= 0.0 || sc.y >= 1.0 || sc.z >= 1.0) return 1.0;
float bias = u_shadowBias * (1.0 + 3.0 * (1.0 - clamp(abs(ndl), 0.0, 1.0)));
float radius = u_shadowTexel * u_shadowSoftness;
float ref = sc.z - bias;
// Four corner taps first: fully lit or fully shadowed areas (most of the screen) stop here.
float lit = 0.0;
lit += ref <= texture2D(u_shadowMap, sc.xy + vec2(-0.7, -0.7) * radius).r ? 1.0 : 0.0;
lit += ref <= texture2D(u_shadowMap, sc.xy + vec2(0.7, -0.7) * radius).r ? 1.0 : 0.0;
lit += ref <= texture2D(u_shadowMap, sc.xy + vec2(-0.7, 0.7) * radius).r ? 1.0 : 0.0;
lit += ref <= texture2D(u_shadowMap, sc.xy + vec2(0.7, 0.7) * radius).r ? 1.0 : 0.0;
if (lit == 0.0 || lit == 4.0) return lit * 0.25;
for (int i = 0; i < 12; ++i)
lit += ref <= texture2D(u_shadowMap, sc.xy + kPoisson[i] * radius).r ? 1.0 : 0.0;
return lit / 16.0;
}
)";
const char* kModelFragment = R"(
uniform mat4 osg_ViewMatrix;
uniform sampler2D u_texture;
uniform sampler2D u_sphere;
@@ -26,14 +107,23 @@ 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 int u_lightingModel; // 0 MMD toon, 1 Lambert, 2 anime cel, 3 soft studio
uniform int u_receiveShadow;
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;
uniform float u_shadowStrength;
uniform float u_rimStrength;
uniform vec3 u_rimColor;
uniform vec4 u_texMul; // material-morph tints: texel * mul + add
uniform vec4 u_texAdd;
uniform vec4 u_sphereMul;
uniform vec4 u_sphereAdd;
uniform vec4 u_toonMul;
uniform vec4 u_toonAdd;
varying vec3 v_normal;
varying vec3 v_viewPos;
varying vec2 v_uv;
@@ -41,49 +131,179 @@ 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 toLight = -normalize(mat3(osg_ViewMatrix) * u_lightDirection);
vec3 toEye = normalize(-v_viewPos);
float ndl = dot(n, toLight);
float ndv = max(dot(n, toEye), 0.0);
float shadow = u_receiveShadow == 1 ? shadowFactor(v_viewPos, ndl) : 1.0;
float lit = mix(1.0, shadow, u_shadowStrength);
vec4 texel = vec4(1.0);
if (u_useTexture == 1) texel = clamp(texture2D(u_texture, v_uv) * u_texMul + u_texAdd, 0.0, 1.0);
vec4 base = u_diffuse * texel;
float alpha = base.a;
if (alpha < 0.004) discard;
vec3 tex = texel.rgb;
vec3 color;
float alpha = u_diffuse.a;
if (u_lightingModel == 0) {
color = clamp(u_diffuse.rgb * u_lightColor + u_ambient, 0.0, 1.0);
color = clamp(u_diffuse.rgb * u_lightColor + u_ambient, 0.0, 1.0) * tex;
} else if (u_lightingModel == 1) {
color = base.rgb * (0.35 + 0.65 * max(ndl, 0.0) * lit);
} else if (u_lightingModel == 2) {
// Two-tone cel: a hard terminator with a cool, slightly saturated shade colour.
float band = smoothstep(-0.02, 0.06, ndl) * lit;
vec3 shade = base.rgb * vec3(0.66, 0.62, 0.78);
color = mix(shade, base.rgb * (0.85 + 0.25 * u_lightColor), band);
} else {
color = u_diffuse.rgb * (0.35 + 0.65 * max(ndl, 0.0));
// Soft studio: wrapped diffuse, sky/ground ambient and Fresnel-weighted highlights.
vec3 up = normalize(mat3(osg_ViewMatrix) * vec3(0.0, 0.0, 1.0));
float sky = 0.5 + 0.5 * dot(n, up);
vec3 ambient = mix(vec3(0.26, 0.23, 0.22), vec3(0.50, 0.54, 0.62), sky);
float wrap = max((ndl + 0.35) / 1.35, 0.0) * lit;
color = base.rgb * (ambient + wrap * u_lightColor * 1.25);
}
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;
vec3 s = clamp(texture2D(u_sphere, n.xy * 0.5 + 0.5).rgb * u_sphereMul.rgb + u_sphereAdd.rgb, 0.0, 1.0);
if (u_sphereMode == 1) color *= s;
else color += s;
else color += s * (u_lightingModel == 2 ? 0.5 + 0.5 * lit : 1.0);
}
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_lightingModel == 0) {
float t = clamp(ndl + 0.5, 0.0, 1.0);
if (u_useToon == 1) {
vec3 toon = texture2D(u_toon, vec2(0.5, min(t, mix(1.0, t * shadow, u_shadowStrength)))).rgb;
color *= clamp(toon * u_toonMul.rgb + u_toonAdd.rgb, 0.0, 1.0);
}
else color *= mix(1.0, 0.55 + 0.45 * shadow, u_shadowStrength);
}
if (u_shininess > 0.0) {
vec3 h = normalize(toLight + toEye);
color += u_specular * u_lightColor * pow(max(dot(n, h), 0.0), u_shininess);
vec3 h = normalize(toLight + toEye);
float ndh = max(dot(n, h), 0.0);
if (u_lightingModel == 2) {
if (u_shininess > 0.0) color += u_specular * smoothstep(0.90, 0.93, pow(ndh, u_shininess * 0.25)) * 0.6 * lit;
} else if (u_lightingModel == 3) {
float fresnel = 0.04 + 0.96 * pow(1.0 - max(dot(h, toEye), 0.0), 5.0);
float gloss = max(u_shininess, 12.0);
color += (u_specular + 0.08) * u_lightColor * pow(ndh, gloss) * (gloss + 8.0) / 25.0 * fresnel * lit;
} else if (u_shininess > 0.0) {
color += u_specular * u_lightColor * pow(ndh, u_shininess) * (u_lightingModel == 1 ? lit : 1.0);
}
if (u_rimStrength > 0.0) {
float rim = u_lightingModel == 2 ? smoothstep(0.62, 0.70, 1.0 - ndv) : pow(1.0 - ndv, 3.0);
float facing = 0.35 + 0.65 * clamp(dot(n, normalize(toLight + vec3(0.0, 0.0, -0.5))) + 0.5, 0.0, 1.0);
color += u_rimColor * rim * facing * u_rimStrength * (0.4 + 0.6 * lit);
}
gl_FragColor = vec4(clamp(color, 0.0, 1.0), alpha);
}
)";
} // namespace
// MMD-style ink lines: back faces pushed outwards along the screen-space normal, so the
// width stays constant in pixels regardless of distance.
const char* kEdgeVertex = R"(
attribute float a_edgeScale;
uniform float u_edgeSize;
uniform float u_edgeWidth; // global multiplier: pixels per edge-size unit at 720p height
void main() {
vec4 pos;
vec3 nrm;
skinnedVertex(pos, nrm);
vec4 clip = gl_ProjectionMatrix * (gl_ModelViewMatrix * pos);
vec2 dir = (gl_ProjectionMatrix * vec4(gl_NormalMatrix * nrm, 0.0)).xy;
float len = length(dir);
// Thin edges are kept near a pixel wide; sub-pixel lines break up into dots.
float width = u_edgeSize * a_edgeScale;
width = width > 0.0 ? max(width * u_edgeWidth, 0.8) : 0.0;
if (len > 1e-6) {
dir /= len;
float aspect = abs(gl_ProjectionMatrix[1][1] / gl_ProjectionMatrix[0][0]);
dir.x /= aspect;
clip.xy += dir * (width * (2.0 / 720.0)) * clip.w;
}
gl_Position = clip;
}
)";
osg::ref_ptr<osg::Program> createModelProgram() {
const char* kEdgeFragment = R"(
uniform vec4 u_edgeColor;
void main() { gl_FragColor = u_edgeColor; }
)";
const char* kDepthVertex = R"(
varying vec2 v_uv;
void main() {
vec4 pos;
vec3 nrm;
skinnedVertex(pos, nrm);
v_uv = gl_MultiTexCoord0.xy;
gl_Position = gl_ModelViewProjectionMatrix * pos;
}
)";
const char* kDepthFragment = R"(
uniform sampler2D u_texture;
uniform int u_useTexture;
uniform int u_castShadow;
uniform vec4 u_diffuse;
varying vec2 v_uv;
void main() {
if (u_castShadow == 0) discard;
float alpha = u_diffuse.a;
if (u_useTexture == 1) alpha *= texture2D(u_texture, v_uv).a;
if (alpha < 0.5) discard;
gl_FragColor = vec4(1.0);
}
)";
const char* kGroundVertex = R"(
varying vec3 v_viewPos;
void main() {
vec4 viewPos = gl_ModelViewMatrix * gl_Vertex;
v_viewPos = viewPos.xyz;
gl_Position = gl_ProjectionMatrix * viewPos;
}
)";
const char* kGroundFragment = R"(
uniform float u_groundShadowOpacity;
varying vec3 v_viewPos;
void main() {
float shade = 1.0 - shadowFactor(v_viewPos, 1.0);
if (shade <= 0.0) discard;
gl_FragColor = vec4(0.0, 0.0, 0.0, shade * u_groundShadowOpacity);
}
)";
osg::ref_ptr<osg::Program> makeProgram(const char* name, const std::string& vertex, const std::string& fragment,
bool skinned) {
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));
program->setName(name);
const std::string header = "#version 120\n";
program->addShader(new osg::Shader(osg::Shader::VERTEX, header + (skinned ? kSkinning : "") + vertex));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, header + fragment));
if (skinned) {
program->addBindAttribLocation("a_boneIndices", kBoneIndexAttrib);
program->addBindAttribLocation("a_boneWeights", kBoneWeightAttrib);
}
return program;
}
} // namespace
osg::ref_ptr<osg::Program> createModelProgram() {
return makeProgram("ModelProgram", kModelVertex, std::string(kShadowLookup) + kModelFragment, true);
}
osg::ref_ptr<osg::Program> createEdgeProgram() {
osg::ref_ptr<osg::Program> program = makeProgram("EdgeProgram", kEdgeVertex, kEdgeFragment, true);
program->addBindAttribLocation("a_edgeScale", kEdgeScaleAttrib);
return program;
}
osg::ref_ptr<osg::Program> createShadowDepthProgram() {
return makeProgram("ShadowDepthProgram", kDepthVertex, kDepthFragment, true);
}
osg::ref_ptr<osg::Program> createGroundShadowProgram() {
return makeProgram("GroundShadowProgram", kGroundVertex, std::string(kShadowLookup) + kGroundFragment, false);
}
} // namespace mr
+16
View File
@@ -4,6 +4,22 @@
namespace mr {
// Generic attribute slots for skinning data; 6 and 7 do not alias any fixed-function attribute.
constexpr unsigned kBoneIndexAttrib = 6;
constexpr unsigned kBoneWeightAttrib = 7;
constexpr unsigned kBoneTextureUnit = 3;
constexpr int kBonesPerTextureRow = 1024;
constexpr unsigned kEdgeScaleAttrib = 5;
constexpr unsigned kShadowTextureUnit = 4;
// Node-mask bit the shadow pass draws; nodes without it do not cast shadows.
constexpr unsigned kShadowCasterMask = 0x4;
osg::ref_ptr<osg::Program> createModelProgram();
// Outline pass for materials with MMD edges.
osg::ref_ptr<osg::Program> createEdgeProgram();
// Depth-only pass that renders shadow casters from the light.
osg::ref_ptr<osg::Program> createShadowDepthProgram();
// Transparent floor that only shows shadows (used when no stage is visible).
osg::ref_ptr<osg::Program> createGroundShadowProgram();
} // namespace mr
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <osg/Vec3f>
namespace mr {
// Scene-wide visual settings shown in the Look panel and saved in scene files.
struct LookSettings {
int shading = 0; // 0 MMD toon, 1 Lambert, 2 anime cel, 3 soft studio
osg::Vec3f lightColor{0.6f, 0.6f, 0.6f};
float lightAzimuth = -45.f; // degrees around +Z; direction the light comes from
float lightElevation = 54.7f; // degrees above the floor
bool lightFollowsCamera = false;
bool outlines = true;
float outlineWidth = 1.f;
bool shadows = true;
int shadowQuality = 1; // 0 low (1024), 1 medium (2048), 2 high (4096)
float shadowSoftness = 1.5f;
float shadowStrength = 0.65f;
bool stageShadows = false; // stages cast shadows too (costly on old GPUs)
bool groundShadow = true; // shadow-only floor when no stage is visible
float groundShadowOpacity = 0.45f;
float rimStrength = 0.f;
osg::Vec3f rimColor{1.f, 1.f, 1.f};
// Post-processing; with all of it off the scene is drawn directly, at no extra cost.
bool bloom = false;
float bloomStrength = 0.4f;
float bloomThreshold = 0.8f;
float bloomRadius = 1.f;
bool ambientOcclusion = false;
float aoStrength = 1.f;
float aoRadius = 1.5f; // world units; a character is about 20 tall
int toneMapping = 0; // 0 off, 1 filmic
float exposure = 1.f;
float contrast = 1.f;
float saturation = 1.f;
float temperature = 0.f; // -1 cool .. 1 warm
float vignette = 0.f;
bool fxaa = false;
};
} // namespace mr
+291
View File
@@ -0,0 +1,291 @@
#include "scene/SceneFile.h"
#include "model/PathUtil.h"
#include <nlohmann/json.hpp>
#include <algorithm>
#include <filesystem>
#include <fstream>
namespace fs = std::filesystem;
using json = nlohmann::ordered_json;
namespace mr {
namespace {
json vec(const osg::Vec3f& v) { return json::array({v.x(), v.y(), v.z()}); }
json vec(const osg::Vec3d& v) { return json::array({v.x(), v.y(), v.z()}); }
const char* const kShadingNames[] = {"toon", "lambert", "cel", "soft"};
int shadingFromName(const std::string& name) {
for (int i = 0; i < 4; ++i)
if (name == kShadingNames[i]) return i;
return 0;
}
template <typename V>
void readVec(const json& j, const char* key, V& out) {
auto it = j.find(key);
if (it == j.end() || !it->is_array() || it->size() != 3) return;
for (int i = 0; i < 3; ++i) out[i] = (*it)[i].get<typename V::value_type>();
}
template <typename T>
void read(const json& j, const char* key, T& out) {
auto it = j.find(key);
if (it != j.end() && !it->is_null()) out = it->get<T>();
}
// Relative to the scene's folder when possible, always with forward slashes.
std::string relativePath(const std::string& path, const fs::path& baseDir) {
if (path.empty()) return {};
std::error_code ec;
const fs::path p = pathFromUtf8(path);
fs::path rel = fs::relative(p, baseDir, ec);
if (ec || rel.empty() || p.root_name() != baseDir.root_name()) rel = p;
std::string out = pathToUtf8(rel);
std::replace(out.begin(), out.end(), '\\', '/');
return out;
}
std::string absolutePath(const std::string& stored, const fs::path& baseDir) {
if (stored.empty()) return {};
fs::path p = pathFromUtf8(stored);
if (p.is_relative()) p = baseDir / p;
return pathToUtf8(p.lexically_normal().make_preferred());
}
} // namespace
bool saveScene(const Scene& scene, const std::string& path, std::string& error) {
std::error_code ec;
const fs::path file = fs::absolute(pathFromUtf8(path), ec);
const fs::path dir = file.parent_path();
json j;
j["format"] = "mr-scene";
j["version"] = kSceneFormatVersion;
json models = json::array();
for (const SceneModel& m : scene.models) {
json jm;
jm["path"] = relativePath(m.path, dir);
jm["stage"] = m.stage;
jm["visible"] = m.visible;
jm["position"] = vec(m.position);
jm["rotationY"] = m.rotationY;
jm["scale"] = m.scale;
if (!m.motionPath.empty()) jm["motion"] = relativePath(m.motionPath, dir);
json poses = json::object();
for (const auto& [name, pose] : m.bonePoses)
poses[name] = {{"rotation", vec(pose.eulerDegrees)}, {"translation", vec(pose.translation)}};
if (!poses.empty()) jm["bones"] = poses;
json morphs = json::object();
for (const auto& [name, weight] : m.morphWeights) morphs[name] = weight;
if (!morphs.empty()) jm["morphs"] = morphs;
models.push_back(jm);
}
j["models"] = models;
j["activeModel"] = scene.activeModel;
j["timeline"] = {{"frame", scene.frame}, {"loop", scene.loop}};
if (!scene.cameraMotionPath.empty()) j["timeline"]["camera"] = relativePath(scene.cameraMotionPath, dir);
j["timeline"]["followCamera"] = scene.followCamera;
j["timeline"]["cameraFit"] = {{"madeForHeight", scene.cameraMadeFor},
{"heightScale", scene.cameraHeightScale},
{"distance", scene.cameraDistance},
{"offset", vec(scene.cameraOffset)},
{"followModel", scene.cameraFollowModel}};
if (!scene.audioPath.empty()) j["timeline"]["audio"] = relativePath(scene.audioPath, dir);
j["timeline"]["volume"] = scene.volume;
if (scene.view.valid)
j["view"] = {{"eye", vec(scene.view.eye)}, {"center", vec(scene.view.center)}, {"up", vec(scene.view.up)}};
j["settings"] = {{"grid", scene.showGrid},
{"physics", scene.physics},
{"ik", scene.ik},
{"gpuSkinning", scene.gpuSkinning},
{"skeleton", scene.skeleton},
{"wireframe", scene.wireframe},
{"backfaceCulling", scene.backfaceCulling},
{"lightFollowsCamera", scene.look.lightFollowsCamera},
{"shading", kShadingNames[std::clamp(scene.look.shading, 0, 3)]}};
const LookSettings& look = scene.look;
j["look"] = {{"lightColor", vec(look.lightColor)},
{"lightAzimuth", look.lightAzimuth},
{"lightElevation", look.lightElevation},
{"outlines", look.outlines},
{"outlineWidth", look.outlineWidth},
{"shadows", look.shadows},
{"shadowQuality", look.shadowQuality},
{"shadowSoftness", look.shadowSoftness},
{"shadowStrength", look.shadowStrength},
{"stageShadows", look.stageShadows},
{"groundShadow", look.groundShadow},
{"groundShadowOpacity", look.groundShadowOpacity},
{"rimStrength", look.rimStrength},
{"rimColor", vec(look.rimColor)},
{"bloom", look.bloom},
{"bloomStrength", look.bloomStrength},
{"bloomThreshold", look.bloomThreshold},
{"bloomRadius", look.bloomRadius},
{"ambientOcclusion", look.ambientOcclusion},
{"aoStrength", look.aoStrength},
{"aoRadius", look.aoRadius},
{"toneMapping", look.toneMapping == 1 ? "filmic" : "off"},
{"exposure", look.exposure},
{"contrast", look.contrast},
{"saturation", look.saturation},
{"temperature", look.temperature},
{"vignette", look.vignette},
{"fxaa", look.fxaa}};
j["render"] = {{"width", scene.renderWidth},
{"height", scene.renderHeight},
{"transparent", scene.renderTransparent},
{"mp4", scene.renderMp4},
{"audio", scene.renderAudio}};
const fs::path tmp = fs::path(file).concat(".tmp");
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
if (!out) {
error = "Cannot write " + path;
return false;
}
out << j.dump(2) << "\n";
if (!out) {
error = "Failed writing " + path;
return false;
}
}
fs::rename(tmp, file, ec); // replace atomically so a failed save never truncates the old scene
if (ec) {
fs::remove(tmp, ec);
error = "Cannot replace " + path + ": " + ec.message();
return false;
}
return true;
}
bool loadScene(const std::string& path, Scene& scene, std::string& error) {
std::vector<uint8_t> bytes;
if (!readFileBytes(path, bytes)) {
error = "Cannot read " + path;
return false;
}
json j = json::parse(bytes.begin(), bytes.end(), nullptr, false);
if (j.is_discarded() || !j.is_object()) {
error = path + " is not a valid scene file";
return false;
}
if (j.value("format", std::string()) != "mr-scene") {
error = path + " is not a model renderer scene";
return false;
}
if (j.value("version", 0) > kSceneFormatVersion) {
error = path + " was saved by a newer version of the program";
return false;
}
std::error_code ec;
const fs::path dir = fs::absolute(pathFromUtf8(path), ec).parent_path();
try {
scene = Scene();
for (const json& jm : j.value("models", json::array())) {
SceneModel m;
m.path = absolutePath(jm.value("path", std::string()), dir);
read(jm, "stage", m.stage);
read(jm, "visible", m.visible);
readVec(jm, "position", m.position);
read(jm, "rotationY", m.rotationY);
read(jm, "scale", m.scale);
if (!(m.scale > 0.f)) m.scale = 1.f;
m.motionPath = absolutePath(jm.value("motion", std::string()), dir);
if (auto it = jm.find("bones"); it != jm.end() && it->is_object())
for (const auto& [name, jp] : it->items()) {
BonePose pose;
readVec(jp, "rotation", pose.eulerDegrees);
readVec(jp, "translation", pose.translation);
m.bonePoses.emplace_back(name, pose);
}
if (auto it = jm.find("morphs"); it != jm.end() && it->is_object())
for (const auto& [name, w] : it->items()) m.morphWeights.emplace_back(name, w.get<float>());
if (!m.path.empty()) scene.models.push_back(std::move(m));
}
read(j, "activeModel", scene.activeModel);
if (auto it = j.find("timeline"); it != j.end() && it->is_object()) {
read(*it, "frame", scene.frame);
read(*it, "loop", scene.loop);
scene.cameraMotionPath = absolutePath(it->value("camera", std::string()), dir);
read(*it, "followCamera", scene.followCamera);
if (auto fit = it->find("cameraFit"); fit != it->end() && fit->is_object()) {
read(*fit, "madeForHeight", scene.cameraMadeFor);
read(*fit, "heightScale", scene.cameraHeightScale);
read(*fit, "distance", scene.cameraDistance);
readVec(*fit, "offset", scene.cameraOffset);
read(*fit, "followModel", scene.cameraFollowModel);
}
scene.audioPath = absolutePath(it->value("audio", std::string()), dir);
read(*it, "volume", scene.volume);
}
if (auto it = j.find("view"); it != j.end() && it->is_object()) {
readVec(*it, "eye", scene.view.eye);
readVec(*it, "center", scene.view.center);
readVec(*it, "up", scene.view.up);
scene.view.valid = true;
}
if (auto it = j.find("settings"); it != j.end() && it->is_object()) {
read(*it, "grid", scene.showGrid);
read(*it, "physics", scene.physics);
read(*it, "ik", scene.ik);
read(*it, "gpuSkinning", scene.gpuSkinning);
read(*it, "skeleton", scene.skeleton);
read(*it, "wireframe", scene.wireframe);
read(*it, "backfaceCulling", scene.backfaceCulling);
read(*it, "lightFollowsCamera", scene.look.lightFollowsCamera);
scene.look.shading = shadingFromName(it->value("shading", std::string("toon")));
}
if (auto it = j.find("look"); it != j.end() && it->is_object()) {
LookSettings& look = scene.look;
readVec(*it, "lightColor", look.lightColor);
read(*it, "lightAzimuth", look.lightAzimuth);
read(*it, "lightElevation", look.lightElevation);
read(*it, "outlines", look.outlines);
read(*it, "outlineWidth", look.outlineWidth);
read(*it, "shadows", look.shadows);
read(*it, "shadowQuality", look.shadowQuality);
read(*it, "shadowSoftness", look.shadowSoftness);
read(*it, "shadowStrength", look.shadowStrength);
read(*it, "stageShadows", look.stageShadows);
read(*it, "groundShadow", look.groundShadow);
read(*it, "groundShadowOpacity", look.groundShadowOpacity);
read(*it, "rimStrength", look.rimStrength);
readVec(*it, "rimColor", look.rimColor);
read(*it, "bloom", look.bloom);
read(*it, "bloomStrength", look.bloomStrength);
read(*it, "bloomThreshold", look.bloomThreshold);
read(*it, "bloomRadius", look.bloomRadius);
read(*it, "ambientOcclusion", look.ambientOcclusion);
read(*it, "aoStrength", look.aoStrength);
read(*it, "aoRadius", look.aoRadius);
look.toneMapping = it->value("toneMapping", std::string("off")) == "filmic" ? 1 : 0;
read(*it, "exposure", look.exposure);
read(*it, "contrast", look.contrast);
read(*it, "saturation", look.saturation);
read(*it, "temperature", look.temperature);
read(*it, "vignette", look.vignette);
read(*it, "fxaa", look.fxaa);
}
if (auto it = j.find("render"); it != j.end() && it->is_object()) {
read(*it, "width", scene.renderWidth);
read(*it, "height", scene.renderHeight);
read(*it, "transparent", scene.renderTransparent);
read(*it, "mp4", scene.renderMp4);
read(*it, "audio", scene.renderAudio);
}
} catch (const json::exception& e) {
error = path + ": " + e.what();
return false;
}
return true;
}
} // namespace mr
+60
View File
@@ -0,0 +1,60 @@
#pragma once
// Scene files (.mrscene): which models, stages, motions and audio make up a scene, how they are
// placed and posed, and the editor's view settings. JSON, with file paths stored relative to the
// scene file so a project folder can be moved or shared as a whole.
#include "model/Poser.h"
#include "scene/LookSettings.h"
#include <osg/Vec3d>
#include <osg/Vec3f>
#include <string>
#include <utility>
#include <vector>
namespace mr {
struct SceneModel {
std::string path; // absolute in memory
bool stage = false, visible = true;
osg::Vec3f position;
float rotationY = 0.f; // degrees
float scale = 1.f;
std::string motionPath;
std::vector<std::pair<std::string, BonePose>> bonePoses; // by bone name; non-rest poses only
std::vector<std::pair<std::string, float>> morphWeights; // by morph name; non-zero only
};
struct SceneView {
bool valid = false;
osg::Vec3d eye, center, up{0.0, 0.0, 1.0};
};
struct Scene {
std::vector<SceneModel> models;
int activeModel = -1;
std::string cameraMotionPath, audioPath;
float frame = 0.f;
bool loop = true, followCamera = true;
// Camera motion fit: heights scale by cameraHeightScale, shots move closer/farther by
// cameraDistance, then everything shifts by cameraOffset (model space, Y up).
float cameraMadeFor = 20.f, cameraHeightScale = 1.f, cameraDistance = 1.f;
osg::Vec3d cameraOffset;
bool cameraFollowModel = true;
float volume = 1.f;
SceneView view;
bool showGrid = true, physics = true, ik = true, gpuSkinning = true;
bool skeleton = false, wireframe = false, backfaceCulling = true;
LookSettings look;
int renderWidth = 1920, renderHeight = 1080;
bool renderTransparent = false, renderMp4 = true, renderAudio = true;
};
constexpr int kSceneFormatVersion = 1;
bool saveScene(const Scene& scene, const std::string& path, std::string& error);
bool loadScene(const std::string& path, Scene& scene, std::string& error);
} // namespace mr
+17 -6
View File
@@ -106,8 +106,15 @@ private:
};
class EventHandler : public osgGA::GUIEventHandler {
public:
explicit EventHandler(osg::Camera* camera) : camera_(camera) {}
osg::observer_ptr<osg::Camera> camera_;
public:
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&) override {
// Events from other windows (the popped-out viewport) belong to the 3D view only.
if (camera_.valid() && ea.getGraphicsContext() && ea.getGraphicsContext() != camera_->getGraphicsContext())
return false;
if (!ImGui::GetCurrentContext()) return false;
ImGuiIO& io = ImGui::GetIO();
using E = osgGA::GUIEventAdapter;
@@ -137,16 +144,14 @@ public:
switch (ea.getEventType()) {
case E::PUSH:
case E::DOUBLECLICK: // macOS sends the second press of a double-click as DOUBLECLICK, not PUSH
case E::RELEASE: {
mousePos();
updateMods();
int b = button();
if (b >= 0) io.AddMouseButtonEvent(b, ea.getEventType() == E::PUSH);
if (b >= 0) io.AddMouseButtonEvent(b, ea.getEventType() != E::RELEASE);
return io.WantCaptureMouse;
}
case E::DOUBLECLICK:
mousePos();
return io.WantCaptureMouse;
case E::DRAG:
case E::MOVE:
mousePos();
@@ -192,7 +197,13 @@ ImGuiOsg::ImGuiOsg(DrawFunction draw) : draw_(std::move(draw)) {
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = nullptr;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
// Panel layout persists between runs.
static std::string iniPath;
const char* home = std::getenv("HOME");
if (!home) home = std::getenv("USERPROFILE");
iniPath = home ? std::string(home) + "/.model_renderer_layout.ini" : "model_renderer_layout.ini";
io.IniFilename = iniPath.c_str();
#if !defined(_WIN32) && !defined(__APPLE__)
ImGuiPlatformIO& platformIo = ImGui::GetPlatformIO();
platformIo.Platform_GetClipboardTextFn = getClipboardText;
@@ -256,7 +267,7 @@ void ImGuiOsg::setUiScale(float scale) {
void ImGuiOsg::attach(osgViewer::Viewer& viewer) {
camera_ = viewer.getCamera();
viewer.setRealizeOperation(new InitOperation(this));
viewer.addEventHandler(new EventHandler);
viewer.addEventHandler(new EventHandler(viewer.getCamera()));
viewer.getCamera()->setFinalDrawCallback(new DrawCallback(this));
}
Binary file not shown.
Binary file not shown.
+308
View File
@@ -1,10 +1,14 @@
// Loader and posing tests. Test models are generated by tools/make_test_models.py.
#include "model/ModelLoader.h"
#include "audio/AudioPlayer.h"
#include "model/Motion.h"
#include "model/PathUtil.h"
#include "model/Poser.h"
#include "scene/SceneFile.h"
#include <cmath>
#include <cstdio>
#include <filesystem>
#include <string>
namespace {
@@ -89,6 +93,37 @@ void testPmx() {
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));
// Hardware mode: emulating the vertex shader (texel k = column k of the bone matrix) on the
// CPU-provided skin matrices and morphed positions must match software skinning.
poser.morphWeights()[0] = 0.5f;
poser.update();
mr::Poser gpu(model);
gpu.setSkinningMode(mr::SkinningMode::Hardware);
gpu.bonePoses() = poser.bonePoses();
gpu.morphWeights() = poser.morphWeights();
CHECK(gpu.update());
CHECK(gpu.morphsChangedInLastUpdate());
float maxErr = 0.f;
for (size_t i = 0; i < model->vertices.size(); ++i) {
const mr::Vertex& v = model->vertices[i];
const osg::Vec4f pos(gpu.morphedPositions()[i], 1.f);
osg::Vec3f p = gpu.morphedPositions()[i];
if (v.bones[0] >= 0) {
p.set(0, 0, 0);
for (int k = 0; k < 4; ++k) {
if (v.bones[k] < 0) continue;
const osg::Matrixf& m = gpu.skinMatrices()[v.bones[k]];
for (int c = 0; c < 3; ++c)
p[c] += v.weights[k] * (pos * osg::Vec4f(m(0, c), m(1, c), m(2, c), m(3, c)));
}
}
maxErr = std::max(maxErr, (p - poser.positions()[i]).length());
}
CHECK(maxErr < 1e-4f);
gpu.bonePoses()[1].eulerDegrees.set(0, 0, 45);
CHECK(gpu.update());
CHECK(!gpu.morphsChangedInLastUpdate());
}
void testPmd() {
@@ -122,6 +157,104 @@ void testPmd() {
CHECK(near(poser.positions()[16], osg::Vec3f(-5, 6, 1), 1e-3f));
}
// column.pmx: IK bone at (0, 10, 0) pulls the eye (0, 9, 0) via the upper body (pivot (0, 5, 0)),
// limited to [-1, 1] rad about X.
void testIk() {
auto model = load("column.pmx");
CHECK(model);
if (!model) return;
const int ik = model->findBone("IK"), upper = model->findBone("上半身"), eye = model->findBone("目");
CHECK(ik >= 0 && model->bones[ik].isIK && model->bones[ik].ikTarget == eye);
CHECK(model->bones[ik].ikLinks.size() == 1 && model->bones[ik].ikLinks[0].bone == upper);
CHECK(near(model->bones[ik].ikLinks[0].lower.x(), -1.f) && near(model->bones[ik].ikLinks[0].upper.x(), 1.f));
if (ik < 0 || upper < 0 || eye < 0) return;
mr::Poser poser(model);
poser.update();
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);
auto reach = [&](float deg) {
const float a = osg::DegreesToRadians(deg);
poser.bonePoses()[ik].translation.set(0, 5 * std::cos(a) - 5, 5 * std::sin(a));
poser.update();
return poser.boneGlobals()[eye].getTrans();
};
const float a30 = osg::DegreesToRadians(30.f);
CHECK(near(reach(30), osg::Vec3f(0, 5 + 4 * std::cos(a30), 4 * std::sin(a30)), 1e-2f));
CHECK(near(reach(80), osg::Vec3f(0, 5 + 4 * std::cos(1.f), 4 * std::sin(1.f)), 1e-2f)); // clamped at 1 rad
poser.setIkEnabled(false);
poser.update();
CHECK(near(poser.boneGlobals()[eye].getTrans(), osg::Vec3f(0, 9, 0)));
}
void testVmd() {
mr::BezierCurve linear;
CHECK(near(linear.eval(0.5f), 0.5f, 1e-3f));
mr::BezierCurve easeIn{1.f, 0.f, 1.f, 1.f};
CHECK(easeIn.eval(0.5f) < 0.4f && near(easeIn.eval(1.f), 1.f));
std::string error;
auto motion = mr::loadVmd(std::string(MR_TEST_DATA_DIR) + "/column.vmd", error);
CHECK(motion);
if (!motion) {
std::printf("loadVmd failed: %s\n", error.c_str());
return;
}
CHECK(motion->modelName == "テスト");
CHECK(motion->lastFrame == 20 && motion->boneTracks.size() == 2 && motion->morphTracks.size() == 1);
CHECK(motion->ikKeyframes.size() == 1);
auto model = load("column.pmx");
if (!model) return;
mr::MotionPlayer player(motion, *model);
CHECK(player.boundBones() == 2 && player.boundMorphs() == 1);
mr::Poser poser(model);
// Frame 5: upper body 45 deg about Z, center up 1, mouth morph 0.5, IK switched off by the motion.
player.apply(5.f, poser);
poser.update();
CHECK(poser.ikBoneEnabled()[model->findBone("IK")] == 0);
CHECK(near(poser.morphWeights()[0], 0.5f));
const float h = std::sqrt(0.5f);
CHECK(near(poser.positions()[16], osg::Vec3f(h * (1.5f - 5.f), 6.f + h * (1.5f + 5.f), 1.25f), 1e-3f));
player.apply(100.f, poser); // past the end holds the last key
poser.update();
CHECK(near(poser.positions()[16], osg::Vec3f(-5, 9, 1.5f), 1e-3f)); // morph held at 1
}
void testCameraAndAudio() {
std::vector<mr::CameraKeyframe> keys(3);
keys[0].distance = -45.f;
keys[0].target.set(0, 10, 0);
keys[1] = keys[0];
keys[1].frame = 30;
keys[1].rotation.set(0, osg::PI_2f, 0);
keys[1].fov = 50.f;
keys[2] = keys[1];
keys[2].frame = 31;
keys[2].target.set(0, 20, 0);
mr::CameraPose c = mr::evaluateCamera(keys, 0.f);
CHECK(near(c.eye, osg::Vec3f(0, 10, 45)) && near(c.center, osg::Vec3f(0, 10, 0)) && near(c.up, osg::Vec3f(0, 1, 0)));
CHECK(near(c.fov, 30.f));
c = mr::evaluateCamera(keys, 30.5f); // cut: holds frame 30
CHECK(near(c.eye, osg::Vec3f(45, 10, 0), 1e-3f) && near(c.fov, 50.f));
c = mr::evaluateCamera(keys, 15.f);
CHECK(near(c.fov, 40.f, 1e-2f) && near(c.eye.length2(), 0.f) == false);
CHECK(near((c.eye - c.center).length(), 45.f, 1e-3f));
c = mr::evaluateCamera(keys, 99.f);
CHECK(near(c.center, osg::Vec3f(0, 20, 0)));
mr::AudioPlayer audio;
std::string error;
CHECK(audio.load(std::string(MR_TEST_DATA_DIR) + "/tone.wav", error));
CHECK(near(static_cast<float>(audio.length()), 0.5f, 1e-2f));
audio.seek(0.25);
CHECK(near(static_cast<float>(audio.position()), 0.25f, 1e-2f));
CHECK(!audio.load(std::string(MR_TEST_DATA_DIR) + "/missing.wav", error));
}
void testFbx() {
auto model = load("rigged_box.fbx");
CHECK(model);
@@ -158,10 +291,185 @@ void testFbx() {
} // namespace
// A bone with a horizontal capsule hinged to a fixed body should swing down under gravity.
void testPhysics() {
auto model = std::make_shared<mr::Model>();
model->bones.resize(2);
const osg::Vec3f rootPos(0, 10, 0);
for (int i = 0; i < 2; ++i) {
mr::Bone& b = model->bones[i];
b.name = i ? "arm" : "root";
b.parent = i - 1;
b.restPosition = rootPos;
b.localBind = i ? osg::Matrixf() : osg::Matrixf::translate(rootPos);
b.inverseBind = osg::Matrixf::translate(-rootPos);
}
mr::RigidBody anchor;
anchor.bone = 0;
anchor.shape = mr::RigidShape::Sphere;
anchor.size = osg::Vec3f(0.5f, 0, 0);
anchor.position = rootPos;
anchor.collisionMask = 0;
mr::RigidBody arm;
arm.bone = 1;
arm.shape = mr::RigidShape::Capsule;
arm.size = osg::Vec3f(0.3f, 3.f, 0);
arm.position = rootPos + osg::Vec3f(2.5f, 0, 0);
arm.rotation = osg::Quat(osg::PI_2, osg::Z_AXIS); // lie along X
arm.mass = 1.f;
arm.group = 1;
arm.collisionMask = 0;
arm.mode = mr::RigidMode::Physics;
model->rigidBodies = {anchor, arm};
mr::Joint hinge;
hinge.bodyA = 0;
hinge.bodyB = 1;
hinge.position = rootPos;
hinge.angularLower = osg::Vec3f(0, 0, -3.f);
hinge.angularUpper = osg::Vec3f(0, 0, 3.f);
model->joints = {hinge};
mr::Poser poser(model);
CHECK(poser.hasPhysics());
poser.setPhysicsEnabled(false);
poser.update();
const osg::Vec3f restTip = osg::Vec3f(3, 0, 0) * poser.boneGlobals()[1];
CHECK(near(restTip.y(), 10.f));
poser.setPhysicsEnabled(true);
poser.update(); // reset + settle
for (int i = 0; i < 60; ++i) {
poser.stepPhysics(1.f / 60.f);
poser.update();
}
const osg::Vec3f tip = osg::Vec3f(3, 0, 0) * poser.boneGlobals()[1];
std::printf("physics: arm tip %.2f %.2f %.2f\n", tip.x(), tip.y(), tip.z());
CHECK(tip.y() < 8.f); // swung down
CHECK(near((tip - rootPos).length(), 3.f, 0.3f)); // still attached at the hinge
CHECK(near(poser.boneGlobals()[0].getTrans().y(), 10.f));
}
// Scene files round-trip and store paths relative to the scene file.
void testSceneFile() {
namespace fs = std::filesystem;
const fs::path dir = fs::temp_directory_path() / "mr_scene_test";
fs::remove_all(dir);
fs::create_directories(dir / "project" / "models");
mr::Scene scene;
mr::SceneModel m;
m.path = mr::pathToUtf8(dir / "project" / "models" / "ステージ.x");
m.stage = true;
m.visible = false;
m.position.set(1.f, 2.f, 3.f);
m.rotationY = 45.f;
m.scale = 10.f;
m.motionPath = mr::pathToUtf8(dir / "dance.vmd");
mr::BonePose pose;
pose.eulerDegrees.set(10.f, 20.f, 30.f);
m.bonePoses.emplace_back("頭", pose);
m.morphWeights.emplace_back("まばたき", 0.5f);
scene.models.push_back(m);
scene.activeModel = 0;
scene.frame = 120.f;
scene.audioPath = mr::pathToUtf8(dir / "project" / "song.wav");
scene.view.valid = true;
scene.view.eye.set(0, -40, 10);
scene.look.shading = 2;
scene.look.shadows = false;
scene.look.rimStrength = 0.5f;
scene.look.rimColor = osg::Vec3f(1.f, 0.5f, 0.25f);
scene.look.bloom = true;
scene.look.ambientOcclusion = true;
scene.look.toneMapping = 1;
scene.look.vignette = 0.3f;
scene.renderWidth = 1280;
scene.cameraMadeFor = 18.5f;
scene.cameraHeightScale = 1.25f;
scene.cameraOffset = osg::Vec3d(1, 2, 3);
const std::string file = mr::pathToUtf8(dir / "project" / "test.mrscene");
std::string error;
CHECK(mr::saveScene(scene, file, error));
std::vector<uint8_t> bytes;
CHECK(mr::readFileBytes(file, bytes));
const std::string text(bytes.begin(), bytes.end());
CHECK(text.find("\"models/ステージ.x\"") != std::string::npos);
CHECK(text.find("\"../dance.vmd\"") != std::string::npos);
mr::Scene loaded;
CHECK(mr::loadScene(file, loaded, error));
CHECK(loaded.models.size() == 1);
CHECK(near(loaded.cameraMadeFor, 18.5f) && near(loaded.cameraHeightScale, 1.25f) && near(loaded.cameraDistance, 1.f));
CHECK(loaded.cameraOffset == osg::Vec3d(1, 2, 3));
if (loaded.models.size() == 1) {
const mr::SceneModel& l = loaded.models[0];
CHECK(fs::equivalent(mr::pathFromUtf8(l.path).parent_path(), dir / "project" / "models"));
CHECK(mr::pathToUtf8(mr::pathFromUtf8(l.path).filename()) == "ステージ.x");
CHECK(fs::path(mr::pathFromUtf8(l.motionPath)).lexically_normal() == (dir / "dance.vmd").lexically_normal());
CHECK(l.stage && !l.visible);
CHECK(near(l.position, osg::Vec3f(1.f, 2.f, 3.f)) && near(l.rotationY, 45.f) && near(l.scale, 10.f));
CHECK(l.bonePoses.size() == 1 && l.bonePoses[0].first == "頭" &&
near(l.bonePoses[0].second.eulerDegrees, osg::Vec3f(10.f, 20.f, 30.f)));
CHECK(l.morphWeights.size() == 1 && l.morphWeights[0].first == "まばたき" && near(l.morphWeights[0].second, 0.5f));
}
CHECK(loaded.activeModel == 0 && near(loaded.frame, 120.f) && loaded.view.valid && loaded.view.eye.y() == -40.0);
CHECK(loaded.look.shading == 2 && loaded.renderWidth == 1280);
CHECK(!loaded.look.shadows && loaded.look.outlines && std::abs(loaded.look.rimStrength - 0.5f) < 1e-6f);
CHECK(std::abs(loaded.look.rimColor.y() - 0.5f) < 1e-6f);
CHECK(loaded.look.bloom && loaded.look.ambientOcclusion && loaded.look.toneMapping == 1 && !loaded.look.fxaa);
CHECK(std::abs(loaded.look.vignette - 0.3f) < 1e-6f);
CHECK(!loaded.audioPath.empty() && loaded.cameraMotionPath.empty());
const std::string bad = mr::pathToUtf8(dir / "bad.mrscene");
{ std::FILE* f = std::fopen(bad.c_str(), "wb"); std::fputs("{\"format\":\"other\"}", f); std::fclose(f); }
CHECK(!mr::loadScene(bad, loaded, error));
fs::remove_all(dir);
}
// UV morphs offset the main UVs; material morphs combine as base * mul + add, like MMD.
void testUvAndMaterialMorphs() {
auto model = load("column.pmx");
mr::Morph uv;
uv.type = mr::MorphType::UV;
uv.uvOffsets.push_back({16, osg::Vec2f(0.25f, -0.5f)});
model->morphs.push_back(uv);
mr::Morph mat;
mat.type = mr::MorphType::Material;
mr::MaterialMorphOffset fade; // multiply every material's alpha toward 0
fade.diffuse = osg::Vec4f(1, 1, 1, 0);
fade.specular = fade.ambient = osg::Vec3f(1, 1, 1);
fade.shininess = fade.edgeSize = 1.f;
fade.edgeColor = fade.textureTint = fade.sphereTint = fade.toonTint = osg::Vec4f(1, 1, 1, 1);
mr::MaterialMorphOffset tint; // add red to material 0's texture
tint.material = 0;
tint.op = mr::MaterialMorphOp::Add;
tint.textureTint = osg::Vec4f(0.2f, 0, 0, 0);
mat.materialOffsets = {fade, tint};
model->morphs.push_back(mat);
const int uvMorph = static_cast<int>(model->morphs.size()) - 2, matMorph = uvMorph + 1;
mr::Poser poser(model);
poser.update();
CHECK((poser.morphedUvs()[16] - model->vertices[16].uv).length() < 1e-6f);
CHECK(poser.materialStates()[0].diffuse == model->materials[0].diffuse);
poser.morphWeights()[uvMorph] = 1.f;
poser.morphWeights()[matMorph] = 0.5f;
poser.update();
CHECK((poser.morphedUvs()[16] - (model->vertices[16].uv + osg::Vec2f(0.25f, -0.5f))).length() < 1e-6f);
for (size_t i = 0; i < model->materials.size(); ++i)
CHECK(std::abs(poser.materialStates()[i].diffuse.a() - model->materials[i].diffuse.a() * 0.5f) < 1e-6f);
CHECK(std::abs(poser.materialStates()[0].textureAdd.x() - 0.1f) < 1e-6f);
CHECK(poser.materialStates()[0].textureMul == osg::Vec4f(1, 1, 1, 1));
}
int main() {
testPmx();
testUvAndMaterialMorphs();
testPmd();
testFbx();
testIk();
testVmd();
testCameraAndAudio();
testPhysics();
testSceneFile();
if (g_failures == 0) std::printf("All tests passed\n");
return g_failures == 0 ? 0 : 1;
}
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Writes VMD motions: tests/data/column.vmd for the unit tests, or a demo dance for MMD-rigged
models with --demo OUT (standard Japanese bone/morph names; unknown names are ignored)."""
import math
import os
import struct
import sys
LINEAR = bytes([20] * 8 + [107] * 8) + bytes(48)
def name(s, n):
b = s.encode("cp932")[:n]
return b + b"\0" * (n - len(b))
def quat(axis, deg):
# Right-handed rotation converted to MMD's left-handed space: (x, y, z, w) -> (-x, -y, z, w).
s, c = math.sin(math.radians(deg) / 2), math.cos(math.radians(deg) / 2)
x, y, z = (a * s for a in axis)
return (-x, -y, z, c)
def bone(nm, frame, pos=(0, 0, 0), rot=(0, 0, 0, 1)):
# pos is right-handed (+Z = forward), stored left-handed.
return name(nm, 15) + struct.pack("<I3f4f", frame, pos[0], pos[1], -pos[2], *rot) + LINEAR
def write(path, model, bones, morphs, iks=()):
out = b"Vocaloid Motion Data 0002".ljust(30, b"\0") + name(model, 20)
out += struct.pack("<I", len(bones)) + b"".join(bones)
out += struct.pack("<I", len(morphs)) + b"".join(name(n, 15) + struct.pack("<If", f, w) for n, f, w in morphs)
out += struct.pack("<III", 0, 0, 0) # camera, light, self shadow
out += struct.pack("<I", len(iks))
for frame, states in iks:
out += struct.pack("<IBI", frame, 1, len(states))
out += b"".join(name(n, 20) + bytes([on]) for n, on in states)
with open(path, "wb") as f:
f.write(out)
def column(path):
bones = [bone("上半身", 0), bone("上半身", 10, rot=quat((0, 0, 1), 90)), bone("上半身", 20, rot=quat((0, 0, 1), 90)),
bone("センター", 0), bone("センター", 10, pos=(0, 2, 0))]
write(path, "テスト", bones, [("あ", 0, 0.0), ("あ", 10, 1.0)], [(0, [("IK", 0)])])
def demo(path):
bones, morphs = [], []
for f in range(0, 121, 15):
down = (f // 15) % 2 == 1
bones.append(bone("センター", f, pos=(0, -0.8 if down else 0, 0)))
bones.append(bone("左腕", f, rot=quat((0, 0, 1), -35 if down else -20)))
bones.append(bone("右腕", f, rot=quat((0, 0, 1), 35 if down else 20)))
bones.append(bone("頭", f, rot=quat((1, 0, 0), 10 if down else -5)))
morphs += [("あ", f, 0.8 if down else 0.0)]
bones += [bone("左足IK", 0), bone("左足IK", 30, pos=(0, 1.5, 1.5)), bone("左足IK", 60),
bone("右足IK", 60), bone("右足IK", 90, pos=(0, 1.5, 1.5)), bone("右足IK", 120)]
for blink in ("まばたき", "blink"):
morphs += [(blink, 40, 0.0), (blink, 44, 1.0), (blink, 48, 0.0)]
write(path, "demo", bones, morphs)
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "--demo":
demo(sys.argv[2])
else:
column(os.path.join(os.path.dirname(__file__), "..", "tests", "data", "column.vmd"))