Look panel: outlines, shadows, cel/studio shading, rim light #9

Merged
dev merged 4 commits from devin/1796104981-shaders into main 2026-12-01 01:31:16 -05:00
20 changed files with 759 additions and 82 deletions

No files matched your search

+1
View File
@@ -141,6 +141,7 @@ add_executable(model_renderer
src/app/SceneIo.cpp
src/render/Grid.cpp
src/render/ModelNode.cpp
src/render/Look.cpp
src/render/TextureLoader.cpp
src/render/Shaders.cpp
src/render/GpuCaps.cpp
+8 -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
@@ -145,8 +145,14 @@ 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`.
* **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.
+123 -9
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>
@@ -75,6 +76,30 @@ App::App(osgViewer::Viewer& viewer, osg::Group* root, osgGA::TrackballManipulato
imgui_->attach(viewer_);
grid_ = createGrid(50.f, 5.f);
root_->addChild(grid_);
sceneGroup_ = new osg::Group;
root_->addChild(sceneGroup_);
sceneLook_ = std::make_unique<SceneLook>(root_.get(), sceneGroup_.get());
}
void App::setLook(const LookSettings& look) {
look_ = look;
applyViewSettings();
}
void App::updateLook() {
if (gpuCaps().probed) sceneLook_->setShadowsSupported(gpuCaps().shadows);
// 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 +126,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 +151,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;
@@ -146,18 +171,21 @@ void App::updatePlacement(SceneItem& item) {
}
void App::applyViewSettings() {
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);
}
}
@@ -421,6 +449,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_) {
@@ -512,6 +541,7 @@ void App::drawUi() {
ImGui::End();
}
}
drawLookWindow();
drawTimelineWindow();
drawRenderDialog();
if (showDemo_) ImGui::ShowDemoWindow(&showDemo_);
@@ -532,6 +562,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 +592,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 +768,85 @@ 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;
};
const Preset presets[] = {{"MMD classic", 0, true, 0.f, {0.6f, 0.6f, 0.6f}},
{"Anime", 2, true, 0.6f, {0.85f, 0.82f, 0.8f}},
{"Studio", 3, false, 0.35f, {0.95f, 0.9f, 0.82f}}};
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;
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::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();
+8 -2
View File
@@ -6,6 +6,7 @@
#include "app/FileBrowser.h"
#include "audio/AudioPlayer.h"
#include "model/Motion.h"
#include "render/Look.h"
#include "render/ModelNode.h"
#include "ui/ImGuiOsg.h"
@@ -40,6 +41,8 @@ public:
void setShowSkeleton(bool show);
void setGpuSkinning(bool enabled);
void setPhysicsEnabled(bool enabled);
const LookSettings& look() const { return look_; }
void setLook(const LookSettings& look);
bool loadMotion(const std::string& path);
void unloadMotion();
@@ -64,6 +67,8 @@ private:
void drawBonesWindow();
void drawBoneEditor();
void drawMorphsWindow();
void drawLookWindow();
void updateLook();
void applyViewSettings();
void drawTimelineWindow();
void drawTimelineTracks(float end);
@@ -84,6 +89,8 @@ private:
osgViewer::Viewer& viewer_;
osg::ref_ptr<osg::Group> root_;
osg::ref_ptr<osg::Group> sceneGroup_; // models and stages
std::unique_ptr<SceneLook> sceneLook_;
osg::ref_ptr<osgGA::TrackballManipulator> manipulator_;
osg::ref_ptr<ImGuiOsg> imgui_;
struct SceneItem {
@@ -118,8 +125,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;
+2 -4
View File
@@ -74,8 +74,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,8 +139,7 @@ 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;
volume_ = scene.volume;
+23
View File
@@ -75,6 +75,10 @@ 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"
" --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"
@@ -172,6 +176,8 @@ int main(int argc, char** argv) {
float modelScale = 1.f, stageScale = 1.f;
std::string saveScenePath;
bool orbitSet = false, physicsSet = false;
int shading = -1, shadows = -1, outlines = -1;
float rim = -1.f;
int reloadTest = 0;
std::string renderDir;
int renderStart = 0, renderEnd = -1, renderW = 1920, renderH = 1080;
@@ -243,6 +249,15 @@ 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 == "--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 +316,14 @@ 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 (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();
+3
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;
};
+3 -1
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();
+2
View File
@@ -25,6 +25,8 @@ 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.probed = true;
if (next_) (*next_)(gc);
}
+1
View File
@@ -9,6 +9,7 @@ namespace mr {
struct GpuCaps {
bool probed = false;
bool skinning = false; // vertex texture fetch + float textures
bool shadows = false; // depth textures + framebuffer objects
std::string renderer;
};
+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
+57 -17
View File
@@ -17,9 +17,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 +51,9 @@ 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)));
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);
@@ -119,6 +110,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);
@@ -164,8 +157,60 @@ void ModelNode::buildMesh() {
}
meshGroup_ = geode;
addChild(meshGroup_);
buildEdges(uvs.get());
}
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();
es->addUniform(new osg::Uniform("u_edgeColor", m.edgeColor));
es->addUniform(new osg::Uniform("u_edgeSize", m.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 +317,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;
@@ -381,6 +427,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 +438,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);
+9 -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,7 @@ private:
osg::StateSet* buildMaterialState(const Material& material, int order);
void preloadTextureImages();
osg::Texture2D* texture(int index, bool clamp);
void buildEdges(osg::Vec2Array* uvs);
void buildSkinning();
void uploadBoneMatrices();
void buildSkeleton();
@@ -78,8 +82,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
+210 -35
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,17 @@ 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;
varying vec3 v_normal;
varying vec3 v_viewPos;
varying vec2 v_uv;
@@ -74,51 +125,175 @@ 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 base = u_diffuse;
if (u_useTexture == 1) base *= texture2D(u_texture, v_uv);
float alpha = base.a;
if (alpha < 0.004) discard;
vec3 tex = u_useTexture == 1 ? texture2D(u_texture, v_uv).rgb : vec3(1.0);
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;
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) color *= texture2D(u_toon, vec2(0.5, min(t, mix(1.0, t * shadow, u_shadowStrength)))).rgb;
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
+30
View File
@@ -0,0 +1,30 @@
#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};
};
} // namespace mr
+44 -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);
@@ -94,8 +102,23 @@ 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)}};
j["render"] = {{"width", scene.renderWidth},
{"height", scene.renderHeight},
{"transparent", scene.renderTransparent},
@@ -191,8 +214,25 @@ 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);
}
if (auto it = j.find("render"); it != j.end() && it->is_object()) {
read(*it, "width", scene.renderWidth);
+3 -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>
@@ -39,8 +40,8 @@ struct Scene {
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;
+7 -2
View File
@@ -373,7 +373,10 @@ 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.renderWidth = 1280;
const std::string file = mr::pathToUtf8(dir / "project" / "test.mrscene");
std::string error;
@@ -399,7 +402,9 @@ 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.audioPath.empty() && loaded.cameraMotionPath.empty());
const std::string bad = mr::pathToUtf8(dir / "bad.mrscene");