Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21d0910e8e | ||
|
|
73834b8c70 | ||
|
|
dc9d9fa46e | ||
|
|
302e7c4f20 | ||
|
|
799c4ac344 | ||
|
|
e786a88dec | ||
|
|
637a2c12f2 | ||
|
|
4b33a676eb | ||
|
|
5be372d773 | ||
|
|
fd6f56826e | ||
|
|
bb6f154d60 | ||
|
|
2c625254f3 | ||
|
|
33458062ff | ||
|
|
3154e4fab9 | ||
|
|
30d8c98891 | ||
|
|
6a1c1e409f | ||
|
|
269e107b70 | ||
|
|
a48caace28 | ||
|
|
2e2551c0ec | ||
|
|
2ab57412ca | ||
|
|
ba6fafc344 | ||
|
|
0d44e05fe9 | ||
|
|
637b8ef220 | ||
|
|
9d22dc687b | ||
|
|
935203f11a | ||
|
|
becfb7b7e8 | ||
|
|
b3d0afdd24 |
No files matched your search
+48
-2
@@ -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)
|
||||
@@ -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
|
||||
@@ -77,10 +104,14 @@ add_library(mr_core STATIC
|
||||
src/model/AssimpLoader.cpp
|
||||
src/model/ModelLoader.cpp
|
||||
src/model/Poser.cpp
|
||||
src/model/Motion.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()
|
||||
@@ -107,12 +138,27 @@ add_executable(model_renderer
|
||||
src/app/FileBrowser.cpp
|
||||
src/app/Timeline.cpp
|
||||
src/app/Render.cpp
|
||||
src/app/SceneIo.cpp
|
||||
src/render/Grid.cpp
|
||||
src/render/ModelNode.cpp
|
||||
src/render/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 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)
|
||||
|
||||
@@ -30,7 +30,7 @@ Supported: textures (incl. MMD sphere `.sph`/`.spa` and toon maps), vertex/group
|
||||
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:
|
||||
physics, VMD light/self-shadow, UV and material morphs, edge outlines.
|
||||
VMD light/self-shadow keys, UV and material morphs.
|
||||
|
||||
## Building
|
||||
|
||||
@@ -112,8 +112,22 @@ the **Timeline** at the bottom and the 3D view in the middle. Drag a panel's tab
|
||||
float it; the layout is saved to `~/.model_renderer_layout.ini` (**View > Reset panel layout**
|
||||
restores the default).
|
||||
|
||||
* **File > Open** (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.
|
||||
* **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.
|
||||
@@ -122,12 +136,35 @@ restores the default).
|
||||
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.
|
||||
* **View**: skeleton overlay, wireframe, culling, MMD toon vs Lambert shading, GPU vs CPU skinning,
|
||||
* **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.
|
||||
|
||||
@@ -140,6 +177,10 @@ Command-line options (`--help`) allow scripted renders, e.g.
|
||||
|
||||
`--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.
|
||||
|
||||
|
||||
+517
-55
@@ -1,7 +1,10 @@
|
||||
#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>
|
||||
@@ -39,6 +42,14 @@ 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 {
|
||||
@@ -63,9 +74,60 @@ App::App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulato
|
||||
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) {
|
||||
@@ -73,33 +135,80 @@ 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_);
|
||||
player_.reset(motion_ ? new MotionPlayer(motion_, *model) : nullptr);
|
||||
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_);
|
||||
modelNode_->setSkinningMode(skinning_ == 1 ? SkinningMode::Hardware : SkinningMode::Software);
|
||||
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) {
|
||||
@@ -118,13 +227,18 @@ bool App::loadMotion(const std::string& path) {
|
||||
if (!motion->cameraKeys.empty()) {
|
||||
camera_ = motion;
|
||||
cameraName_ = name;
|
||||
cameraPath_ = path;
|
||||
}
|
||||
if (!motion->boneTracks.empty() || !motion->morphTracks.empty() || motion->cameraKeys.empty()) {
|
||||
motion_ = motion;
|
||||
motionName_ = name;
|
||||
if (modelNode_) {
|
||||
modelNode_->poser().resetMotion();
|
||||
player_.reset(new MotionPlayer(motion_, modelNode_->model()));
|
||||
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);
|
||||
@@ -148,18 +262,27 @@ bool App::loadAudio(const std::string& path) {
|
||||
|
||||
void App::unloadMotion() {
|
||||
setPlaying(false);
|
||||
player_.reset();
|
||||
motion_.reset();
|
||||
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;
|
||||
if (modelNode_) modelNode_->poser().resetMotion();
|
||||
}
|
||||
|
||||
float App::timelineEnd() const {
|
||||
float end = 0.f;
|
||||
if (motion_) end = std::max(end, static_cast<float>(motion_->lastFrame));
|
||||
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;
|
||||
@@ -175,7 +298,14 @@ void App::setPlaying(bool playing) {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -183,18 +313,87 @@ void App::setMotionFrame(float frame) {
|
||||
}
|
||||
|
||||
void App::applyFrame() {
|
||||
if (player_ && modelNode_) player_->apply(motionFrame_, modelNode_->poser());
|
||||
for (auto& item : items_)
|
||||
if (item->player) item->player->apply(motionFrame_, item->node->poser());
|
||||
if (camera_ && useMotionCamera_) applyCamera();
|
||||
}
|
||||
|
||||
void App::applyCamera() {
|
||||
const CameraPose pose = evaluateCamera(camera_->cameraKeys, motionFrame_);
|
||||
const osg::Matrixd toWorld = osg::Matrixd::rotate(osg::PI_2, osg::X_AXIS); // as ModelNode
|
||||
manipulator_->setTransformation(osg::Vec3d(pose.eye) * toWorld, osg::Vec3d(pose.center) * toWorld,
|
||||
osg::Vec3d(pose.up) * toWorld);
|
||||
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;
|
||||
}
|
||||
@@ -205,6 +404,18 @@ void App::updatePopOut() {
|
||||
osg::Camera* master = viewer_.getCamera();
|
||||
if (popCamera_ && !(popCamera_->getGraphicsContext() && popCamera_->getGraphicsContext()->valid()))
|
||||
wantPopOut_ = false; // the window was closed
|
||||
if (wantPopOut_ && !popCamera_ && parkedPopCamera_) {
|
||||
osg::GraphicsContext* gc = parkedPopCamera_->getGraphicsContext();
|
||||
if (gc && gc->valid()) {
|
||||
// Drop events queued while hidden, such as repeated close requests.
|
||||
if (auto* window = dynamic_cast<osgViewer::GraphicsWindow*>(gc)) window->getEventQueue()->clear();
|
||||
popCamera_ = parkedPopCamera_;
|
||||
setWindowVisible(gc, true);
|
||||
viewer_.addSlave(popCamera_.get(), true);
|
||||
master->setCullMask(0);
|
||||
}
|
||||
parkedPopCamera_ = nullptr;
|
||||
}
|
||||
if (wantPopOut_ && !popCamera_) {
|
||||
osg::GraphicsContext* mainGc = master->getGraphicsContext();
|
||||
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
|
||||
@@ -228,6 +439,7 @@ void App::updatePopOut() {
|
||||
return;
|
||||
}
|
||||
gc->realize();
|
||||
prepareReusableWindow(gc.get());
|
||||
popCamera_ = new osg::Camera;
|
||||
popCamera_->setGraphicsContext(gc.get());
|
||||
popCamera_->setViewport(0, 0, traits->width, traits->height);
|
||||
@@ -237,6 +449,7 @@ void App::updatePopOut() {
|
||||
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);
|
||||
@@ -245,11 +458,15 @@ void App::updatePopOut() {
|
||||
} else if (!wantPopOut_ && popCamera_) {
|
||||
const unsigned index = viewer_.findSlaveIndexForCamera(popCamera_.get());
|
||||
if (index < viewer_.getNumSlaves()) viewer_.removeSlave(index);
|
||||
osg::ref_ptr<osg::GraphicsContext> gc = popCamera_->getGraphicsContext();
|
||||
popCamera_->setGraphicsContext(nullptr);
|
||||
if (gc && gc->valid()) gc->close();
|
||||
osg::GraphicsContext* gc = popCamera_->getGraphicsContext();
|
||||
if (gc && gc->valid()) {
|
||||
setWindowVisible(gc, false);
|
||||
parkedPopCamera_ = popCamera_;
|
||||
} else {
|
||||
popCamera_->setGraphicsContext(nullptr);
|
||||
}
|
||||
popCamera_ = nullptr;
|
||||
master->setCullMask(~0u);
|
||||
master->setCullMask(kMainViewMask | kGridNodeMask);
|
||||
}
|
||||
if (!popCamera_) return;
|
||||
const osg::GraphicsContext::Traits* traits = popCamera_->getGraphicsContext()->getTraits();
|
||||
@@ -259,6 +476,19 @@ void App::updatePopOut() {
|
||||
popCamera_->setViewMatrix(manipulator_->getInverseMatrix());
|
||||
}
|
||||
|
||||
void App::catchPopOutClose() {
|
||||
auto* window = popCamera_ ? dynamic_cast<osgViewer::GraphicsWindow*>(popCamera_->getGraphicsContext()) : nullptr;
|
||||
if (!window || !window->valid()) return;
|
||||
window->checkEvents();
|
||||
osgGA::EventQueue::Events events;
|
||||
window->getEventQueue()->takeEvents(events);
|
||||
for (const auto& event : events) {
|
||||
const osgGA::GUIEventAdapter* ea = event->asGUIEventAdapter();
|
||||
if (ea && ea->getEventType() == osgGA::GUIEventAdapter::CLOSE_WINDOW) wantPopOut_ = false;
|
||||
else window->getEventQueue()->addEvent(event.get());
|
||||
}
|
||||
}
|
||||
|
||||
void App::drawViewportOverlay() {
|
||||
if (viewRect_.z() < 8.f) return;
|
||||
ImGui::SetNextWindowPos(ImVec2(viewRect_.x() + 8.f, viewRect_.y() + 8.f));
|
||||
@@ -300,12 +530,19 @@ void App::updateProjection() {
|
||||
|
||||
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();
|
||||
if (modelNode_) modelNode_->poser().setIkEnabled(ikEnabled_);
|
||||
if (!player_ && !camera_ && !audio_.loaded()) return;
|
||||
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;
|
||||
@@ -331,13 +568,16 @@ void App::openFile(const std::string& path) {
|
||||
const size_t n = std::strlen(ext);
|
||||
return lower.size() > n && lower.compare(lower.size() - n, n, ext) == 0;
|
||||
};
|
||||
if (endsWith(".vmd")) {
|
||||
if (endsWith(".mrscene")) {
|
||||
openScene(path);
|
||||
} else if (endsWith(".vmd")) {
|
||||
loadMotion(path);
|
||||
} else if (endsWith(".wav") || endsWith(".mp3") || endsWith(".flac")) {
|
||||
loadAudio(path);
|
||||
} else {
|
||||
loadModel(path);
|
||||
loadModel(path, openAsStage_);
|
||||
}
|
||||
openAsStage_ = false;
|
||||
}
|
||||
|
||||
void App::setShowSkeleton(bool show) {
|
||||
@@ -372,19 +612,39 @@ void App::drawUi() {
|
||||
if (ImGui::Button("Dismiss")) loadError_.clear();
|
||||
ImGui::End();
|
||||
}
|
||||
if (fileBrowser_.draw()) openFile(fileBrowser_.selectedPath());
|
||||
if (!ImGui::GetIO().WantTextInput) {
|
||||
if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_S)) requestSaveScene(true);
|
||||
else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_S)) requestSaveScene(false);
|
||||
else if (ImGui::IsKeyChordPressed(ImGuiMod_Ctrl | ImGuiKey_O)) fileBrowser_.open(FileBrowser::Mode::Open, {}, ".mrscene");
|
||||
}
|
||||
if (!fileBrowser_.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 {
|
||||
for (const char* name : {"Scene", "Bones", "Morphs"}) {
|
||||
for (const char* name : {"Bones", "Morphs"}) {
|
||||
ImGui::Begin(name);
|
||||
ImGui::TextDisabled("No model loaded.");
|
||||
if (name[0] == 'S' && ImGui::Button("Open model...")) fileBrowser_.open();
|
||||
ImGui::TextDisabled("No model selected.");
|
||||
ImGui::End();
|
||||
}
|
||||
}
|
||||
drawLookWindow();
|
||||
drawTimelineWindow();
|
||||
drawRenderDialog();
|
||||
if (showDemo_) ImGui::ShowDemoWindow(&showDemo_);
|
||||
@@ -405,6 +665,7 @@ void App::buildLayout(unsigned dockspace) {
|
||||
ImGui::DockBuilderDockWindow("Scene", left);
|
||||
ImGui::DockBuilderDockWindow("Bones", leftBottom);
|
||||
ImGui::DockBuilderDockWindow("Morphs", right);
|
||||
ImGui::DockBuilderDockWindow("Look", right);
|
||||
ImGui::DockBuilderDockWindow("Timeline", bottom);
|
||||
ImGui::DockBuilderFinish(dockspace);
|
||||
}
|
||||
@@ -412,21 +673,41 @@ void App::buildLayout(unsigned dockspace) {
|
||||
void App::drawMenuBar() {
|
||||
if (!ImGui::BeginMainMenuBar()) return;
|
||||
if (ImGui::BeginMenu("File")) {
|
||||
if (ImGui::MenuItem("Open model or motion...")) 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);
|
||||
@@ -450,19 +731,83 @@ 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() {
|
||||
const Model& m = modelNode_->model();
|
||||
ImGui::Begin("Scene");
|
||||
ImGui::TextWrapped("%s", m.name.c_str());
|
||||
drawSceneList();
|
||||
if (!modelNode_) {
|
||||
ImGui::End();
|
||||
return;
|
||||
}
|
||||
SceneItem& item = *activeItem();
|
||||
const Model& m = modelNode_->model();
|
||||
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();
|
||||
@@ -526,6 +871,124 @@ 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();
|
||||
@@ -551,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);
|
||||
@@ -560,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();
|
||||
|
||||
+75
-8
@@ -6,13 +6,16 @@
|
||||
#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 {
|
||||
|
||||
@@ -20,12 +23,40 @@ 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();
|
||||
@@ -36,6 +67,8 @@ public:
|
||||
void tick(double time);
|
||||
void setViewportPoppedOut(bool popped) { wantPopOut_ = popped; }
|
||||
bool viewportPoppedOut() const { return popCamera_.valid(); }
|
||||
// Call before the viewer's event traversal: turns closing the pop-out window into docking it back.
|
||||
void catchPopOutClose();
|
||||
// Batch render (command line): renders frames [start, end] into dir, then quits.
|
||||
void renderToFolder(const std::string& dir, int start, int end, int width, int height);
|
||||
ImGuiOsg* imgui() { return imgui_.get(); }
|
||||
@@ -48,6 +81,8 @@ private:
|
||||
void drawBonesWindow();
|
||||
void drawBoneEditor();
|
||||
void drawMorphsWindow();
|
||||
void drawLookWindow();
|
||||
void updateLook();
|
||||
void applyViewSettings();
|
||||
void drawTimelineWindow();
|
||||
void drawTimelineTracks(float end);
|
||||
@@ -68,22 +103,48 @@ private:
|
||||
|
||||
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;
|
||||
std::shared_ptr<Motion> motion_;
|
||||
std::unique_ptr<MotionPlayer> player_;
|
||||
std::string motionName_;
|
||||
float motionFrame_ = 0.f;
|
||||
bool playing_ = false;
|
||||
bool loopMotion_ = true;
|
||||
@@ -91,11 +152,15 @@ private:
|
||||
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 {
|
||||
@@ -110,6 +175,8 @@ private:
|
||||
std::shared_ptr<std::atomic<int>> encodeResult;
|
||||
} render_;
|
||||
osg::ref_ptr<osg::Camera> popCamera_; // renders the scene into the separate viewport window
|
||||
// Hidden pop-out kept for reuse: closing its context would also delete GL objects shared with the main window.
|
||||
osg::ref_ptr<osg::Camera> parkedPopCamera_;
|
||||
float timelineZoom_ = 4.f; // pixels per frame
|
||||
float timelineScroll_ = 0.f; // frame at the left edge
|
||||
AudioPlayer audio_;
|
||||
|
||||
+53
-11
@@ -15,7 +15,7 @@ namespace mr {
|
||||
namespace {
|
||||
bool isModelFile(const std::string& name) {
|
||||
std::string lower = toLowerAscii(name);
|
||||
for (const char* ext : {".pmx", ".pmd", ".fbx", ".vmd", ".wav", ".mp3", ".flac", ".obj", ".gltf", ".glb", ".dae"})
|
||||
for (const char* ext : {".mrscene", ".pmx", ".pmd", ".fbx", ".x", ".vmd", ".wav", ".mp3", ".flac", ".obj", ".gltf", ".glb", ".dae"})
|
||||
if (lower.size() >= std::strlen(ext) && lower.compare(lower.size() - std::strlen(ext), std::string::npos, ext) == 0)
|
||||
return true;
|
||||
return false;
|
||||
@@ -27,7 +27,16 @@ FileBrowser::FileBrowser() {
|
||||
currentDir_ = pathToUtf8(fs::current_path(ec));
|
||||
}
|
||||
|
||||
void FileBrowser::open() {
|
||||
void FileBrowser::open(Mode mode, const std::string& defaultPath, const std::string& extension) {
|
||||
mode_ = mode;
|
||||
extension_ = extension;
|
||||
nameBuffer_[0] = '\0';
|
||||
if (mode == Mode::Save && !defaultPath.empty()) {
|
||||
const fs::path p = pathFromUtf8(defaultPath);
|
||||
std::error_code ec;
|
||||
if (p.has_parent_path() && fs::is_directory(p.parent_path(), ec)) currentDir_ = pathToUtf8(p.parent_path());
|
||||
std::snprintf(nameBuffer_, sizeof(nameBuffer_), "%s", pathToUtf8(p.filename()).c_str());
|
||||
}
|
||||
openRequested_ = true;
|
||||
refresh();
|
||||
}
|
||||
@@ -35,13 +44,16 @@ void FileBrowser::open() {
|
||||
void FileBrowser::refresh() {
|
||||
entries_.clear();
|
||||
error_.clear();
|
||||
highlighted_.clear();
|
||||
std::snprintf(pathBuffer_, sizeof(pathBuffer_), "%s", currentDir_.c_str());
|
||||
std::error_code ec;
|
||||
for (const auto& e : fs::directory_iterator(pathFromUtf8(currentDir_), fs::directory_options::skip_permission_denied, ec)) {
|
||||
std::string name = pathToUtf8(e.path().filename());
|
||||
if (name.empty() || name[0] == '.') continue;
|
||||
bool dir = e.is_directory(ec);
|
||||
if (dir || isModelFile(name)) entries_.push_back({name, dir});
|
||||
const bool listed = extension_.empty() ? isModelFile(name)
|
||||
: toLowerAscii(e.path().extension().string()) == extension_;
|
||||
if (dir || listed) entries_.push_back({name, dir});
|
||||
}
|
||||
if (ec) error_ = ec.message();
|
||||
std::sort(entries_.begin(), entries_.end(), [](const auto& a, const auto& b) {
|
||||
@@ -52,12 +64,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("Models: .pmx .pmd .fbx (also .obj .gltf .glb .dae) Motions: .vmd Audio: .wav .mp3 .flac");
|
||||
if (saving) {
|
||||
ImGui::SetNextItemWidth(-80.f);
|
||||
const bool enter = ImGui::InputText("##name", nameBuffer_, sizeof(nameBuffer_), ImGuiInputTextFlags_EnterReturnsTrue);
|
||||
ImGui::SameLine();
|
||||
if ((ImGui::Button("Save") || enter) && nameBuffer_[0]) {
|
||||
std::string name = nameBuffer_;
|
||||
if (!extension_.empty() && toLowerAscii(fs::path(name).extension().string()) != extension_)
|
||||
name += extension_;
|
||||
selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name));
|
||||
chosen = true;
|
||||
}
|
||||
} else if (extension_.empty()) {
|
||||
ImGui::TextDisabled("Scenes: .mrscene Models: .pmx .pmd .fbx .x (also .obj .gltf .glb .dae) Motions: .vmd Audio: .wav .mp3 .flac");
|
||||
}
|
||||
if (!error_.empty()) ImGui::TextColored(ImVec4(1, 0.4f, 0.4f, 1), "%s", error_.c_str());
|
||||
ImGui::BeginChild("entries", ImVec2(0, -ImGui::GetFrameHeightWithSpacing()), ImGuiChildFlags_Borders);
|
||||
std::string enterDir;
|
||||
for (const auto& [name, dir] : entries_) {
|
||||
std::string label = dir ? "[dir] " + name : name;
|
||||
if (ImGui::Selectable(label.c_str(), false, ImGuiSelectableFlags_AllowDoubleClick) &&
|
||||
(dir || ImGui::IsMouseDoubleClicked(0))) {
|
||||
if (dir) enterDir = name;
|
||||
else {
|
||||
if (!ImGui::Selectable(label.c_str(), !dir && name == highlighted_, ImGuiSelectableFlags_AllowDoubleClick))
|
||||
continue;
|
||||
if (dir) {
|
||||
enterDir = name;
|
||||
} else if (saving) {
|
||||
std::snprintf(nameBuffer_, sizeof(nameBuffer_), "%s", name.c_str());
|
||||
} else {
|
||||
highlighted_ = name;
|
||||
if (ImGui::IsMouseDoubleClicked(0)) {
|
||||
selected_ = pathToUtf8(pathFromUtf8(currentDir_) / pathFromUtf8(name));
|
||||
chosen = true;
|
||||
}
|
||||
@@ -95,6 +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
@@ -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
|
||||
+4
-1
@@ -1,4 +1,5 @@
|
||||
#include "app/AppUi.h"
|
||||
#include "render/Grid.h"
|
||||
#include <imgui.h>
|
||||
#include <osgDB/WriteFile>
|
||||
#include <osgViewer/Renderer>
|
||||
@@ -79,10 +80,12 @@ void App::startRender() {
|
||||
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(~0u);
|
||||
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()));
|
||||
|
||||
@@ -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
|
||||
@@ -75,6 +75,12 @@ void App::drawTimelineWindow() {
|
||||
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();
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+187
-7
@@ -1,4 +1,5 @@
|
||||
#include "app/AppUi.h"
|
||||
#include "model/PathUtil.h"
|
||||
|
||||
#include "render/GpuCaps.h"
|
||||
#include "render/ModelNode.h"
|
||||
@@ -9,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:
|
||||
@@ -28,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"
|
||||
@@ -45,6 +68,22 @@ void printUsage() {
|
||||
" --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"
|
||||
@@ -60,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;
|
||||
@@ -115,6 +176,19 @@ int main(int argc, char** argv) {
|
||||
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;
|
||||
@@ -149,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") {
|
||||
@@ -171,6 +246,52 @@ int main(int argc, char** argv) {
|
||||
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") {
|
||||
@@ -192,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));
|
||||
@@ -204,10 +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();
|
||||
|
||||
@@ -244,16 +397,43 @@ int main(int argc, char** argv) {
|
||||
if (!motionPath.empty() || !cameraPath.empty() || !audioPath.empty()) {
|
||||
app.setMotionFrame(motionFrame);
|
||||
app.setPlaying(play);
|
||||
app.setViewportPoppedOut(popOut);
|
||||
if (!renderDir.empty()) app.renderToFolder(renderDir, renderStart, renderEnd, renderW, renderH);
|
||||
}
|
||||
app.setShowSkeleton(skeleton);
|
||||
app.frameModel(azimuth, elevation);
|
||||
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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -73,4 +73,30 @@ void validateIk(Bone& bone, int index, int boneCount) {
|
||||
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
|
||||
@@ -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,6 +52,8 @@ 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;
|
||||
};
|
||||
@@ -117,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;
|
||||
@@ -125,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;
|
||||
@@ -138,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;
|
||||
|
||||
@@ -255,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];
|
||||
|
||||
+78
-7
@@ -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();
|
||||
@@ -300,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
|
||||
@@ -326,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_;
|
||||
|
||||
+122
-1
@@ -1,4 +1,5 @@
|
||||
#include "model/Poser.h"
|
||||
#include "physics/PhysicsWorld.h"
|
||||
|
||||
#include "model/Parallel.h"
|
||||
|
||||
@@ -31,6 +32,10 @@ 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);
|
||||
@@ -40,6 +45,15 @@ Poser::Poser(std::shared_ptr<const Model> model) : model_(std::move(model)) {
|
||||
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);
|
||||
@@ -131,6 +145,89 @@ 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;
|
||||
@@ -209,8 +306,19 @@ void Poser::solveIk(int ikBone) {
|
||||
}
|
||||
}
|
||||
|
||||
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_ && motion_ == lastMotion_ &&
|
||||
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_;
|
||||
@@ -256,6 +364,18 @@ bool Poser::update() {
|
||||
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();
|
||||
@@ -269,6 +389,7 @@ bool Poser::update() {
|
||||
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;
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
|
||||
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 };
|
||||
@@ -33,6 +35,7 @@ struct MotionPose {
|
||||
class Poser {
|
||||
public:
|
||||
explicit Poser(std::shared_ptr<const Model> model);
|
||||
~Poser();
|
||||
|
||||
const Model& model() const { return *model_; }
|
||||
std::vector<BonePose>& bonePoses() { return poses_; }
|
||||
@@ -42,6 +45,15 @@ public:
|
||||
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]; }
|
||||
@@ -65,10 +77,16 @@ public:
|
||||
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);
|
||||
|
||||
@@ -81,6 +99,10 @@ private:
|
||||
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;
|
||||
|
||||
@@ -93,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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -25,6 +25,10 @@ void GpuCapsProbe::operator()(osg::GraphicsContext* gc) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ 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;
|
||||
};
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+114
-22
@@ -5,6 +5,7 @@
|
||||
#include "render/Shaders.h"
|
||||
#include "render/TextureLoader.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <osg/BlendFunc>
|
||||
#include <osg/CullFace>
|
||||
#include <osg/Depth>
|
||||
@@ -17,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 {
|
||||
@@ -54,15 +52,11 @@ 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);
|
||||
@@ -97,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);
|
||||
@@ -119,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);
|
||||
@@ -133,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;
|
||||
@@ -141,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) {
|
||||
@@ -164,8 +173,62 @@ void ModelNode::buildMesh() {
|
||||
}
|
||||
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();
|
||||
@@ -272,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;
|
||||
@@ -339,6 +403,7 @@ void ModelNode::updateDeformation() {
|
||||
}
|
||||
}
|
||||
if (poser_.update()) {
|
||||
if (poser_.morphsChangedInLastUpdate()) applyMorphedMaterials();
|
||||
if (activeSkinning_ == SkinningMode::Software) {
|
||||
const auto& p = poser_.positions();
|
||||
const auto& n = poser_.normals();
|
||||
@@ -363,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;
|
||||
@@ -381,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),
|
||||
@@ -390,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);
|
||||
|
||||
+17
-4
@@ -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,10 @@ 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_; }
|
||||
@@ -44,6 +47,8 @@ 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();
|
||||
@@ -54,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_;
|
||||
@@ -78,8 +90,9 @@ private:
|
||||
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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+221
-36
@@ -1,5 +1,7 @@
|
||||
#include "render/Shaders.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace mr {
|
||||
|
||||
namespace {
|
||||
@@ -7,15 +9,12 @@ namespace {
|
||||
// GLSL 1.20 so the same shaders run on macOS legacy contexts, Windows and Linux.
|
||||
// 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* kVertexShader = R"(#version 120
|
||||
const char* kSkinning = R"(
|
||||
uniform int u_skinning;
|
||||
uniform sampler2D u_boneTexture;
|
||||
uniform vec2 u_boneTexSize;
|
||||
attribute vec4 a_boneIndices;
|
||||
attribute vec4 a_boneWeights;
|
||||
varying vec3 v_normal;
|
||||
varying vec3 v_viewPos;
|
||||
varying vec2 v_uv;
|
||||
|
||||
vec4 boneColumn(float bone, float k) {
|
||||
vec2 texel = vec2(mod(bone, 1024.0) * 3.0 + k, floor(bone / 1024.0));
|
||||
@@ -30,9 +29,9 @@ void skin(float bone, float weight, vec4 pos, vec3 nrm, inout vec3 outPos, inout
|
||||
outNrm += weight * vec3(dot(nrm, c0.xyz), dot(nrm, c1.xyz), dot(nrm, c2.xyz));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec4 pos = gl_Vertex;
|
||||
vec3 nrm = gl_Normal;
|
||||
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);
|
||||
@@ -43,6 +42,18 @@ void main() {
|
||||
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 pos;
|
||||
vec3 nrm;
|
||||
skinnedVertex(pos, nrm);
|
||||
vec4 viewPos = gl_ModelViewMatrix * pos;
|
||||
v_viewPos = viewPos.xyz;
|
||||
v_normal = gl_NormalMatrix * nrm;
|
||||
@@ -51,7 +62,44 @@ void main() {
|
||||
}
|
||||
)";
|
||||
|
||||
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;
|
||||
@@ -59,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;
|
||||
@@ -74,51 +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->addBindAttribLocation("a_boneIndices", kBoneIndexAttrib);
|
||||
program->addBindAttribLocation("a_boneWeights", kBoneWeightAttrib);
|
||||
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
|
||||
@@ -9,7 +9,17 @@ 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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+2
-4
@@ -144,16 +144,14 @@ public:
|
||||
|
||||
switch (ea.getEventType()) {
|
||||
case E::PUSH:
|
||||
case E::DOUBLECLICK: // macOS sends the second press of a double-click as DOUBLECLICK, not PUSH
|
||||
case E::RELEASE: {
|
||||
mousePos();
|
||||
updateMods();
|
||||
int b = button();
|
||||
if (b >= 0) io.AddMouseButtonEvent(b, ea.getEventType() == E::PUSH);
|
||||
if (b >= 0) io.AddMouseButtonEvent(b, ea.getEventType() != E::RELEASE);
|
||||
return io.WantCaptureMouse;
|
||||
}
|
||||
case E::DOUBLECLICK:
|
||||
mousePos();
|
||||
return io.WantCaptureMouse;
|
||||
case E::DRAG:
|
||||
case E::MOVE:
|
||||
mousePos();
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
#include "model/Motion.h"
|
||||
#include "model/PathUtil.h"
|
||||
#include "model/Poser.h"
|
||||
#include "scene/SceneFile.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
@@ -289,13 +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;
|
||||
}
|
||||
Reference in new issue
Block a user