Compare commits

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

No files matched your search

+2
View File
@@ -141,6 +141,8 @@ add_executable(model_renderer
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
+20 -2
View File
@@ -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
@@ -136,6 +136,13 @@ 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
@@ -145,8 +152,19 @@ restores the default).
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, MMD toon vs Lambert shading, GPU vs CPU skinning,
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.
+274 -19
View File
@@ -4,6 +4,7 @@
#include "model/ModelLoader.h"
#include "render/GpuCaps.h"
#include "render/Grid.h"
#include "render/Shaders.h"
#include <imgui.h>
#include <imgui_internal.h>
@@ -73,8 +74,52 @@ 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;
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);
}
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) {
@@ -101,12 +146,12 @@ bool App::loadModel(const std::string& path, bool stage) {
item->path = path;
item->stage = stage || looksLikeStage(path, *model);
item->name = model->name.empty() ? path.substr(path.find_last_of("/\\") + 1) : model->name;
root_->addChild(item->node);
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) lightingModel_ = model->format == SourceFormat::Assimp ? 1 : 0;
if (firstCharacter) look_.shading = model->format == SourceFormat::Assimp ? 1 : 0;
selectModel(static_cast<int>(items_.size()) - 1);
if (frame) frameModel();
return true;
@@ -126,7 +171,7 @@ void App::selectModel(int index) {
void App::removeModel(int index) {
if (index < 0 || index >= static_cast<int>(items_.size())) return;
root_->removeChild(items_[index]->node);
sceneGroup_->removeChild(items_[index]->node);
items_.erase(items_.begin() + index);
modelNode_ = nullptr;
player_ = nullptr;
@@ -143,21 +188,26 @@ 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() {
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->setLightFollowsCamera(lightFollowsCamera_);
node->setLightingModel(static_cast<LightingModel>(lightingModel_));
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);
node->setNodeMask(item->visible ? ~0u : 0u);
const bool casts = !item->stage || look_.stageShadows;
node->setNodeMask(!item->visible ? 0u : casts ? ~0u : ~kShadowCasterMask);
}
}
@@ -269,13 +319,81 @@ void App::applyFrame() {
}
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;
}
@@ -331,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);
@@ -347,7 +466,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();
@@ -421,6 +540,7 @@ void App::tick(double time) {
}
updatePopOut();
updateProjection();
updateLook();
const bool anyMotion = std::any_of(items_.begin(), items_.end(), [](const auto& i) { return i->player != nullptr; });
if (!anyMotion && !camera_ && !audio_.loaded()) return;
if (playing_) {
@@ -497,9 +617,21 @@ void App::drawUi() {
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 openFile(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_) {
@@ -512,6 +644,7 @@ void App::drawUi() {
ImGui::End();
}
}
drawLookWindow();
drawTimelineWindow();
drawRenderDialog();
if (showDemo_) ImGui::ShowDemoWindow(&showDemo_);
@@ -532,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);
}
@@ -561,15 +695,19 @@ void App::drawMenuBar() {
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);
@@ -733,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();
@@ -758,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);
@@ -767,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();
+28 -2
View File
@@ -6,7 +6,9 @@
#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>
@@ -40,6 +42,21 @@ public:
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();
@@ -64,6 +81,8 @@ private:
void drawBonesWindow();
void drawBoneEditor();
void drawMorphsWindow();
void drawLookWindow();
void updateLook();
void applyViewSettings();
void drawTimelineWindow();
void drawTimelineTracks(float end);
@@ -84,6 +103,10 @@ 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_;
struct SceneItem {
@@ -98,6 +121,7 @@ private:
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();
@@ -118,8 +142,7 @@ private:
bool showSkeleton_ = false;
bool backfaceCulling_ = true;
bool wireframe_ = false;
bool lightFollowsCamera_ = false;
int lightingModel_ = 0;
LookSettings look_;
int skinning_ = 1; // 1 hardware (GPU), 0 software (CPU)
bool ikEnabled_ = true;
float motionFrame_ = 0.f;
@@ -129,6 +152,9 @@ 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;
+3 -1
View File
@@ -70,7 +70,9 @@ bool FileBrowser::draw() {
bool chosen = false;
ImGui::SetNextWindowSize(ImVec2(640, 460), ImGuiCond_FirstUseEver);
const bool saving = mode_ == Mode::Save;
if (ImGui::BeginPopupModal(saving ? "Save scene###filebrowser" : extension_ == ".mrscene" ? "Open scene###filebrowser" : "Open###filebrowser", nullptr)) {
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();
+2 -1
View File
@@ -17,6 +17,7 @@ public:
// 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();
@@ -26,7 +27,7 @@ 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_;
+3 -1
View File
@@ -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()));
+12 -4
View File
@@ -64,6 +64,11 @@ bool App::saveScene(const std::string& path) {
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);
@@ -74,8 +79,7 @@ bool App::saveScene(const std::string& path) {
scene.skeleton = showSkeleton_;
scene.wireframe = wireframe_;
scene.backfaceCulling = backfaceCulling_;
scene.lightFollowsCamera = lightFollowsCamera_;
scene.lightingModel = lightingModel_;
scene.look = look_;
scene.renderWidth = render_.width;
scene.renderHeight = render_.height;
scene.renderTransparent = render_.transparent;
@@ -140,10 +144,14 @@ bool App::openScene(const std::string& path) {
showSkeleton_ = scene.skeleton;
wireframe_ = scene.wireframe;
backfaceCulling_ = scene.backfaceCulling;
lightFollowsCamera_ = scene.lightFollowsCamera;
lightingModel_ = scene.lightingModel;
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;
+6
View File
@@ -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();
+69
View File
@@ -13,6 +13,7 @@
#include <functional>
#include <cstdlib>
#include <iostream>
#include <optional>
#if defined(_WIN32)
#define NOMINMAX
@@ -75,6 +76,14 @@ void printUsage() {
" --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"
@@ -170,8 +179,15 @@ int main(int argc, char** argv) {
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;
@@ -236,6 +252,18 @@ int main(int argc, char** argv) {
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") {
@@ -243,6 +271,23 @@ int main(int argc, char** argv) {
} 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") {
@@ -301,6 +346,21 @@ int main(int argc, char** argv) {
// 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();
@@ -341,6 +401,15 @@ int main(int argc, char** argv) {
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";
+37
View File
@@ -24,6 +24,7 @@ struct Vertex {
osg::Vec2f uv; // OpenGL convention: (0,0) is the bottom-left of the image
int32_t bones[4] = {-1, -1, -1, -1};
float weights[4] = {0.f, 0.f, 0.f, 0.f};
float edgeScale = 1.f; // PMX per-vertex outline width multiplier
};
enum class SphereMode { None, Multiply, Add, SubTexture };
@@ -51,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,6 +160,8 @@ 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 };
+22 -6
View File
@@ -112,7 +112,7 @@ private:
break;
default: throw std::runtime_error("unknown PMX weight type");
}
r_.f32(); // edge scale
v.edgeScale = r_.f32();
}
}
@@ -168,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();
@@ -301,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
+88
View File
@@ -32,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);
@@ -141,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;
@@ -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;
+9
View File
@@ -77,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);
@@ -109,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
+4
View File
@@ -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);
}
+3
View File
@@ -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;
};
+15 -2
View File
@@ -1,9 +1,11 @@
#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 {
@@ -63,8 +65,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 +77,15 @@ 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,
"#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;
}
+175
View File
@@ -0,0 +1,175 @@
#include "render/Look.h"
#include "render/Shaders.h"
#include <osg/BlendFunc>
#include <osg/ColorMask>
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <algorithm>
#include <cmath>
namespace mr {
namespace {
constexpr float kGroundExtent = 50.f;
osg::ref_ptr<osg::Node> createGroundShadow() {
osg::ref_ptr<osg::Geometry> quad = osg::createTexturedQuadGeometry(
osg::Vec3(-kGroundExtent, -kGroundExtent, 0.f), osg::Vec3(2.f * kGroundExtent, 0.f, 0.f),
osg::Vec3(0.f, 2.f * kGroundExtent, 0.f));
quad->setUseDisplayList(false);
quad->setUseVertexBufferObjects(true);
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(quad);
osg::StateSet* ss = geode->getOrCreateStateSet();
ss->setAttributeAndModes(createGroundShadowProgram(), osg::StateAttribute::ON);
ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg::StateAttribute::ON);
ss->setAttributeAndModes(new osg::Depth(osg::Depth::LEQUAL, 0.0, 1.0, false), osg::StateAttribute::ON);
ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
ss->setRenderBinDetails(5, "RenderBin");
return geode;
}
} // namespace
SceneLook::SceneLook(osg::Group* root, osg::Group* casters) : root_(root) {
osg::StateSet* ss = root_->getOrCreateStateSet();
lightDir_ = new osg::Uniform("u_lightDirection", osg::Vec3f(-0.5f, 0.5f, -1.f));
lightColor_ = new osg::Uniform("u_lightColor", settings_.lightColor);
shadowEnabled_ = new osg::Uniform("u_shadowEnabled", 0);
shadowMatrix_ = new osg::Uniform("u_shadowMatrix", osg::Matrixf());
shadowTexel_ = new osg::Uniform("u_shadowTexel", 1.f / 2048.f);
shadowSoftness_ = new osg::Uniform("u_shadowSoftness", 1.5f);
shadowBias_ = new osg::Uniform("u_shadowBias", 0.001f);
shadowStrength_ = new osg::Uniform("u_shadowStrength", 0.f);
groundOpacity_ = new osg::Uniform("u_groundShadowOpacity", 0.45f);
rimStrength_ = new osg::Uniform("u_rimStrength", 0.f);
rimColor_ = new osg::Uniform("u_rimColor", settings_.rimColor);
for (osg::Uniform* u : {lightDir_.get(), lightColor_.get(), shadowEnabled_.get(), shadowMatrix_.get(),
shadowTexel_.get(), shadowSoftness_.get(), shadowBias_.get(), shadowStrength_.get(),
groundOpacity_.get(), rimStrength_.get(), rimColor_.get()})
ss->addUniform(u);
ss->addUniform(new osg::Uniform("u_shadowMap", static_cast<int>(kShadowTextureUnit)));
{
shadowMap_ = new osg::Texture2D;
shadowMap_->setInternalFormat(GL_DEPTH_COMPONENT);
shadowMap_->setSourceFormat(GL_DEPTH_COMPONENT);
shadowMap_->setSourceType(GL_FLOAT);
shadowMap_->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
shadowMap_->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
shadowMap_->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
shadowMap_->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
ss->setTextureAttribute(kShadowTextureUnit, shadowMap_);
shadowCamera_ = new osg::Camera;
shadowCamera_->setName("ShadowCamera");
shadowCamera_->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
shadowCamera_->setRenderOrder(osg::Camera::PRE_RENDER);
shadowCamera_->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
shadowCamera_->setClearMask(GL_DEPTH_BUFFER_BIT);
shadowCamera_->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
shadowCamera_->setCullingMode(osg::CullSettings::VIEW_FRUSTUM_CULLING);
shadowCamera_->setCullMask(kShadowCasterMask);
shadowCamera_->setDrawBuffer(GL_NONE);
shadowCamera_->setReadBuffer(GL_NONE);
osg::StateSet* cs = shadowCamera_->getOrCreateStateSet();
cs->setAttributeAndModes(createShadowDepthProgram(),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
cs->setAttribute(new osg::ColorMask(false, false, false, false),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
cs->setMode(GL_BLEND, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
// The depth map must not be bound for sampling while it is being rendered.
cs->setTextureAttribute(kShadowTextureUnit, new osg::Texture2D,
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
shadowCamera_->addChild(casters);
root_->addChild(shadowCamera_);
resizeShadowMap(2048);
ground_ = createGroundShadow();
root_->addChild(ground_);
}
apply(settings_);
}
void SceneLook::setShadowsSupported(bool supported) {
if (supported == shadowsSupported_) return;
shadowsSupported_ = supported;
apply(settings_);
}
void SceneLook::resizeShadowMap(int size) {
if (size == shadowSize_) return;
shadowSize_ = size;
shadowMap_->setTextureSize(size, size);
shadowMap_->dirtyTextureObject();
shadowCamera_->setViewport(0, 0, size, size);
shadowCamera_->detach(osg::Camera::DEPTH_BUFFER);
shadowCamera_->attach(osg::Camera::DEPTH_BUFFER, shadowMap_.get());
shadowCamera_->setRenderingCache(nullptr); // rebuild the FBO at the new size
shadowTexel_->set(1.f / static_cast<float>(size));
}
void SceneLook::apply(const LookSettings& settings) {
settings_ = settings;
lightColor_->set(settings.lightColor);
rimStrength_->set(settings.rimStrength);
rimColor_->set(settings.rimColor);
shadowSoftness_->set(settings.shadowSoftness);
groundOpacity_->set(settings.groundShadowOpacity);
const bool shadows = shadowsSupported_ && settings.shadows;
shadowEnabled_->set(shadows ? 1 : 0);
shadowStrength_->set(shadows ? settings.shadowStrength : 0.f);
resizeShadowMap(1024 << std::clamp(settings.shadowQuality, 0, 2));
shadowCamera_->setNodeMask(shadows ? ~0u : 0u);
if (!shadows) ground_->setNodeMask(0u);
}
osg::Vec3f SceneLook::lightDirection(const osg::Matrixd& view) const {
if (settings_.lightFollowsCamera) {
// Light from the upper left, slightly in front of the camera.
osg::Vec3d viewDir(0.3, -0.5, -1.0);
osg::Vec3d world = osg::Matrixd::transform3x3(viewDir, osg::Matrixd::inverse(view));
world.normalize();
return osg::Vec3f(world);
}
const double az = osg::DegreesToRadians(double(settings_.lightAzimuth));
const double el = osg::DegreesToRadians(double(settings_.lightElevation));
osg::Vec3d from(std::cos(el) * std::cos(az), std::cos(el) * std::sin(az), std::sin(el));
return osg::Vec3f(-from);
}
void SceneLook::update(const osg::Matrixd& view, const osg::BoundingSphere& focus, bool groundVisible) {
const osg::Vec3f dir = lightDirection(view);
lightDir_->set(dir);
const bool shadows = shadowsSupported_ && settings_.shadows && focus.valid();
shadowCamera_->setNodeMask(shadows ? ~0u : 0u);
shadowEnabled_->set(shadows ? 1 : 0);
ground_->setNodeMask(shadows && settings_.groundShadow && groundVisible ? ~0u : 0u);
if (!shadows) return;
const double radius = std::max(focus.radius() * 1.1, 0.1);
const osg::Vec3d center = focus.center();
const osg::Vec3d d(dir);
const osg::Vec3d up = std::abs(d.z()) > 0.99 ? osg::Vec3d(0.0, 1.0, 0.0) : osg::Vec3d(0.0, 0.0, 1.0);
const double distance = radius * 4.0;
osg::Matrixd lightView = osg::Matrixd::lookAt(center - d * distance, center, up);
// Snap the light-space origin to whole texels so shadow edges do not shimmer as the camera moves.
const double texel = 2.0 * radius / shadowSize_;
osg::Vec3d origin = osg::Vec3d(0.0, 0.0, 0.0) * lightView;
lightView.postMultTranslate(osg::Vec3d(std::floor(origin.x() / texel) * texel - origin.x(),
std::floor(origin.y() / texel) * texel - origin.y(), 0.0));
osg::Matrixd lightProj = osg::Matrixd::ortho(-radius, radius, -radius, radius, 0.05, distance + radius * 4.0);
shadowCamera_->setViewMatrix(lightView);
shadowCamera_->setProjectionMatrix(lightProj);
const osg::Matrixd bias = osg::Matrixd::translate(1.0, 1.0, 1.0) * osg::Matrixd::scale(0.5, 0.5, 0.5);
shadowMatrix_->set(osg::Matrixf(lightView * lightProj * bias));
// Depth bias in shadow-map units: about one texel of world-space slope.
shadowBias_->set(static_cast<float>(1.5 * texel / (distance + radius * 4.0)));
}
} // namespace mr
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <osg/BoundingSphere>
#include <osg/Camera>
#include <osg/Group>
#include <osg/Texture2D>
#include <osg/Uniform>
#include "scene/LookSettings.h"
namespace mr {
// Owns the global lighting uniforms, the shadow map pass and the ground shadow floor.
class SceneLook {
public:
// Uniforms go on root's state set; the shadow pass renders `casters`.
SceneLook(osg::Group* root, osg::Group* casters);
void apply(const LookSettings& settings);
// Per frame: view is the active camera's view matrix, focus the region shadows must cover.
void update(const osg::Matrixd& view, const osg::BoundingSphere& focus, bool groundVisible);
bool shadowsSupported() const { return shadowsSupported_; }
void setShadowsSupported(bool supported);
osg::Vec3f lightDirection(const osg::Matrixd& view) const; // world space, direction of travel
private:
void resizeShadowMap(int size);
osg::ref_ptr<osg::Group> root_;
osg::ref_ptr<osg::Camera> shadowCamera_;
osg::ref_ptr<osg::Texture2D> shadowMap_;
osg::ref_ptr<osg::Node> ground_;
bool shadowsSupported_ = true;
int shadowSize_ = 0;
LookSettings settings_;
osg::ref_ptr<osg::Uniform> lightDir_, lightColor_, shadowEnabled_, shadowMatrix_, shadowTexel_, shadowSoftness_,
shadowBias_, shadowStrength_, groundOpacity_, rimStrength_, rimColor_;
};
} // namespace mr
+114 -22
View File
@@ -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
View File
@@ -12,7 +12,7 @@
namespace mr {
enum class LightingModel { MmdToon = 0, Lambert = 1 };
enum class LightingModel { MmdToon = 0, Lambert = 1, AnimeCel = 2, SoftStudio = 3 };
// Scene graph for one model. Converts the model's Y-up space to OSG's Z-up world
// and re-uploads deformed vertices whenever the pose or morph weights change.
@@ -28,7 +28,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
+443
View File
@@ -0,0 +1,443 @@
#include "render/PostFx.h"
#include <osg/Depth>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Program>
#include <osgUtil/CullVisitor>
#include <algorithm>
#include <cmath>
#ifndef GL_RGBA16F_ARB
#define GL_RGBA16F_ARB 0x881A
#endif
#ifndef GL_DEPTH_COMPONENT24
#define GL_DEPTH_COMPONENT24 0x81A6
#endif
namespace mr {
namespace {
// GLSL 1.20 throughout, for macOS's legacy OpenGL profile.
const char* kQuadVertex = R"(#version 120
varying vec2 v_uv;
void main() {
v_uv = gl_MultiTexCoord0.xy;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
)";
// Downsample with a soft-knee threshold: only bright areas glow.
const char* kBrightFragment = R"(#version 120
uniform sampler2D u_color;
uniform vec2 u_texel;
uniform float u_threshold;
varying vec2 v_uv;
void main() {
vec3 c = 0.25 * (texture2D(u_color, v_uv + u_texel * vec2(-1.0, -1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(1.0, -1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(-1.0, 1.0)).rgb +
texture2D(u_color, v_uv + u_texel * vec2(1.0, 1.0)).rgb);
float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
float knee = 0.5 * u_threshold + 1e-4;
float soft = clamp(l - u_threshold + knee, 0.0, 2.0 * knee);
soft = soft * soft / (4.0 * knee);
gl_FragColor = vec4(c * (max(soft, l - u_threshold) / max(l, 1e-4)), 1.0);
}
)";
// 9-tap Gaussian using bilinear taps.
const char* kBlurFragment = R"(#version 120
uniform sampler2D u_src;
uniform vec2 u_dir;
varying vec2 v_uv;
void main() {
vec3 c = texture2D(u_src, v_uv).rgb * 0.227027;
c += (texture2D(u_src, v_uv + u_dir * 1.384615).rgb + texture2D(u_src, v_uv - u_dir * 1.384615).rgb) * 0.316216;
c += (texture2D(u_src, v_uv + u_dir * 3.230769).rgb + texture2D(u_src, v_uv - u_dir * 3.230769).rgb) * 0.070270;
gl_FragColor = vec4(c, 1.0);
}
)";
// Screen-space ambient occlusion from the depth buffer (normals from depth derivatives).
const char* kAoFragment = R"(#version 120
uniform sampler2D u_depth;
uniform vec4 u_proj; // projection m00, m11, m20, m21
uniform vec2 u_projZ; // projection m22, m32
uniform float u_radius;
uniform float u_strength;
varying vec2 v_uv;
vec3 viewPos(vec2 uv) {
float zn = texture2D(u_depth, uv).r * 2.0 - 1.0;
float z = u_projZ.y / (zn + u_projZ.x);
vec2 ndc = uv * 2.0 - 1.0;
return vec3(z * (ndc.x + u_proj.z) / u_proj.x, z * (ndc.y + u_proj.w) / u_proj.y, z);
}
void main() {
if (texture2D(u_depth, v_uv).r >= 1.0) { gl_FragColor = vec4(1.0); return; }
vec3 p = viewPos(v_uv);
vec3 n = normalize(cross(dFdx(p), dFdy(p)));
if (n.z > 0.0) n = -n;
vec2 r = vec2(u_proj.x, u_proj.y) * (0.5 * u_radius / p.z);
float angle = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
float occlusion = 0.0;
for (int i = 0; i < 12; ++i) {
float t = (float(i) + 0.5) / 12.0;
float a = angle + float(i) * 2.3999632;
vec3 v = viewPos(v_uv + vec2(cos(a), sin(a)) * t * r) - p;
float vv = dot(v, v);
float falloff = max(0.0, 1.0 - vv / (u_radius * u_radius));
// The distance-scaled bias stops flat ground self-occluding as depth precision drops.
occlusion += falloff * max(0.0, (dot(v, n) - 0.004 * p.z) * inversesqrt(vv + 1e-6) - 0.15);
}
float ao = clamp(1.0 - u_strength * occlusion / 4.0, 0.0, 1.0);
// Depth precision runs out far away (sky domes, distant terrain): fade out instead of banding.
ao = mix(ao, 1.0, smoothstep(60.0 * u_radius, 120.0 * u_radius, p.z));
gl_FragColor = vec4(ao, ao, ao, 1.0);
}
)";
const char* kCompositeFragment = R"(#version 120
uniform sampler2D u_color;
uniform sampler2D u_bloom;
uniform sampler2D u_ao;
uniform vec2 u_aoTexel;
uniform int u_bloomOn;
uniform int u_aoOn;
uniform int u_toneMap;
uniform float u_bloomStrength;
uniform float u_exposure;
uniform float u_contrast;
uniform float u_saturation;
uniform vec3 u_tint;
uniform float u_vignette;
varying vec2 v_uv;
vec3 aces(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); }
void main() {
vec4 src = texture2D(u_color, v_uv);
vec3 c = src.rgb;
if (u_aoOn == 1) {
float ao = 0.25 * (texture2D(u_ao, v_uv + u_aoTexel * vec2(-0.75, -0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(0.75, -0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(-0.75, 0.75)).r +
texture2D(u_ao, v_uv + u_aoTexel * vec2(0.75, 0.75)).r);
c *= ao;
}
if (u_bloomOn == 1) c += texture2D(u_bloom, v_uv).rgb * u_bloomStrength;
c *= u_exposure * u_tint;
// Filmic: ACES fit, scaled so white lands near 0.85 and highlights roll off instead of clipping.
if (u_toneMap == 1) c = pow(aces(max(c, 0.0) * 0.8) / 0.886, vec3(1.15));
c = (c - 0.5) * u_contrast + 0.5;
float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
c = mix(vec3(l), c, u_saturation);
vec2 d = v_uv - 0.5;
c *= 1.0 - u_vignette * smoothstep(0.25, 0.75, dot(d, d) * 2.0);
gl_FragColor = vec4(clamp(c, 0.0, 1.0), src.a);
}
)";
// FXAA (the compact "console" variant) or a plain copy.
const char* kFinalFragment = R"(#version 120
uniform sampler2D u_src;
uniform vec2 u_texel;
uniform int u_fxaa;
varying vec2 v_uv;
float luma(vec3 c) { return dot(c, vec3(0.299, 0.587, 0.114)); }
void main() {
vec4 m = texture2D(u_src, v_uv);
if (u_fxaa == 0) { gl_FragColor = m; return; }
float lNW = luma(texture2D(u_src, v_uv + vec2(-1.0, -1.0) * u_texel).rgb);
float lNE = luma(texture2D(u_src, v_uv + vec2(1.0, -1.0) * u_texel).rgb);
float lSW = luma(texture2D(u_src, v_uv + vec2(-1.0, 1.0) * u_texel).rgb);
float lSE = luma(texture2D(u_src, v_uv + vec2(1.0, 1.0) * u_texel).rgb);
float lM = luma(m.rgb);
float lMin = min(lM, min(min(lNW, lNE), min(lSW, lSE)));
float lMax = max(lM, max(max(lNW, lNE), max(lSW, lSE)));
vec2 dir = vec2(-((lNW + lNE) - (lSW + lSE)), (lNW + lSW) - (lNE + lSE));
float reduce = max((lNW + lNE + lSW + lSE) * 0.03125, 1.0 / 128.0);
float rcp = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce);
dir = clamp(dir * rcp, vec2(-8.0), vec2(8.0)) * u_texel;
vec3 a = 0.5 * (texture2D(u_src, v_uv - dir / 6.0).rgb + texture2D(u_src, v_uv + dir / 6.0).rgb);
vec3 b = a * 0.5 + 0.25 * (texture2D(u_src, v_uv - dir * 0.5).rgb + texture2D(u_src, v_uv + dir * 0.5).rgb);
float lB = luma(b);
gl_FragColor = vec4((lB < lMin || lB > lMax) ? a : b, m.a);
}
)";
osg::ref_ptr<osg::Texture2D> makeTexture(GLint internalFormat, GLenum format, GLenum type, bool linear) {
osg::ref_ptr<osg::Texture2D> t = new osg::Texture2D;
t->setInternalFormat(internalFormat);
t->setSourceFormat(format);
t->setSourceType(type);
const osg::Texture::FilterMode f = linear ? osg::Texture::LINEAR : osg::Texture::NEAREST;
t->setFilter(osg::Texture::MIN_FILTER, f);
t->setFilter(osg::Texture::MAG_FILTER, f);
t->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
t->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
t->setResizeNonPowerOfTwoHint(false);
t->setTextureSize(4, 4);
return t;
}
// A pass that draws one fullscreen quad with `fragment` into `target` (or into the parent camera).
osg::ref_ptr<osg::Camera> makePass(const char* name, const char* fragment, osg::Texture2D* target, int order) {
osg::ref_ptr<osg::Camera> cam = new osg::Camera;
cam->setName(name);
cam->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
cam->setProjectionMatrix(osg::Matrixd::ortho2D(0.0, 1.0, 0.0, 1.0));
cam->setViewMatrix(osg::Matrixd::identity());
cam->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
cam->setInheritanceMask(cam->getInheritanceMask() & ~osg::CullSettings::CULL_MASK);
cam->setCullMask(~0u);
if (target) {
cam->setRenderOrder(osg::Camera::PRE_RENDER, order);
cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
cam->setClearMask(0);
cam->attach(osg::Camera::COLOR_BUFFER, target);
} else {
cam->setRenderOrder(osg::Camera::NESTED_RENDER);
cam->setClearMask(0);
}
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0, 0, 0), osg::Vec3(1, 0, 0), osg::Vec3(0, 1, 0)));
geode->setCullingActive(false);
osg::StateSet* ss = geode->getOrCreateStateSet();
osg::ref_ptr<osg::Program> program = new osg::Program;
program->setName(name);
program->addShader(new osg::Shader(osg::Shader::VERTEX, kQuadVertex));
program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragment));
ss->setAttributeAndModes(program, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_BLEND, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
ss->setAttributeAndModes(new osg::Depth(osg::Depth::ALWAYS, 0.0, 1.0, false),
osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
cam->addChild(geode);
return cam;
}
void bind(osg::Camera* pass, unsigned unit, osg::Texture2D* tex, const char* sampler) {
osg::StateSet* ss = pass->getChild(0)->getOrCreateStateSet();
ss->setTextureAttribute(unit, tex, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
ss->addUniform(new osg::Uniform(sampler, static_cast<int>(unit)));
}
osg::Uniform* uniform(osg::Camera* pass, osg::Uniform* u) {
pass->getChild(0)->getOrCreateStateSet()->addUniform(u);
return u;
}
void resizeTarget(osg::Camera* cam, osg::Camera::BufferComponent buffer, osg::Texture2D* tex, int w, int h) {
tex->setTextureSize(w, h);
tex->dirtyTextureObject();
cam->setViewport(0, 0, w, h);
cam->detach(buffer);
cam->attach(buffer, tex);
cam->setRenderingCache(nullptr);
}
class ProjectionCallback : public osg::NodeCallback {
public:
void operator()(osg::Node* node, osg::NodeVisitor* nv) override {
if (auto* cv = nv->asCullVisitor())
if (cv->getProjectionMatrix() && cv->getModelViewMatrix())
static_cast<PostChain*>(node)->cullUpdate(*cv->getProjectionMatrix(), *cv->getModelViewMatrix());
traverse(node, nv);
}
};
} // namespace
bool postFxActive(const LookSettings& s) {
return s.bloom || s.ambientOcclusion || s.toneMapping != 0 || s.fxaa || s.exposure != 1.f || s.contrast != 1.f ||
s.saturation != 1.f || s.temperature != 0.f || s.vignette > 0.f;
}
PostChain::PostChain(osg::Node* scene, unsigned viewMask) : scene_(scene) {
setNodeMask(viewMask);
setCullCallback(new ProjectionCallback);
addChild(scene_);
}
void PostChain::setSupported(bool framebufferObjects, bool floatTextures) {
if (framebufferObjects == supported_ && floatTextures == floatColor_) return;
supported_ = framebufferObjects;
if (!built_) floatColor_ = floatTextures;
refresh();
}
void PostChain::apply(const LookSettings& settings) {
settings_ = settings;
refresh();
}
void PostChain::setClearColor(const osg::Vec4& color) {
clearColor_ = color;
if (sceneCam_) sceneCam_->setClearColor(color);
}
void PostChain::cullUpdate(const osg::Matrixd& p, const osg::Matrixd& view) {
if (!active_) return;
osg::Matrixd fitted = p;
const osg::BoundingSphere bs = scene_->getBound();
if (p(2, 3) != 0.0 && p(3, 2) != 0.0 && bs.valid()) {
// Perspective: re-fit near/far around the scene, as OSG does for the output camera itself,
// so large stages and sky domes are not clipped.
const double dist = -(bs.center() * view).z(), r = bs.radius();
const double f = std::max(dist + r, 1.0);
// Same near/far ratio OSG uses for the window, which keeps depth precision for sky domes.
const double n = std::max(std::max(dist - r, f * 0.0005), 0.1);
const double m22 = -(f + n) / (f - n), m32 = -2.0 * f * n / (f - n);
osg::Matrixd correction; // remaps clip-space z only
correction(2, 2) = m32 / p(3, 2);
correction(3, 2) = p(2, 2) * m32 / p(3, 2) - m22;
fitted = p * correction;
}
sceneCam_->setViewMatrix(view);
sceneCam_->setProjectionMatrix(fitted);
proj_->set(osg::Vec4f(fitted(0, 0), fitted(1, 1), fitted(2, 0), fitted(2, 1)));
projZ_->set(osg::Vec2f(fitted(2, 2), fitted(3, 2)));
}
void PostChain::build() {
// Model shaders clamp to [0, 1], so 8-bit targets lose nothing and halve the bandwidth of float ones.
const GLint colorFormat = GL_RGBA8;
const GLenum colorType = GL_UNSIGNED_BYTE;
color_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
depth_ = makeTexture(GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false);
bloomA_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
bloomB_ = makeTexture(colorFormat, GL_RGBA, colorType, true);
ao_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true);
ldr_ = makeTexture(GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, true);
// Uses the output camera's view and projection (set each cull) and inherits its cull mask.
sceneCam_ = new osg::Camera;
sceneCam_->setName("PostSceneCamera");
sceneCam_->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
sceneCam_->setRenderOrder(osg::Camera::PRE_RENDER, 0);
sceneCam_->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
sceneCam_->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
sceneCam_->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
sceneCam_->setClearColor(clearColor_);
sceneCam_->attach(osg::Camera::COLOR_BUFFER, color_.get());
sceneCam_->attach(osg::Camera::DEPTH_BUFFER, depth_.get());
sceneCam_->addChild(scene_);
brightCam_ = makePass("PostBright", kBrightFragment, bloomA_.get(), 1);
bind(brightCam_, 0, color_.get(), "u_color");
brightTexel_ = uniform(brightCam_, new osg::Uniform("u_texel", osg::Vec2f()));
threshold_ = uniform(brightCam_, new osg::Uniform("u_threshold", 0.75f));
blurHCam_ = makePass("PostBlurH", kBlurFragment, bloomB_.get(), 2);
bind(blurHCam_, 0, bloomA_.get(), "u_src");
blurHDir_ = uniform(blurHCam_, new osg::Uniform("u_dir", osg::Vec2f()));
blurVCam_ = makePass("PostBlurV", kBlurFragment, bloomA_.get(), 3);
bind(blurVCam_, 0, bloomB_.get(), "u_src");
blurVDir_ = uniform(blurVCam_, new osg::Uniform("u_dir", osg::Vec2f()));
aoCam_ = makePass("PostAo", kAoFragment, ao_.get(), 4);
bind(aoCam_, 0, depth_.get(), "u_depth");
proj_ = uniform(aoCam_, new osg::Uniform("u_proj", osg::Vec4f(1, 1, 0, 0)));
projZ_ = uniform(aoCam_, new osg::Uniform("u_projZ", osg::Vec2f(-1, -0.2f)));
aoRadius_ = uniform(aoCam_, new osg::Uniform("u_radius", 1.5f));
aoStrength_ = uniform(aoCam_, new osg::Uniform("u_strength", 1.f));
compositeCam_ = makePass("PostComposite", kCompositeFragment, ldr_.get(), 5);
bind(compositeCam_, 0, color_.get(), "u_color");
bind(compositeCam_, 1, bloomA_.get(), "u_bloom");
bind(compositeCam_, 2, ao_.get(), "u_ao");
compositeAoTexel_ = uniform(compositeCam_, new osg::Uniform("u_aoTexel", osg::Vec2f()));
bloomOn_ = uniform(compositeCam_, new osg::Uniform("u_bloomOn", 0));
aoOn_ = uniform(compositeCam_, new osg::Uniform("u_aoOn", 0));
toneMap_ = uniform(compositeCam_, new osg::Uniform("u_toneMap", 0));
bloomStrength_ = uniform(compositeCam_, new osg::Uniform("u_bloomStrength", 0.5f));
exposure_ = uniform(compositeCam_, new osg::Uniform("u_exposure", 1.f));
contrast_ = uniform(compositeCam_, new osg::Uniform("u_contrast", 1.f));
saturation_ = uniform(compositeCam_, new osg::Uniform("u_saturation", 1.f));
tint_ = uniform(compositeCam_, new osg::Uniform("u_tint", osg::Vec3f(1, 1, 1)));
vignette_ = uniform(compositeCam_, new osg::Uniform("u_vignette", 0.f));
finalCam_ = makePass("PostFinal", kFinalFragment, nullptr, 0);
bind(finalCam_, 0, ldr_.get(), "u_src");
fxaaOn_ = uniform(finalCam_, new osg::Uniform("u_fxaa", 0));
fxaaTexel_ = uniform(finalCam_, new osg::Uniform("u_texel", osg::Vec2f()));
built_ = true;
const int w = width_, h = height_;
width_ = height_ = 0;
setSize(std::max(w, 1), std::max(h, 1));
}
void PostChain::setSize(int width, int height) {
width = std::max(width, 1);
height = std::max(height, 1);
if (width == width_ && height == height_) return;
width_ = width;
height_ = height;
if (!built_) return;
const int bw = std::max(width / 4, 1), bh = std::max(height / 4, 1);
const int aw = std::max(width / 2, 1), ah = std::max(height / 2, 1);
resizeTarget(sceneCam_, osg::Camera::COLOR_BUFFER, color_, width, height);
resizeTarget(sceneCam_, osg::Camera::DEPTH_BUFFER, depth_, width, height);
resizeTarget(brightCam_, osg::Camera::COLOR_BUFFER, bloomA_, bw, bh);
resizeTarget(blurHCam_, osg::Camera::COLOR_BUFFER, bloomB_, bw, bh);
blurVCam_->setViewport(0, 0, bw, bh);
blurVCam_->setRenderingCache(nullptr);
resizeTarget(aoCam_, osg::Camera::COLOR_BUFFER, ao_, aw, ah);
resizeTarget(compositeCam_, osg::Camera::COLOR_BUFFER, ldr_, width, height);
brightTexel_->set(osg::Vec2f(1.f / width, 1.f / height));
compositeAoTexel_->set(osg::Vec2f(1.f / aw, 1.f / ah));
fxaaTexel_->set(osg::Vec2f(1.f / width, 1.f / height));
refresh();
}
void PostChain::refresh() {
const bool active = supported_ && postFxActive(settings_);
if (active && !built_) build();
if (active != active_) {
active_ = active;
removeChildren(0, getNumChildren());
if (active) {
for (osg::Camera* cam : {sceneCam_.get(), brightCam_.get(), blurHCam_.get(), blurVCam_.get(), aoCam_.get(),
compositeCam_.get(), finalCam_.get()})
addChild(cam);
} else {
addChild(scene_);
}
}
if (!built_) return;
const LookSettings& s = settings_;
const unsigned bloomMask = s.bloom ? ~0u : 0u;
brightCam_->setNodeMask(bloomMask);
blurHCam_->setNodeMask(bloomMask);
blurVCam_->setNodeMask(bloomMask);
aoCam_->setNodeMask(s.ambientOcclusion ? ~0u : 0u);
// FXAA alone reads the scene directly and skips the full-screen composite pass.
const bool composite = s.bloom || s.ambientOcclusion || s.toneMapping != 0 || s.exposure != 1.f ||
s.contrast != 1.f || s.saturation != 1.f || s.temperature != 0.f || s.vignette > 0.f;
compositeCam_->setNodeMask(composite ? ~0u : 0u);
finalCam_->getChild(0)->getOrCreateStateSet()->setTextureAttribute(
0, composite ? ldr_.get() : color_.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
const float bw = static_cast<float>(std::max(width_ / 4, 1)), bh = static_cast<float>(std::max(height_ / 4, 1));
// Blur radius scales with the image height so the glow looks the same at any resolution.
const float spread = s.bloomRadius * std::max(height_, 1) / 540.f;
blurHDir_->set(osg::Vec2f(spread / bw, 0.f));
blurVDir_->set(osg::Vec2f(0.f, spread / bh));
threshold_->set(s.bloomThreshold);
bloomOn_->set(s.bloom ? 1 : 0);
bloomStrength_->set(s.bloomStrength);
aoOn_->set(s.ambientOcclusion ? 1 : 0);
aoRadius_->set(s.aoRadius);
aoStrength_->set(s.aoStrength);
toneMap_->set(s.toneMapping);
exposure_->set(s.exposure);
contrast_->set(s.contrast);
saturation_->set(s.saturation);
const float t = std::clamp(s.temperature, -1.f, 1.f);
tint_->set(osg::Vec3f(1.f + 0.12f * t, 1.f + 0.02f * t, 1.f - 0.15f * t));
vignette_->set(s.vignette);
fxaaOn_->set(s.fxaa ? 1 : 0);
}
} // namespace mr
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include <osg/Camera>
#include <osg/Group>
#include <osg/Texture2D>
#include <osg/Uniform>
#include "scene/LookSettings.h"
namespace mr {
// Node-mask bits that pick which output camera draws which post-processing chain.
constexpr unsigned kMainViewMask = 0x10;
constexpr unsigned kPopViewMask = 0x20;
constexpr unsigned kRenderViewMask = 0x40;
// True when any post-processing effect is switched on.
bool postFxActive(const LookSettings& settings);
// Post-processing for one output camera. Nested cameras render the scene into textures with the
// output camera's view and projection, then bloom, ambient occlusion, tone mapping, colour grading
// and FXAA are composited onto a fullscreen quad. With every effect off the scene is drawn directly.
class PostChain : public osg::Group {
public:
PostChain(osg::Node* scene, unsigned viewMask);
void setSupported(bool framebufferObjects, bool floatTextures);
bool supported() const { return supported_; }
void apply(const LookSettings& settings);
void setSize(int width, int height);
void setClearColor(const osg::Vec4& color);
// Called while culling: fits near/far to the scene (the output camera's are fixed) and
// passes the resulting projection to the ambient-occlusion pass.
void cullUpdate(const osg::Matrixd& projection, const osg::Matrixd& view);
private:
void build();
void refresh();
osg::ref_ptr<osg::Node> scene_;
LookSettings settings_;
bool supported_ = false, floatColor_ = false, built_ = false, active_ = false;
int width_ = 0, height_ = 0;
osg::Vec4 clearColor_{0.f, 0.f, 0.f, 1.f};
osg::ref_ptr<osg::Texture2D> color_, depth_, bloomA_, bloomB_, ao_, ldr_;
osg::ref_ptr<osg::Camera> sceneCam_, brightCam_, blurHCam_, blurVCam_, aoCam_, compositeCam_, finalCam_;
osg::ref_ptr<osg::Uniform> brightTexel_, threshold_, blurHDir_, blurVDir_, aoTexel_, aoRadius_, aoStrength_,
proj_, projZ_, bloomOn_, aoOn_, bloomStrength_, toneMap_, exposure_, contrast_, saturation_, tint_,
vignette_, compositeAoTexel_, fxaaOn_, fxaaTexel_;
};
} // namespace mr
+221 -36
View File
@@ -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
+10
View File
@@ -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
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <osg/Vec3f>
namespace mr {
// Scene-wide visual settings shown in the Look panel and saved in scene files.
struct LookSettings {
int shading = 0; // 0 MMD toon, 1 Lambert, 2 anime cel, 3 soft studio
osg::Vec3f lightColor{0.6f, 0.6f, 0.6f};
float lightAzimuth = -45.f; // degrees around +Z; direction the light comes from
float lightElevation = 54.7f; // degrees above the floor
bool lightFollowsCamera = false;
bool outlines = true;
float outlineWidth = 1.f;
bool shadows = true;
int shadowQuality = 1; // 0 low (1024), 1 medium (2048), 2 high (4096)
float shadowSoftness = 1.5f;
float shadowStrength = 0.65f;
bool stageShadows = false; // stages cast shadows too (costly on old GPUs)
bool groundShadow = true; // shadow-only floor when no stage is visible
float groundShadowOpacity = 0.45f;
float rimStrength = 0.f;
osg::Vec3f rimColor{1.f, 1.f, 1.f};
// Post-processing; with all of it off the scene is drawn directly, at no extra cost.
bool bloom = false;
float bloomStrength = 0.4f;
float bloomThreshold = 0.8f;
float bloomRadius = 1.f;
bool ambientOcclusion = false;
float aoStrength = 1.f;
float aoRadius = 1.5f; // world units; a character is about 20 tall
int toneMapping = 0; // 0 off, 1 filmic
float exposure = 1.f;
float contrast = 1.f;
float saturation = 1.f;
float temperature = 0.f; // -1 cool .. 1 warm
float vignette = 0.f;
bool fxaa = false;
};
} // namespace mr
+84 -4
View File
@@ -18,6 +18,14 @@ 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);
@@ -83,6 +91,11 @@ bool saveScene(const Scene& scene, const std::string& path, std::string& error)
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)
@@ -94,8 +107,37 @@ bool saveScene(const Scene& scene, const std::string& path, std::string& error)
{"skeleton", scene.skeleton},
{"wireframe", scene.wireframe},
{"backfaceCulling", scene.backfaceCulling},
{"lightFollowsCamera", scene.lightFollowsCamera},
{"shading", scene.lightingModel == 1 ? "lambert" : "toon"}};
{"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},
@@ -174,6 +216,13 @@ bool loadScene(const std::string& path, Scene& scene, std::string& error) {
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);
}
@@ -191,8 +240,39 @@ bool loadScene(const std::string& path, Scene& scene, std::string& error) {
read(*it, "skeleton", scene.skeleton);
read(*it, "wireframe", scene.wireframe);
read(*it, "backfaceCulling", scene.backfaceCulling);
read(*it, "lightFollowsCamera", scene.lightFollowsCamera);
scene.lightingModel = it->value("shading", std::string("toon")) == "lambert" ? 1 : 0;
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);
+8 -2
View File
@@ -3,6 +3,7 @@
// 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>
@@ -35,12 +36,17 @@ struct Scene {
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, lightFollowsCamera = false;
int lightingModel = 0; // 0 MMD toon, 1 Lambert
bool skeleton = false, wireframe = false, backfaceCulling = true;
LookSettings look;
int renderWidth = 1920, renderHeight = 1080;
bool renderTransparent = false, renderMp4 = true, renderAudio = true;
+55 -2
View File
@@ -373,8 +373,18 @@ void testSceneFile() {
scene.audioPath = mr::pathToUtf8(dir / "project" / "song.wav");
scene.view.valid = true;
scene.view.eye.set(0, -40, 10);
scene.lightingModel = 1;
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));
@@ -387,6 +397,8 @@ void testSceneFile() {
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"));
@@ -399,7 +411,11 @@ void testSceneFile() {
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.lightingModel == 1 && loaded.renderWidth == 1280);
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");
@@ -408,8 +424,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<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();