Skip to content

An OpenMW mod that lets you play the whole Elder Scrolls III: Morrowind as a top-down isometric game — with full online co-op or MMO modes.

C++

Top-down view: the cutaway rebuilt; a porthole and a see-through ghost where the player is hidden, and indoors the other floors go

pw-tff0fc517562b9
diff --git a/apps/openmw/CMakeLists.txt b/apps/openmw/CMakeLists.txt
index 41f0c8d..176c6a2 100644
--- a/apps/openmw/CMakeLists.txt
+++ b/apps/openmw/CMakeLists.txt
@@ -23,7 +23,7 @@ add_openmw_dir (mwrender
bulletdebugdraw globalmap characterpreview camera localmap water terrainstorage ripplesimulation
renderbin actoranimation landmanager navmesh actorspaths recastmesh fogmanager objectpaging groundcover
postprocessor pingpongcull luminancecalculator pingpongcanvas transparentpass precipitationocclusion ripples
- actorutil distortion animationpriority bonegroup blendmask animblendcontroller playermask occlusionfader
+ actorutil distortion animationpriority bonegroup blendmask animblendcontroller playermask cutaway ghostlayer
)
add_openmw_dir (mwinput
diff --git a/apps/openmw/mwclass/door.cpp b/apps/openmw/mwclass/door.cpp
index e045204..596e72f 100644
--- a/apps/openmw/mwclass/door.cpp
+++ b/apps/openmw/mwclass/door.cpp
@@ -65,9 +65,9 @@ namespace MWClass
{
renderingInterface.getObjects().insertModel(ptr, model);
ptr.getRefData().getBaseNode()->setNodeMask(MWRender::Mask_Static);
- // Doors stay visible in the top-down cutaway (shaders/lib/util/cutaway.glsl), so they can be found
- // even in a wall that is cut away, and are drawn double-sided: their back is never modelled, since in
- // first person it can't be seen, but the top-down camera often looks at it.
+ // Doors are drawn double-sided: their back is never modelled, since in first person it can't be seen,
+ // but the top-down camera often looks at it. They are never cut away by it (MWRender::Cutaway) but with
+ // the storey above the player, as characters are, so there is always a way out to be seen.
osg::StateSet* stateset = ptr.getRefData().getBaseNode()->getOrCreateStateSet();
stateset->addUniform(new osg::Uniform("noCutaway", 0.75f));
stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE);
diff --git a/apps/openmw/mwlua/camerabindings.cpp b/apps/openmw/mwlua/camerabindings.cpp
index 92293ba..5ce9fe9 100644
--- a/apps/openmw/mwlua/camerabindings.cpp
+++ b/apps/openmw/mwlua/camerabindings.cpp
@@ -8,6 +8,7 @@
#include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp"
#include "../mwrender/camera.hpp"
+#include "../mwrender/cutaway.hpp"
#include "../mwrender/renderingmanager.hpp"
#include "object.hpp"
@@ -74,16 +75,25 @@ namespace MWLua
api["getExtraRoll"] = [camera]() { return -camera->getExtraRoll(); };
api["getProjectionOffset"] = [renderingManager]() { return renderingManager->getProjectionOffset(); };
- // Isowind: the objects the top-down camera fades because they stand in front of the player
- api["getFadedObjects"] = [renderingManager]() {
- auto ids = std::make_shared<std::vector<ObjectId>>();
- for (const MWWorld::Ptr& ptr : renderingManager->getFadedObjects())
- ids->push_back(getId(ptr));
- return LObjectList{ std::move(ids) };
+ // Isowind: whether the top-down camera cuts this point away, exactly as it is drawn (actor: it is on a
+ // character, creature or door, never in the porthole; object: what it is on, gone if on another floor
+ // indoors); see MWRender::Cutaway
+ api["isCutAway"] = [renderingManager](
+ const osg::Vec3f& point, sol::optional<bool> actor, sol::optional<LObject> object) {
+ const MWRender::Cutaway& cutaway = renderingManager->getCutaway();
+ return (object && cutaway.isHidden(object->ptr())) || cutaway.isCut(point, actor.value_or(false));
+ };
+ // Isowind: draw what the top-down camera cuts away tinted instead (blue: the porthole, orange: another floor
+ // going); 4 shows the ghost's own pass (magenta: drawn see-through, cyan: the clear opening, dark blue: left to
+ // the main view), -1 cuts nothing at all (to compare). true is 1, false or 0 is off.
+ api["setCutawayDebug"] = [renderingManager](sol::object level) {
+ int value = 0;
+ if (level.is<bool>())
+ value = level.as<bool>() ? 1 : 0;
+ else if (level.is<double>())
+ value = static_cast<int>(level.as<double>());
+ renderingManager->getCutaway().setDebug(value);
};
- // Isowind: the radius around the player within which the top-down camera cuts the room (ceilings and upper
- // floors over them, the walls in the way), indoors and under cover outdoors; 0 where nothing is cut
- api["getCutawayRadius"] = [renderingManager]() { return renderingManager->getCutawayRadius(); };
api["getThirdPersonDistance"] = [camera]() { return camera->getCameraDistance(); };
api["setPreferredThirdPersonDistance"]
diff --git a/apps/openmw/mwrender/animation.cpp b/apps/openmw/mwrender/animation.cpp
index 38dac7c..6d6706e 100644
--- a/apps/openmw/mwrender/animation.cpp
+++ b/apps/openmw/mwrender/animation.cpp
@@ -573,8 +573,8 @@ namespace MWRender
mLightListCallback = new SceneUtil::LightListCallback;
- // The top-down cutaway (shaders/lib/util/cutaway.glsl) never fades characters or creatures; indoors they
- // only go with the storey above the player.
+ // The top-down cutaway (MWRender::Cutaway) never cuts into characters or creatures; indoors they only go
+ // with the storey above the player.
if (!ptr.isEmpty() && ptr.getClass().isActor() && mInsert)
mInsert->getOrCreateStateSet()->addUniform(new osg::Uniform("noCutaway", 0.75f));
}
diff --git a/apps/openmw/mwrender/cutaway.cpp b/apps/openmw/mwrender/cutaway.cpp
new file mode 100644
index 0000000..d8d642d
--- /dev/null
+++ b/apps/openmw/mwrender/cutaway.cpp
@@ -0,0 +1,624 @@
+#include "cutaway.hpp"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <random>
+
+#include <osg/Camera>
+#include <osg/ComputeBoundsVisitor>
+#include <osg/Group>
+#include <osg/Texture2D>
+#include <osg/UserDataContainer>
+#include <osgUtil/CullVisitor>
+#include <osgUtil/IntersectionVisitor>
+#include <osgUtil/LineSegmentIntersector>
+
+#include <components/sceneutil/nodecallback.hpp>
+#include <components/sceneutil/positionattitudetransform.hpp>
+
+#include "../mwbase/environment.hpp"
+#include "../mwbase/world.hpp"
+#include "../mwworld/class.hpp"
+
+#include "objects.hpp"
+#include "playermask.hpp"
+#include "vismask.hpp"
+
+namespace MWRender
+{
+ namespace
+ {
+ // The porthole: an upper body this high over the feet, revealed within this radius of it on screen (plus a
+ // soft band); never what is within this of it or below the waist
+ constexpr float sBodyFrom = 70.f;
+ constexpr float sBodyTo = 120.f;
+ constexpr float sCoreRadius = 170.f;
+ constexpr float sSoftBand = 110.f;
+ constexpr float sBodyNear = 15.f;
+ constexpr float sBodySoft = 35.f;
+ constexpr float sWaist = 90.f;
+ constexpr float sWaistSoft = 25.f;
+ // ...nor what is behind the player, past this far behind them along the ground (fading over this much): seen
+ // from above, the top of an arch or a pole behind them is nearer the camera than they are
+ constexpr float sBehindFrom = 20.f;
+ constexpr float sBehindSoft = 40.f;
+ // Around the opening what is in the way is see-through: this opaque next to it, whole again this far from the
+ // body
+ constexpr float sGhostOpacity = 0.45f;
+ constexpr float sGhostReach = 520.f;
+
+ // When the porthole opens: rays to points over the body a few times a second; open when more than half of
+ // them are hidden, closed again under this much, after a moment; and how long opening and closing take
+ constexpr float sRayInterval = 0.1f;
+ constexpr float sOpenAbove = 0.5f;
+ constexpr float sCloseBelow = 0.3f;
+ constexpr float sOpenDelay = 0.05f;
+ constexpr float sCloseDelay = 0.3f;
+ constexpr float sOpenTime = 0.2f;
+ constexpr float sCloseTime = 0.6f;
+
+ // Indoors, another floor: what stands wholly this far above the player's floor (over the doors and the lamps
+ // on the walls; a character: standing this high), or wholly this far below it, with this much slack once it
+ // is; it dissolves away over this long. A character is this tall.
+ constexpr float sAbove = 220.f;
+ constexpr float sActorAbove = 150.f;
+ constexpr float sBelow = 40.f;
+ constexpr float sFloorSlack = 16.f;
+ constexpr float sFloorFade = 0.3f;
+ constexpr float sActorHeight = 120.f;
+
+ // How fast the floor follows the player's feet (per second), and how far is a teleport
+ constexpr float sFloorRate = 12.f;
+ constexpr float sTeleportDistance = 500.f;
+
+ constexpr int sNoiseSize = 64; // cutaway.glsl's CUTAWAY_NOISE_SIZE
+
+ float smoothstep(float edge0, float edge1, float x)
+ {
+ const float t = std::clamp((x - edge0) / (edge1 - edge0), 0.f, 1.f);
+ return t * t * (3.f - 2.f * t);
+ }
+
+ // The object a scene node is the base node of
+ MWWorld::Ptr ptrOf(const osg::Node& node)
+ {
+ if (const osg::UserDataContainer* container = node.getUserDataContainer())
+ {
+ for (unsigned int i = 0; i < container->getNumUserObjects(); ++i)
+ {
+ if (const PtrHolder* holder = dynamic_cast<const PtrHolder*>(container->getUserObject(i)))
+ return holder->mPtr;
+ }
+ }
+ return MWWorld::Ptr();
+ }
+
+ // What the scene's geometry is, for the rays: no terrain, characters, effects or the sky
+ unsigned int geometryMask()
+ {
+ return ~(Mask_RenderToTexture | Mask_Sky | Mask_Debug | Mask_Effect | Mask_Water | Mask_SimpleWater
+ | Mask_Groundcover | Mask_Actor | Mask_Player | Mask_Terrain | Mask_ParticleSystem
+ | Mask_WeatherParticles | Mask_FirstPerson | Mask_GUI);
+ }
+
+ // A blue noise tile (void and cluster): thresholds that dissolve a surface evenly, with no visible pattern.
+ // Values 1..254, so neither 0 nor 1 opacity is ever dithered.
+ osg::ref_ptr<osg::Image> makeBlueNoise()
+ {
+ constexpr int n = sNoiseSize;
+ constexpr int count = n * n;
+ constexpr int radius = 6;
+ constexpr float sigma = 1.9f;
+ std::array<float, (2 * radius + 1) * (2 * radius + 1)> kernel;
+ for (int dy = -radius; dy <= radius; ++dy)
+ for (int dx = -radius; dx <= radius; ++dx)
+ kernel[(dy + radius) * (2 * radius + 1) + dx + radius]
+ = std::exp(-(dx * dx + dy * dy) / (2.f * sigma * sigma));
+
+ std::vector<float> energy(count, 0.f);
+ std::vector<char> bits(count, 0);
+ auto splat = [&](std::vector<float>& field, int index, float sign) {
+ const int x0 = index % n;
+ const int y0 = index / n;
+ for (int dy = -radius; dy <= radius; ++dy)
+ for (int dx = -radius; dx <= radius; ++dx)
+ field[((y0 + dy + n) % n) * n + (x0 + dx + n) % n]
+ += sign * kernel[(dy + radius) * (2 * radius + 1) + dx + radius];
+ };
+ auto tightest = [&](const std::vector<float>& field, const std::vector<char>& set) {
+ int best = -1;
+ for (int i = 0; i < count; ++i)
+ if (set[i] && (best < 0 || field[i] > field[best]))
+ best = i;
+ return best;
+ };
+ auto emptiest = [&](const std::vector<float>& field, const std::vector<char>& set) {
+ int best = -1;
+ for (int i = 0; i < count; ++i)
+ if (!set[i] && (best < 0 || field[i] < field[best]))
+ best = i;
+ return best;
+ };
+
+ std::mt19937 random(1);
+ const int initial = count / 10;
+ for (int placed = 0; placed < initial;)
+ {
+ const int i = static_cast<int>(random() % count);
+ if (bits[i])
+ continue;
+ bits[i] = 1;
+ splat(energy, i, 1.f);
+ ++placed;
+ }
+ // Spread them evenly: move the most crowded point to the emptiest place until that is where it was
+ for (int iteration = 0; iteration < count; ++iteration)
+ {
+ const int crowded = tightest(energy, bits);
+ bits[crowded] = 0;
+ splat(energy, crowded, -1.f);
+ const int empty = emptiest(energy, bits);
+ bits[empty] = 1;
+ splat(energy, empty, 1.f);
+ if (empty == crowded)
+ break;
+ }
+
+ std::vector<int> rank(count, 0);
+ {
+ std::vector<float> field = energy;
+ std::vector<char> set = bits;
+ for (int r = initial - 1; r >= 0; --r)
+ {
+ const int crowded = tightest(field, set);
+ set[crowded] = 0;
+ splat(field, crowded, -1.f);
+ rank[crowded] = r;
+ }
+ }
+ for (int r = initial; r < count; ++r)
+ {
+ const int empty = emptiest(energy, bits);
+ bits[empty] = 1;
+ splat(energy, empty, 1.f);
+ rank[empty] = r;
+ }
+
+ osg::ref_ptr<osg::Image> image = new osg::Image;
+ image->allocateImage(n, n, 1, GL_RGBA, GL_UNSIGNED_BYTE);
+ unsigned char* data = image->data();
+ for (int i = 0; i < count; ++i)
+ {
+ const auto value = static_cast<unsigned char>(1 + (rank[i] * 253) / (count - 1));
+ std::fill(data + i * 4, data + i * 4 + 4, value);
+ }
+ return image;
+ }
+
+ // The cut (with its textures) for the main camera's view only: its state is pushed while the main camera is
+ // the one culling the scene, so the shadow cameras' and every render to texture's view of it (water, the map)
+ // stay whole.
+ class MainViewCallback : public SceneUtil::NodeCallback<MainViewCallback, osg::Node*, osgUtil::CullVisitor*>
+ {
+ public:
+ MainViewCallback(osg::Camera* mainCamera, osg::StateSet* stateset, PlayerMask* mask, int unit)
+ : mMainCamera(mainCamera)
+ , mStateSet(stateset)
+ , mMask(mask)
+ , mUnit(unit)
+ {
+ }
+
+ void operator()(osg::Node* node, osgUtil::CullVisitor* cv)
+ {
+ if (cv->getCurrentCamera() != mMainCamera)
+ {
+ traverse(node, cv);
+ return;
+ }
+ if (mMask && !mBound)
+ {
+ mStateSet->setTextureAttribute(mUnit, mMask->getColorTexture(cv), osg::StateAttribute::ON);
+ mBound = true;
+ }
+ cv->pushStateSet(mStateSet);
+ traverse(node, cv);
+ cv->popStateSet();
+ }
+
+ private:
+ osg::Camera* mMainCamera;
+ osg::ref_ptr<osg::StateSet> mStateSet;
+ osg::ref_ptr<PlayerMask> mMask;
+ int mUnit;
+ bool mBound = false;
+ };
+ }
+
+ Cutaway::Cutaway(osg::Group* rootNode, osg::Group* sceneRoot, osg::Camera* mainCamera, PlayerMask* playerMask,
+ int playerMaskUnit, int noiseUnit)
+ : mRootNode(rootNode)
+ , mSceneRoot(sceneRoot)
+ , mMainCamera(mainCamera)
+ , mRayVisitor(new osgUtil::IntersectionVisitor)
+ {
+ auto dynamic = [](osg::Uniform* uniform) {
+ uniform->setDataVariance(osg::Object::DYNAMIC);
+ return uniform;
+ };
+ // Everything but the switch and the textures is on the root node, so every view has them; only the main view
+ // turns the cut on.
+ osg::StateSet* stateset = rootNode->getOrCreateStateSet();
+ stateset->addUniform(new osg::Uniform("cutawayEnabled", 0.f));
+ stateset->addUniform(new osg::Uniform("noCutaway", 0.f));
+ stateset->addUniform(new osg::Uniform("cutawayGhostPass", 0.f));
+ stateset->addUniform(new osg::Uniform("cutawayFade", 0.f));
+ mGhostUniform = dynamic(new osg::Uniform("cutawayGhost", osg::Vec4f()));
+ mEyeUniform = dynamic(new osg::Uniform("cutawayEye", osg::Vec3f()));
+ mCapsuleA = dynamic(new osg::Uniform("cutawayCapA", osg::Vec3f()));
+ mCapsuleB = dynamic(new osg::Uniform("cutawayCapB", osg::Vec3f()));
+ mSight = dynamic(new osg::Uniform("cutawaySight", osg::Vec4f()));
+ mLevelUniform = dynamic(new osg::Uniform("cutawayLevel", osg::Vec4f()));
+ mAwayUniform = dynamic(new osg::Uniform("cutawayAway", osg::Vec4f()));
+ for (osg::Uniform* uniform : { mGhostUniform.get(), mEyeUniform.get(), mCapsuleA.get(), mCapsuleB.get(),
+ mSight.get(), mLevelUniform.get(), mAwayUniform.get() })
+ stateset->addUniform(uniform);
+ stateset->addUniform(new osg::Uniform("playerMaskTex", playerMaskUnit));
+ stateset->addUniform(new osg::Uniform("cutawayNoise", noiseUnit));
+
+ mEnabled = dynamic(new osg::Uniform("cutawayEnabled", 0.f));
+ mMainViewState = new osg::StateSet;
+ mMainViewState->setDataVariance(osg::Object::DYNAMIC);
+ mMainViewState->addUniform(mEnabled);
+
+ osg::ref_ptr<osg::Texture2D> noise = new osg::Texture2D(makeBlueNoise());
+ noise->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
+ noise->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
+ noise->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
+ noise->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
+ mMainViewState->setTextureAttribute(noiseUnit, noise, osg::StateAttribute::ON);
+
+ sceneRoot->addCullCallback(new MainViewCallback(mainCamera, mMainViewState, playerMask, playerMaskUnit));
+
+ // The ghost's pass: the cut on, as in the main view, with its texture, drawing only the ghost
+ mGhostState = new osg::StateSet;
+ mGhostState->setDataVariance(osg::Object::DYNAMIC);
+ mGhostState->addUniform(mEnabled);
+ mGhostState->addUniform(new osg::Uniform("cutawayGhostPass", 1.f));
+ mGhostState->setTextureAttribute(noiseUnit, noise, osg::StateAttribute::ON);
+ mGhostComposite = new GhostComposite;
+ mGhostComposite->setNodeMask(0);
+ rootNode->addChild(mGhostComposite);
+ mRayVisitor->setTraversalMask(geometryMask());
+ }
+
+ Cutaway::~Cutaway()
+ {
+ restoreFloors();
+ }
+
+ void Cutaway::update(float dt, const osg::Vec3f& eye, const MWWorld::Ptr& player, bool active, bool indoors,
+ osg::Group* cellNode)
+ {
+ mActive = active && !player.isEmpty() && player.isInCell() && mDebug >= 0;
+ mEnabled->set(mActive ? 1.f : 0.f);
+ if (!mActive)
+ {
+ mReset = true;
+ restoreFloors();
+ updateGhost(false);
+ return;
+ }
+
+ const osg::Vec3f feet = player.getRefData().getPosition().asVec3();
+ // Moved farther than anyone walks in a frame: a door or a teleport, so nothing eases over from before
+ if ((feet - mLastFeet).length() > sTeleportDistance)
+ mReset = true;
+ mLastFeet = feet;
+ mFeet = feet;
+
+ // The floor: where the player stands, and held while they are in the air, except that it follows them
+ // straight down (off a ledge), so jumping never changes which floor they are on
+ MWBase::World* world = MWBase::Environment::get().getWorld();
+ const bool grounded = world->isOnGround(player) || world->isFlying(player) || world->isSwimming(player);
+ if (mReset)
+ mFloor = feet.z();
+ else if (grounded)
+ mFloor += (feet.z() - mFloor) * (1.f - std::exp(-sFloorRate * dt));
+ mFloor = std::min(mFloor, feet.z());
+
+ mIndoors = indoors;
+ mEye = eye;
+ osg::Vec2f away(feet.x() - eye.x(), feet.y() - eye.y());
+ if (away.normalize() > 1e-3f)
+ mAway = away;
+
+ if (mIndoors)
+ updateFloors(dt, cellNode, player);
+ else
+ restoreFloors();
+ updateCoverage(dt);
+ mReset = false;
+ // (Not in the debug view, which tints what the porthole takes instead, but for 4: the ghost in magenta)
+ updateGhost((mDebug == 0 || mDebug == 4) && mSightStrength > 0.f);
+
+ mEyeUniform->set(mEye);
+ mCapsuleA->set(feet + osg::Vec3f(0.f, 0.f, sBodyFrom));
+ mCapsuleB->set(feet + osg::Vec3f(0.f, 0.f, sBodyTo));
+ mSight->set(osg::Vec4f(sCoreRadius, sSoftBand, mSightStrength, 0.f));
+ mLevelUniform->set(osg::Vec4f(mFloor, sWaist, 0.f, 0.f));
+ mAwayUniform->set(osg::Vec4f(mAway.x(), mAway.y(), 0.f, static_cast<float>(mDebug)));
+ }
+
+ void Cutaway::updateFloors(float dt, osg::Group* cellNode, const MWWorld::Ptr& player)
+ {
+ if (cellNode != mCellNode)
+ {
+ restoreFloors();
+ mCellNode = cellNode;
+ }
+ if (!mCellNode)
+ return;
+
+ // The cell's objects, as they come and go (a dropped item, someone arriving); the player isn't one
+ const osg::Node* playerNode = player.getRefData().getBaseNode();
+ std::map<osg::Node*, Floored> seen;
+ for (unsigned int i = 0; i < mCellNode->getNumChildren(); ++i)
+ {
+ osg::Node* node = mCellNode->getChild(i);
+ if (node == playerNode)
+ continue;
+ auto found = mFloored.find(node);
+ if (found != mFloored.end())
+ {
+ seen.emplace(node, std::move(found->second));
+ mFloored.erase(found);
+ continue;
+ }
+ const MWWorld::Ptr ptr = ptrOf(*node);
+ if (ptr.isEmpty() || ptr == player)
+ continue;
+ Floored object;
+ object.mNode = node;
+ object.mActor = ptr.getClass().isActor();
+ if (!object.mActor)
+ {
+ osg::ComputeBoundsVisitor bounds;
+ bounds.setTraversalMask(~0u);
+ node->accept(bounds);
+ object.mBounds = bounds.getBoundingBox();
+ if (!object.mBounds.valid())
+ continue;
+ }
+ seen.emplace(node, std::move(object));
+ }
+ // Whatever left the cell (or went to another) is whole again
+ for (auto& [node, object] : mFloored)
+ setFade(object, 0.f);
+ mFloored.swap(seen);
+
+ // Wholly above the player's floor or wholly below it: on another floor. A little slack once it is, so walking
+ // up stairs doesn't flick things in and out.
+ for (auto& [node, object] : mFloored)
+ {
+ float bottom = object.mBounds.zMin();
+ float top = object.mBounds.zMax();
+ if (object.mActor)
+ {
+ const MWWorld::Ptr ptr = ptrOf(*node);
+ if (ptr.isEmpty())
+ continue;
+ bottom = ptr.getRefData().getPosition().pos[2];
+ top = bottom + sActorHeight;
+ }
+ const float slack = object.mOther ? sFloorSlack : 0.f;
+ const float above = object.mActor ? sActorAbove : sAbove;
+ object.mOther = bottom > mFloor + above - slack || top < mFloor - sBelow + slack;
+ const float target = object.mOther ? 1.f : 0.f;
+ if (mReset)
+ setFade(object, target);
+ else if (object.mAmount != target)
+ setFade(object, object.mOther ? std::min(1.f, object.mAmount + dt / sFloorFade)
+ : std::max(0.f, object.mAmount - dt / sFloorFade));
+ }
+ }
+
+ void Cutaway::setFade(Floored& object, float amount)
+ {
+ object.mAmount = amount;
+ if (amount > 0.f && !object.mFade)
+ {
+ object.mFade = new osg::Uniform("cutawayFade", amount);
+ object.mFade->setDataVariance(osg::Object::DYNAMIC);
+ osg::StateSet* stateset = object.mNode->getOrCreateStateSet();
+ stateset->setDataVariance(osg::Object::DYNAMIC);
+ stateset->addUniform(object.mFade);
+ }
+ if (!object.mFade)
+ return;
+ if (amount > 0.f)
+ object.mFade->set(amount);
+ else
+ {
+ if (osg::StateSet* stateset = object.mNode->getStateSet())
+ stateset->removeUniform(object.mFade);
+ object.mFade = nullptr;
+ }
+ }
+
+ void Cutaway::restoreFloors()
+ {
+ for (auto& [node, object] : mFloored)
+ setFade(object, 0.f);
+ mFloored.clear();
+ mCellNode = nullptr;
+ }
+
+ bool Cutaway::isHidden(const MWWorld::ConstPtr& ptr) const
+ {
+ if (!mActive || ptr.isEmpty())
+ return false;
+ const osg::Node* node = ptr.getRefData().getBaseNode();
+ const auto found = mFloored.find(const_cast<osg::Node*>(node));
+ return found != mFloored.end() && found->second.mOther && found->second.mAmount > 0.5f;
+ }
+
+ void Cutaway::updateGhost(bool on)
+ {
+ // The pass is as big as the scene is drawn (made again when that changes), so the composite reads it pixel
+ // for pixel; with no size yet, no ghost
+ const uint32_t width = mRenderWidth;
+ const uint32_t height = mRenderHeight;
+ if (width == 0 || height == 0)
+ on = false;
+ if (on && (!mGhostLayer || mGhostLayer->width() != width || mGhostLayer->height() != height))
+ {
+ if (mGhostLayer)
+ mRootNode->removeChild(mGhostLayer);
+ mGhostLayer = new GhostLayer(mSceneRoot, mGhostState, width, height);
+ mRootNode->addChild(mGhostLayer);
+ mGhostComposite->setLayer(mGhostLayer);
+ }
+ if (on)
+ {
+ // Sorted behind every transparent thing
+ osg::Vec3f forward = mFeet + osg::Vec3f(0.f, 0.f, sBodyFrom) - mEye;
+ forward.normalize();
+ mGhostComposite->placeBehind(mEye, forward);
+ }
+
+ // The main view leaves the ghost out only while the pass draws it
+ mGhostOn = on;
+ mGhostUniform->set(osg::Vec4f(sGhostReach, sGhostOpacity, on ? 1.f : 0.f, 0.f));
+ if (mGhostLayer)
+ mGhostLayer->setNodeMask(on ? Mask_RenderToTexture : 0);
+ mGhostComposite->setNodeMask(on ? ~0u : 0);
+ }
+
+ void Cutaway::updateCoverage(float dt)
+ {
+ mRayTimer -= dt;
+ if (mRayTimer <= 0.f || mReset)
+ {
+ mRayTimer = sRayInterval;
+ // Points over the body, from the feet to the head and to either side, each as much of it as the others
+ const osg::Vec3f across = osg::Vec3f(-mAway.y(), mAway.x(), 0.f) * 22.f;
+ const std::array<osg::Vec3f, 8> points = {
+ osg::Vec3f(0.f, 0.f, 15.f),
+ osg::Vec3f(0.f, 0.f, 40.f),
+ osg::Vec3f(0.f, 0.f, 65.f),
+ osg::Vec3f(0.f, 0.f, 90.f),
+ osg::Vec3f(0.f, 0.f, 110.f),
+ osg::Vec3f(0.f, 0.f, 125.f),
+ osg::Vec3f(0.f, 0.f, 80.f) + across,
+ osg::Vec3f(0.f, 0.f, 80.f) - across,
+ };
+ osg::ref_ptr<osgUtil::IntersectorGroup> group = new osgUtil::IntersectorGroup;
+ std::array<osg::ref_ptr<osgUtil::LineSegmentIntersector>, points.size()> rays;
+ for (size_t i = 0; i < points.size(); ++i)
+ {
+ rays[i] = new osgUtil::LineSegmentIntersector(
+ osgUtil::Intersector::MODEL, mEye, mFeet + points[i]);
+ rays[i]->setIntersectionLimit(osgUtil::Intersector::NO_LIMIT);
+ group->addIntersector(rays[i]);
+ }
+ mRayVisitor->reset();
+ mRayVisitor->setIntersector(group);
+ mSceneRoot->accept(*mRayVisitor);
+
+ // A point is hidden by anything drawn on its way (not what is on another floor: that is gone)
+ int hidden = 0;
+ for (const auto& ray : rays)
+ {
+ for (const auto& hit : ray->getIntersections())
+ {
+ if (onOtherFloor(hit.nodePath))
+ continue;
+ ++hidden;
+ break;
+ }
+ }
+ mCoverage = static_cast<float>(hidden) / static_cast<float>(points.size());
+ }
+
+ // Open past one threshold, closed under a lower one, each after a moment, so walking along an edge doesn't
+ // flicker; then eased, quickly open and slowly closed
+ const bool wantOpen = mOpen ? mCoverage > sCloseBelow : mCoverage > sOpenAbove;
+ if (wantOpen != mOpen)
+ {
+ mOpenFor += dt;
+ if (mReset || mOpenFor >= (mOpen ? sCloseDelay : sOpenDelay))
+ {
+ mOpen = wantOpen;
+ mOpenFor = 0.f;
+ }
+ }
+ else
+ mOpenFor = 0.f;
+ const float target = mOpen ? 1.f : 0.f;
+ if (mReset)
+ mSightStrength = target;
+ else
+ mSightStrength += (target - mSightStrength) * (1.f - std::exp(-dt * 3.f / (mOpen ? sOpenTime : sCloseTime)));
+ }
+
+ bool Cutaway::onOtherFloor(const osg::NodePath& path) const
+ {
+ for (osg::Node* node : path)
+ {
+ const auto found = mFloored.find(node);
+ if (found != mFloored.end())
+ return found->second.mOther && found->second.mAmount > 0.5f;
+ }
+ return false;
+ }
+
+ // The porthole and the ghost, as shaders/lib/util/cutaway.glsl has them (cutawaySightAmounts), without the ragged
+ // edge
+ osg::Vec2f Cutaway::sightAt(const osg::Vec3f& point) const
+ {
+ if (mSightStrength <= 0.f)
+ return osg::Vec2f();
+ const osg::Vec3f a = mFeet + osg::Vec3f(0.f, 0.f, sBodyFrom);
+ const osg::Vec3f b = mFeet + osg::Vec3f(0.f, 0.f, sBodyTo);
+ osg::Vec3f ray = point - mEye;
+ const float length = ray.normalize();
+ const osg::Vec3f axis = b - a;
+ const osg::Vec3f fromBody = mEye - a;
+ const float along = ray * axis;
+ const float denom = std::max(axis * axis - along * along, 1e-4f);
+ const float s = std::clamp((axis * fromBody - along * (ray * fromBody)) / denom, 0.f, 1.f);
+ const osg::Vec3f nearest = a + axis * s;
+ const float atBody = (nearest - mEye) * ray;
+ const float distance = (mEye + ray * atBody - nearest).length();
+ const float footprint = 1.f - smoothstep(sCoreRadius, sCoreRadius + sSoftBand, distance);
+ const float ghost = 1.f - smoothstep(sCoreRadius, sGhostReach, distance);
+ const float inFront = 1.f - smoothstep(atBody - sBodyNear - sBodySoft, atBody - sBodyNear, length);
+ const float high = smoothstep(sWaist - sWaistSoft, sWaist + sWaistSoft, point.z() - mFloor);
+ const float ahead = -((point.x() - mFeet.x()) * mAway.x() + (point.y() - mFeet.y()) * mAway.y());
+ const float notBehind = smoothstep(-sBehindFrom - sBehindSoft, -sBehindFrom, ahead);
+ return osg::Vec2f(footprint, ghost) * (inFront * high * notBehind * mSightStrength);
+ }
+
+ bool Cutaway::isCut(const osg::Vec3f& point, bool actor) const
+ {
+ if (!mActive || actor)
+ return false;
+ // Where less than half the surface is left (the porthole, the faintest of the ghost), the cursor goes through
+ const osg::Vec2f sight = sightAt(point);
+ const float left = mGhostOn ? (1.f - sight.x()) * (1.f + (sGhostOpacity - 1.f) * sight.y()) : 1.f - sight.x();
+ return left < 0.5f;
+ }
+
+ void Cutaway::setRenderSize(int width, int height)
+ {
+ mRenderWidth = static_cast<uint32_t>(std::max(width, 0));
+ mRenderHeight = static_cast<uint32_t>(std::max(height, 0));
+ }
+
+ void Cutaway::setDebug(int level)
+ {
+ mDebug = level;
+ }
+}
diff --git a/apps/openmw/mwrender/cutaway.hpp b/apps/openmw/mwrender/cutaway.hpp
new file mode 100644
index 0000000..869cde0
--- /dev/null
+++ b/apps/openmw/mwrender/cutaway.hpp
@@ -0,0 +1,141 @@
+#ifndef OPENMW_MWRENDER_CUTAWAY_H
+#define OPENMW_MWRENDER_CUTAWAY_H
+
+#include <map>
+
+#include <osg/BoundingBox>
+#include <osg/Node>
+#include <osg/Uniform>
+#include <osg/Vec2f>
+#include <osg/Vec3f>
+#include <osg/ref_ptr>
+
+#include "../mwworld/ptr.hpp"
+
+#include "ghostlayer.hpp"
+
+namespace osg
+{
+ class Camera;
+ class Group;
+ class Node;
+ class StateSet;
+}
+
+namespace osgUtil
+{
+ class IntersectionVisitor;
+}
+
+namespace MWRender
+{
+ class PlayerMask;
+
+ /// Isowind's top-down camera: what is removed so the player can be seen.
+ /// - The porthole, in and out of doors: where more than half of the player is hidden (raycasts to points of their
+ /// body), what lies on the view rays in front of their upper body goes, as a clear opening in a see-through
+ /// ghost of it (GhostLayer); never anything behind them or below their waist, so a bar or a table in front of
+ /// them leaves them standing behind it. Evaluated per pixel by shaders/lib/util/cutaway.glsl and the same way
+ /// by isCut(), so the cursor never lands on what isn't drawn.
+ /// - Indoors, the other floors: every object standing wholly above the player's floor or wholly below it (walls,
+ /// upper floors, furniture, doors, people) dissolves away; whatever reaches the player's floor (their room,
+ /// the stairs) stays. Morrowind's rooms only show their ceilings from inside, so from above the room is seen
+ /// without them. (Gone only from the view: their lamps still light, and they still cast shadows.)
+ /// Only the main view is cut: shadows, reflections and the map see the whole scene.
+ class Cutaway
+ {
+ public:
+ Cutaway(osg::Group* rootNode, osg::Group* sceneRoot, osg::Camera* mainCamera, PlayerMask* playerMask,
+ int playerMaskUnit, int noiseUnit);
+ ~Cutaway();
+
+ /// Moves the cut to this frame's camera and player. active: the top-down camera is in use; cellNode: the
+ /// scene node of the objects of the cell the player is in, when indoors.
+ void update(float dt, const osg::Vec3f& eye, const MWWorld::Ptr& player, bool active, bool indoors,
+ osg::Group* cellNode);
+
+ /// Whether the point is cut away by the porthole, as the shaders cut it; actor: the point is on a character,
+ /// a creature or a door. (What is on another floor is left out of the scene, so rays never hit it.)
+ bool isCut(const osg::Vec3f& point, bool actor) const;
+
+ /// Whether the object is on another floor and gone from the view (indoors), so the cursor goes through it.
+ bool isHidden(const MWWorld::ConstPtr& ptr) const;
+
+ /// The size the scene is drawn at (the post-processor's, smaller than the window with the pixel art look):
+ /// the ghost's pass is drawn at it too, pixel for pixel.
+ void setRenderSize(int width, int height);
+
+ /// Debug view: what the cut removes is drawn tinted instead (blue: the porthole, orange: another floor going);
+ /// 4 shows the ghost's own pass (magenta: drawn see-through, cyan: the clear opening, dark blue: left to the
+ /// main view); -1 cuts nothing, to compare.
+ void setDebug(int level);
+
+ private:
+ // An object of the cell indoors, and how far it has dissolved away
+ struct Floored
+ {
+ osg::ref_ptr<osg::Node> mNode;
+ osg::BoundingBox mBounds; // (world; for an actor, worked out where it stands each time)
+ bool mActor = false;
+ osg::ref_ptr<osg::Uniform> mFade;
+ float mAmount = 0.f;
+ bool mOther = false; // on another floor
+ };
+
+ void updateFloors(float dt, osg::Group* cellNode, const MWWorld::Ptr& player);
+ void setFade(Floored& object, float amount);
+ void restoreFloors();
+ void updateCoverage(float dt);
+ void updateGhost(bool on);
+ bool onOtherFloor(const osg::NodePath& path) const;
+ osg::Vec2f sightAt(const osg::Vec3f& point) const;
+
+ osg::ref_ptr<osg::Group> mRootNode;
+ osg::ref_ptr<osg::Group> mSceneRoot;
+ osg::Camera* mMainCamera;
+ osg::ref_ptr<osgUtil::IntersectionVisitor> mRayVisitor;
+
+ osg::ref_ptr<osg::StateSet> mMainViewState; // pushed for the main camera only
+ osg::ref_ptr<osg::Uniform> mEnabled;
+ osg::ref_ptr<osg::Uniform> mEyeUniform;
+ osg::ref_ptr<osg::Uniform> mCapsuleA;
+ osg::ref_ptr<osg::Uniform> mCapsuleB;
+ osg::ref_ptr<osg::Uniform> mSight;
+ osg::ref_ptr<osg::Uniform> mLevelUniform;
+ osg::ref_ptr<osg::Uniform> mAwayUniform;
+ osg::ref_ptr<osg::Uniform> mGhostUniform;
+ int mDebug = 0;
+
+ // The values the shaders get, kept for isCut
+ bool mActive = false;
+ bool mIndoors = false;
+ osg::Vec3f mEye;
+ osg::Vec3f mFeet;
+ osg::Vec3f mLastFeet;
+ osg::Vec2f mAway{ 0.f, 1.f }; // away from the camera along the ground
+ float mFloor = 0.f;
+ bool mReset = true;
+
+ // The porthole: how much of the player is hidden (raycasts a few times a second), whether that's enough to
+ // open it, and how open it is (eased)
+ float mRayTimer = 0.f;
+ float mCoverage = 0.f;
+ bool mOpen = false;
+ float mOpenFor = 0.f; // seconds the coverage has been on the other side of the threshold
+ float mSightStrength = 0.f;
+
+ // The ghost: the pass that draws it (made for the scene's size), and what lays it over the view
+ osg::ref_ptr<osg::StateSet> mGhostState;
+ osg::ref_ptr<GhostLayer> mGhostLayer;
+ osg::ref_ptr<GhostComposite> mGhostComposite;
+ bool mGhostOn = false;
+ uint32_t mRenderWidth = 0;
+ uint32_t mRenderHeight = 0;
+
+ // The other floors: the cell's objects, by node
+ osg::ref_ptr<osg::Group> mCellNode;
+ std::map<osg::Node*, Floored> mFloored;
+ };
+}
+
+#endif
diff --git a/apps/openmw/mwrender/ghostlayer.cpp b/apps/openmw/mwrender/ghostlayer.cpp
new file mode 100644
index 0000000..65d8dd8
--- /dev/null
+++ b/apps/openmw/mwrender/ghostlayer.cpp
@@ -0,0 +1,164 @@
+#include "ghostlayer.hpp"
+
+#include <osg/BlendFunc>
+#include <osg/Camera>
+#include <osg/ColorMaski>
+#include <osg/Program>
+#include <osgUtil/CullVisitor>
+
+#include <components/sceneutil/depth.hpp>
+#include <components/sceneutil/nodecallback.hpp>
+
+#include "vismask.hpp"
+
+namespace MWRender
+{
+ namespace
+ {
+ // Keeps the main view's eye point (for LODs) as the camera's own: the pass must draw what the main view
+ // would, down to the level of detail, or its edge would show (as Water's InheritViewPointCallback)
+ class InheritViewPoint : public SceneUtil::NodeCallback<InheritViewPoint, osg::Node*, osgUtil::CullVisitor*>
+ {
+ public:
+ void operator()(osg::Node* node, osgUtil::CullVisitor* cv)
+ {
+ osg::ref_ptr<osg::RefMatrix> modelViewMatrix = new osg::RefMatrix(*cv->getModelViewMatrix());
+ cv->popModelViewMatrix();
+ cv->pushModelViewMatrix(modelViewMatrix, osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
+ traverse(node, cv);
+ }
+ };
+
+ // Binds the layer's textures for the composite, as the main view sees them
+ class BindLayer : public SceneUtil::NodeCallback<BindLayer, GhostComposite*, osgUtil::CullVisitor*>
+ {
+ public:
+ void operator()(GhostComposite* node, osgUtil::CullVisitor* cv)
+ {
+ GhostLayer* layer = node->getLayer();
+ if (!layer)
+ return;
+ osg::StateSet* stateset = node->getOrCreateStateSet();
+ // Read texel for pixel: filtering would blend a surface's depth with the empty background at its
+ // edges, and the edges would fail the depth test (bright slivers where the sky is behind)
+ osg::Texture* textures[] = { layer->getColorTexture(cv), layer->getDepthTexture(cv) };
+ for (int unit = 0; unit < 2; ++unit)
+ {
+ osg::Texture* texture = textures[unit];
+ if (texture->getFilter(osg::Texture::MIN_FILTER) != osg::Texture::NEAREST)
+ {
+ texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
+ texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
+ }
+ stateset->setTextureAttribute(unit, texture, osg::StateAttribute::ON);
+ }
+ traverse(node, cv);
+ }
+ };
+
+ // The composite's bounds: wherever placeBehind put them, whatever its vertices (they are screen positions)
+ struct FarBounds : public osg::Drawable::ComputeBoundingBoxCallback
+ {
+ osg::BoundingBox mBox;
+ osg::BoundingBox computeBound(const osg::Drawable&) const override { return mBox; }
+ };
+
+ constexpr const char* sVertexShader = R"GLSL(
+#version 120
+void main()
+{
+ gl_Position = vec4(gl_Vertex.xy, 0.0, 1.0);
+}
+)GLSL";
+
+ // The layer's colour, as see-through as its alpha, at its own depth
+ constexpr const char* sFragmentShader = R"GLSL(
+#version 120
+uniform sampler2D ghostColour;
+uniform sampler2D ghostDepth;
+uniform vec2 screenRes;
+void main()
+{
+ vec2 uv = gl_FragCoord.xy / screenRes;
+ vec4 colour = texture2D(ghostColour, uv);
+ // (Next to nothing, as in the opening: it isn't there, for depth either)
+ if (colour.a < 0.02)
+ discard;
+ gl_FragDepth = texture2D(ghostDepth, uv).r;
+ gl_FragData[0] = colour;
+}
+)GLSL";
+ }
+
+ GhostLayer::GhostLayer(osg::Node* scene, osg::StateSet* passState, uint32_t width, uint32_t height)
+ : RTTNode(width, height, 0, false, 1, StereoAwareness::Unaware, false)
+ , mScene(scene)
+ , mPassState(passState)
+ {
+ setColorBufferInternalFormat(GL_RGBA8);
+ setNodeMask(Mask_RenderToTexture);
+ }
+
+ void GhostLayer::setDefaults(osg::Camera* camera)
+ {
+ // The main camera's view and projection (as Water's refraction), so it matches the main view exactly
+ camera->setReferenceFrame(osg::Camera::RELATIVE_RF);
+ camera->addCullCallback(new InheritViewPoint);
+ camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
+ camera->setName("CutawayGhostCamera");
+ camera->setNodeMask(Mask_RenderToTexture);
+ camera->setClearColor(osg::Vec4f(0.f, 0.f, 0.f, 0.f));
+ // What can turn see-through (statics and objects; the terrain for the objects merged into it far off, though
+ // the ground itself never does), and the lights
+ camera->setCullMask(Mask_Scene | Mask_Static | Mask_Object | Mask_Terrain | Mask_Lighting | Mask_Sun);
+ camera->getOrCreateStateSet()->merge(*mPassState);
+ camera->addChild(mScene);
+ }
+
+ GhostComposite::GhostComposite()
+ : mTriangle(new osg::Geometry)
+ {
+ // One triangle over the whole screen
+ osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array;
+ vertices->push_back(osg::Vec3f(-1.f, -1.f, 0.f));
+ vertices->push_back(osg::Vec3f(3.f, -1.f, 0.f));
+ vertices->push_back(osg::Vec3f(-1.f, 3.f, 0.f));
+ mTriangle->setVertexArray(vertices);
+ mTriangle->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLES, 0, 3));
+ mTriangle->setUseDisplayList(false);
+ mTriangle->setCullingActive(false);
+ mTriangle->setComputeBoundingBoxCallback(new FarBounds);
+ addChild(mTriangle);
+ setCullingActive(false);
+ addCullCallback(new BindLayer);
+
+ osg::StateSet* stateset = getOrCreateStateSet();
+ osg::ref_ptr<osg::Program> program = new osg::Program;
+ program->addShader(new osg::Shader(osg::Shader::VERTEX, sVertexShader));
+ program->addShader(new osg::Shader(osg::Shader::FRAGMENT, sFragmentShader));
+ const auto force = osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED;
+ stateset->setAttributeAndModes(program, osg::StateAttribute::ON | force);
+ stateset->addUniform(new osg::Uniform("ghostColour", 0));
+ stateset->addUniform(new osg::Uniform("ghostDepth", 1));
+ stateset->setAttributeAndModes(
+ new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA),
+ osg::StateAttribute::ON | force);
+ // Tested against what the main view drew, and written: post-processing that reads depth (fog, ambient
+ // occlusion) must see the see-through surface where it is, not what is behind it (the sky would fog it white)
+ stateset->setAttributeAndModes(
+ new SceneUtil::AutoDepth(osg::Depth::LEQUAL, 0.0, 1.0, true), osg::StateAttribute::ON | force);
+ stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | force);
+ // Only the colour: the normals the post-processing reads (a second target, when there is one) stay as drawn
+ stateset->setAttribute(new osg::ColorMaski(1, false, false, false, false), osg::StateAttribute::ON | force);
+ stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
+ }
+
+ void GhostComposite::placeBehind(const osg::Vec3f& eye, const osg::Vec3f& forward)
+ {
+ // The transparent bin is drawn back to front by the distance of each thing's bounds
+ const osg::Vec3f far = eye + forward * 1e6f;
+ static_cast<FarBounds*>(mTriangle->getComputeBoundingBoxCallback())->mBox
+ = osg::BoundingBox(far - osg::Vec3f(1.f, 1.f, 1.f), far + osg::Vec3f(1.f, 1.f, 1.f));
+ mTriangle->dirtyBound();
+ }
+}
diff --git a/apps/openmw/mwrender/ghostlayer.hpp b/apps/openmw/mwrender/ghostlayer.hpp
new file mode 100644
index 0000000..023122f
--- /dev/null
+++ b/apps/openmw/mwrender/ghostlayer.hpp
@@ -0,0 +1,55 @@
+#ifndef OPENMW_MWRENDER_GHOSTLAYER_H
+#define OPENMW_MWRENDER_GHOSTLAYER_H
+
+#include <osg/Geometry>
+#include <osg/Group>
+#include <osg/ref_ptr>
+
+#include <components/sceneutil/rtt.hpp>
+
+namespace osg
+{
+ class StateSet;
+}
+
+namespace MWRender
+{
+ /// Isowind's top-down camera, outdoors: what stands between the camera and the player turns see-through around
+ /// them (shaders/lib/util/cutaway.glsl). The main view leaves those surfaces out; this pass draws only them, from the
+ /// same view, into a texture, with its own depth buffer, so of a building only its nearest surface is kept (blending
+ /// a whole mesh would show its own back walls and floors through it). GhostComposite then lays that over the main
+ /// view, as see-through as the shader made each pixel, behind whatever stands in front of it.
+ class GhostLayer : public SceneUtil::RTTNode
+ {
+ public:
+ /// passState: what the pass needs set (the cut's switch, its textures, cutawayGhostPass).
+ GhostLayer(osg::Node* scene, osg::StateSet* passState, uint32_t width, uint32_t height);
+
+ void setDefaults(osg::Camera* camera) override;
+
+ private:
+ osg::ref_ptr<osg::Node> mScene;
+ osg::ref_ptr<osg::StateSet> mPassState;
+ };
+
+ /// Lays a GhostLayer over the main view: a full screen triangle, drawn first among the transparent things (after
+ /// the water), blended, and depth-tested at the ghost's own depth, so whoever stands in front of the building stays
+ /// in front of it. Add it to the main camera's scene only.
+ class GhostComposite : public osg::Group
+ {
+ public:
+ GhostComposite();
+
+ void setLayer(GhostLayer* layer) { mLayer = layer; }
+ GhostLayer* getLayer() const { return mLayer.get(); }
+
+ /// Keeps it sorted behind every transparent thing: its (unculled) bounds are put far along the view.
+ void placeBehind(const osg::Vec3f& eye, const osg::Vec3f& forward);
+
+ private:
+ osg::ref_ptr<GhostLayer> mLayer;
+ osg::ref_ptr<osg::Geometry> mTriangle;
+ };
+}
+
+#endif
diff --git a/apps/openmw/mwrender/objectpaging.cpp b/apps/openmw/mwrender/objectpaging.cpp
index cc8d3ae..1b60247 100644
--- a/apps/openmw/mwrender/objectpaging.cpp
+++ b/apps/openmw/mwrender/objectpaging.cpp
@@ -63,7 +63,8 @@ namespace MWRender
case ESM::REC_DOOR4:
case ESM::REC_TREE4:
return true;
- // Nearby doors keep their own nodes: the top-down cutaway never hides them (see Door).
+ // Nearby doors keep their own nodes: the top-down camera draws them double-sided and never cuts them
+ // (see Door).
case ESM::REC_DOOR:
return far;
case ESM::REC_CONT:
diff --git a/apps/openmw/mwrender/objects.cpp b/apps/openmw/mwrender/objects.cpp
index 9393846..2539033 100644
--- a/apps/openmw/mwrender/objects.cpp
+++ b/apps/openmw/mwrender/objects.cpp
@@ -37,6 +37,12 @@ namespace MWRender
mCellSceneNodes.clear();
}
+ osg::Group* Objects::getCellNode(const MWWorld::CellStore* store) const
+ {
+ const auto found = mCellSceneNodes.find(store);
+ return found != mCellSceneNodes.end() ? found->second.get() : nullptr;
+ }
+
void Objects::insertBegin(const MWWorld::Ptr& ptr)
{
assert(mObjects.find(ptr.mRef) == mObjects.end());
diff --git a/apps/openmw/mwrender/objects.hpp b/apps/openmw/mwrender/objects.hpp
index b4359fd..d141525 100644
--- a/apps/openmw/mwrender/objects.hpp
+++ b/apps/openmw/mwrender/objects.hpp
@@ -86,6 +86,9 @@ namespace MWRender
void removeCell(const MWWorld::CellStore* store);
+ /// Isowind: the scene node holding a cell's objects, or nullptr
+ osg::Group* getCellNode(const MWWorld::CellStore* store) const;
+
/// Updates containing cell for object rendering data
void updatePtr(const MWWorld::Ptr& old, const MWWorld::Ptr& cur);
diff --git a/apps/openmw/mwrender/occlusionfader.cpp b/apps/openmw/mwrender/occlusionfader.cpp
deleted file mode 100644
index 80fb4b1..0000000
--- a/apps/openmw/mwrender/occlusionfader.cpp
+++ /dev/null
@@ -1,280 +0,0 @@
-#include "occlusionfader.hpp"
-
-#include <algorithm>
-#include <array>
-#include <cmath>
-
-#include <osg/BlendFunc>
-#include <osg/Group>
-#include <osg/UserDataContainer>
-#include <osgUtil/IntersectionVisitor>
-#include <osgUtil/LineSegmentIntersector>
-
-#include <components/esm3/loaddoor.hpp>
-#include <components/sceneutil/depth.hpp>
-#include <components/sceneutil/positionattitudetransform.hpp>
-
-#include "../mwworld/class.hpp"
-
-#include "objects.hpp"
-#include "vismask.hpp"
-
-namespace MWRender
-{
- namespace
- {
- // How see-through a faded object gets is up to the shader; this is how fast it gets there and back.
- constexpr float sFadeInRate = 6.f; // per second
- constexpr float sFadeOutRate = 2.5f;
- // How long something must have stopped being in the way before it fades back, so walking past a row of
- // posts or along a wall's edge doesn't make it flicker.
- constexpr float sFadeOutDelay = 0.35f;
- // Cover (isPlayerCovered): looked for straight up from this far over the player's feet (over their head), to
- // this far up, from over them and from this far around them; and only something this level counts (the
- // first thing hit: a branch or a leaf of a tree over them is no roof).
- constexpr float sCoverFrom = 135.f;
- constexpr float sCoverHeight = 1200.f;
- constexpr float sCoverSpread = 200.f;
- constexpr float sCoverFlatness = 0.6f;
-
- MWWorld::Ptr findPtr(const osg::NodePath& nodePath)
- {
- // The innermost object holding a Ptr (the reference's base node)
- for (auto it = nodePath.rbegin(); it != nodePath.rend(); ++it)
- {
- const osg::UserDataContainer* container = (*it)->getUserDataContainer();
- if (!container)
- continue;
- for (unsigned int i = 0; i < container->getNumUserObjects(); ++i)
- {
- if (const PtrHolder* holder = dynamic_cast<const PtrHolder*>(container->getUserObject(i)))
- return holder->mPtr;
- }
- }
- return MWWorld::Ptr();
- }
- }
-
- OcclusionFader::OcclusionFader(osg::Group* sceneRoot)
- : mSceneRoot(sceneRoot)
- , mVisitor(new osgUtil::IntersectionVisitor)
- {
- // Only what can be faded: no terrain (the silhouette shows the player behind hills), characters, effects,
- // water or the sky.
- unsigned int mask = ~0u;
- mask &= ~(Mask_RenderToTexture | Mask_Sky | Mask_Debug | Mask_Effect | Mask_Water | Mask_SimpleWater
- | Mask_Groundcover | Mask_Actor | Mask_Player | Mask_Terrain | Mask_ParticleSystem
- | Mask_WeatherParticles | Mask_FirstPerson);
- mVisitor->setTraversalMask(mask);
- }
-
- OcclusionFader::~OcclusionFader()
- {
- clear();
- }
-
- bool OcclusionFader::canFade(const MWWorld::Ptr& ptr)
- {
- if (ptr.isEmpty())
- return false;
- // Characters and creatures are what the player looks for, and doors are how they get around
- return !ptr.getClass().isActor() && ptr.getType() != ESM::Door::sRecordId;
- }
-
- void OcclusionFader::findOccluders(
- const osg::Vec3f& eye, const MWWorld::Ptr& player, std::vector<MWWorld::Ptr>& out)
- {
- const osg::Vec3f feet = player.getRefData().getPosition().asVec3();
-
- // Points over the player's body and around it (about as far as the shader's keyhole, the circle in which
- // cutaway.glsl opens faded objects), so whatever covers part of it is found, not only what covers their middle.
- osg::Vec3f across = (feet - eye) ^ osg::Vec3f(0.f, 0.f, 1.f);
- if (across.normalize() < 1e-3f)
- across = osg::Vec3f(1.f, 0.f, 0.f);
- const std::array<osg::Vec3f, 11> points = {
- feet + osg::Vec3f(0.f, 0.f, 30.f),
- feet + osg::Vec3f(0.f, 0.f, 75.f),
- feet + osg::Vec3f(0.f, 0.f, 120.f),
- feet + osg::Vec3f(0.f, 0.f, 160.f),
- feet + osg::Vec3f(0.f, 0.f, 70.f) + across * 160.f,
- feet + osg::Vec3f(0.f, 0.f, 70.f) - across * 160.f,
- feet + osg::Vec3f(0.f, 0.f, 150.f) + across * 110.f,
- feet + osg::Vec3f(0.f, 0.f, 150.f) - across * 110.f,
- feet + osg::Vec3f(0.f, 0.f, 20.f) + across * 110.f,
- feet + osg::Vec3f(0.f, 0.f, 20.f) - across * 110.f,
- feet + osg::Vec3f(0.f, 0.f, 70.f),
- };
-
- osg::ref_ptr<osgUtil::IntersectorGroup> group = new osgUtil::IntersectorGroup;
- std::vector<osg::ref_ptr<osgUtil::LineSegmentIntersector>> toPlayer;
- for (const osg::Vec3f& point : points)
- {
- osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector
- = new osgUtil::LineSegmentIntersector(osgUtil::Intersector::MODEL, eye, point);
- // Every object along the way, not only the nearest
- intersector->setIntersectionLimit(osgUtil::Intersector::NO_LIMIT);
- group->addIntersector(intersector);
- toPlayer.push_back(intersector);
- }
-
- // Straight up from over the player's head and from around them, for whatever hangs over them (isPlayerCovered)
- const osg::Vec3f along = across ^ osg::Vec3f(0.f, 0.f, 1.f);
- const osg::Vec3f overhead = feet + osg::Vec3f(0.f, 0.f, sCoverFrom);
- const std::array<osg::Vec3f, 5> coverFrom = {
- overhead,
- overhead + across * sCoverSpread,
- overhead - across * sCoverSpread,
- overhead + along * sCoverSpread,
- overhead - along * sCoverSpread,
- };
- std::vector<osg::ref_ptr<osgUtil::LineSegmentIntersector>> upward;
- for (const osg::Vec3f& from : coverFrom)
- {
- osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector = new osgUtil::LineSegmentIntersector(
- osgUtil::Intersector::MODEL, from, from + osg::Vec3f(0.f, 0.f, sCoverHeight));
- intersector->setIntersectionLimit(osgUtil::Intersector::LIMIT_NEAREST);
- group->addIntersector(intersector);
- upward.push_back(intersector);
- }
-
- mVisitor->reset();
- mVisitor->setIntersector(group);
- mSceneRoot->accept(*mVisitor);
-
- for (const auto& intersector : toPlayer)
- {
- for (const auto& intersection : intersector->getIntersections())
- {
- MWWorld::Ptr ptr = findPtr(intersection.nodePath);
- // (Paged objects, merged with their neighbours, have no Ptr of their own and can't be faded alone)
- if (canFade(ptr) && std::find(out.begin(), out.end(), ptr) == out.end())
- out.push_back(ptr);
- }
- }
-
- mPlayerCovered = false;
- for (const auto& intersector : upward)
- {
- const auto& intersections = intersector->getIntersections();
- if (intersections.empty())
- continue;
- if (std::abs(intersections.begin()->getWorldIntersectNormal().z()) > sCoverFlatness)
- {
- mPlayerCovered = true;
- break;
- }
- }
- }
-
- void OcclusionFader::update(float dt, const osg::Vec3f& eye, const MWWorld::Ptr& player, bool active)
- {
- // Objects whose node left the scene (deleted, or their cell unloaded) are gone
- for (auto it = mFaded.begin(); it != mFaded.end();)
- {
- if (it->second.mNode->getNumParents() == 0)
- it = mFaded.erase(it);
- else
- ++it;
- }
-
- std::vector<MWWorld::Ptr> occluders;
- if (active && !player.isEmpty() && player.isInCell())
- findOccluders(eye, player, occluders);
- else
- mPlayerCovered = false;
-
- for (const MWWorld::Ptr& ptr : occluders)
- {
- osg::Node* node = ptr.getRefData().getBaseNode();
- if (!node)
- continue;
- auto it = mFaded.find(node);
- if (it == mFaded.end())
- {
- Faded faded;
- faded.mPtr = ptr;
- faded.mNode = node;
- startFading(faded);
- it = mFaded.emplace(node, faded).first;
- }
- it->second.mOccludingFor = 0.f;
- it->second.mFade = std::min(1.f, it->second.mFade + dt * sFadeInRate);
- }
-
- for (auto it = mFaded.begin(); it != mFaded.end();)
- {
- Faded& faded = it->second;
- const bool occluding
- = std::find(occluders.begin(), occluders.end(), faded.mPtr) != occluders.end();
- if (!occluding)
- {
- faded.mOccludingFor += dt;
- if (faded.mOccludingFor > sFadeOutDelay)
- faded.mFade = std::max(0.f, faded.mFade - dt * sFadeOutRate);
- }
- faded.mUniform->set(faded.mFade);
-
- if (faded.mFade <= 0.f && !occluding)
- {
- stopFading(faded);
- it = mFaded.erase(it);
- }
- else
- ++it;
- }
- }
-
- void OcclusionFader::clear()
- {
- for (auto& [node, faded] : mFaded)
- stopFading(faded);
- mFaded.clear();
- }
-
- void OcclusionFader::startFading(Faded& faded)
- {
- faded.mUniform = new osg::Uniform("occluderFade", 0.f);
- faded.mUniform->setDataVariance(osg::Object::DYNAMIC);
- osg::StateSet* stateset = faded.mNode->getOrCreateStateSet();
- stateset->setDataVariance(osg::Object::DYNAMIC);
- stateset->addUniform(faded.mUniform);
-
- // Blended with what is behind, and not in the depth buffer, so post-processing that reads depth (ambient
- // occlusion, fog) works on the scene behind it
- faded.mRenderingHint = stateset->getRenderingHint();
- faded.mRenderBinMode = stateset->getRenderBinMode();
- faded.mBinNumber = stateset->getBinNumber();
- faded.mBinName = stateset->getBinName();
- stateset->setAttributeAndModes(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA),
- osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
- stateset->setAttributeAndModes(new SceneUtil::AutoDepth(osg::Depth::LEQUAL, 0.0, 1.0, false),
- osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE);
- stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
- stateset->setRenderBinMode(osg::StateSet::OVERRIDE_RENDERBIN_DETAILS);
- }
-
- void OcclusionFader::stopFading(Faded& faded)
- {
- osg::StateSet* stateset = faded.mNode->getStateSet();
- if (!stateset)
- return;
- stateset->removeUniform(faded.mUniform);
- stateset->removeAttribute(osg::StateAttribute::BLENDFUNC);
- stateset->removeMode(GL_BLEND);
- stateset->removeAttribute(osg::StateAttribute::DEPTH);
- stateset->setRenderingHint(faded.mRenderingHint);
- stateset->setRenderBinDetails(faded.mBinNumber, faded.mBinName,
- static_cast<osg::StateSet::RenderBinMode>(faded.mRenderBinMode));
- }
-
- std::vector<MWWorld::Ptr> OcclusionFader::getFadedObjects() const
- {
- std::vector<MWWorld::Ptr> result;
- for (const auto& [node, faded] : mFaded)
- {
- if (faded.mFade > 0.05f && faded.mNode->getNumParents() > 0)
- result.push_back(faded.mPtr);
- }
- return result;
- }
-}
diff --git a/apps/openmw/mwrender/occlusionfader.hpp b/apps/openmw/mwrender/occlusionfader.hpp
deleted file mode 100644
index 5530948..0000000
--- a/apps/openmw/mwrender/occlusionfader.hpp
+++ /dev/null
@@ -1,77 +0,0 @@
-#ifndef OPENMW_MWRENDER_OCCLUSIONFADER_H
-#define OPENMW_MWRENDER_OCCLUSIONFADER_H
-
-#include <map>
-#include <vector>
-
-#include <osg/Uniform>
-#include <osg/Vec3f>
-#include <osg/ref_ptr>
-
-#include "../mwworld/ptr.hpp"
-
-namespace osg
-{
- class Group;
- class Node;
-}
-
-namespace osgUtil
-{
- class IntersectionVisitor;
-}
-
-namespace MWRender
-{
- /// Isowind's top-down camera: fades whole objects that stand between the camera and the player (a house, a wall,
- /// a bridge, a tree) to a see-through ghost, rather than cutting holes into the scene, and fades them back once
- /// they no longer do. Each faded object gets its own occluderFade uniform, which shaders/lib/util/cutaway.glsl
- /// turns into a dithered fade. Characters, creatures and doors are never faded.
- class OcclusionFader
- {
- public:
- explicit OcclusionFader(osg::Group* sceneRoot);
- ~OcclusionFader();
-
- /// Finds what is between eye and the player now (only while active, otherwise everything fades back) and
- /// moves each object's fade towards where it should be.
- void update(float dt, const osg::Vec3f& eye, const MWWorld::Ptr& player, bool active);
-
- /// Forgets every object at once (the scene is changing).
- void clear();
-
- /// Objects currently fading out or faded; the top-down cursor picks through these.
- std::vector<MWWorld::Ptr> getFadedObjects() const;
-
- /// Whether something level (a floor, a bridge, a canton's tier) hangs over the player or right around them,
- /// as of the last update while active; the room-like cut then applies outdoors too (RenderingManager::update).
- bool isPlayerCovered() const { return mPlayerCovered; }
-
- private:
- struct Faded
- {
- MWWorld::Ptr mPtr;
- osg::ref_ptr<osg::Node> mNode;
- osg::ref_ptr<osg::Uniform> mUniform;
- // While it fades it is blended and kept out of the depth buffer (see cutaway.glsl): its render bin before
- int mRenderingHint = 0;
- int mRenderBinMode = 0;
- int mBinNumber = 0;
- std::string mBinName;
- float mFade = 0.f;
- float mOccludingFor = 0.f; // seconds since it last stood in the way, while it no longer does
- };
-
- void startFading(Faded& faded);
- void stopFading(Faded& faded);
- void findOccluders(const osg::Vec3f& eye, const MWWorld::Ptr& player, std::vector<MWWorld::Ptr>& out);
- static bool canFade(const MWWorld::Ptr& ptr);
-
- osg::ref_ptr<osg::Group> mSceneRoot;
- osg::ref_ptr<osgUtil::IntersectionVisitor> mVisitor;
- std::map<osg::Node*, Faded> mFaded;
- bool mPlayerCovered = false;
- };
-}
-
-#endif
diff --git a/apps/openmw/mwrender/renderingmanager.cpp b/apps/openmw/mwrender/renderingmanager.cpp
index f021a13..5351afc 100644
--- a/apps/openmw/mwrender/renderingmanager.cpp
+++ b/apps/openmw/mwrender/renderingmanager.cpp
@@ -77,7 +77,7 @@
#include "npcanimation.hpp"
#include "objectpaging.hpp"
#include "pathgrid.hpp"
-#include "occlusionfader.hpp"
+#include "cutaway.hpp"
#include "playermask.hpp"
#include "postprocessor.hpp"
#include "recastmesh.hpp"
@@ -90,35 +90,6 @@
namespace MWRender
{
- // Binds the player mask (see PlayerMask) for everything drawn below the node, for the top-down cutaway.
- class BindPlayerMaskCallback
- : public SceneUtil::NodeCallback<BindPlayerMaskCallback, osg::Node*, osgUtil::CullVisitor*>
- {
- public:
- BindPlayerMaskCallback(PlayerMask* mask, int unit)
- : mMask(mask)
- , mUnit(unit)
- {
- }
-
- void operator()(osg::Node* node, osgUtil::CullVisitor* cv)
- {
- if (!mStateSet)
- {
- mStateSet = new osg::StateSet;
- mStateSet->setTextureAttribute(mUnit, mMask->getColorTexture(cv), osg::StateAttribute::ON);
- }
- cv->pushStateSet(mStateSet);
- traverse(node, cv);
- cv->popStateSet();
- }
-
- private:
- osg::ref_ptr<PlayerMask> mMask;
- int mUnit;
- osg::ref_ptr<osg::StateSet> mStateSet;
- };
-
class PreloadCommonAssetsWorkItem : public SceneUtil::WorkItem
{
public:
@@ -337,23 +308,16 @@ namespace MWRender
sceneRoot->getOrCreateStateSet()->addUniform(new osg::Uniform("emissiveMult", 1.f));
sceneRoot->getOrCreateStateSet()->addUniform(new osg::Uniform("specStrength", 1.f));
sceneRoot->getOrCreateStateSet()->addUniform(new osg::Uniform("distortionStrength", 0.f));
- // Top-down cutaway uniforms (shaders/lib/util/cutaway.glsl). On the root node rather than the scene root so
- // they also reach paged objects (merged statics), which otherwise would see whatever value was set last.
- // Actors and doors override noCutaway with 0.75 (see Animation, MWClass::Door): the cutaway never fades them.
- mRootNode->getOrCreateStateSet()->addUniform(new osg::Uniform("noCutaway", 0.f));
- mCutawayOverheadUniform = new osg::Uniform("cutawayOverheadRadius", 0.f);
- mRootNode->getOrCreateStateSet()->addUniform(mCutawayOverheadUniform);
- // Objects faded by the OcclusionFader override this with their own
- mRootNode->getOrCreateStateSet()->addUniform(new osg::Uniform("occluderFade", 0.f));
- mOcclusionFader = std::make_unique<OcclusionFader>(mRootNode);
- // The player rendered alone into a small texture, so the cutaway can remove exactly what hides them.
+ // Top-down camera: what is cut away so the player can be seen (shaders/lib/util/cutaway.glsl), with the
+ // player rendered alone into a small texture, to outline them where something still covers them.
{
osg::ref_ptr<PlayerMask> playerMask = new PlayerMask(sceneRoot);
mRootNode->addChild(playerMask);
- const int unit = resourceSystem->getSceneManager()->getShaderManager().reserveGlobalTextureUnits(
- Shader::ShaderManager::Slot::PlayerMask);
- mRootNode->getOrCreateStateSet()->addUniform(new osg::Uniform("playerMaskTex", unit));
- mRootNode->addCullCallback(new BindPlayerMaskCallback(playerMask, unit));
+ Shader::ShaderManager& shaderManager = resourceSystem->getSceneManager()->getShaderManager();
+ const int maskUnit = shaderManager.reserveGlobalTextureUnits(Shader::ShaderManager::Slot::PlayerMask);
+ const int noiseUnit = shaderManager.reserveGlobalTextureUnits(Shader::ShaderManager::Slot::CutawayNoise);
+ mCutaway = std::make_unique<Cutaway>(
+ mRootNode, sceneRoot, mViewer->getCamera(), playerMask, maskUnit, noiseUnit);
}
resourceSystem->getSceneManager()->setUpNormalsRTForStateSet(sceneRoot->getOrCreateStateSet(), true);
@@ -594,9 +558,6 @@ namespace MWRender
}
void RenderingManager::removeCell(const MWWorld::CellStore* store)
{
- // The faded objects may be in it
- mOcclusionFader->clear();
-
mPathgrid->removeCell(store);
mActorsPaths->removeCell(store);
mObjects->removeCell(store);
@@ -723,25 +684,6 @@ namespace MWRender
float windSpeed = mSky->getBaseWindSpeed();
mSharedUniformStateUpdater->setWindSpeed(windSpeed);
mSharedUniformStateUpdater->setPlayerPos(playerPos);
-
- // Top-down camera (shaders/lib/util/cutaway.glsl): outdoors, whole objects between the camera and the
- // player fade out (OcclusionFader); indoors the room is cut cleanly instead (walls in front, the roof and
- // upper floors), with nothing left see-through. Outdoors under a floor, a bridge or a canton's tier the
- // room-like cut applies as well, close around the player: the fade alone leaves whatever hangs over the
- // way ahead of them whole.
- constexpr float indoorCutawayRadius = 4000.f;
- constexpr float coveredCutawayRadius = 900.f;
- const bool topDown = mCamera->getMode() == Camera::Mode::Static;
- const bool indoors = player.isInCell() && !player.getCell()->getCell()->isExterior();
- mOcclusionFader->update(dt, mCamera->getPosition(), player, topDown && !indoors);
-
- float overheadTarget = 0.f;
- if (topDown && indoors)
- overheadTarget = indoorCutawayRadius;
- else if (topDown && mOcclusionFader->isPlayerCovered())
- overheadTarget = coveredCutawayRadius;
- mCutawayOverheadRadius += (overheadTarget - mCutawayOverheadRadius) * std::min(1.f, dt * 5.f);
- mCutawayOverheadUniform->set(mCutawayOverheadRadius);
}
updateNavMesh();
@@ -754,6 +696,18 @@ namespace MWRender
}
mCamera->update(dt, paused);
+ // Top-down camera: the cut follows the camera, as it is this frame, and the player (see Cutaway)
+ if (!paused)
+ {
+ const MWWorld::Ptr& player = mPlayerAnimation->getPtr();
+ const bool topDown = mCamera->getMode() == Camera::Mode::Static;
+ // (Mournhold's plazas are interiors that behave like the outdoors, and are cut like them)
+ const bool indoors = player.isInCell() && !player.getCell()->getCell()->isExterior()
+ && !player.getCell()->getCell()->isQuasiExterior();
+ mCutaway->update(dt, mCamera->getPosition(), player, topDown, indoors,
+ indoors ? mObjects->getCellNode(player.getCell()) : nullptr);
+ }
+
bool isUnderwater = mWater->isUnderwater(mCamera->getPosition());
float fogStart = mFog->getFogStart(isUnderwater);
@@ -1042,11 +996,6 @@ namespace MWRender
return mIntersectionVisitor;
}
- std::vector<MWWorld::Ptr> RenderingManager::getFadedObjects() const
- {
- return mOcclusionFader->getFadedObjects();
- }
-
RenderingManager::RayResult RenderingManager::castRay(const osg::Vec3f& origin, const osg::Vec3f& dest,
bool ignorePlayer, bool ignoreActors, std::span<const MWWorld::Ptr> ignoreList)
{
@@ -1290,6 +1239,10 @@ namespace MWRender
void RenderingManager::setScreenRes(int width, int height)
{
mSharedUniformStateUpdater->setScreenRes(static_cast<float>(width), static_cast<float>(height));
+ // (The size the scene is drawn at: smaller than the window with the pixel art look. The post-processor sets
+ // it while it is made, before the cut is.)
+ if (mCutaway)
+ mCutaway->setRenderSize(width, height);
}
void RenderingManager::updateTextureFiltering()
diff --git a/apps/openmw/mwrender/renderingmanager.hpp b/apps/openmw/mwrender/renderingmanager.hpp
index 2c04422..da75fce 100644
--- a/apps/openmw/mwrender/renderingmanager.hpp
+++ b/apps/openmw/mwrender/renderingmanager.hpp
@@ -88,7 +88,7 @@ namespace Debug
namespace MWRender
{
- class OcclusionFader;
+ class Cutaway;
class IntersectionVisitorWithIgnoreList;
class EffectManager;
@@ -179,12 +179,8 @@ namespace MWRender
float mRatio;
};
- /// The objects the top-down camera currently fades out because they stand in front of the player.
- std::vector<MWWorld::Ptr> getFadedObjects() const;
-
- /// The radius around the player within which the top-down camera cuts the room (ceilings and upper floors
- /// over them, the walls in the way): indoors, and outdoors under cover; 0 where nothing is cut.
- float getCutawayRadius() const { return mCutawayOverheadRadius; }
+ /// What the top-down camera cuts away so the player can be seen (see Cutaway).
+ Cutaway& getCutaway() { return *mCutaway; }
RayResult castRay(const osg::Vec3f& origin, const osg::Vec3f& dest, bool ignorePlayer,
bool ignoreActors = false, std::span<const MWWorld::Ptr> ignoreList = {});
@@ -375,12 +371,8 @@ namespace MWRender
osg::Vec2f mProjectionOffset;
const MWWorld::GroundcoverStore& mGroundCoverStore;
- // Top-down camera: what stands between it and the player fades out (see OcclusionFader)
- std::unique_ptr<OcclusionFader> mOcclusionFader;
- // Indoors (and outdoors under cover), ceilings and upper floors over the player are removed within this
- // radius around them, and the walls in the way cut
- float mCutawayOverheadRadius = 0.f;
- osg::ref_ptr<osg::Uniform> mCutawayOverheadUniform;
+ // Top-down camera: what is cut away so the player can be seen
+ std::unique_ptr<Cutaway> mCutaway;
void operator=(const RenderingManager&);
RenderingManager(const RenderingManager&);
diff --git a/components/resource/scenemanager.cpp b/components/resource/scenemanager.cpp
index fd9def8..9b46648 100644
--- a/components/resource/scenemanager.cpp
+++ b/components/resource/scenemanager.cpp
@@ -124,6 +124,9 @@ namespace
partsys->addUpdateCallback(new InitWorldSpaceParticlesCallback);
}
partsys->setNodeMask(mMask);
+ // Isowind's top-down camera only takes particles away with the storey above the player, as it does
+ // characters: never in its porthole or ghost (they aren't in the ghost's pass, and would vanish)
+ partsys->getOrCreateStateSet()->addUniform(new osg::Uniform("noCutaway", 0.75f));
}
}
diff --git a/components/shader/shadermanager.cpp b/components/shader/shadermanager.cpp
index 0115461..7c4170e 100644
--- a/components/shader/shadermanager.cpp
+++ b/components/shader/shadermanager.cpp
@@ -719,6 +719,9 @@ namespace Shader
case Slot::PlayerMask:
slotDescr = "player mask";
break;
+ case Slot::CutawayNoise:
+ slotDescr = "cutaway noise";
+ break;
default:
slotDescr = "UNKNOWN";
}
diff --git a/components/shader/shadermanager.hpp b/components/shader/shadermanager.hpp
index 4ede4fe..fb71df9 100644
--- a/components/shader/shadermanager.hpp
+++ b/components/shader/shadermanager.hpp
@@ -81,6 +81,7 @@ namespace Shader
SkyTexture,
ShadowMaps,
PlayerMask,
+ CutawayNoise,
SLOT_COUNT
};
diff --git a/files/shaders/compatibility/objects.frag b/files/shaders/compatibility/objects.frag
index fb63756..3da8823 100644
--- a/files/shaders/compatibility/objects.frag
+++ b/files/shaders/compatibility/objects.frag
@@ -117,7 +117,7 @@ varying vec3 orthoDepthMapCoord;
void main()
{
- vec2 cutawaySilhouette = applyCutaway(passViewPos, normalize(gl_NormalMatrix * passNormal), false);
+ vec4 cutaway = applyCutaway(passViewPos, false);
#if @particleOcclusion
applyOcclusionDiscard(orthoDepthMapCoord, texture2D(orthoDepthMap, orthoDepthMapCoord.xy * 0.5 + 0.5).r);
@@ -249,9 +249,7 @@ vec2 screenCoords = gl_FragCoord.xy / screenRes;
#endif
gl_FragData[0] = applyFogAtPos(gl_FragData[0], passViewPos, far);
- gl_FragData[0].xyz = applyCutawaySilhouette(gl_FragData[0].xyz, cutawaySilhouette);
- // Faded by the top-down cutaway: OcclusionFader blends such objects
- gl_FragData[0].a *= cutawayAlpha;
+ gl_FragData[0].xyz = applyCutawayColour(gl_FragData[0].xyz, cutaway);
#if !defined(FORCE_OPAQUE) && @softParticles
gl_FragData[0].a *= calcSoftParticleFade(
@@ -276,5 +274,8 @@ vec2 screenCoords = gl_FragCoord.xy / screenRes;
gl_FragData[1].xyz = viewNormal * 0.5 + 0.5;
#endif
+ // The top-down camera's see-through ghost (lib/util/cutaway.glsl) keeps its own opacity
+ gl_FragData[0].a = applyCutawayAlpha(gl_FragData[0].a);
+
applyShadowDebugOverlay();
}
diff --git a/files/shaders/compatibility/terrain.frag b/files/shaders/compatibility/terrain.frag
index 101f73d..593bb09 100644
--- a/files/shaders/compatibility/terrain.frag
+++ b/files/shaders/compatibility/terrain.frag
@@ -47,7 +47,7 @@ uniform float far;
void main()
{
- vec2 cutawaySilhouette = applyCutaway(passViewPos, normalize(gl_NormalMatrix * passNormal), true);
+ vec4 cutaway = applyCutaway(passViewPos, true);
vec2 adjustedUV = (gl_TextureMatrix[0] * vec4(uv, 0.0, 1.0)).xy;
@@ -100,7 +100,7 @@ void main()
gl_FragData[0].xyz = gl_FragData[0].xyz * lighting + specular;
gl_FragData[0] = applyFogAtDist(gl_FragData[0], euclideanDepth, linearDepth, far);
- gl_FragData[0].xyz = applyCutawaySilhouette(gl_FragData[0].xyz, cutawaySilhouette);
+ gl_FragData[0].xyz = applyCutawayColour(gl_FragData[0].xyz, cutaway);
#if !@disableNormals && @writeNormals
gl_FragData[1].xyz = viewNormal * 0.5 + 0.5;
diff --git a/files/shaders/lib/util/cutaway.glsl b/files/shaders/lib/util/cutaway.glsl
index 6652327..c782653 100644
--- a/files/shaders/lib/util/cutaway.glsl
+++ b/files/shaders/lib/util/cutaway.glsl
@@ -1,82 +1,116 @@
#ifndef LIB_UTIL_CUTAWAY
#define LIB_UTIL_CUTAWAY
-// Isowind's top-down camera: what stands between the camera and the player stays recognisable instead of being cut
-// into:
-// - objects in the way (a house, a wall, a bridge, a tree) fade, each on its own (occluderFade, set per object by
-// MWRender::OcclusionFader), and come back when they no longer are in the way: right around the player they open
-// completely, so the player shows clearly through them, around that they turn see-through, more so the nearer
-// the player, and farther out they stay whole. The fade is real transparency (cutawayAlpha, which the object
-// shader applies; OcclusionFader blends faded objects and keeps them out of the depth buffer), so post-processing
-// that reads depth (ambient occlusion, fog) sees the scene behind them rather than a dither;
-// - indoors (cutawayOverheadRadius, set by RenderingManager::update; nothing fades there) the room is seen like a
-// dollhouse, cut with clean edges: the walls between the player and the camera (the faces that hide the room from
-// it, not a wall seen from the player's own side) end at waist height, and everything above door height (roof,
-// rafters, ceilings, upper floors, people upstairs) is removed. Outdoors the same happens, in a smaller circle,
-// while a floor, a bridge or a canton's tier hangs over the player (OcclusionFader::isPlayerCovered): the fade
-// alone would leave whatever hangs over the way ahead of them whole;
-// - wherever something still covers the player (a hill, a faded ghost), it shows their silhouette, outlined, so
-// they are never lost.
-// Nothing at or below the player's feet is faded, so floors and the ground they stand on stay solid even when they
-// belong to an object that fades. Characters, creatures and doors are never faded (noCutaway; only the storey above
-// goes), nor is water. Only
-// active with a narrow field of view and a camera far from the player, which is how the top-down camera is set up,
-// so normal views are unaffected.
-
-uniform vec3 playerPos;
-uniform mat4 osg_ViewMatrix;
+// Isowind's top-down camera: what is removed so the player can be seen. The rules are MWRender::Cutaway's
+// (apps/openmw/mwrender/cutaway.cpp, whose isCut() answers them the same way for the cursor), and all the numbers come
+// from there:
+// - the porthole (cutawaySightAmounts): where more than half the player is hidden, what lies on the view rays in
+// front of their upper body goes, with a ragged edge; nothing behind the player or below their waist is touched.
+// It is a clear opening in a see-through ghost of what is around it (MWRender::GhostLayer: this shader draws those
+// surfaces in a pass of their own, cutawayGhostPass, and the main view leaves them out);
+// - indoors, the other floors: whatever stands wholly above or below the player's floor (walls, upper floors,
+// furniture, doors, people) dissolves away as a whole (cutawayFade, set on each such object by Cutaway, which then
+// leaves it out of the view altogether).
+// Characters, creatures and doors are never in the porthole (noCutaway 0.75), water is never cut (noCutaway 1), and
+// the ground is never cut: where it, or anything else, still covers the player, their outline shows on it.
+// cutawayEnabled is only set in the main view, so shadows, reflections and the map are whole.
+
uniform mat4 osg_ViewMatrixInverse;
-uniform mat4 projectionMatrix;
-// 0: cut away as described; 0.75 (characters, creatures, doors): never faded, only cut above the storey indoors;
-// 1 (water and its reflections): never cut at all
+uniform float cutawayEnabled;
+uniform vec3 cutawayEye;
+// The player's upper body, as a segment
+uniform vec3 cutawayCapA;
+uniform vec3 cutawayCapB;
+// x: the porthole's radius, y: its soft band, z: how open it is (0..1)
+uniform vec4 cutawaySight;
+// x: the player's floor (z), y: the waist's height over it
+uniform vec4 cutawayLevel;
+// xy: away from the camera along the ground, w: debug view
+uniform vec4 cutawayAway;
+// x: how far out the ghost reaches (as the porthole's radius), y: how opaque it is next to the opening, z: it is on
+uniform vec4 cutawayGhost;
+// 1 in the ghost's own pass (GhostLayer), which draws only what the main view leaves out for it
+uniform float cutawayGhostPass;
+// How far an object on another floor has dissolved away (0..1)
+uniform float cutawayFade;
+// 0: cut as described; 0.75 (characters, creatures, doors, particles): never in the porthole; 1 (water and its
+// reflections): never
uniform float noCutaway;
-uniform float occluderFade;
-uniform float cutawayOverheadRadius;
// The player mask (PlayerMask in apps/openmw/mwrender/playermask.cpp): the player rendered alone, red = their view
// depth, alpha = coverage. screenRes is declared by the including shader.
uniform sampler2D playerMaskTex;
+// Blue noise thresholds (1..254 / 255), tiled over the screen
+uniform sampler2D cutawayNoise;
-// How opaque this fragment of a faded object stays (set by applyCutaway, applied by the object shader).
-float cutawayAlpha = 1.0;
-
-// Nothing lower than this above the player's feet is faded.
-#define CUTAWAY_FLOOR_CLEARANCE 25.0
-// How see-through a faded object gets just outside the keyhole, and how many keyhole radii out that fades back to
-// whole; behind the player it is always whole, so a big tree or house only clears around the player.
-#define CUTAWAY_GHOST 0.65
-// How see-through the keyhole itself is: not quite clear, so what is under a roof blends into the fade around it
-#define CUTAWAY_KEYHOLE_CLEAR 0.9
-#define CUTAWAY_WINDOW_OUTER 3.0
-// How far toward the camera (on the ground, world units) from the middle of the player something must be to count as
-// in front of them.
-#define CUTAWAY_FRONT_MARGIN 10.0
-// Indoors, how high above the player's feet everything ends: above the doors, below the rafters and the roof.
-#define CUTAWAY_STOREY_HEIGHT 230.0
-// Indoors, how high above the player's feet what stands between them and the camera ends.
-#define CUTAWAY_WALL_HEIGHT 110.0
-// The circle around the player in which a faded object opens completely: centred on the middle of their body, as big
-// as a margin of this much (world units at the player's distance; they are about 125 units tall) around the line from
-// their feet to their head would be, times CUTAWAY_KEYHOLE_SCALE.
-#define CUTAWAY_KEYHOLE_RADIUS 70.0
-#define CUTAWAY_KEYHOLE_SCALE 1.2
// The silhouette's colour, and how strongly its inside and its outline show.
#define CUTAWAY_SILHOUETTE_COLOUR vec3(0.95, 0.78, 0.38)
#define CUTAWAY_SILHOUETTE_FILL 0.3
#define CUTAWAY_SILHOUETTE_EDGE 0.85
// The player mask's resolution (PlayerMask's sMaskSize)
#define CUTAWAY_MASK_SIZE 512.0
+// The noise tile's size (Cutaway's sNoiseSize)
+#define CUTAWAY_NOISE_SIZE 64.0
+// The porthole's ragged edge: this far in and out (world units), in bumps this many pixels apart
+#define CUTAWAY_EDGE_NOISE 8.0
+#define CUTAWAY_EDGE_SCALE 48.0
+// How close to the body and how softly the porthole stops in front of it, and how softly at the waist
+// (Cutaway's sBodyNear, sBodySoft, sWaistSoft)
+#define CUTAWAY_BODY_NEAR 15.0
+#define CUTAWAY_BODY_SOFT 35.0
+#define CUTAWAY_WAIST_SOFT 25.0
+// ...nor what is behind the player along the ground, past this far (fading over this much): the top of an arch or a
+// pole behind them is nearer the camera than they are (Cutaway's sBehindFrom, sBehindSoft)
+#define CUTAWAY_BEHIND_FROM 20.0
+#define CUTAWAY_BEHIND_SOFT 40.0
+// The ghost: its pass draws what is at least this far into it, and the main view leaves out only what is this far,
+// so at its outer edge both draw the same surface for a little way, and no gap opens between them
+#define CUTAWAY_GHOST_MIN 0.004
+#define CUTAWAY_GHOST_MAIN 0.03
+
+float cutawayHash(vec2 p)
+{
+ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
+}
-// 4x4 ordered dither, 0..15/16.
-float cutawayBayer2(vec2 a)
+// Smooth noise in -1..1 over the screen: the same for every surface on a pixel
+float cutawayEdgeNoise()
{
- a = floor(a);
- return fract(dot(a, vec2(0.5, a.y * 0.75)));
+ vec2 p = gl_FragCoord.xy / CUTAWAY_EDGE_SCALE;
+ vec2 i = floor(p);
+ vec2 f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ float n = mix(mix(cutawayHash(i), cutawayHash(i + vec2(1.0, 0.0)), f.x),
+ mix(cutawayHash(i + vec2(0.0, 1.0)), cutawayHash(i + vec2(1.0, 1.0)), f.x), f.y);
+ return n * 2.0 - 1.0;
}
-float cutawayBayer4(vec2 a)
+// How opaque the ghost pass makes what it draws (set by applyCutaway, applied by applyCutawayAlpha)
+float cutawayLayerAlpha = 1.0;
+
+// How much the porthole removes of a point (x, 0..1), and how far it is in the ghost (y, 0..1). Cutaway::sightAt.
+vec2 cutawaySightAmounts(vec3 world)
{
- return cutawayBayer2(0.5 * a) * 0.25 + cutawayBayer2(a);
+ vec3 ray = world - cutawayEye;
+ float len = length(ray);
+ ray /= len;
+ vec3 axis = cutawayCapB - cutawayCapA;
+ vec3 fromBody = cutawayEye - cutawayCapA;
+ float along = dot(ray, axis);
+ float denom = max(dot(axis, axis) - along * along, 1e-4);
+ float s = clamp((dot(axis, fromBody) - along * dot(ray, fromBody)) / denom, 0.0, 1.0);
+ vec3 nearest = cutawayCapA + axis * s;
+ float atBody = dot(nearest - cutawayEye, ray);
+ float dist = length(cutawayEye + ray * atBody - nearest) + cutawayEdgeNoise() * CUTAWAY_EDGE_NOISE;
+ float footprint = 1.0 - smoothstep(cutawaySight.x, cutawaySight.x + cutawaySight.y, dist);
+ float ghost = 1.0 - smoothstep(cutawaySight.x, cutawayGhost.x, dist);
+ float inFront = 1.0 - smoothstep(atBody - CUTAWAY_BODY_NEAR - CUTAWAY_BODY_SOFT, atBody - CUTAWAY_BODY_NEAR, len);
+ float high = smoothstep(cutawayLevel.y - CUTAWAY_WAIST_SOFT, cutawayLevel.y + CUTAWAY_WAIST_SOFT,
+ world.z - cutawayLevel.x);
+ float ahead = -dot(world.xy - cutawayCapA.xy, cutawayAway.xy);
+ float notBehind = smoothstep(-CUTAWAY_BEHIND_FROM - CUTAWAY_BEHIND_SOFT, -CUTAWAY_BEHIND_FROM, ahead);
+ float amount = inFront * high * notBehind * cutawaySight.z;
+ return vec2(footprint, ghost) * amount;
}
// Whether the player is on screen at uv, behind something at fragDepth.
@@ -87,144 +121,104 @@ float cutawayCoversPlayer(vec2 uv, float fragDepth)
return (mask.a > 0.5 && fragDepth < mask.r / mask.a - 20.0) ? 1.0 : 0.0;
}
-// Whether this view is the top-down camera; feet and head are the player's, in view space.
-bool cutawayTopDown(out vec3 feet, out vec3 head)
-{
- feet = (osg_ViewMatrix * vec4(playerPos + vec3(0.0, 0.0, 10.0), 1.0)).xyz;
- head = (osg_ViewMatrix * vec4(playerPos + vec3(0.0, 0.0, 125.0), 1.0)).xyz;
- // projectionMatrix[1][1] is 1 / tan(fovY / 2); above 2.7 means a field of view narrower than about 40 degrees.
- // The top-down camera can slide in close (to stay above the ground), so the distance only rules out first person.
- return noCutaway < 0.9 && projectionMatrix[1][1] >= 2.7 && -0.5 * (feet.z + head.z) >= 150.0;
-}
-
-// Fades this fragment as described above (discarding it), and returns how strongly the player's silhouette shows
-// on it: x = its inside, y = its outline (pass to applyCutawaySilhouette once the colour is known).
-// terrain: the ground can't fade, it only shows the silhouette.
-vec2 applyCutaway(vec3 viewPos, vec3 viewNormal, bool terrain)
+// Cuts this fragment away (discarding it) if the rules say so. Returns what applyCutawayColour needs once the colour
+// is known: x = the player's silhouette inside, y = its outline, z = unused, w = the debug tint (2: the porthole,
+// 3: another floor dissolving away). terrain: the ground is never cut. Call it before anything else in main().
+vec4 applyCutaway(vec3 viewPos, bool terrain)
{
- vec3 feet;
- vec3 head;
- if (!cutawayTopDown(feet, head))
- return vec2(0.0);
+ if (cutawayEnabled < 0.5 || noCutaway > 0.9)
+ return vec4(0.0);
- float fragDepth = -viewPos.z;
- vec3 world = (osg_ViewMatrixInverse * vec4(viewPos, 1.0)).xyz;
+ float threshold = texture2D(cutawayNoise, gl_FragCoord.xy / CUTAWAY_NOISE_SIZE).r;
+ float debugTint = 0.0;
- // Characters, creatures and doors: only gone with the storey above the player indoors (people upstairs)
- if (noCutaway > 0.5)
+ // Another floor, dissolving away as a whole
+ if (cutawayFade > 0.0 && threshold < cutawayFade)
{
- if (cutawayOverheadRadius > 1.0)
- {
- float above = step(CUTAWAY_STOREY_HEIGHT, world.z - playerPos.z);
- float around = 1.0 - smoothstep(cutawayOverheadRadius * 0.8, cutawayOverheadRadius,
- length(world.xy - playerPos.xy));
- if (above * around > 0.0 && cutawayBayer4(gl_FragCoord.xy) < above * around)
- discard;
- }
- return vec2(0.0);
+ if (cutawayAway.w < 0.5 || cutawayGhostPass > 0.5)
+ discard;
+ debugTint = 3.0;
}
- if (!terrain && world.z >= playerPos.z + CUTAWAY_FLOOR_CLEARANCE)
+ vec3 world = (osg_ViewMatrixInverse * vec4(viewPos, 1.0)).xyz;
+ bool actor = noCutaway > 0.5;
+ bool cut = false;
+ bool ghost = false;
+ if (!terrain && !actor && cutawaySight.z > 0.0)
{
- // In front of the player means between them and the camera on the ground, not only nearer the camera: seen
- // from above, the top of a wall at the player's back is nearer than they are, and must stay
- vec3 cameraForward = -(osg_ViewMatrixInverse * vec4(0.0, 0.0, 1.0, 0.0)).xyz;
- vec2 towardCamera = -normalize(cameraForward.xy + vec2(1e-5));
- bool inFront = dot(world.xy - playerPos.xy, towardCamera) > CUTAWAY_FRONT_MARGIN;
-
- // Level surfaces below the player's waist (swamp scum on a pool they wade in, rugs, tabletops, lower steps)
- // never hide them from above, so a faded object stays whole there
- vec3 worldNormal = (osg_ViewMatrixInverse * vec4(viewNormal, 0.0)).xyz;
- bool lowFloor = abs(worldNormal.z) > 0.7 && world.z < playerPos.z + CUTAWAY_WALL_HEIGHT;
-
- float cut = 0.0;
- if (occluderFade > 0.0 && !lowFloor)
+ vec2 sight = cutawaySightAmounts(world);
+ if (cutawayGhost.z > 0.5)
{
- // Open in a circle around the player on screen (measured at their distance) and see-through around it,
- // where this fragment is in front of them
- float transparency = 0.0;
- float playerDepth = -0.5 * (feet.z + head.z);
- if (fragDepth < playerDepth && inFront)
- {
- vec2 onScreen = viewPos.xy * (playerDepth / max(fragDepth, 1.0));
- vec2 feetOnScreen = feet.xy * (playerDepth / -feet.z);
- vec2 headOnScreen = head.xy * (playerDepth / -head.z);
- // The area of the margin around their outline, as a circle
- float halfLength = 0.5 * length(headOnScreen - feetOnScreen);
- float radius = CUTAWAY_KEYHOLE_SCALE
- * sqrt(CUTAWAY_KEYHOLE_RADIUS * (CUTAWAY_KEYHOLE_RADIUS + halfLength * 4.0 / 3.14159));
- float dist = length(onScreen - 0.5 * (feetOnScreen + headOnScreen));
- float keyhole = CUTAWAY_KEYHOLE_CLEAR * (1.0 - smoothstep(radius * 0.5, radius, dist));
- float ghost = 1.0 - smoothstep(radius, radius * CUTAWAY_WINDOW_OUTER, dist);
- transparency = occluderFade * max(keyhole, CUTAWAY_GHOST * ghost);
- }
- cutawayAlpha = 1.0 - transparency;
- if (cutawayAlpha < 0.02)
- discard;
+ // What is in the ghost's reach is drawn by the ghost's pass alone, see-through, and clear in the opening
+ ghost = sight.y > CUTAWAY_GHOST_MIN;
+ if (sight.y > CUTAWAY_GHOST_MAIN && cutawayGhostPass < 0.5)
+ cut = true;
+ cutawayLayerAlpha = (1.0 - sight.x) * mix(1.0, cutawayGhost.y, sight.y);
}
-
- // Indoors: walls (and anything else tall) between the player and the camera end at waist height across the
- // room, like a dollhouse, so the room and whoever is in it can be seen; outdoors only the window above opens.
- // Only the faces that hide the room: a face seen from the player's side (it points their way) has the room
- // in front of it, so it stays whole however the wall runs; before, every bit of a wall nearer the camera
- // than the player was cut, and a wall running diagonally past them lost its half toward the camera. A face
- // seen from behind (two-sided geometry) is turned round first. Tops and other level surfaces have no side:
- // they are cut within the right angle toward the camera from the player, which for a wall running past the
- // player is where its faces are cut too.
- if (cutawayOverheadRadius > 1.0 && inFront)
+ else if (threshold >= 1.0 - sight.x)
+ cut = true; // (the debug view: what the porthole takes, tinted instead)
+ }
+ if (cutawayGhostPass > 0.5)
+ {
+ // The ghost's pass: nothing else, and nothing too faint to see (it would hide what is behind it)
+ // (Debug view 4: what this pass draws, in magenta, what is clear in the opening, cyan, and the rest, dark blue)
+ if (cutawayAway.w > 3.5 && ghost && cutawayLayerAlpha < CUTAWAY_GHOST_MIN)
{
- vec3 facing = gl_FrontFacing ? worldNormal : -worldNormal;
- vec2 fromPlayer = world.xy - playerPos.xy;
- bool hidesRoom;
- if (abs(facing.z) < 0.7)
- hidesRoom = dot(facing.xy, fromPlayer) > 0.0;
- else
- {
- float ahead = dot(fromPlayer, towardCamera);
- float aside = length(fromPlayer - towardCamera * ahead);
- hidesRoom = ahead > aside;
- }
- if (hidesRoom)
- {
- float around = 1.0 - smoothstep(cutawayOverheadRadius * 0.8, cutawayOverheadRadius,
- length(fromPlayer));
- cut = max(cut, around * step(CUTAWAY_WALL_HEIGHT, world.z - playerPos.z));
- }
+ cutawayLayerAlpha = 1.0;
+ return vec4(0.0, 0.0, 0.0, 6.0);
}
-
- // Indoors: ceilings and upper floors above the player's head (surfaces facing up or down), and everything
- // higher than door height above their feet (the roof, rafters and beams), so walls end there and nothing
- // overhead clutters the room
- if (cutawayOverheadRadius > 1.0 && world.z > playerPos.z + 200.0)
+ if (cutawayAway.w > 3.5 && !ghost)
{
- float around = 1.0 - smoothstep(cutawayOverheadRadius * 0.8, cutawayOverheadRadius,
- length(world.xy - playerPos.xy));
- if (abs(worldNormal.z) > 0.5)
- cut = max(cut, around);
- cut = max(cut, around * step(CUTAWAY_STOREY_HEIGHT, world.z - playerPos.z));
+ cutawayLayerAlpha = 1.0;
+ return vec4(0.0, 0.0, 0.0, 7.0);
}
+ if (!ghost || cutawayLayerAlpha < CUTAWAY_GHOST_MIN)
+ discard;
+ return vec4(0.0, 0.0, 0.0, cutawayAway.w > 3.5 ? 5.0 : 0.0);
+ }
- if (cut > 0.0 && cutawayBayer4(gl_FragCoord.xy) < cut)
+ if (cut)
+ {
+ if (cutawayAway.w < 0.5 || cutawayAway.w > 3.5)
discard;
+ debugTint = 2.0;
}
// The silhouette, where this fragment is in front of the player on screen
+ float fragDepth = -viewPos.z;
vec2 uv = gl_FragCoord.xy / screenRes;
- float inside = cutawayCoversPlayer(uv, fragDepth);
- if (inside == 0.0)
- return vec2(0.0);
+ float covers = cutawayCoversPlayer(uv, fragDepth);
+ if (covers == 0.0)
+ return vec4(0.0, 0.0, 0.0, debugTint);
vec2 texel = vec2(1.5 / CUTAWAY_MASK_SIZE);
float around = 0.25 * (cutawayCoversPlayer(uv + vec2(texel.x, 0.0), fragDepth)
+ cutawayCoversPlayer(uv - vec2(texel.x, 0.0), fragDepth)
+ cutawayCoversPlayer(uv + vec2(0.0, texel.y), fragDepth)
+ cutawayCoversPlayer(uv - vec2(0.0, texel.y), fragDepth));
- return vec2(inside, inside * (1.0 - around));
+ return vec4(covers, covers * (1.0 - around), 0.0, debugTint);
+}
+
+// The ghost's pass draws what it keeps this opaque; anywhere else alpha is what it was
+float applyCutawayAlpha(float alpha)
+{
+ return cutawayGhostPass > 0.5 ? cutawayLayerAlpha : alpha;
}
-vec3 applyCutawaySilhouette(vec3 colour, vec2 silhouette)
+vec3 applyCutawayColour(vec3 colour, vec4 cut)
{
- float amount = max(silhouette.x * CUTAWAY_SILHOUETTE_FILL, silhouette.y * CUTAWAY_SILHOUETTE_EDGE);
- return mix(colour, CUTAWAY_SILHOUETTE_COLOUR, amount);
+ float amount = max(cut.x * CUTAWAY_SILHOUETTE_FILL, cut.y * CUTAWAY_SILHOUETTE_EDGE);
+ colour = mix(colour, CUTAWAY_SILHOUETTE_COLOUR, amount);
+ if (cut.w > 6.5)
+ colour = vec3(0.0, 0.0, 0.5);
+ else if (cut.w > 5.5)
+ colour = vec3(0.0, 1.0, 1.0);
+ else if (cut.w > 4.5)
+ colour = vec3(1.0, 0.0, 1.0);
+ else if (cut.w > 2.5)
+ colour = mix(colour, vec3(1.0, 0.6, 0.1), 0.6);
+ else if (cut.w > 1.5)
+ colour = mix(colour, vec3(0.1, 0.4, 1.0), 0.6);
+ return colour;
}
#endif
diff --git a/isowind/mod/scripts/isowind/topdown.lua b/isowind/mod/scripts/isowind/topdown.lua
index 15811f9..fcf8bf4 100644
--- a/isowind/mod/scripts/isowind/topdown.lua
+++ b/isowind/mod/scripts/isowind/topdown.lua
@@ -358,56 +358,6 @@ local function segmentDistance(p, a, b)
return (p - (a + ab * t)):length()
end
--- What the camera cuts away (shaders/lib/util/cutaway.glsl): the engine fades whole objects that stand in front of
--- the player (camera.getFadedObjects), and indoors, or under a floor or a bridge outdoors, removes ceilings and upper
--- floors over them and cuts the walls in the way, within camera.getCutawayRadius of them. Floors and the ground below
--- their knees always stay.
-local fadedObjects = {}
-local cutawayRadius = 0
-
-local function updateFadedObjects()
- fadedObjects = {}
- for _, object in ipairs(camera.getFadedObjects()) do
- fadedObjects[object.id] = true
- end
- cutawayRadius = camera.getCutawayRadius and camera.getCutawayRadius() or 0
-end
-
--- Toward the camera along the ground (unit length)
-local function towardCamera()
- local f = view.forward
- local length = math.sqrt(f.x * f.x + f.y * f.y)
- if length < 1e-4 then return v3(0, -1, 0) end
- return v3(-f.x / length, -f.y / length, 0)
-end
-
--- The shader's rules, for a surface the cursor's ray hit from its front (normal: its facing)
-local function isCutAway(pos, object, normal)
- local height = pos.z - self.position.z
- if height < 25 then return false end
- if object and fadedObjects[object.id] then return true end
- if cutawayRadius <= 1 then return false end
- local rel = pos - self.position
- local flat = math.sqrt(rel.x * rel.x + rel.y * rel.y)
- if flat > cutawayRadius * 0.9 then return false end
- -- Everything above the storey, and ceilings and upper floors over the player's head
- if height > 230 then return true end
- if height > 200 and normal and math.abs(normal.z) > 0.5 then return true end
- -- Above waist height between the player and the camera: faces that hide the room from it (pointing away from the
- -- player), and level surfaces within the right angle toward the camera
- if height > 110 and normal then
- local toward = towardCamera()
- local ahead = rel.x * toward.x + rel.y * toward.y
- if ahead > 10 then
- if math.abs(normal.z) < 0.7 then
- return normal.x * rel.x + normal.y * rel.y > 0
- end
- return ahead > math.sqrt(math.max(0, flat * flat - ahead * ahead))
- end
- end
- return false
-end
-
-- Cast through the cursor, passing through what isn't drawn: back faces (many ceilings and outer walls are only
-- visible from inside) and whatever the cutaway removes. Otherwise the cursor would land on a hidden ceiling.
local function castThroughCutaway(from, dir)
@@ -418,9 +368,11 @@ local function castThroughCutaway(from, dir)
if not result.hit then return result end
-- Characters and doors are drawn from both sides, so their back faces are solid.
local object = result.hitObject
- local backFace = result.hitNormal and result.hitNormal:dot(dir) > 0
- and not (object and (types.Actor.objectIsInstance(object) or types.Door.objectIsInstance(object)))
- if not backFace and not isCutAway(result.hitPos, result.hitObject, result.hitNormal) then
+ -- Characters and doors are only ever cut away with the storey above, and drawn from both sides
+ local whole = object and (types.Actor.objectIsInstance(object) or types.Door.objectIsInstance(object))
+ local backFace = result.hitNormal and result.hitNormal:dot(dir) > 0 and not whole
+ -- What the camera cuts away is the engine's to say (MWRender::Cutaway): it draws by the same rule
+ if not backFace and not camera.isCutAway(result.hitPos, whole, object) then
return result
end
start = result.hitPos + dir * 2
@@ -1094,7 +1046,6 @@ local function onFrame(dt)
updateCursor()
updateCamera(dt)
- updateFadedObjects()
if gamepad then updateGamepadPick() else updatePick() end
updateLabel()
setUiVisible(true)