diff --git a/apps/openmw/CMakeLists.txt b/apps/openmw/CMakeLists.txt index 818cf6369f..314b2b5c3d 100644 --- a/apps/openmw/CMakeLists.txt +++ b/apps/openmw/CMakeLists.txt @@ -88,7 +88,7 @@ add_openmw_dir (mwworld add_openmw_dir (mwphysics physicssystem trace collisiontype actor convert object heightfield closestnotmerayresultcallback - contacttestresultcallback stepper movementsolver projectile + contacttestresultcallback stepper movementsolver projectile mantle actorconvexcallback raycasting mtphysics contacttestwrapper projectileconvexcallback ) diff --git a/apps/openmw/mwbase/luamanager.hpp b/apps/openmw/mwbase/luamanager.hpp index 69c4652b77..15540f9b63 100644 --- a/apps/openmw/mwbase/luamanager.hpp +++ b/apps/openmw/mwbase/luamanager.hpp @@ -102,6 +102,8 @@ namespace MWBase = 0; virtual void exteriorCreated(MWWorld::CellStore& cell) = 0; virtual void actorDied(const MWWorld::Ptr& actor) = 0; + // Ashlar mantling: the actor started climbing a ledge this high above its feet. + virtual void actorMantled(const MWWorld::Ptr& actor, float height) = 0; virtual void onDialogueResponse( const MWWorld::Ptr& actor, const ESM::DialInfo& info, const ESM::Dialogue& record) = 0; @@ -158,6 +160,7 @@ namespace MWBase bool mSneak = false; bool mBlock = false; // Ashlar active blocking bool mSprint = false; // Ashlar sprint + bool mMantle = true; // Ashlar mantling: false vetoes mantles float mMovement = 0; float mSideMovement = 0; float mPitchChange = 0; diff --git a/apps/openmw/mwlua/localscripts.cpp b/apps/openmw/mwlua/localscripts.cpp index d788863b9d..c39d146284 100644 --- a/apps/openmw/mwlua/localscripts.cpp +++ b/apps/openmw/mwlua/localscripts.cpp @@ -68,6 +68,7 @@ namespace MWLua controls["jump"] = CONTROL(bool, mJump); controls["block"] = CONTROL(bool, mBlock); controls["sprint"] = CONTROL(bool, mSprint); + controls["mantle"] = CONTROL(bool, mMantle); controls["use"] = CONTROL(MWMechanics::AttackType, mUse); #undef CONTROL diff --git a/apps/openmw/mwlua/luamanagerimp.cpp b/apps/openmw/mwlua/luamanagerimp.cpp index d02bf2e1e2..38bc14307e 100644 --- a/apps/openmw/mwlua/luamanagerimp.cpp +++ b/apps/openmw/mwlua/luamanagerimp.cpp @@ -542,6 +542,17 @@ namespace MWLua mLuaEvents.addLocalEvent({ getId(actor), "Died", {} }); } + void LuaManager::actorMantled(const MWWorld::Ptr& actor, float height) + { + if (actor.isEmpty()) + return; + mLua.protectedCall([&](LuaUtil::LuaView& view) { + sol::table data = view.newTable(); + data["height"] = height; + sendLocalEvent(actor, "AshlarMantle", data); + }); + } + void LuaManager::onDialogueResponse( const MWWorld::Ptr& actor, const ESM::DialInfo& info, const ESM::Dialogue& record) { diff --git a/apps/openmw/mwlua/luamanagerimp.hpp b/apps/openmw/mwlua/luamanagerimp.hpp index 2fac2a9639..6f5ccfbf91 100644 --- a/apps/openmw/mwlua/luamanagerimp.hpp +++ b/apps/openmw/mwlua/luamanagerimp.hpp @@ -125,6 +125,7 @@ namespace MWLua void uiModeChanged(const MWWorld::Ptr& arg) override; void viewportResized(int width, int height) override; void actorDied(const MWWorld::Ptr& actor) override; + void actorMantled(const MWWorld::Ptr& actor, float height) override; void onDialogueResponse( const MWWorld::Ptr& actor, const ESM::DialInfo& info, const ESM::Dialogue& record) override; void applyMagicEffects(ESM::RefId id, const MWWorld::Ptr& caster, ESM::RefNum item, const MWWorld::Ptr& target, diff --git a/apps/openmw/mwmechanics/actors.cpp b/apps/openmw/mwmechanics/actors.cpp index fb1a4bb881..b9a54a8c1a 100644 --- a/apps/openmw/mwmechanics/actors.cpp +++ b/apps/openmw/mwmechanics/actors.cpp @@ -388,6 +388,7 @@ namespace MWMechanics stats.setMovementFlag(MWMechanics::CreatureStats::Flag_Sneak, controls.mSneak); stats.setBlockHeld(controls.mBlock); stats.setSprintHeld(controls.mSprint); + stats.setMantleAllowed(controls.mMantle); stats.setAttackingOrSpell(controls.mUse != AttackType::NoAttack); stats.setAttackType(attackTypeName(controls.mUse)); diff --git a/apps/openmw/mwmechanics/creaturestats.hpp b/apps/openmw/mwmechanics/creaturestats.hpp index be7b10ac9b..dc426f9616 100644 --- a/apps/openmw/mwmechanics/creaturestats.hpp +++ b/apps/openmw/mwmechanics/creaturestats.hpp @@ -64,6 +64,7 @@ namespace MWMechanics bool mSprintHeld = false; bool mSprinting = false; bool mSprintCancelled = false; + bool mMantleAllowed = true; float mPendingFlinch = 0.f; float mReactionTime = 0.f; unsigned int mMovementFlags = 0; @@ -243,6 +244,9 @@ namespace MWMechanics // Ashlar: block stance requested by combat AI. Cleared every frame before AI runs. Not saved. void setAiBlockHeld(bool value) { mAiBlockHeld = value; } bool getAiBlockHeld() const { return mAiBlockHeld; } + // Ashlar mantling: false while Lua vetoes mantles (self.controls.mantle). Not saved. + void setMantleAllowed(bool value) { mMantleAllowed = value; } + bool getMantleAllowed() const { return mMantleAllowed; } // Ashlar sprint: the Sprint control, whether the actor sprints this frame, and whether Use cancelled the // sprint until Sprint is released. Not saved. void setSprintHeld(bool value) { mSprintHeld = value; } diff --git a/apps/openmw/mwphysics/actor.cpp b/apps/openmw/mwphysics/actor.cpp index f2e9cffec1..e049a7dbce 100644 --- a/apps/openmw/mwphysics/actor.cpp +++ b/apps/openmw/mwphysics/actor.cpp @@ -333,4 +333,27 @@ namespace MWPhysics return (tracer.mFraction >= 1.0f); } + + void Actor::setMantleState(const Mantle::State& state) + { + if (state.mActive && (!mMantle.mActive || state.mElapsed < mMantle.mElapsed)) + mMantleStarted = state.mHeight; + if (mMantle.mActive && !state.mActive) + mMantleFinished = true; + mMantle = state; + } + + float Actor::takeMantleStarted() + { + const float height = mMantleStarted; + mMantleStarted = -1.f; + return height; + } + + bool Actor::takeMantleFinished() + { + const bool finished = mMantleFinished; + mMantleFinished = false; + return finished; + } } diff --git a/apps/openmw/mwphysics/actor.hpp b/apps/openmw/mwphysics/actor.hpp index da8ae1ab44..f4acce82ec 100644 --- a/apps/openmw/mwphysics/actor.hpp +++ b/apps/openmw/mwphysics/actor.hpp @@ -4,6 +4,7 @@ #include #include +#include "mantle.hpp" #include "ptrholder.hpp" #include @@ -142,6 +143,14 @@ namespace MWPhysics bool canMoveToWaterSurface(float waterlevel, const btCollisionWorld* world) const; + // Ashlar mantling: the mantle in progress, written back by the physics sync. Not saved. + const Mantle::State& getMantleState() const { return mMantle; } + void setMantleState(const Mantle::State& state); + /// Height of a mantle that started since the last call, or a negative value. Main thread only. + float takeMantleStarted(); + /// Whether a mantle ended since the last call. Main thread only. + bool takeMantleFinished(); + bool isActive() const { return mActive; } void setActive(bool value) { mActive = value; } @@ -182,6 +191,10 @@ namespace MWPhysics unsigned int mStuckFrames; osg::Vec3f mLastStuckPosition; + Mantle::State mMantle; + float mMantleStarted = -1.f; + bool mMantleFinished = false; + osg::Vec3f mForce; bool mOnGround; bool mOnSlope; diff --git a/apps/openmw/mwphysics/mantle.cpp b/apps/openmw/mwphysics/mantle.cpp new file mode 100644 index 0000000000..fcd0cfcb10 --- /dev/null +++ b/apps/openmw/mwphysics/mantle.cpp @@ -0,0 +1,137 @@ +#include "mantle.hpp" + +#include +#include + +#include "movementsolver.hpp" + +namespace MWPhysics::Mantle +{ + osg::Vec3f intoWall(const osg::Vec3f& wallNormal) + { + osg::Vec3f dir(-wallNormal.x(), -wallNormal.y(), 0.f); + const float length = dir.length(); + if (length < 1e-3f) + return osg::Vec3f(); + return dir / length; + } + + bool wantsMantle( + bool onGround, bool flying, bool underwater, const osg::Vec3f& moveDir, const osg::Vec3f& wallNormal) + { + if (onGround || flying || underwater) + return false; + // A floor or a ceiling isn't something to climb. + if (isWalkableSlope(wallNormal) || wallNormal.z() < -0.5f) + return false; + const osg::Vec3f into = intoWall(wallNormal); + osg::Vec3f move(moveDir.x(), moveDir.y(), 0.f); + const float length = move.length(); + if (into.length2() == 0.f || length < 1e-3f) + return false; + return (move / length) * into >= sMinPushCos; + } + + float probeRise(float actorHeight, float maxHeightFactor) + { + return std::max(0.f, actorHeight * maxHeightFactor) + sClearance; + } + + const char* resultName(Result result) + { + switch (result) + { + case Result::Ok: + return "ok"; + case Result::NoHeadroom: + return "no headroom"; + case Result::Blocked: + return "blocked"; + case Result::NoSurface: + return "no surface"; + case Result::Steep: + return "steep"; + case Result::TooLow: + return "too low"; + case Result::TooHigh: + return "too high"; + } + return "unknown"; + } + + Result evaluate(const Probe& probe) + { + if (probe.mRiseReached < sMinRise) + return Result::NoHeadroom; + if (probe.mForwardReached < probe.mForwardNeeded) + return Result::Blocked; + if (!probe.mSurfaceHit) + return Result::NoSurface; + if (!isWalkableSlope(probe.mSurfaceNormal)) + return Result::Steep; + const float height = probe.mSurfaceFeetZ - probe.mFeetZ; + if (height < sMinHeight) + return Result::TooLow; + if (height > probe.mActorHeight * probe.mMaxHeightFactor) + return Result::TooHigh; + // The surface has to sit below the height the probe crossed at, with the clearance kept. + if (probe.mSurfaceFeetZ - probe.mFeetZ + sClearance > probe.mRiseReached + 1e-3f) + return Result::NoHeadroom; + return Result::Ok; + } + + osg::Vec3f pathPosition(const osg::Vec3f& start, float peakZ, const osg::Vec3f& target, float fraction) + { + const float t = std::clamp(fraction, 0.f, 1.f); + // Smoothstep: starts and ends gently. + const float eased = t * t * (3.f - 2.f * t); + + const osg::Vec3f up(start.x(), start.y(), peakZ); + const osg::Vec3f across(target.x(), target.y(), peakZ); + const float l1 = std::abs(peakZ - start.z()); + const float l2 = (across - up).length(); + const float l3 = std::abs(peakZ - target.z()); + const float total = l1 + l2 + l3; + if (total <= 1e-4f) + return target; + + float d = eased * total; + if (d <= l1) + return start + (up - start) * (l1 > 0.f ? d / l1 : 1.f); + d -= l1; + if (d <= l2) + return up + (across - up) * (l2 > 0.f ? d / l2 : 1.f); + d -= l2; + return across + (target - across) * (l3 > 0.f ? std::min(d / l3, 1.f) : 1.f); + } + + State start(const osg::Vec3f& startPos, float peakZ, const osg::Vec3f& target, float duration, float height) + { + State state; + state.mActive = true; + state.mStart = startPos; + state.mPeakZ = std::max({ peakZ, startPos.z(), target.z() }); + state.mTarget = target; + state.mLast = startPos; + state.mElapsed = 0.f; + state.mDuration = std::max(duration, 0.01f); + state.mHeight = height; + return state; + } + + osg::Vec3f advance(State& state, float dt) + { + if (!state.mActive) + return state.mLast; + state.mElapsed += std::max(dt, 0.f); + const float fraction = state.mElapsed / state.mDuration; + if (fraction >= 1.f) + { + state.mActive = false; + state.mLast = state.mTarget; + return state.mTarget; + } + state.mLast = pathPosition(state.mStart, state.mPeakZ, state.mTarget, fraction); + return state.mLast; + } +} diff --git a/apps/openmw/mwphysics/mantle.hpp b/apps/openmw/mwphysics/mantle.hpp new file mode 100644 index 0000000000..44ca13a43d --- /dev/null +++ b/apps/openmw/mwphysics/mantle.hpp @@ -0,0 +1,95 @@ +#ifndef OPENMW_MWPHYSICS_MANTLE_H +#define OPENMW_MWPHYSICS_MANTLE_H + +#include + +// Ashlar ledge mantling ([Game] mantling). The geometry rules live here, apart from the physics calls, so that they +// can be unit tested. MovementSolver runs the shape casts and feeds their results to evaluate(). +namespace MWPhysics::Mantle +{ + /// Extra height the probe rises above the reachable ledge height, and the clearance kept over a ledge while + /// moving across it. + constexpr float sClearance = 4.f; + /// Smallest rise the probe needs before it can look for a ledge at all. + constexpr float sMinRise = 8.f; + /// A found surface has to be at least this far above the feet to count as a ledge. + constexpr float sMinHeight = 2.f; + /// Cosine of the widest angle between the movement and the way into the wall that still counts as pushing into + /// it (60 degrees). + constexpr float sMinPushCos = 0.5f; + + /// Per-frame inputs decided on the main thread. + struct Params + { + bool mCanStart = false; ///< setting on, player, not vetoed by Lua, able to act + float mMaxHeightFactor = 1.1f; ///< highest ledge, as a multiple of the actor's height above its feet + float mDuration = 0.4f; ///< seconds a mantle takes + }; + + /// A mantle in progress. Positions are collision shape centres in world space. + struct State + { + bool mActive = false; + osg::Vec3f mStart; + float mPeakZ = 0.f; ///< height of the move across the ledge + osg::Vec3f mTarget; + osg::Vec3f mLast; ///< where the last step put the actor, to notice scripted moves + float mElapsed = 0.f; + float mDuration = 0.4f; + float mHeight = 0.f; ///< ledge height above the feet when it started + }; + + /// Whether the actor is trying to climb: in the air, pushing horizontally into a wall. + /// @param moveDir horizontal movement direction in world space (need not be normalized) + /// @param wallNormal normal of the wall that was hit, pointing towards the actor + bool wantsMantle(bool onGround, bool flying, bool underwater, const osg::Vec3f& moveDir, + const osg::Vec3f& wallNormal); + + /// Horizontal unit direction into the wall, or a zero vector if the wall normal has no horizontal part. + osg::Vec3f intoWall(const osg::Vec3f& wallNormal); + + /// How far up the probe rises, from the shape centre. + float probeRise(float actorHeight, float maxHeightFactor); + + enum class Result + { + Ok, + NoHeadroom, ///< something above the actor stops it rising + Blocked, ///< the wall goes on above the reach, or there is no room on top for the actor + NoSurface, ///< nothing to stand on beyond the edge + Steep, ///< the surface on top is too steep to stand on + TooLow, ///< the surface isn't above the feet; ordinary stepping or falling handles it + TooHigh, ///< the surface is above the reach + }; + + const char* resultName(Result result); + + /// What the three shape casts found. + struct Probe + { + float mFeetZ = 0.f; ///< current feet height + float mActorHeight = 0.f; + float mMaxHeightFactor = 1.1f; + float mRiseReached = 0.f; ///< how far the shape rose before hitting anything (up to probeRise) + float mForwardNeeded = 0.f; ///< how far the shape must move across the edge + float mForwardReached = 0.f; ///< how far it moved before hitting anything + bool mSurfaceHit = false; ///< whether the cast down found something + float mSurfaceFeetZ = 0.f; ///< feet height standing on the found surface + osg::Vec3f mSurfaceNormal{ 0.f, 0.f, 1.f }; + }; + + Result evaluate(const Probe& probe); + + /// Position along the mantle path: straight up from the start to the peak height, across to above the target, + /// then down onto it. The path is split by length, and progress eases in and out. + /// @param fraction 0 at the start, 1 at the end; clamped + osg::Vec3f pathPosition(const osg::Vec3f& start, float peakZ, const osg::Vec3f& target, float fraction); + + /// Starts a mantle. + State start(const osg::Vec3f& start, float peakZ, const osg::Vec3f& target, float duration, float height); + + /// Advances a mantle by dt and returns the new position. Ends it (mActive false) once it reaches the target. + osg::Vec3f advance(State& state, float dt); +} + +#endif diff --git a/apps/openmw/mwphysics/movementsolver.cpp b/apps/openmw/mwphysics/movementsolver.cpp index 562eb3c34f..a0c7ae4e96 100644 --- a/apps/openmw/mwphysics/movementsolver.cpp +++ b/apps/openmw/mwphysics/movementsolver.cpp @@ -15,6 +15,7 @@ #include "collisiontype.hpp" #include "constants.hpp" #include "contacttestwrapper.h" +#include "mantle.hpp" #include "object.hpp" #include "physicssystem.hpp" #include "projectile.hpp" @@ -84,6 +85,69 @@ namespace MWPhysics protected: btVector3 mVelocity; }; + + // Ashlar mantling: a mantle that moved the actor further than this since the last step was interrupted by a + // script or a teleport. + constexpr float sMantleDrift = 30.f; + + // Ashlar mantling: runs the shape casts for a ledge in front of the actor. position is the shape centre. + // Starts actor.mMantle and returns true if there is a ledge to climb. + bool tryMantle(ActorFrameData& actor, const osg::Vec3f& position, const osg::Vec3f& wallNormal, + const btCollisionWorld* collisionWorld) + { + const osg::Vec3f into = Mantle::intoWall(wallNormal); + const float actorHeight = actor.mHalfExtentsZ * 2.f; + Mantle::Probe probe; + probe.mFeetZ = position.z() - actor.mHalfExtentsZ; + probe.mActorHeight = actorHeight; + probe.mMaxHeightFactor = actor.mMantleParams.mMaxHeightFactor; + // Across the whole shape, so it stands clear of the edge. + probe.mForwardNeeded = actor.mHalfExtentsXY * 2.f + Mantle::sClearance; + + ActorTracer tracer; + // 1. Up: the headroom above the actor. + const float rise = Mantle::probeRise(actorHeight, probe.mMaxHeightFactor); + tracer.doTrace(actor.mCollisionObject, position, position + osg::Vec3f(0, 0, rise), collisionWorld); + const osg::Vec3f top = tracer.mEndPos; + probe.mRiseReached = top.z() - position.z(); + if (probe.mRiseReached >= Mantle::sMinRise) + { + // 2. Across, above the wall. + tracer.doTrace( + actor.mCollisionObject, top, top + into * probe.mForwardNeeded, collisionWorld); + const osg::Vec3f across = tracer.mEndPos; + probe.mForwardReached = tracer.mFraction >= 1.f ? probe.mForwardNeeded : (across - top).length(); + if (probe.mForwardReached >= probe.mForwardNeeded) + { + // 3. Down onto the ledge, no lower than the feet are now. + tracer.doTrace(actor.mCollisionObject, across, + osg::Vec3f(across.x(), across.y(), position.z()), collisionWorld); + probe.mSurfaceHit = tracer.mFraction < 1.f && !isActor(tracer.mHitObject); + probe.mSurfaceNormal = tracer.mPlaneNormal; + probe.mSurfaceFeetZ = tracer.mEndPos.z() - actor.mHalfExtentsZ; + } + } + + const Mantle::Result result = Mantle::evaluate(probe); + if (result != Mantle::Result::Ok) + return false; + + const osg::Vec3f target = tracer.mEndPos + osg::Vec3f(0, 0, sGroundOffset); + // Cross just above the ledge if that is clear, rather than at the top of the probe. + float peakZ = top.z(); + const float lowZ = target.z() + Mantle::sClearance; + if (lowZ < peakZ) + { + const osg::Vec3f lowStart(position.x(), position.y(), lowZ); + const osg::Vec3f lowEnd(target.x(), target.y(), lowZ); + tracer.doTrace(actor.mCollisionObject, lowStart, lowEnd, collisionWorld); + if (tracer.mFraction >= 1.f) + peakZ = lowZ; + } + actor.mMantle = Mantle::start(position, peakZ, target, actor.mMantleParams.mDuration, + probe.mSurfaceFeetZ - probe.mFeetZ); + return true; + } } osg::Vec3f MovementSolver::traceDown(const MWWorld::Ptr& ptr, const osg::Vec3f& position, Actor* actor, @@ -134,6 +198,7 @@ namespace MWPhysics // Anything to collide with? if (actor.mSkipCollisionDetection) { + actor.mMantle.mActive = false; actor.mPosition += (osg::Quat(actor.mRotation.x(), osg::Vec3f(-1, 0, 0)) * osg::Quat(actor.mRotation.y(), osg::Vec3f(0, 0, -1))) * actor.mMovement * time; @@ -147,6 +212,22 @@ namespace MWPhysics // physicActor->getScaledMeshTranslation() actor.mPosition.z() += actor.mHalfExtentsZ; // vanilla-accurate + // Ashlar mantling: a mantle in progress moves the actor along its path and ignores movement input. + if (actor.mMantle.mActive) + { + if (actor.mInert || (actor.mPosition - actor.mMantle.mLast).length2() > sMantleDrift * sMantleDrift) + actor.mMantle.mActive = false; // knocked out, or moved by a script + else + { + actor.mPosition = Mantle::advance(actor.mMantle, time); + actor.mInertia = osg::Vec3f(); + actor.mIsOnGround = !actor.mMantle.mActive; + actor.mIsOnSlope = false; + actor.mPosition.z() -= actor.mHalfExtentsZ; + return; + } + } + float swimlevel = actor.mSwimLevel + actor.mHalfExtentsZ; ActorTracer tracer; @@ -199,6 +280,8 @@ namespace MWPhysics osg::Vec3f lastSlideNormal(0, 0, 1); osg::Vec3f lastSlideNormalFallback(0, 0, 1); bool forceGroundTest = false; + bool hitWall = false; + osg::Vec3f wallNormal; for (int iterations = 0; iterations < sMaxIterations && remainingTime > 0.0001f; ++iterations) { @@ -270,6 +353,11 @@ namespace MWPhysics else { // Can't step up, so slide against what we ran into + if (!hitWall && !isActor(tracer.mHitObject) && !isWalkableSlope(tracer.mPlaneNormal)) + { + hitWall = true; + wallNormal = tracer.mPlaneNormal; + } remainingTime *= (1.0f - tracer.mFraction); auto planeNormal = tracer.mPlaneNormal; @@ -427,6 +515,23 @@ namespace MWPhysics } } + // Ashlar mantling: jumping or falling into a wall while moving towards it climbs a ledge if there is one. + if (hitWall && actor.mMantleParams.mCanStart && actor.mMovement.y() > 0.f) + { + const osg::Vec3f moveDir = osg::Quat(actor.mRotation.y(), osg::Vec3f(0, 0, -1)) + * osg::Vec3f(actor.mMovement.x(), actor.mMovement.y(), 0.f); + if (Mantle::wantsMantle(isOnGround, actor.mFlying, newPosition.z() < swimlevel, moveDir, wallNormal) + && tryMantle(actor, newPosition, wallNormal, collisionWorld)) + { + actor.mInertia = osg::Vec3f(); + actor.mIsOnGround = false; + actor.mIsOnSlope = false; + actor.mPosition = newPosition; + actor.mPosition.z() -= actor.mHalfExtentsZ; + return; + } + } + if ((isOnGround && !isOnSlope) || newPosition.z() < swimlevel || actor.mFlying) actor.mInertia = osg::Vec3f(0.f, 0.f, 0.f); else @@ -488,6 +593,9 @@ namespace MWPhysics if (actor.mSkipCollisionDetection) // noclipping/tcl return; + if (actor.mMantle.mActive) // Ashlar: the mantle path is already checked with shape casts + return; + if (actor.mMovement.length2() == 0) // no AI nor player attempted to move, current position is assumed correct return; diff --git a/apps/openmw/mwphysics/mtphysics.cpp b/apps/openmw/mwphysics/mtphysics.cpp index 2b55bd233f..114f8713e6 100644 --- a/apps/openmw/mwphysics/mtphysics.cpp +++ b/apps/openmw/mwphysics/mtphysics.cpp @@ -261,7 +261,10 @@ namespace const float heightDiff = frameData.mPosition.z() - frameData.mOldHeight; const bool isStillOnGround = (mAdvanceSimulation && frameData.mWasOnGround && frameData.mIsOnGround); - if (isStillOnGround || frameData.mFlying || isUnderWater(frameData) || frameData.mSlowFall < 1) + // Ashlar mantling: climbing a ledge ends a fall without fall damage. + if (frameData.mMantle.mActive || actor->getMantleState().mActive) + stats.land(ptr == MWMechanics::getPlayer()); + else if (isStillOnGround || frameData.mFlying || isUnderWater(frameData) || frameData.mSlowFall < 1) stats.land(ptr == MWMechanics::getPlayer() && (frameData.mFlying || isUnderWater(frameData))); else if (heightDiff < 0) stats.addToFallHeight(-heightDiff); @@ -287,6 +290,7 @@ namespace actor->setOnSlope(frameData.mIsOnSlope); actor->setWalkingOnWater(frameData.mWalkingOnWater); actor->setInertialForce(frameData.mInertia); + actor->setMantleState(frameData.mMantle); } } void operator()(MWPhysics::ProjectileSimulation& sim) const diff --git a/apps/openmw/mwphysics/physicssystem.cpp b/apps/openmw/mwphysics/physicssystem.cpp index 3cad4b6eba..97f00dee3f 100644 --- a/apps/openmw/mwphysics/physicssystem.cpp +++ b/apps/openmw/mwphysics/physicssystem.cpp @@ -27,6 +27,7 @@ #include #include "../mwbase/environment.hpp" +#include "../mwbase/luamanager.hpp" #include "../mwbase/world.hpp" #include "../mwmechanics/actorutil.hpp" @@ -83,6 +84,35 @@ namespace ptr.getClass().getMovementSettings(ptr).mPosition[2] = 0; } + // Ashlar mantling: whether the player may start a mantle this frame, decided on the main thread. + MWPhysics::Mantle::Params mantleParams(const MWWorld::Ptr& ptr, const MWPhysics::Actor& actor, bool inert) + { + MWPhysics::Mantle::Params params; + params.mMaxHeightFactor = Settings::game().mMantleMaxHeight; + params.mDuration = Settings::game().mMantleDuration; + if (!Settings::game().mMantling || inert || !actor.getCollisionMode()) + return params; + const MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); + params.mCanStart = stats.getMantleAllowed() && !stats.getKnockedDown() && !stats.getHitRecovery(); + return params; + } + + // Ashlar mantling: logs mantles and tells the actor's Lua scripts. Main thread. + void reportMantle(const MWWorld::Ptr& ptr, MWPhysics::Actor& actor) + { + const float height = actor.takeMantleStarted(); + if (height >= 0.f) + { + Log(Debug::Verbose) << "Ashlar mantle: " << ptr.getCellRef().getRefId() << " climbs " << height << " onto a ledge"; + MWBase::Environment::get().getLuaManager()->actorMantled(ptr, height); + } + if (actor.takeMantleFinished()) + { + const osg::Vec3f pos = ptr.getRefData().getPosition().asVec3(); + Log(Debug::Verbose) << "Ashlar mantle: " << ptr.getCellRef().getRefId() << " finished at " << pos.x() << " " + << pos.y() << " " << pos.z(); + } + } } namespace MWPhysics @@ -672,8 +702,15 @@ namespace MWPhysics const bool inert = stats.isDead() || (!godmode && stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Paralyze).getModifier() > 0); - simulations.emplace_back(ActorSimulation{ - physicActor, ActorFrameData{ *physicActor, inert, waterCollision, slowFall, waterlevel, isPlayer } }); + reportMantle(ptr, *physicActor); + // No jumping out of a mantle. + if (physicActor->getMantleState().mActive) + ptr.getClass().getMovementSettings(ptr).mPosition[2] = 0; + + ActorFrameData frameData{ *physicActor, inert, waterCollision, slowFall, waterlevel, isPlayer }; + if (isPlayer) + frameData.mMantleParams = mantleParams(ptr, *physicActor, inert); + simulations.emplace_back(ActorSimulation{ physicActor, std::move(frameData) }); // if the simulation will run, a jump request will be fulfilled. Update mechanics accordingly. if (willSimulate) @@ -900,6 +937,8 @@ namespace MWPhysics , mWaterCollision(waterCollision) , mSkipCollisionDetection(!actor.getCollisionMode()) , mIsPlayer(isPlayer) + , mMantle(actor.getMantleState()) + , mHalfExtentsXY(std::max(actor.getHalfExtents().x(), actor.getHalfExtents().y())) { } diff --git a/apps/openmw/mwphysics/physicssystem.hpp b/apps/openmw/mwphysics/physicssystem.hpp index 80c272294b..b425bcad3d 100644 --- a/apps/openmw/mwphysics/physicssystem.hpp +++ b/apps/openmw/mwphysics/physicssystem.hpp @@ -20,6 +20,7 @@ #include "../mwworld/ptr.hpp" #include "collisiontype.hpp" +#include "mantle.hpp" #include "raycasting.hpp" namespace Resource @@ -97,6 +98,10 @@ namespace MWPhysics const bool mWaterCollision; const bool mSkipCollisionDetection; const bool mIsPlayer; + // Ashlar mantling + Mantle::Params mMantleParams; + Mantle::State mMantle; + float mHalfExtentsXY; }; struct ProjectileFrameData diff --git a/apps/openmw_tests/CMakeLists.txt b/apps/openmw_tests/CMakeLists.txt index 5bde3c401a..bc8e28e9f1 100644 --- a/apps/openmw_tests/CMakeLists.txt +++ b/apps/openmw_tests/CMakeLists.txt @@ -28,6 +28,7 @@ file(GLOB UNITTEST_SRC_FILES mwmechanics/testhitreaction.cpp mwmechanics/testmovementramp.cpp mwmechanics/testsprint.cpp + mwphysics/testmantle.cpp mwmechanics/testcombat.cpp mwscript/testscripts.cpp diff --git a/apps/openmw_tests/mwphysics/testmantle.cpp b/apps/openmw_tests/mwphysics/testmantle.cpp new file mode 100644 index 0000000000..cb1fcd4cb4 --- /dev/null +++ b/apps/openmw_tests/mwphysics/testmantle.cpp @@ -0,0 +1,209 @@ +#include + +#include + +#include + +namespace +{ + using namespace MWPhysics::Mantle; + + constexpr float sTolerance = 1e-3f; + constexpr float sHeight = 128.f; // actor height + + // A wall facing the actor, which moves along +y. + const osg::Vec3f sWall(0.f, -1.f, 0.f); + const osg::Vec3f sForward(0.f, 1.f, 0.f); + + // A probe that found a flat ledge `height` above the feet, with full headroom and room on top. + Probe ledge(float height) + { + Probe probe; + probe.mFeetZ = 100.f; + probe.mActorHeight = sHeight; + probe.mMaxHeightFactor = 1.1f; + probe.mRiseReached = probeRise(sHeight, 1.1f); + probe.mForwardNeeded = 60.f; + probe.mForwardReached = 60.f; + probe.mSurfaceHit = true; + probe.mSurfaceFeetZ = probe.mFeetZ + height; + probe.mSurfaceNormal = osg::Vec3f(0.f, 0.f, 1.f); + return probe; + } + + TEST(MWPhysicsMantleTest, wantsMantleWhenPushingIntoWallInAir) + { + EXPECT_TRUE(wantsMantle(false, false, false, sForward, sWall)); + // Within 60 degrees of straight in. + EXPECT_TRUE(wantsMantle(false, false, false, osg::Vec3f(0.5f, 1.f, 0.f), sWall)); + } + + TEST(MWPhysicsMantleTest, noMantleOnGroundFlyingOrSwimming) + { + EXPECT_FALSE(wantsMantle(true, false, false, sForward, sWall)); + EXPECT_FALSE(wantsMantle(false, true, false, sForward, sWall)); + EXPECT_FALSE(wantsMantle(false, false, true, sForward, sWall)); + } + + TEST(MWPhysicsMantleTest, noMantleWhenMovingAlongOrAwayFromWall) + { + EXPECT_FALSE(wantsMantle(false, false, false, osg::Vec3f(1.f, 0.f, 0.f), sWall)); + EXPECT_FALSE(wantsMantle(false, false, false, osg::Vec3f(1.f, 0.3f, 0.f), sWall)); + EXPECT_FALSE(wantsMantle(false, false, false, -sForward, sWall)); + EXPECT_FALSE(wantsMantle(false, false, false, osg::Vec3f(), sWall)); + } + + TEST(MWPhysicsMantleTest, floorsAndCeilingsAreNotWalls) + { + EXPECT_FALSE(wantsMantle(false, false, false, sForward, osg::Vec3f(0.f, 0.f, 1.f))); + EXPECT_FALSE(wantsMantle(false, false, false, sForward, osg::Vec3f(0.f, 0.f, -1.f))); + EXPECT_FALSE(wantsMantle(false, false, false, sForward, osg::Vec3f(0.f, -0.6f, -0.8f))); + // A steep overhang-free slope still counts as a wall. + EXPECT_TRUE(wantsMantle(false, false, false, sForward, osg::Vec3f(0.f, -0.94f, 0.34f))); + } + + TEST(MWPhysicsMantleTest, intoWallIsHorizontalUnit) + { + const osg::Vec3f into = intoWall(osg::Vec3f(0.f, -0.8f, 0.6f)); + EXPECT_NEAR(into.x(), 0.f, sTolerance); + EXPECT_NEAR(into.y(), 1.f, sTolerance); + EXPECT_NEAR(into.z(), 0.f, sTolerance); + EXPECT_EQ(intoWall(osg::Vec3f(0.f, 0.f, 1.f)), osg::Vec3f()); + } + + TEST(MWPhysicsMantleTest, probeRiseCoversReachAndClearance) + { + EXPECT_NEAR(probeRise(sHeight, 1.1f), sHeight * 1.1f + sClearance, sTolerance); + EXPECT_NEAR(probeRise(sHeight, 0.f), sClearance, sTolerance); + } + + TEST(MWPhysicsMantleTest, ledgeWithinReachIsOk) + { + EXPECT_EQ(evaluate(ledge(40.f)), Result::Ok); + EXPECT_EQ(evaluate(ledge(sHeight)), Result::Ok); + EXPECT_EQ(evaluate(ledge(sHeight * 1.1f - 0.5f)), Result::Ok); + } + + TEST(MWPhysicsMantleTest, ledgeAboveReachIsTooHigh) + { + EXPECT_EQ(evaluate(ledge(sHeight * 1.1f + 1.f)), Result::TooHigh); + Probe probe = ledge(100.f); + probe.mMaxHeightFactor = 0.5f; + EXPECT_EQ(evaluate(probe), Result::TooHigh); + } + + TEST(MWPhysicsMantleTest, surfaceAtFeetIsTooLow) + { + EXPECT_EQ(evaluate(ledge(0.f)), Result::TooLow); + EXPECT_EQ(evaluate(ledge(sMinHeight - 0.5f)), Result::TooLow); + EXPECT_EQ(evaluate(ledge(-10.f)), Result::TooLow); + } + + TEST(MWPhysicsMantleTest, lowCeilingIsNoHeadroom) + { + Probe probe = ledge(40.f); + probe.mRiseReached = sMinRise - 1.f; + EXPECT_EQ(evaluate(probe), Result::NoHeadroom); + // The actor can rise, but not far enough to clear the ledge. + probe = ledge(40.f); + probe.mRiseReached = 42.f; + EXPECT_EQ(evaluate(probe), Result::NoHeadroom); + probe.mRiseReached = 40.f + sClearance; + EXPECT_EQ(evaluate(probe), Result::Ok); + } + + TEST(MWPhysicsMantleTest, wallAboveReachIsBlocked) + { + Probe probe = ledge(40.f); + probe.mForwardReached = 10.f; + EXPECT_EQ(evaluate(probe), Result::Blocked); + } + + TEST(MWPhysicsMantleTest, nothingBeyondTheEdgeIsNoSurface) + { + Probe probe = ledge(40.f); + probe.mSurfaceHit = false; + EXPECT_EQ(evaluate(probe), Result::NoSurface); + } + + TEST(MWPhysicsMantleTest, steepTopIsRejected) + { + Probe probe = ledge(40.f); + probe.mSurfaceNormal = osg::Vec3f(0.f, -0.8f, 0.6f); // about 53 degrees + EXPECT_EQ(evaluate(probe), Result::Steep); + probe.mSurfaceNormal = osg::Vec3f(0.f, -0.5f, 0.866f); // 30 degrees + EXPECT_EQ(evaluate(probe), Result::Ok); + } + + TEST(MWPhysicsMantleTest, resultNamesAreDistinct) + { + EXPECT_STREQ(resultName(Result::Ok), "ok"); + EXPECT_STREQ(resultName(Result::TooHigh), "too high"); + EXPECT_STREQ(resultName(Result::TooLow), "too low"); + } + + TEST(MWPhysicsMantleTest, pathRisesThenCrossesThenSettles) + { + const osg::Vec3f start(0.f, 0.f, 0.f); + const osg::Vec3f target(0.f, 50.f, 80.f); + const float peak = 90.f; + EXPECT_EQ(pathPosition(start, peak, target, 0.f), start); + EXPECT_EQ(pathPosition(start, peak, target, 1.f), target); + EXPECT_EQ(pathPosition(start, peak, target, 2.f), target); + + // Never further from the wall than the start, never below it, never above the peak, and it moves forward + // only once it is high enough. + osg::Vec3f last = start; + for (int i = 1; i <= 100; ++i) + { + const osg::Vec3f pos = pathPosition(start, peak, target, i / 100.f); + EXPECT_GE(pos.y(), last.y() - sTolerance); + EXPECT_GE(pos.z(), start.z() - sTolerance); + EXPECT_LE(pos.z(), peak + sTolerance); + if (pos.y() > sTolerance) + EXPECT_NEAR(pos.z(), pos.y() < target.y() - sTolerance ? peak : pos.z(), sTolerance); + last = pos; + } + } + + TEST(MWPhysicsMantleTest, pathIsSymmetricInTime) + { + // Eased: the middle of the time is the middle of the path length. + const osg::Vec3f start(0.f, 0.f, 0.f); + const osg::Vec3f target(0.f, 0.f, 100.f); + EXPECT_NEAR(pathPosition(start, 100.f, target, 0.5f).z(), 50.f, sTolerance); + EXPECT_LT(pathPosition(start, 100.f, target, 0.1f).z(), 10.f); + } + + TEST(MWPhysicsMantleTest, advanceEndsOnTargetAfterDuration) + { + const osg::Vec3f startPos(0.f, 0.f, 0.f); + const osg::Vec3f target(0.f, 40.f, 60.f); + State state = start(startPos, 64.f, target, 0.4f, 60.f); + EXPECT_TRUE(state.mActive); + EXPECT_NEAR(state.mHeight, 60.f, sTolerance); + + int steps = 0; + osg::Vec3f pos; + while (state.mActive && steps < 100) + { + pos = advance(state, 1.f / 60.f); + ++steps; + } + EXPECT_FALSE(state.mActive); + EXPECT_EQ(pos, target); + EXPECT_EQ(state.mLast, target); + // 0.4 s at 60 steps a second. + EXPECT_GE(steps, 24); + EXPECT_LE(steps, 25); + // Further steps stay put. + EXPECT_EQ(advance(state, 1.f / 60.f), target); + } + + TEST(MWPhysicsMantleTest, startKeepsPeakAboveBothEnds) + { + const State state = start(osg::Vec3f(0.f, 0.f, 10.f), 0.f, osg::Vec3f(0.f, 30.f, 50.f), 0.f, 40.f); + EXPECT_NEAR(state.mPeakZ, 50.f, sTolerance); + EXPECT_GT(state.mDuration, 0.f); + } +} diff --git a/components/settings/categories/game.hpp b/components/settings/categories/game.hpp index c9a5fb8390..36de305fe0 100644 --- a/components/settings/categories/game.hpp +++ b/components/settings/categories/game.hpp @@ -99,6 +99,9 @@ namespace Settings SettingValue mSprintFatigueDrain{ mIndex, "Game", "sprint fatigue drain", makeMaxSanitizerFloat(0) }; SettingValue mSprintFatigueThreshold{ mIndex, "Game", "sprint fatigue threshold", makeClampSanitizerFloat(0, 1) }; + SettingValue mMantling{ mIndex, "Game", "mantling" }; + SettingValue mMantleMaxHeight{ mIndex, "Game", "mantle max height", makeClampSanitizerFloat(0, 3) }; + SettingValue mMantleDuration{ mIndex, "Game", "mantle duration", makeClampSanitizerFloat(0.05f, 5) }; }; } diff --git a/docker/ashlar-run.sh b/docker/ashlar-run.sh index 7099864cd3..7543de9d44 100755 --- a/docker/ashlar-run.sh +++ b/docker/ashlar-run.sh @@ -4,7 +4,8 @@ # # SCENARIO=combat also loads docker/scenarios/combat, our own CC0 test content: a hostile duelist with a shield # and blade fights the player, and block events are summarized at the end. SCENARIO=movement logs the player's -# speed as it starts, stops and reverses. See docs/ashlar/SCENARIOS.md. +# speed as it starts, stops and reverses. SCENARIO=mantle jumps the player at a test ledge. See +# docs/ashlar/SCENARIOS.md. set -euo pipefail repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -72,7 +73,8 @@ docker run --rm \ echo "Screenshot: $run/boot.png" if [ -n "$scenario" ]; then echo "Scenario $scenario:" - grep -E 'ASHLAR_COMBAT|Ashlar (block|reaction|stamina):|scripts/ashlar' "$run/stdout.log" | tail -60 || true + grep -E 'ASHLAR_(COMBAT|MANTLE)|Ashlar (block|reaction|stamina|mantle):|scripts/ashlar' "$run/stdout.log" \ + | tail -60 || true fi if [ "$scenario" = movement ]; then grep -E 'ASHLAR_MOVE .*(phase|reached|stopped)|Ashlar sprint:' "$run/stdout.log" || true @@ -81,6 +83,9 @@ if [ "$scenario" = movement ]; then echo "Highest speed in $p (share of run speed): $(grep -oP "ASHLAR_MOVE $p applied=\S+ speed=\K[0-9.]+" \ "$run/stdout.log" | sort -n | tail -1)" done +elif [ "$scenario" = mantle ]; then + echo "Engine mantles: $(grep -c 'Ashlar mantle: .* climbs' "$run/stdout.log" || true)" + grep -E 'ASHLAR_MANTLE result' "$run/stdout.log" || true elif [ -n "$scenario" ]; then echo "Player blocks: $(grep -ci 'Ashlar block: "player" blocked' "$run/stdout.log" || true)" echo "Player parries: $(grep -ci 'Ashlar block: "player" blocked .* with weapon' "$run/stdout.log" || true)" diff --git a/docker/scenarios/mantle/ashlarmantle.omwscripts b/docker/scenarios/mantle/ashlarmantle.omwscripts new file mode 100644 index 0000000000..1a44749846 --- /dev/null +++ b/docker/scenarios/mantle/ashlarmantle.omwscripts @@ -0,0 +1,2 @@ +GLOBAL: scripts/ashlarmantle/global.lua +PLAYER: scripts/ashlarmantle/player.lua diff --git a/docker/scenarios/mantle/meshes/ashlar_ledge.dae b/docker/scenarios/mantle/meshes/ashlar_ledge.dae new file mode 100644 index 0000000000..026ffad52b --- /dev/null +++ b/docker/scenarios/mantle/meshes/ashlar_ledge.dae @@ -0,0 +1,28 @@ + + + +Z_UP + +0.25 0.22 0.2 1.0 +0.55 0.5 0.45 1.0 + + + +-80 -80 80 80 -80 80 80 80 80 -80 80 80 -80 -80 -40 -80 80 -40 80 80 -40 80 -80 -40 80 -80 -40 80 80 -40 80 80 80 80 -80 80 -80 -80 -40 -80 -80 80 -80 80 80 -80 80 -40 -80 80 -40 -80 80 80 80 80 80 80 80 -40 -80 -80 -40 80 -80 -40 80 -80 80 -80 -80 80 + +0 0 1 0 0 -1 1 0 0 -1 0 0 0 1 0 0 -1 0 + + + + + +

0 0 1 0 2 0 0 0 2 0 3 0 4 1 5 1 6 1 4 1 6 1 7 1 8 2 9 2 10 2 8 2 10 2 11 2 12 3 13 3 14 3 12 3 14 3 15 3 16 4 17 4 18 4 16 4 18 4 19 4 20 5 21 5 22 5 20 5 22 5 23 5

+
+
+ + + + + + +
diff --git a/docker/scenarios/mantle/scripts/ashlarmantle/global.lua b/docker/scenarios/mantle/scripts/ashlarmantle/global.lua new file mode 100644 index 0000000000..bb90bf6d0c --- /dev/null +++ b/docker/scenarios/mantle/scripts/ashlarmantle/global.lua @@ -0,0 +1,35 @@ +-- Ashlar headless mantle scenario (CC0). Places a test ledge (meshes/ashlar_ledge.dae, a plain box whose top is 80 +-- units above its origin) in front of the player, moves it and the player on request, and scales it up into a wall +-- too high to climb for the last phase. +local world = require('openmw.world') +local types = require('openmw.types') +local util = require('openmw.util') + +local started = false +local ledge + +local function log(...) + print('ASHLAR_MANTLE', ...) +end + +local function place(player, start, distance, scale) + local yaw = start.rotation:getYaw() + local forward = util.vector3(math.sin(yaw), math.cos(yaw), 0) + ledge:setScale(scale) + ledge:teleport(player.cell, start.position + forward * distance) + log(string.format('ledge at %.0f units, scale %.1f, top %.0f above the start', distance, scale, 80 * scale)) +end + +return { + eventHandlers = { + AshlarMantleSetup = function(data) + if not ledge then + local rec = world.createRecord(types.Static.createRecordDraft { model = 'meshes/ashlar_ledge.dae' }) + ledge = world.createObject(rec.id) + end + place(data.player, data.start, data.distance, data.scale) + data.player:teleport(data.player.cell, data.start.position, + { rotation = data.start.rotation, onGround = true }) + end, + }, +} diff --git a/docker/scenarios/mantle/scripts/ashlarmantle/player.lua b/docker/scenarios/mantle/scripts/ashlarmantle/player.lua new file mode 100644 index 0000000000..0a0569096c --- /dev/null +++ b/docker/scenarios/mantle/scripts/ashlarmantle/player.lua @@ -0,0 +1,101 @@ +-- Ashlar headless mantle scenario (CC0). The player runs at a test ledge and jumps, three times: +-- mantle a ledge 80 units high: the player must climb it and end up on top +-- veto the same ledge with self.controls.mantle = false: no climb +-- toohigh the ledge scaled into a 240 unit wall: no climb +-- Each phase starts by putting the player back at the start. The engine logs "Ashlar mantle:" lines at verbose +-- level, and this script logs AshlarMantle events and where the player ends up. +local core = require('openmw.core') +local self = require('openmw.self') +local I = require('openmw.interfaces') + +local PHASES = { + { name = 'settle', at = 0 }, + { name = 'mantle', at = 2, distance = 150, scale = 1, mantle = true }, + { name = 'veto', at = 8, distance = 150, scale = 1, mantle = false }, + { name = 'toohigh', at = 14, distance = 330, scale = 3, mantle = true }, + { name = 'done', at = 20 }, +} + +local t = 0 +local applied = 0 +local phase +local start +local events = 0 +local peak = 0 +local climbed + +local function log(fmt, ...) + print('ASHLAR_MANTLE ' .. string.format(fmt, ...)) +end + +local function finishPhase() + if not phase or not phase.distance then + return + end + local dz = self.position.z - start.position.z + log('result %s events=%d peak=%.1f dz=%.1f', phase.name, events, peak, dz) +end + +local function enterPhase(p) + finishPhase() + phase = p + applied = 0 + events = 0 + peak = 0 + climbed = false + if p.distance then + core.sendGlobalEvent('AshlarMantleSetup', { player = self.object, start = start, distance = p.distance, + scale = p.scale }) + end + log('phase %s', p.name) +end + +return { + eventHandlers = { + AshlarMantle = function(e) + events = events + 1 + climbed = true + log('event %s height=%.1f', phase and phase.name or '?', e.height) + end, + }, + engineHandlers = { + onFrame = function(dt) + if dt <= 0 or (phase and phase.name == 'done') then + return + end + if not phase then + I.Controls.overrideMovementControls(true) + I.Controls.overrideCombatControls(true) + start = { position = self.position, rotation = self.rotation } + enterPhase(PHASES[1]) + end + t = t + dt + local nextPhase = phase + for _, p in ipairs(PHASES) do + if t >= p.at then + nextPhase = p + end + end + if nextPhase ~= phase then + enterPhase(nextPhase) + end + + -- Skip the first moments, before the teleport back to the start has happened. + if phase.distance and applied >= 0.3 then + peak = math.max(peak, self.position.z - start.position.z) + end + -- Run at the ledge after a moment to settle, jumping every half second, until a climb starts. + local go = phase.distance ~= nil and applied >= 0.5 and not climbed + self.controls.movement = go and 1 or 0 + self.controls.sideMovement = 0 + self.controls.run = true + self.controls.jump = go and (applied % 0.5) < dt + self.controls.yawChange = 0 + self.controls.use = 0 + if phase.mantle ~= nil then + self.controls.mantle = phase.mantle + end + applied = applied + dt + end, + }, +} diff --git a/docs/ashlar/SCENARIOS.md b/docs/ashlar/SCENARIOS.md index 8d0d811915..31fbbae53b 100644 --- a/docs/ashlar/SCENARIOS.md +++ b/docs/ashlar/SCENARIOS.md @@ -133,3 +133,38 @@ report full speed after about 0.15 s, not on the first frame; with the setting o ```bash SCENARIO=movement BOOT_SECONDS=90 docker/ashlar-run.sh ``` + +## `mantle` + +`docker/scenarios/mantle/` tests `[Game] mantling`. The Game Template has no box or wall mesh, so the scenario +ships its own: `meshes/ashlar_ledge.dae`, a plain 160 by 160 unit box written for Ashlar (CC0), whose top is 80 +units above its origin and which reaches 40 units below it so it sits in the ground. The global script turns it +into a static and places it in front of the start point; collision comes from the mesh itself. + +The player script puts the player back at the start for each phase, runs at the box and jumps every half second +until a climb starts: + +| Phase | Time | What happens | +|---|---|---| +| `mantle` | 2 to 8 | Ledge 80 units high, 150 units ahead. The player must climb it and end up about 80 units above the start. | +| `veto` | 8 to 14 | Same ledge with `self.controls.mantle = false`. No climb; the player stays at ground level. | +| `toohigh` | 14 to 20 | The box scaled by 3 into a wall 240 units high, 330 units ahead, above `mantle max height`. No climb. | + +```bash +SCENARIO=mantle BOOT_SECONDS=90 docker/ashlar-run.sh +``` + +The engine logs each climb at verbose level, and the player script logs the `AshlarMantle` event and a result per +phase: + +``` +Ashlar mantle: "player" climbs 61.3 onto a ledge +Ashlar mantle: "player" finished at +ASHLAR_MANTLE event mantle height=61.3 +ASHLAR_MANTLE result mantle events=1 peak=81.0 dz=81.0 +``` + +`dz` is the player's height above the start at the end of the phase, and `peak` the highest it got. The climb +height is measured from the feet at the moment the player touches the wall, so it is less than 80 when the jump has +already lifted them. A good run has one event in `mantle` with `dz` near 81 (the box top plus the ground offset, +give or take the terrain under the start), and no events in `veto` or `toohigh` with `dz` near 0. diff --git a/docs/source/reference/lua-scripting/events.rst b/docs/source/reference/lua-scripting/events.rst index 5b3b27ac7c..4a79bb079f 100644 --- a/docs/source/reference/lua-scripting/events.rst +++ b/docs/source/reference/lua-scripting/events.rst @@ -41,6 +41,19 @@ This event is sent to an actor's local script when that actor dies. end } +**AshlarMantle** + +Ashlar. Sent to an actor's local scripts when the actor starts climbing onto a ledge (``[Game] mantling``). ``height`` +is how far the ledge is above the actor's feet. To stop climbs, set ``self.controls.mantle = false``. + +.. code-block:: Lua + + eventHandlers = { + AshlarMantle = function(e) + print('Climbing a ledge', e.height, 'units up') + end + } + **StartAIPackage, RemoveAIPackages** Any script can send to any actor (except player, for player will be ignored) events ``StartAIPackage`` and ``RemoveAIPackages``. diff --git a/docs/source/reference/modding/settings/game.rst b/docs/source/reference/modding/settings/game.rst index 563aad98d3..2684e71b82 100644 --- a/docs/source/reference/modding/settings/game.rst +++ b/docs/source/reference/modding/settings/game.rst @@ -695,3 +695,35 @@ Game Settings Ashlar setting. Share of maximum fatigue an actor needs to start a sprint. Once started, a sprint carries on until fatigue falls below 1% of maximum. + +.. omw-setting:: + :title: mantling + :type: boolean + :range: true, false + :default: true + + Ashlar setting. If enabled, the player climbs onto a ledge when jumping or falling into it while moving towards it, + instead of sliding down the wall. The ledge has to be flat enough to stand on, no higher than mantle max height + above the feet, with room on top and nothing above the player in the way; the engine checks this with the player's + collision shape. The climb takes mantle duration seconds, ignores movement and jump input, and ends any fall without + fall damage. It needs no animation. + + Lua scripts can stop climbs by setting ``self.controls.mantle = false``, and get an ``AshlarMantle`` event when one + starts. NPCs and creatures don't climb. If disabled, behaviour is unchanged from OpenMW. + +.. omw-setting:: + :title: mantle max height + :type: float32 + :range: [0, 3] + :default: 1.1 + + Ashlar setting. Highest ledge the player can climb, as a multiple of their height, measured from the feet at the + moment they touch the wall. + +.. omw-setting:: + :title: mantle duration + :type: float32 + :range: [0.05, 5] + :default: 0.4 + + Ashlar setting. Seconds a climb onto a ledge takes. diff --git a/files/lua_api/openmw/self.lua b/files/lua_api/openmw/self.lua index f1e47d8f53..89e4373c88 100644 --- a/files/lua_api/openmw/self.lua +++ b/files/lua_api/openmw/self.lua @@ -48,6 +48,7 @@ -- @field [parent=#ActorControls] #boolean jump If true - initiate a jump -- @field [parent=#ActorControls] #boolean block Ashlar: if true, hold the block stance. Has an effect with real time combat on (for NPCs and creatures, also ai active blocking) and the weapon drawn, with a shield or a melee weapon equipped. Combat AI raises its own block separately, and that is not reported here. -- @field [parent=#ActorControls] #boolean sprint Ashlar: if true, sprint while moving forward. Has an effect with [Game] sprint on, for NPCs and the player; see the setting for the conditions. +-- @field [parent=#ActorControls] #boolean mantle Ashlar: true by default. Set to false to stop the actor from climbing ledges (see [Game] mantling, player only) until it is set back to true. The actor's scripts get an `AshlarMantle` event when a climb starts. -- @field [parent=#ActorControls] #ATTACK_TYPE use Activates the readied weapon/spell according to a provided value. For weapons, keeping this value modified will charge the attack until set to @{#ATTACK_TYPE.NoAttack}. If an @{#ATTACK_TYPE} not appropriate for a currently equipped weapon provided - an appropriate @{#ATTACK_TYPE} will be used instead. --- diff --git a/files/settings-default.cfg b/files/settings-default.cfg index 40d14417c6..f9c433f59f 100644 --- a/files/settings-default.cfg +++ b/files/settings-default.cfg @@ -456,6 +456,17 @@ sprint fatigue drain = 10 # when fatigue runs out (below 1% of maximum). sprint fatigue threshold = 0.1 +# Ashlar: jumping or falling against a ledge while moving forward climbs +# onto it. Player only. Set to false to slide off ledges as before. +mantling = true + +# Ashlar: highest ledge that can be climbed, as a multiple of the +# actor's height above its feet. +mantle max height = 1.1 + +# Ashlar: seconds a climb onto a ledge takes. +mantle duration = 0.4 + [General] # Anisotropy reduces distortion in textures at low angles (e.g. 0 to 16).