From 5be372d773dbad95d7cdc516f778aa0d5f6bc076 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Tue, 1 Dec 2026 06:34:45 +0000 Subject: [PATCH 1/6] Post-processing: bloom, ambient occlusion, filmic tone mapping, colour grading, FXAA Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CMakeLists.txt | 1 + src/app/AppUi.cpp | 77 +++++++- src/app/AppUi.h | 3 + src/app/Render.cpp | 4 +- src/app/main.cpp | 21 ++ src/render/GpuCaps.cpp | 2 + src/render/GpuCaps.h | 2 + src/render/PostFx.cpp | 415 +++++++++++++++++++++++++++++++++++++++ src/render/PostFx.h | 52 +++++ src/scene/LookSettings.h | 16 ++ src/scene/SceneFile.cpp | 30 ++- tests/test_main.cpp | 6 + 12 files changed, 619 insertions(+), 10 deletions(-) create mode 100644 src/render/PostFx.cpp create mode 100644 src/render/PostFx.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e152d3d..c2b6302 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -142,6 +142,7 @@ add_executable(model_renderer 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 diff --git a/src/app/AppUi.cpp b/src/app/AppUi.cpp index 79d2e71..39b6e93 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -74,11 +74,18 @@ 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); - root_->addChild(grid_); + sceneRoot_->addChild(grid_); sceneGroup_ = new osg::Group; - root_->addChild(sceneGroup_); - sceneLook_ = std::make_unique(root_.get(), sceneGroup_.get()); + sceneRoot_->addChild(sceneGroup_); + sceneLook_ = std::make_unique(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); } void App::setLook(const LookSettings& look) { @@ -87,7 +94,20 @@ void App::setLook(const LookSettings& look) { } void App::updateLook() { - if (gpuCaps().probed) sceneLook_->setShadowsSupported(gpuCaps().shadows); + 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(vp->width()), static_cast(vp->height())); + mainChain_->setClearColor(master->getClearColor()); + if (popCamera_ && popCamera_->getViewport()) { + popChain_->setSize(static_cast(popCamera_->getViewport()->width()), + static_cast(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_) { @@ -171,6 +191,7 @@ void App::updatePlacement(SceneItem& item) { } void App::applyViewSettings() { + for (PostChain* chain : {mainChain_.get(), popChain_.get(), renderChain_.get()}) chain->apply(look_); sceneLook_->apply(look_); for (auto& item : items_) { ModelNode* node = item->node.get(); @@ -359,6 +380,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); @@ -375,7 +397,7 @@ void App::updatePopOut() { popCamera_->setGraphicsContext(nullptr); } popCamera_ = nullptr; - master->setCullMask(~0u); + master->setCullMask(kMainViewMask | kGridNodeMask); } if (!popCamera_) return; const osg::GraphicsContext::Traits* traits = popCamera_->getGraphicsContext()->getTraits(); @@ -778,10 +800,14 @@ void App::drawLookWindow() { 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}}, - {"Anime", 2, true, 0.6f, {0.85f, 0.82f, 0.8f}}, - {"Studio", 3, false, 0.35f, {0.95f, 0.9f, 0.82f}}}; + 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)) { @@ -790,6 +816,12 @@ void App::drawLookWindow() { 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; } } @@ -836,6 +868,35 @@ void App::drawLookWindow() { 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; diff --git a/src/app/AppUi.h b/src/app/AppUi.h index a458c5e..4008eec 100644 --- a/src/app/AppUi.h +++ b/src/app/AppUi.h @@ -8,6 +8,7 @@ #include "model/Motion.h" #include "render/Look.h" #include "render/ModelNode.h" +#include "render/PostFx.h" #include "ui/ImGuiOsg.h" #include @@ -89,7 +90,9 @@ private: osgViewer::Viewer& viewer_; osg::ref_ptr root_; + osg::ref_ptr sceneRoot_; // everything 3D; drawn through a post-processing chain osg::ref_ptr sceneGroup_; // models and stages + osg::ref_ptr mainChain_, popChain_, renderChain_; std::unique_ptr sceneLook_; osg::ref_ptr manipulator_; osg::ref_ptr imgui_; diff --git a/src/app/Render.cpp b/src/app/Render.cpp index 68f3188..cf390e9 100644 --- a/src/app/Render.cpp +++ b/src/app/Render.cpp @@ -80,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(~kGridNodeMask); + 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())); diff --git a/src/app/main.cpp b/src/app/main.cpp index 415960c..15cf4b2 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -79,6 +79,10 @@ void printUsage() { " --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" @@ -177,6 +181,8 @@ int main(int argc, char** argv) { 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; @@ -256,6 +262,14 @@ int main(int argc, char** argv) { 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") { @@ -319,6 +333,13 @@ int main(int argc, char** argv) { { 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; diff --git a/src/render/GpuCaps.cpp b/src/render/GpuCaps.cpp index 71acd13..7e08fae 100644 --- a/src/render/GpuCaps.cpp +++ b/src/render/GpuCaps.cpp @@ -27,6 +27,8 @@ void GpuCapsProbe::operator()(osg::GraphicsContext* gc) { 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); } diff --git a/src/render/GpuCaps.h b/src/render/GpuCaps.h index 2168e90..22215a5 100644 --- a/src/render/GpuCaps.h +++ b/src/render/GpuCaps.h @@ -10,6 +10,8 @@ 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; }; diff --git a/src/render/PostFx.cpp b/src/render/PostFx.cpp new file mode 100644 index 0000000..f87bcc9 --- /dev/null +++ b/src/render/PostFx.cpp @@ -0,0 +1,415 @@ +#include "render/PostFx.h" + +#include +#include +#include +#include +#include + +#include +#include + +#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 = max(c.r, max(c.g, c.b)); + 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)); + occlusion += falloff * max(0.0, dot(v, n) * inversesqrt(vv + 1e-6) - 0.15); + } + float ao = clamp(1.0 - u_strength * occlusion / 4.0, 0.0, 1.0); + 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 makeTexture(GLint internalFormat, GLenum format, GLenum type, bool linear) { + osg::ref_ptr 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 makePass(const char* name, const char* fragment, osg::Texture2D* target, int order) { + osg::ref_ptr 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 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 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(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()) static_cast(node)->setProjection(*cv->getProjectionMatrix()); + 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::setProjection(const osg::Matrixd& p) { + if (!proj_) return; + proj_->set(osg::Vec4f(p(0, 0), p(1, 1), p(2, 0), p(2, 1))); + projZ_->set(osg::Vec2f(p(2, 2), p(3, 2))); +} + +void PostChain::build() { + const GLint colorFormat = floatColor_ ? GL_RGBA16F_ARB : GL_RGBA8; + const GLenum colorType = floatColor_ ? GL_FLOAT : 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); + + // Inherits the output camera's view, projection and cull mask. + sceneCam_ = new osg::Camera; + sceneCam_->setName("PostSceneCamera"); + sceneCam_->setReferenceFrame(osg::Transform::RELATIVE_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); + const float bw = static_cast(std::max(width_ / 4, 1)), bh = static_cast(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 diff --git a/src/render/PostFx.h b/src/render/PostFx.h new file mode 100644 index 0000000..a9d024a --- /dev/null +++ b/src/render/PostFx.h @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include + +#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: the projection the scene is drawn with. + void setProjection(const osg::Matrixd& projection); + +private: + void build(); + void refresh(); + + osg::ref_ptr 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 color_, depth_, bloomA_, bloomB_, ao_, ldr_; + osg::ref_ptr sceneCam_, brightCam_, blurHCam_, blurVCam_, aoCam_, compositeCam_, finalCam_; + osg::ref_ptr brightTexel_, threshold_, blurHDir_, blurVDir_, aoTexel_, aoRadius_, aoStrength_, + proj_, projZ_, bloomOn_, aoOn_, bloomStrength_, toneMap_, exposure_, contrast_, saturation_, tint_, + vignette_, compositeAoTexel_, fxaaOn_, fxaaTexel_; +}; + +} // namespace mr diff --git a/src/scene/LookSettings.h b/src/scene/LookSettings.h index 2457f04..32c78c1 100644 --- a/src/scene/LookSettings.h +++ b/src/scene/LookSettings.h @@ -25,6 +25,22 @@ struct LookSettings { 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.5f; + float bloomThreshold = 0.75f; + 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 diff --git a/src/scene/SceneFile.cpp b/src/scene/SceneFile.cpp index ba2d8f4..9c9974c 100644 --- a/src/scene/SceneFile.cpp +++ b/src/scene/SceneFile.cpp @@ -118,7 +118,21 @@ bool saveScene(const Scene& scene, const std::string& path, std::string& error) {"groundShadow", look.groundShadow}, {"groundShadowOpacity", look.groundShadowOpacity}, {"rimStrength", look.rimStrength}, - {"rimColor", vec(look.rimColor)}}; + {"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}, @@ -233,6 +247,20 @@ bool loadScene(const std::string& path, Scene& scene, std::string& error) { 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); diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 040bbd3..6498514 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -377,6 +377,10 @@ void testSceneFile() { 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; const std::string file = mr::pathToUtf8(dir / "project" / "test.mrscene"); std::string error; @@ -405,6 +409,8 @@ void testSceneFile() { 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"); -- 2.54.1 From 4b33a676eb28025d8b0d3bb7e33761e8ec09b12b Mon Sep 17 00:00:00 2001 From: gs5579 Date: Tue, 1 Dec 2026 06:35:26 +0000 Subject: [PATCH 2/6] Bloom: luminance threshold, gentler defaults; README Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- README.md | 5 +++++ src/render/PostFx.cpp | 2 +- src/scene/LookSettings.h | 4 ++-- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bcf6027..0cd208b 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,11 @@ restores the default). 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). diff --git a/src/render/PostFx.cpp b/src/render/PostFx.cpp index f87bcc9..2fdf49c 100644 --- a/src/render/PostFx.cpp +++ b/src/render/PostFx.cpp @@ -40,7 +40,7 @@ void main() { 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 = max(c.r, max(c.g, c.b)); + 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); diff --git a/src/scene/LookSettings.h b/src/scene/LookSettings.h index 32c78c1..78001d2 100644 --- a/src/scene/LookSettings.h +++ b/src/scene/LookSettings.h @@ -28,8 +28,8 @@ struct LookSettings { // Post-processing; with all of it off the scene is drawn directly, at no extra cost. bool bloom = false; - float bloomStrength = 0.5f; - float bloomThreshold = 0.75f; + float bloomStrength = 0.4f; + float bloomThreshold = 0.8f; float bloomRadius = 1.f; bool ambientOcclusion = false; float aoStrength = 1.f; -- 2.54.1 From 637a2c12f2eba7ad109a5df1d91546014fa1f20e Mon Sep 17 00:00:00 2001 From: gs5579 Date: Tue, 1 Dec 2026 06:42:48 +0000 Subject: [PATCH 3/6] Post-FX: fit near/far for big stages, explicit grid shader, fade AO with distance Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/render/Grid.cpp | 14 ++++++++++++-- src/render/PostFx.cpp | 34 +++++++++++++++++++++++++++------- src/render/PostFx.h | 5 +++-- 3 files changed, 42 insertions(+), 11 deletions(-) diff --git a/src/render/Grid.cpp b/src/render/Grid.cpp index 641c42f..07b709e 100644 --- a/src/render/Grid.cpp +++ b/src/render/Grid.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include namespace mr { @@ -63,8 +64,10 @@ osg::Node* createGrid(float halfExtent, float spacing) { addLine(av, ac, {0, 0, z}, {0, 0, up}, green); auto* geode = new osg::Geode; - geode->addDrawable(lineGeometry(gv, gc, 1.f)); - geode->addDrawable(lineGeometry(av, ac, 2.f)); + 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)); @@ -73,6 +76,13 @@ osg::Node* createGrid(float halfExtent, float spacing) { 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); + // 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; } diff --git a/src/render/PostFx.cpp b/src/render/PostFx.cpp index 2fdf49c..87a5873 100644 --- a/src/render/PostFx.cpp +++ b/src/render/PostFx.cpp @@ -92,6 +92,8 @@ void main() { occlusion += falloff * max(0.0, dot(v, n) * 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); } )"; @@ -239,7 +241,8 @@ class ProjectionCallback : public osg::NodeCallback { public: void operator()(osg::Node* node, osg::NodeVisitor* nv) override { if (auto* cv = nv->asCullVisitor()) - if (cv->getProjectionMatrix()) static_cast(node)->setProjection(*cv->getProjectionMatrix()); + if (cv->getProjectionMatrix() && cv->getModelViewMatrix()) + static_cast(node)->cullUpdate(*cv->getProjectionMatrix(), *cv->getModelViewMatrix()); traverse(node, nv); } }; @@ -274,10 +277,27 @@ void PostChain::setClearColor(const osg::Vec4& color) { if (sceneCam_) sceneCam_->setClearColor(color); } -void PostChain::setProjection(const osg::Matrixd& p) { - if (!proj_) return; - proj_->set(osg::Vec4f(p(0, 0), p(1, 1), p(2, 0), p(2, 1))); - projZ_->set(osg::Vec2f(p(2, 2), p(3, 2))); +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() { @@ -290,10 +310,10 @@ void PostChain::build() { ao_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true); ldr_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true); - // Inherits the output camera's view, projection and cull mask. + // 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::RELATIVE_RF); + 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); diff --git a/src/render/PostFx.h b/src/render/PostFx.h index a9d024a..150c6ee 100644 --- a/src/render/PostFx.h +++ b/src/render/PostFx.h @@ -29,8 +29,9 @@ public: void apply(const LookSettings& settings); void setSize(int width, int height); void setClearColor(const osg::Vec4& color); - // Called while culling: the projection the scene is drawn with. - void setProjection(const osg::Matrixd& projection); + // 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(); -- 2.54.1 From e786a88decc889d8033b72136adad4ea77ed0cf8 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Tue, 1 Dec 2026 06:47:37 +0000 Subject: [PATCH 4/6] AO: distance-scaled bias against flat-ground self-occlusion Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/render/PostFx.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/render/PostFx.cpp b/src/render/PostFx.cpp index 87a5873..cd8e209 100644 --- a/src/render/PostFx.cpp +++ b/src/render/PostFx.cpp @@ -89,7 +89,8 @@ void main() { 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)); - occlusion += falloff * max(0.0, dot(v, n) * inversesqrt(vv + 1e-6) - 0.15); + // 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. -- 2.54.1 From 799c4ac344a9d5d34d87ec37a056925ac7d06161 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Tue, 1 Dec 2026 06:48:44 +0000 Subject: [PATCH 5/6] Grid: no depth writes so AO ignores it Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/render/Grid.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/render/Grid.cpp b/src/render/Grid.cpp index 07b709e..1a8ad10 100644 --- a/src/render/Grid.cpp +++ b/src/render/Grid.cpp @@ -1,6 +1,7 @@ #include "render/Grid.h" #include +#include #include #include #include @@ -76,6 +77,8 @@ osg::Node* createGrid(float halfExtent, float spacing) { 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, -- 2.54.1 From 302e7c4f20e988203e58093fa5808c476bc764f5 Mon Sep 17 00:00:00 2001 From: gs5579 Date: Tue, 1 Dec 2026 07:03:56 +0000 Subject: [PATCH 6/6] UV and material morphs; FXAA-only path skips composite, 8-bit post targets Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/app/AppUi.cpp | 5 +-- src/model/Model.h | 34 ++++++++++++++++ src/model/PmxLoader.cpp | 24 ++++++++--- src/model/Poser.cpp | 88 ++++++++++++++++++++++++++++++++++++++++ src/model/Poser.h | 9 ++++ src/render/ModelNode.cpp | 68 +++++++++++++++++++++++++++---- src/render/ModelNode.h | 8 ++++ src/render/PostFx.cpp | 11 ++++- src/render/Shaders.cpp | 20 ++++++--- tests/test_main.cpp | 37 +++++++++++++++++ 10 files changed, 281 insertions(+), 23 deletions(-) diff --git a/src/app/AppUi.cpp b/src/app/AppUi.cpp index 39b6e93..86eed30 100644 --- a/src/app/AppUi.cpp +++ b/src/app/AppUi.cpp @@ -933,8 +933,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); @@ -942,7 +941,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(); diff --git a/src/model/Model.h b/src/model/Model.h index af5e473..1ff311b 100644 --- a/src/model/Model.h +++ b/src/model/Model.h @@ -120,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; @@ -128,6 +160,8 @@ struct Morph { std::vector vertexOffsets; std::vector groupOffsets; // Group and Flip std::vector boneOffsets; + std::vector uvOffsets; // main UV channel only + std::vector materialOffsets; }; enum class RigidShape : uint8_t { Sphere = 0, Box = 1, Capsule = 2 }; diff --git a/src/model/PmxLoader.cpp b/src/model/PmxLoader.cpp index b38cd4c..609804a 100644 --- a/src/model/PmxLoader.cpp +++ b/src/model/PmxLoader.cpp @@ -303,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(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(model_.materials.size())) + m.materialOffsets.push_back(o); } break; case 10: // impulse diff --git a/src/model/Poser.cpp b/src/model/Poser.cpp index caa4853..bf70fc1 100644 --- a/src/model/Poser.cpp +++ b/src/model/Poser.cpp @@ -32,6 +32,10 @@ Poser::Poser(std::shared_ptr 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); @@ -141,6 +145,89 @@ void Poser::accumulateMorph(int morph, float weight, int depth) { } } +namespace { + +template +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 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(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; @@ -302,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; diff --git a/src/model/Poser.h b/src/model/Poser.h index 6db62ac..733164b 100644 --- a/src/model/Poser.h +++ b/src/model/Poser.h @@ -77,10 +77,16 @@ public: const std::vector& normals() const { return normals_; } const std::vector& boneGlobals() const { return globals_; } const std::vector& effectiveMorphWeights() const { return effective_; } + // Main UVs after UV morphs; empty when the model has no UV morphs. + const std::vector& morphedUvs() const { return uvs_; } + // Per-material values after material morphs. + const std::vector& 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); @@ -109,6 +115,9 @@ private: std::vector animTranslation_; std::vector globals_, skin_; std::vector morphed_, positions_, normals_; + std::vector uvs_; + std::vector materials_; + bool hasUvMorphs_ = false, hasMaterialMorphs_ = false; }; } // namespace mr diff --git a/src/render/ModelNode.cpp b/src/render/ModelNode.cpp index c81e5eb..ff6ff28 100644 --- a/src/render/ModelNode.cpp +++ b/src/render/ModelNode.cpp @@ -5,6 +5,7 @@ #include "render/Shaders.h" #include "render/TextureLoader.h" +#include #include #include #include @@ -51,6 +52,8 @@ ModelNode::ModelNode(std::shared_ptr 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)); + 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); ss->addUniform(lightingUniform_); @@ -88,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); @@ -126,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 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; @@ -134,6 +149,7 @@ void ModelNode::buildMesh() { } positions_->setDataVariance(osg::Object::DYNAMIC); normals_->setDataVariance(osg::Object::DYNAMIC); + uvs_->setDataVariance(osg::Object::DYNAMIC); osg::ref_ptr geode = new osg::Geode; for (size_t i = 0; i < model.materials.size(); ++i) { @@ -157,7 +173,7 @@ void ModelNode::buildMesh() { } meshGroup_ = geode; addChild(meshGroup_); - buildEdges(uvs.get()); + buildEdges(uvs); } void ModelNode::buildEdges(osg::Vec2Array* uvs) { @@ -191,8 +207,10 @@ void ModelNode::buildEdges(osg::Vec2Array* uvs) { geom->addPrimitiveSet(new osg::DrawElementsUInt(GL_TRIANGLES, model.indices.begin() + m.indexOffset, model.indices.begin() + m.indexOffset + m.indexCount)); osg::StateSet* es = geom->getOrCreateStateSet(); - es->addUniform(new osg::Uniform("u_edgeColor", m.edgeColor)); - es->addUniform(new osg::Uniform("u_edgeSize", m.edgeSize)); + 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(i), "RenderBin"); geom->setComputeBoundingBoxCallback(new PosedBoundsCallback(this)); @@ -385,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(); @@ -409,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; diff --git a/src/render/ModelNode.h b/src/render/ModelNode.h index 7a3b1da..77ba51e 100644 --- a/src/render/ModelNode.h +++ b/src/render/ModelNode.h @@ -48,6 +48,7 @@ private: void preloadTextureImages(); osg::Texture2D* texture(int index, bool clamp); void buildEdges(osg::Vec2Array* uvs); + void applyMorphedMaterials(); void buildSkinning(); void uploadBoneMatrices(); void buildSkeleton(); @@ -58,6 +59,13 @@ private: osg::ref_ptr meshGroup_; osg::ref_ptr positions_; osg::ref_ptr normals_; + osg::ref_ptr uvs_; + // Per-material uniforms that UV/material morphs update. + struct MaterialUniforms { + osg::ref_ptr diffuse, ambient, specular, shininess, textureMul, textureAdd, sphereMul, sphereAdd, + toonMul, toonAdd, edgeColor, edgeSize; + }; + std::vector materialUniforms_; std::vector> geometries_; std::vector> textures_; std::vector textureTried_; diff --git a/src/render/PostFx.cpp b/src/render/PostFx.cpp index cd8e209..850d665 100644 --- a/src/render/PostFx.cpp +++ b/src/render/PostFx.cpp @@ -302,8 +302,9 @@ void PostChain::cullUpdate(const osg::Matrixd& p, const osg::Matrixd& view) { } void PostChain::build() { - const GLint colorFormat = floatColor_ ? GL_RGBA16F_ARB : GL_RGBA8; - const GLenum colorType = floatColor_ ? GL_FLOAT : GL_UNSIGNED_BYTE; + // 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); @@ -412,6 +413,12 @@ void PostChain::refresh() { 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(std::max(width_ / 4, 1)), bh = static_cast(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; diff --git a/src/render/Shaders.cpp b/src/render/Shaders.cpp index 6d51271..c44450e 100644 --- a/src/render/Shaders.cpp +++ b/src/render/Shaders.cpp @@ -118,6 +118,12 @@ 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; @@ -132,11 +138,12 @@ void main() { float shadow = u_receiveShadow == 1 ? shadowFactor(v_viewPos, ndl) : 1.0; float lit = mix(1.0, shadow, u_shadowStrength); - vec4 base = u_diffuse; - if (u_useTexture == 1) base *= texture2D(u_texture, v_uv); + 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 = u_useTexture == 1 ? texture2D(u_texture, v_uv).rgb : vec3(1.0); + vec3 tex = texel.rgb; vec3 color; if (u_lightingModel == 0) { @@ -157,13 +164,16 @@ void main() { color = base.rgb * (ambient + wrap * u_lightColor * 1.25); } 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 * (u_lightingModel == 2 ? 0.5 + 0.5 * lit : 1.0); } if (u_lightingModel == 0) { float t = clamp(ndl + 0.5, 0.0, 1.0); - if (u_useToon == 1) color *= texture2D(u_toon, vec2(0.5, min(t, mix(1.0, t * shadow, u_shadowStrength)))).rgb; + 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); } vec3 h = normalize(toLight + toEye); diff --git a/tests/test_main.cpp b/tests/test_main.cpp index 6498514..8066415 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -419,8 +419,45 @@ void testSceneFile() { 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(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(); -- 2.54.1