From 83b09c11520a0d39931fe60af61b450d29557af2 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 04:26:26 +0000 Subject: [PATCH 01/31] feat: ground steeper than a guild's SLIDE_ANGLE slides like in Gothic - the rule for the hero and NPCs (SlopeSlideDomain), with EditMode tests OpenGothic MoveAlgo::testSlide: slides while sin(SLIDE_ANGLE2) < normal.y < cos(SLIDE_ANGLE) (SLIDE_ANGLE2 now in LedgeRules, 0 in Species.d), gravity along the slope (g * sin), capped at 6 m/s (ours). Steep for 0.2 s before a slide, walkable for 0.1 s before it ends (single steep triangles); a slide that gets nowhere ends as Blocked until moved 0.5 m away; no ground ends it for a fall. S_SLIDE facing downhill, S_SLIDEB backwards. Co-Authored-By: Claude Opus 5.5 --- .../Domain/Movement/SlopeSlideDomain.cs | 219 ++++++++++++++++++ .../Scripts/Models/Movement/LedgeRules.cs | 16 +- .../Models/Movement/SlopeSlideEvent.cs | 30 +++ .../Models/Movement/SlopeSlideState.cs | 50 ++++ .../EditMode/Movement/SlopeSlideDomainTest.cs | 203 ++++++++++++++++ 5 files changed, 517 insertions(+), 1 deletion(-) create mode 100644 Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs create mode 100644 Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs create mode 100644 Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs create mode 100644 Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs new file mode 100644 index 000000000..edd7e6f66 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs @@ -0,0 +1,219 @@ +using Gothic.Core.Models.Movement; +using UnityEngine; + +namespace Gothic.Core.Domain.Movement +{ + /// + /// Gothic's sliding down slopes (OpenGothic MoveAlgo::testSlide and the Slide state of MoveAlgo::tick), for the + /// hero and NPCs alike. Pure rules on a SlopeSlideState - the platform measures the ground under the feet (a ray + /// straight down, so stair risers and walls beside the body don't count) and moves the body. + /// - Ground slides when it's steeper than the guild's SLIDE_ANGLE and not steeper than 90 - SLIDE_ANGLE2 (a wall). + /// - The slide is gravity along the slope: g * sin(angle) downhill, capped at MaxSpeed (ours - Gothic has no cap). + /// - Ours, against single steep triangles (rocks, mesh seams): the ground must be steep for StartSeconds before a + /// slide begins, and walkable for StopSeconds before it ends. + /// - A slide that gets nowhere (a wall, a crevice) ends as Blocked - OpenGothic only slides when the body can move + /// downhill. No new slide then until the body moved BlockedReleaseDistance away or stood on walkable ground. + /// - No ground under the feet ends the slide as LostGround: the fall rules take over. + /// Sliding plays S_SLIDE when the body faces downhill, S_SLIDEB when it slides backwards (GetAnimation). + /// + public static class SlopeSlideDomain + { + public const string SlideAnimation = "S_SLIDE"; + public const string SlideBackwardsAnimation = "S_SLIDEB"; + + /// + /// Seconds the ground must be steep in a row before the slide begins. + /// + public const float StartSeconds = 0.2f; + + /// + /// Seconds of walkable ground in a row that end a slide. + /// + public const float StopSeconds = 0.1f; + + /// + /// m/s - the slide gets no faster. + /// + public const float MaxSpeed = 6f; + + // A slide slower than this (m/s) for StuckSeconds gets nowhere: Blocked. + private const float _stuckSpeed = 0.3f; + private const float _stuckSeconds = 0.3f; + + /// + /// m (horizontal) a blocked body moves away before it can slide again. + /// + public const float BlockedReleaseDistance = 0.5f; + + /// + /// OpenGothic MoveAlgo::testSlide: slideBegin = sin(90 - SLIDE_ANGLE), slideEnd = sin(SLIDE_ANGLE2), the ground + /// slides when slideEnd < normal.y < slideBegin. + /// + public static bool IsSlideGround(Vector3 normal, LedgeRules rules) + { + var slideBegin = Mathf.Min(Mathf.Cos(rules.SlideAngle * Mathf.Deg2Rad), 1f); + var slideEnd = Mathf.Sin(rules.SlideAngle2 * Mathf.Deg2Rad); + return slideEnd < normal.y && normal.y < slideBegin; + } + + /// + /// m/s^2 along the slope, downhill: normal * normal.y - up, times gravity (OpenGothic: cross(n, cross(n, up))). + /// Its length is gravity * sin(angle). + /// + public static Vector3 GetAcceleration(Vector3 normal, float gravity) + { + return (normal * normal.y - Vector3.up) * gravity; + } + + /// + /// Horizontal downhill direction of the ground, zero on flat ground. + /// + public static Vector3 GetDownhill(Vector3 normal) + { + var downhill = new Vector3(normal.x, 0f, normal.z); + return downhill.sqrMagnitude < 0.000001f ? Vector3.zero : downhill.normalized; + } + + /// + /// moved (horizontal) goes up the slope - walking up a steep slope is no slide start for NPCs (ours: their + /// waypoint routes stay as they are, see NpcJumpFall). + /// + public static bool IsMovingUphill(Vector3 moved, Vector3 normal) + { + moved.y = 0f; + return Vector3.Dot(moved, GetDownhill(normal)) < 0f; + } + + /// + /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards (OpenGothic + /// MoveAlgo::slideDir). + /// + public static string GetAnimation(Vector3 velocity, Vector3 facing) + { + velocity.y = 0f; + facing.y = 0f; + return Vector3.Dot(velocity, facing) < 0f ? SlideBackwardsAnimation : SlideAnimation; + } + + /// + /// One frame. feet: where the body stands now, hasGround/normal: the ground straight under it, gravity in m/s^2 + /// (0: no slide, e.g. swimming). + /// + public static SlopeSlideEvent Tick(SlopeSlideState state, Vector3 feet, bool hasGround, Vector3 normal, + LedgeRules rules, float gravity, float deltaTime) + { + var measured = state.HasPreviousFeet && deltaTime > 0f + ? (feet - state.PreviousFeet) / deltaTime + : Vector3.zero; + state.PreviousFeet = feet; + state.HasPreviousFeet = true; + state.GroundAngle = hasGround ? Vector3.Angle(normal, Vector3.up) : 0f; + state.IsSteepGround = hasGround && gravity > 0f && IsSlideGround(normal, rules); + + if (state.IsBlocked && (!state.IsSteepGround || GetFlatDistance(feet, state.BlockedFeet) > + BlockedReleaseDistance)) + state.IsBlocked = false; + + if (!state.IsSliding) + return TickStanding(state, feet, normal, gravity, deltaTime); + + if (!hasGround || gravity <= 0f) + { + Stop(state); + return SlopeSlideEvent.LostGround; + } + + if (!state.IsSteepGround) + { + state.WalkableSeconds += deltaTime; + if (state.WalkableSeconds < StopSeconds) + return SlopeSlideEvent.None; + Stop(state); + return SlopeSlideEvent.Stopped; + } + state.WalkableSeconds = 0f; + + Accelerate(state, measured, normal, gravity, deltaTime); + state.StuckSeconds = state.Velocity.magnitude < _stuckSpeed ? state.StuckSeconds + deltaTime : 0f; + if (state.StuckSeconds < _stuckSeconds) + return SlopeSlideEvent.None; + + Stop(state); + state.IsBlocked = true; + state.BlockedFeet = feet; + return SlopeSlideEvent.Blocked; + } + + /// + /// Not checked right now (climbing, swimming, lying, in the air, teleported...): any slide ends at once, the + /// steep time starts again. true if a slide was running. + /// + public static bool Hold(SlopeSlideState state, Vector3 feet) + { + var wasSliding = state.IsSliding; + Stop(state); + state.IsSteepGround = false; + state.IsBlocked = false; + state.PreviousFeet = feet; + state.HasPreviousFeet = true; + return wasSliding; + } + + /// + /// Horizontal m between the feet and where the slide began. + /// + public static float GetSlidDistance(SlopeSlideState state, Vector3 feet) + { + return GetFlatDistance(feet, state.StartFeet); + } + + private static SlopeSlideEvent TickStanding(SlopeSlideState state, Vector3 feet, Vector3 normal, + float gravity, float deltaTime) + { + state.SteepSeconds = state.IsSteepGround && !state.IsBlocked ? state.SteepSeconds + deltaTime : 0f; + if (state.SteepSeconds < StartSeconds) + return SlopeSlideEvent.None; + + state.IsSliding = true; + state.WalkableSeconds = 0f; + state.StuckSeconds = 0f; + state.StartFeet = feet; + state.Velocity = Vector3.ClampMagnitude(GetAcceleration(normal, gravity) * deltaTime, MaxSpeed); + return SlopeSlideEvent.Started; + } + + /// + /// The speed kept along the ground under the feet, never more than the body really moved along it (a wall or + /// a rock holds it back - like a physics body, without adding the player's own walking), plus this frame's + /// gravity along the slope. + /// + private static void Accelerate(SlopeSlideState state, Vector3 measured, Vector3 normal, float gravity, + float deltaTime) + { + var velocity = Vector3.ProjectOnPlane(state.Velocity, normal); + var speed = velocity.magnitude; + if (speed > 0.0001f) + { + var direction = velocity / speed; + speed = Mathf.Clamp(Vector3.Dot(measured, direction), 0f, speed); + velocity = direction * speed; + } + + state.Velocity = Vector3.ClampMagnitude(velocity + GetAcceleration(normal, gravity) * deltaTime, MaxSpeed); + } + + private static void Stop(SlopeSlideState state) + { + state.IsSliding = false; + state.Velocity = Vector3.zero; + state.SteepSeconds = 0f; + state.WalkableSeconds = 0f; + state.StuckSeconds = 0f; + } + + private static float GetFlatDistance(Vector3 a, Vector3 b) + { + return new Vector2(a.x - b.x, a.z - b.z).magnitude; + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs b/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs index 54d690c17..6c9fff20d 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs @@ -1,9 +1,10 @@ +using UnityEngine; using ZenKit.Daedalus; namespace Gothic.Core.Models.Movement { /// - /// Gothic's climbing values of a guild (C_GILVALUES), converted to metres. Angles in degrees. + /// Gothic's climbing and sliding values of a guild (C_GILVALUES), converted to metres. Angles in degrees. /// public struct LedgeRules { @@ -17,6 +18,7 @@ public struct LedgeRules JumpMidHeight = 2.05f, JumpUpHeight = 2f, SlideAngle = 45f, + SlideAngle2 = 0f, ClimbHeadingAngle = 45f }; @@ -29,7 +31,18 @@ public struct LedgeRules public float JumpLowHeight; public float JumpMidHeight; public float JumpUpHeight; + + /// + /// SLIDE_ANGLE: ground steeper than this slides (SlopeSlideDomain) and is no ledge top. + /// public float SlideAngle; + + /// + /// SLIDE_ANGLE2: ground this close to vertical (degrees from it) is a wall, no slide (OpenGothic + /// MoveAlgo::testSlide). 0 in Gothic's Species.d - only vertical ground stops a slide. + /// + public float SlideAngle2; + public float ClimbHeadingAngle; /// @@ -54,6 +67,7 @@ public static LedgeRules FromGuildValues(GuildValuesInstance values, int guild) JumpMidHeight = Metres(values.GetJumpMidHeight(guild), defaults.JumpMidHeight), JumpUpHeight = Metres(values.GetJumpUpHeight(guild), defaults.JumpUpHeight), SlideAngle = Degrees(values.GetSlideAngle(guild), defaults.SlideAngle), + SlideAngle2 = Mathf.Clamp(values.GetSlideAngle2(guild), 0, 90), ClimbHeadingAngle = Degrees(values.GetClimbHeadingAngle(guild), defaults.ClimbHeadingAngle) }; } diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs new file mode 100644 index 000000000..24f41698a --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs @@ -0,0 +1,30 @@ +namespace Gothic.Core.Models.Movement +{ + /// + /// What changed in a body's slide this frame (SlopeSlideDomain.Tick). + /// + public enum SlopeSlideEvent + { + None, + + /// + /// Steeper than SLIDE_ANGLE long enough: the slide begins (S_SLIDE / S_SLIDEB). + /// + Started, + + /// + /// Walkable ground again: he stands (OpenGothic: back to Run, the speed is dropped). + /// + Stopped, + + /// + /// No ground under the feet anymore (off an edge): a normal fall takes over. + /// + LostGround, + + /// + /// Held at the slope (a wall, a rock, a crevice): he stands where he is, no new slide until he moved away. + /// + Blocked + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs new file mode 100644 index 000000000..044ca7365 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs @@ -0,0 +1,50 @@ +using UnityEngine; + +namespace Gothic.Core.Models.Movement +{ + /// + /// One body's slide down a slope (the hero, an NPC), advanced by SlopeSlideDomain.Tick every frame. Not saved: a + /// loaded game starts standing. + /// + public class SlopeSlideState + { + public bool IsSliding { get; set; } + + /// + /// World m/s along the slope, downhill. Zero while not sliding. + /// + public Vector3 Velocity { get; set; } + + /// + /// The ground under the feet is steeper than SLIDE_ANGLE this frame - no take-off from it (no debounce). + /// + public bool IsSteepGround { get; set; } + + /// + /// Angle of the ground under the feet in degrees this frame, 0 without ground (logs). + /// + public float GroundAngle { get; set; } + + /// + /// Seconds of steep ground in a row (before a slide), of walkable ground in a row (while sliding), and of + /// sliding without getting anywhere. + /// + public float SteepSeconds { get; set; } + public float WalkableSeconds { get; set; } + public float StuckSeconds { get; set; } + + /// + /// Stopped by a block at BlockedFeet: no new slide until he moved away or stands on walkable ground. + /// + public bool IsBlocked { get; set; } + public Vector3 BlockedFeet { get; set; } + + /// + /// Where the slide began (logs: how far he slid). + /// + public Vector3 StartFeet { get; set; } + + public Vector3 PreviousFeet { get; set; } + public bool HasPreviousFeet { get; set; } + } +} diff --git a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs new file mode 100644 index 000000000..38bdb6fea --- /dev/null +++ b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs @@ -0,0 +1,203 @@ +using Gothic.Core.Domain.Movement; +using Gothic.Core.Models.Movement; +using NUnit.Framework; +using UnityEngine; + +namespace Gothic.Tests.EditMode.Movement +{ + /// + /// Sliding down slopes (SlopeSlideDomain): which ground slides (SLIDE_ANGLE, SLIDE_ANGLE2), gravity along the + /// slope, the start/stop debounce against single steep triangles, blocked slides and the end at an edge. + /// + public class SlopeSlideDomainTest + { + private const float _dt = 1f / 72f; + private const float _gravity = 9.81f; + + private static readonly LedgeRules _human = LedgeRules.GothicHumanDefaults; + + private SlopeSlideState _state; + private Vector3 _feet; + + [SetUp] + public void SetUp() + { + _state = new SlopeSlideState(); + _feet = Vector3.zero; + } + + /// + /// The normal of ground sloping down towards +z by angle degrees. + /// + private static Vector3 Slope(float angle) + { + return Quaternion.Euler(angle, 0f, 0f) * Vector3.up; + } + + /// + /// One frame; the body moved by its slide velocity (moves = false: held in place). + /// + private SlopeSlideEvent Tick(Vector3 normal, bool hasGround = true, bool moves = true) + { + if (moves) + _feet += _state.Velocity * _dt; + return SlopeSlideDomain.Tick(_state, _feet, hasGround, normal, _human, _gravity, _dt); + } + + private SlopeSlideEvent TickFor(float seconds, Vector3 normal, bool hasGround = true, bool moves = true) + { + var result = SlopeSlideEvent.None; + for (var time = 0f; time < seconds; time += _dt) + { + var tick = Tick(normal, hasGround, moves); + if (tick != SlopeSlideEvent.None) + result = tick; + } + return result; + } + + [Test] + public void SlidesOnlySteeperThanSlideAngle() + { + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Vector3.up, _human)); + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Slope(40f), _human)); + Assert.IsTrue(SlopeSlideDomain.IsSlideGround(Slope(50f), _human)); + Assert.IsTrue(SlopeSlideDomain.IsSlideGround(Slope(85f), _human)); + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Slope(90f), _human), "a vertical wall isn't ground"); + } + + [Test] + public void SlideAngle2MakesNearVerticalGroundAWall() + { + var rules = _human; + rules.SlideAngle2 = 10f; + Assert.IsTrue(SlopeSlideDomain.IsSlideGround(Slope(75f), rules)); + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Slope(85f), rules)); + } + + [Test] + public void MonsterGuildsSlideFromTheirOwnAngle() + { + var bloodfly = _human; + bloodfly.SlideAngle = 75f; + Assert.IsFalse(SlopeSlideDomain.IsSlideGround(Slope(60f), bloodfly)); + Assert.IsTrue(SlopeSlideDomain.IsSlideGround(Slope(80f), bloodfly)); + } + + [Test] + public void GravityPullsDownTheSlope() + { + var acceleration = SlopeSlideDomain.GetAcceleration(Slope(60f), _gravity); + Assert.AreEqual(_gravity * Mathf.Sin(60f * Mathf.Deg2Rad), acceleration.magnitude, 0.001f); + Assert.Less(acceleration.y, 0f); + Assert.Greater(acceleration.z, 0f, "downhill is +z"); + Assert.AreEqual(0f, Vector3.Dot(acceleration, Slope(60f)), 0.001f, "along the ground"); + } + + [Test] + public void ShortSteepGroundDoesNotSlide() + { + Assert.AreEqual(SlopeSlideEvent.None, TickFor(SlopeSlideDomain.StartSeconds * 0.5f, Slope(60f))); + Assert.IsTrue(_state.IsSteepGround, "steep at once - no take-off from it"); + Tick(Vector3.up); + Assert.AreEqual(SlopeSlideEvent.None, TickFor(SlopeSlideDomain.StartSeconds * 0.5f, Slope(60f))); + Assert.IsFalse(_state.IsSliding); + } + + [Test] + public void SteepGroundStartsASlideThatGetsFaster() + { + Assert.AreEqual(SlopeSlideEvent.Started, TickFor(SlopeSlideDomain.StartSeconds + _dt, Slope(60f))); + var speed = _state.Velocity.magnitude; + TickFor(0.5f, Slope(60f)); + Assert.Greater(_state.Velocity.magnitude, speed + 2f); + Assert.Greater(_state.Velocity.z, 0f); + Assert.Less(_feet.y, 0f, "slid downhill"); + } + + [Test] + public void SlideSpeedIsCapped() + { + TickFor(10f, Slope(80f)); + Assert.IsTrue(_state.IsSliding); + Assert.AreEqual(SlopeSlideDomain.MaxSpeed, _state.Velocity.magnitude, 0.01f); + } + + [Test] + public void WalkableGroundEndsTheSlide() + { + TickFor(1f, Slope(60f)); + Assert.AreEqual(SlopeSlideEvent.None, Tick(Vector3.up), "one flat triangle doesn't end it"); + Assert.AreEqual(SlopeSlideEvent.Stopped, TickFor(SlopeSlideDomain.StopSeconds + _dt, Vector3.up)); + Assert.IsFalse(_state.IsSliding); + Assert.AreEqual(Vector3.zero, _state.Velocity); + } + + [Test] + public void NoGroundEndsTheSlideForAFall() + { + TickFor(1f, Slope(60f)); + Assert.AreEqual(SlopeSlideEvent.LostGround, Tick(Vector3.up, false)); + Assert.IsFalse(_state.IsSliding); + } + + [Test] + public void HeldBackSlideIsBlockedUntilMovedAway() + { + TickFor(SlopeSlideDomain.StartSeconds + _dt, Slope(60f)); + Assert.AreEqual(SlopeSlideEvent.Blocked, TickFor(1f, Slope(60f), moves: false)); + Assert.IsTrue(_state.IsBlocked); + + Assert.AreEqual(SlopeSlideEvent.None, TickFor(1f, Slope(60f), moves: false), "no new slide in place"); + + _feet += Vector3.right * (SlopeSlideDomain.BlockedReleaseDistance + 0.1f); + Assert.AreEqual(SlopeSlideEvent.Started, TickFor(SlopeSlideDomain.StartSeconds + 2f * _dt, Slope(60f))); + } + + [Test] + public void NoSlideWithoutGravity() + { + Assert.AreEqual(SlopeSlideEvent.None, TickWithGravity(1f, 0f)); + Assert.IsFalse(_state.IsSteepGround); + } + + private SlopeSlideEvent TickWithGravity(float seconds, float gravity) + { + var result = SlopeSlideEvent.None; + for (var time = 0f; time < seconds; time += _dt) + { + var tick = SlopeSlideDomain.Tick(_state, _feet, true, Slope(60f), _human, gravity, _dt); + if (tick != SlopeSlideEvent.None) + result = tick; + } + return result; + } + + [Test] + public void HoldEndsTheSlide() + { + TickFor(1f, Slope(60f)); + Assert.IsTrue(SlopeSlideDomain.Hold(_state, _feet)); + Assert.IsFalse(_state.IsSliding); + Assert.AreEqual(SlopeSlideEvent.None, TickFor(SlopeSlideDomain.StartSeconds * 0.5f, Slope(60f)), + "the steep time starts again"); + } + + [Test] + public void FacingDownhillSlidesForwardsElseBackwards() + { + var downhill = new Vector3(0f, -1f, 1f); + Assert.AreEqual(SlopeSlideDomain.SlideAnimation, SlopeSlideDomain.GetAnimation(downhill, Vector3.forward)); + Assert.AreEqual(SlopeSlideDomain.SlideBackwardsAnimation, + SlopeSlideDomain.GetAnimation(downhill, Vector3.back)); + } + + [Test] + public void UphillIsAgainstTheDownhillDirection() + { + Assert.IsTrue(SlopeSlideDomain.IsMovingUphill(Vector3.back, Slope(60f))); + Assert.IsFalse(SlopeSlideDomain.IsMovingUphill(Vector3.forward, Slope(60f))); + Assert.IsFalse(SlopeSlideDomain.IsMovingUphill(Vector3.right, Slope(60f)), "sideways"); + } + } +} From 0f74ca801ffd3b482fe46252289186e9486b2c62 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 04:26:38 +0000 Subject: [PATCH 02/31] fix: the VR hero can't climb a steep slope by jumping again and again anymore, and slides down it like in Gothic - HeroSlideService decides, the XRI rig moves him and refuses the take-off The rig port gets the ground straight under the feet (one ray down per frame - no stair risers), SlideVelocity and IsTakeOffBlocked. VrHeroJumpFall feeds HeroFallService and HeroSlideService with the same sample. XriSlopeSlide queues the slide after XRI's moves (CharacterController.Move, walls still stop it) and takes back the stick's steps up the slope; gravity's fall speed is held and the rig counts as grounded meanwhile, so a slide is no fall. Steeper than SLIDE_ANGLE, a jump press does nothing until released (OpenGothic: no jump while sliding). Not while climbing, swimming, jumping, lying after a fall, transformed or busy. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Models/Movement/HeroFallSample.cs | 17 +- .../Scripts/ReflexProjectInstaller.cs | 1 + .../Services/Movement/HeroFallService.cs | 5 + .../Services/Movement/HeroSlideService.cs | 160 ++++++++++++++++++ .../Scripts/Adapters/Player/VrHeroJumpFall.cs | 29 +++- .../Backends/Xri/GothicJumpProvider.cs | 15 ++ .../Interaction/Backends/Xri/XriRig.cs | 42 ++++- .../Interaction/Backends/Xri/XriSlopeSlide.cs | 139 +++++++++++++++ .../Scripts/Interaction/Ports/IVrRig.cs | 34 ++++ 9 files changed, 432 insertions(+), 10 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs create mode 100644 Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs index 61fb71266..78e415a53 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs @@ -3,8 +3,9 @@ namespace Gothic.Core.Models.Movement { /// - /// One frame's measurement of the player's body for HeroFallService.Tick, given by the platform (VR: the rig port - /// IVrRig, with its grounded grace time). Platform-neutral: the rules don't know where it comes from. + /// One frame's measurement of the player's body for HeroFallService.Tick and HeroSlideService.Tick, given by the + /// platform (VR: the rig port IVrRig, with its grounded grace time). Platform-neutral: the rules don't know where + /// it comes from. /// public readonly struct HeroFallSample { @@ -62,11 +63,19 @@ public readonly struct HeroFallSample public readonly float DeltaTime; + /// + /// Ground straight under the feet (a ray down, not the body's side contacts) - its normal decides a slide + /// (HeroSlideService). false: nothing within the platform's reach below. + /// + public readonly bool HasGround; + + public readonly Vector3 GroundNormal; + public float FeetY => FeetPosition.y; public HeroFallSample(Vector3 feetPosition, Vector3 forward, bool isGrounded, bool isJumping, bool isClimbing, bool isTransformed, float gravity, float maxFallSpeed, float groundSnapHeight, float runSpeed, - float deltaTime) + float deltaTime, bool hasGround = false, Vector3 groundNormal = default) { FeetPosition = feetPosition; Forward = forward; @@ -79,6 +88,8 @@ public HeroFallSample(Vector3 feetPosition, Vector3 forward, bool isGrounded, bo GroundSnapHeight = groundSnapHeight; RunSpeed = runSpeed; DeltaTime = deltaTime; + HasGround = hasGround; + GroundNormal = groundNormal; } } } diff --git a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs index 28af77ce4..a9408b796 100644 --- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs +++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs @@ -147,6 +147,7 @@ public void InstallBindings(ContainerBuilder containerBuilder) containerBuilder.AddSingleton(typeof(RoomService)); containerBuilder.AddSingleton(typeof(LedgeService)); containerBuilder.AddSingleton(typeof(HeroFallService)); + containerBuilder.AddSingleton(typeof(HeroSlideService)); // Misc containerBuilder.AddSingleton(typeof(AudioService)); diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs index 96ded70aa..ff430fd88 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs @@ -88,6 +88,11 @@ public class HeroFallService /// public bool IsRunningJump => _airborne.IsRunningJump; + /// + /// He lies after a fall flat and gets up (walking locked) - no slide meanwhile (HeroSlideService). + /// + public bool IsLyingAfterFall => _isLandingLocked; + public HeroFallService() { GlobalEventDispatcher.LoadGameStart.AddListener(ResetAll); diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs new file mode 100644 index 000000000..fbdbc0984 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs @@ -0,0 +1,160 @@ +using Gothic.Core.Const; +using Gothic.Core.Domain.Movement; +using Gothic.Core.Logging; +using Gothic.Core.Models.Container; +using Gothic.Core.Models.Movement; +using Gothic.Core.Models.Vm; +using Gothic.Core.Services.Npc; +using Reflex.Attributes; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.Core.Services.Movement +{ + /// + /// The hero slides down slopes steeper than his SLIDE_ANGLE like in Gothic (SlopeSlideDomain) - and can't jump off + /// such ground (IsTakeOffBlocked, OpenGothic Npc::tryJump: no jump while sliding). The platform measures the ground + /// straight under the feet and calls Tick every frame (VR: VrHeroJumpFall, from the rig port); it moves the body + /// with Velocity and removes the player's own steps up the slope meanwhile. + /// - A slide is no fall: the body stays on the ground (the platform counts it as grounded), no fall damage. Off an + /// edge the slide ends and HeroFallService's normal fall begins from there. + /// - Body state: BS_STAND while sliding (OpenGothic: BS_NONE for S_SLIDE/S_SLIDEB) - VR: VRHeroMovement. + /// Not checked (no slide, the jump allowed): climbing, transformed (the puppet stands on any slope - its own guild + /// isn't applied), no gravity or water, in the air, lying after a fall flat, down or busy (sitting, mobs). + /// Not saved: a loaded game starts standing. + /// + public class HeroSlideService + { + [Inject] private readonly NpcService _npcService; + [Inject] private readonly LedgeService _ledgeService; + [Inject] private readonly HeroFallService _heroFallService; + + private readonly SlopeSlideState _state = new(); + // Why the hero isn't checked right now (logged when it changes), null = checked. + private string _holdReason; + + public bool IsSliding => _state.IsSliding; + + /// + /// World m/s along the slope - zero while not sliding. + /// + public Vector3 Velocity => _state.IsSliding ? _state.Velocity : Vector3.zero; + + /// + /// The ground under the feet is too steep to jump from (no debounce: also before a slide begins). Without it + /// the hero climbed any slope by jumping again and again. + /// + public bool IsTakeOffBlocked => _holdReason == null && _state.IsSteepGround; + + public HeroSlideService() + { + GlobalEventDispatcher.LoadGameStart.AddListener(ResetAll); + GlobalEventDispatcher.WorldSceneLoaded.AddListener(ResetAll); + } + + /// + /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards. + /// + public string GetAnimation(Vector3 facing) + { + return SlopeSlideDomain.GetAnimation(_state.Velocity, facing); + } + + /// + /// One frame's measurement of the player's body (the same sample HeroFallService gets). + /// + public void Tick(in HeroFallSample sample) + { + var hero = _npcService.GetHeroContainer(); + if (hero?.Props == null) + return; + + var holdReason = GetHoldReason(hero, sample); + if (holdReason != null) + { + Hold(sample.FeetPosition, holdReason); + return; + } + _holdReason = null; + + var rules = _ledgeService.HeroRules; + var feet = sample.FeetPosition; + var speed = _state.Velocity.magnitude; + switch (SlopeSlideDomain.Tick(_state, feet, sample.HasGround, sample.GroundNormal, rules, sample.Gravity, + sample.DeltaTime)) + { + case SlopeSlideEvent.Started: + Logger.Log($"[HeroSlide] Slides down a {_state.GroundAngle:F0} deg slope at {feet.y:F2} " + + $"(SLIDE_ANGLE {rules.SlideAngle:F0}, SLIDE_ANGLE2 {rules.SlideAngle2:F0})", LogCat.Npc); + break; + case SlopeSlideEvent.Stopped: + LogEnd("walkable ground", feet, speed); + break; + case SlopeSlideEvent.LostGround: + LogEnd("no ground below - falls", feet, speed); + break; + case SlopeSlideEvent.Blocked: + LogEnd($"held at the {_state.GroundAngle:F0} deg slope", feet, speed); + break; + } + } + + /// + /// The player was teleported: a slide ends there. + /// + public void OnTeleported(Vector3 feetPosition) + { + Hold(feetPosition, "teleported"); + } + + /// + /// Why the hero isn't checked now, null if he is. + /// + private string GetHoldReason(NpcContainer hero, in HeroFallSample sample) + { + if (sample.IsClimbing) + return "climbing"; + if (sample.IsTransformed) + return "transformed"; + if (sample.Gravity <= 0f) + return "no gravity (swimming, diving)"; + if (sample.IsJumping) + return "jumping"; + if (_heroFallService.IsLyingAfterFall) + return "lying after a fall"; + + var ai = hero.Vob?.AiHuman; + if (ai != null && ai.WaterLevel != (int)ZenGineConst.WaterLevel.Normal) + return "in water"; + + return hero.Props.BodyState is VmGothicEnums.BodyState.BsStand or VmGothicEnums.BodyState.BsWalk + or VmGothicEnums.BodyState.BsRun or VmGothicEnums.BodyState.BsSneak + ? null + : $"body state {hero.Props.BodyState}"; + } + + private void Hold(Vector3 feet, string reason) + { + var speed = _state.Velocity.magnitude; + if (SlopeSlideDomain.Hold(_state, feet)) + LogEnd(reason, feet, speed); + else if (reason != _holdReason) + Logger.LogEditor($"[HeroSlide] Not checked: {reason}", LogCat.Npc); + _holdReason = reason; + } + + private void LogEnd(string reason, Vector3 feet, float speed) + { + var distance = SlopeSlideDomain.GetSlidDistance(_state, feet); + Logger.Log($"[HeroSlide] Slide ended ({reason}) after {distance:F1} m at {speed:F1} m/s, at {feet.y:F2}", + LogCat.Npc); + } + + private void ResetAll() + { + SlopeSlideDomain.Hold(_state, Vector3.zero); + _state.HasPreviousFeet = false; + _holdReason = null; + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs index db18cdfa3..a47a26d2f 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs @@ -11,10 +11,12 @@ namespace Gothic.VR.Adapters.Player { /// - /// Feeds the hero's jumps and falls (HeroFallService: body state, fall damage, lying landing) from the VR rig port: - /// feet height, grounded (with the rig's grace time), jumping, climbing, gravity, ground snap, the speed he runs - /// from (VrHeroSpeeds.RunThreshold), teleports. Measures only - the rules are in Core. - /// Sits next to VRPlayer (added by VRContextInteractionService). + /// Feeds the hero's jumps and falls (HeroFallService: body state, fall damage, lying landing) and his slides + /// down slopes (HeroSlideService) from the VR rig port: feet height, grounded (with the rig's grace time), the + /// ground under the feet, jumping, climbing, gravity, ground snap, the speed he runs from + /// (VrHeroSpeeds.RunThreshold), teleports - and hands the slide back to the rig (its velocity, no take-off from + /// steep ground). Measures only - the rules are in Core. Sits next to VRPlayer (added by + /// VRContextInteractionService). /// A running jump (HeroFallService.IsRunningJump, the sprint) is a long leap at T_RUNL_2_JUMP's forward speed /// (VrHeroSpeeds.RunJump) in the direction of the run, until he lands, grabs or is teleported /// (IVrRig.SetLeapVelocity). The standing and walking jump stays straight up. @@ -22,6 +24,7 @@ namespace Gothic.VR.Adapters.Player public class VrHeroJumpFall : MonoBehaviour { [Inject] private readonly HeroFallService _heroFallService; + [Inject] private readonly HeroSlideService _heroSlideService; [Inject] private readonly VRSpellTransformService _vrSpellTransformService; [Inject] private readonly VRPlayerService _vrPlayerService; @@ -51,6 +54,14 @@ private void Awake() _rig.Teleported += OnTeleported; } + private void OnDisable() + { + if (_rig is not Object rigObject || rigObject == null) + return; + _rig.SlideVelocity = Vector3.zero; + _rig.IsTakeOffBlocked = false; + } + private void OnDestroy() { if (_rig is Object rigObject && rigObject != null) @@ -62,10 +73,16 @@ private void Update() var feet = _rig.Root.position; UpdateHorizontalVelocity(feet); + var hasGround = _rig.TryGetGround(out _, out var groundNormal); var sample = new HeroFallSample(feet, GetFacing(), _rig.IsGrounded, _rig.IsJumping, _rig.IsClimbing, _vrSpellTransformService != null && _vrSpellTransformService.IsTransformed, _rig.Gravity, - _rig.MaxFallSpeed, _rig.GroundSnapHeight, _vrPlayerService.HeroSpeeds.RunThreshold, Time.deltaTime); + _rig.MaxFallSpeed, _rig.GroundSnapHeight, _vrPlayerService.HeroSpeeds.RunThreshold, Time.deltaTime, + hasGround, groundNormal); + // The fall first: a landing on a steep slope is a landing, the slide begins after it. _heroFallService.Tick(sample); + _heroSlideService.Tick(sample); + _rig.SlideVelocity = _heroSlideService.Velocity; + _rig.IsTakeOffBlocked = _heroSlideService.IsTakeOffBlocked; UpdateLeap(); } @@ -139,6 +156,8 @@ private void OnTeleported(Vector3 feetPosition) _horizontalVelocity = Vector3.zero; EndLeap("teleported"); _heroFallService.OnTeleported(feetPosition); + _heroSlideService.OnTeleported(feetPosition); + _rig.SlideVelocity = Vector3.zero; } } } diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicJumpProvider.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicJumpProvider.cs index cf9feac94..6d7e34ff0 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicJumpProvider.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/GothicJumpProvider.cs @@ -1,6 +1,8 @@ +using Gothic.Core.Logging; using Gothic.VR.Interaction.Ports; using UnityEngine; using UnityEngine.XR.Interaction.Toolkit.Locomotion.Jump; +using Logger = Gothic.Core.Logging.Logger; namespace Gothic.VR.Interaction.Backends.Xri { @@ -13,6 +15,8 @@ namespace Gothic.VR.Interaction.Backends.Xri /// curve for a wanted rise. /// - CancelJump(): a hand grabbing a ledge or ladder mid-air ends the jump. Disabled by XriRig while climbing, /// XRI would otherwise keep the jump running and replay its rest after climbing. + /// - IsTakeOffBlocked: no take-off from ground too steep for Gothic (SLIDE_ANGLE) - the press is used up until + /// released. Jumping again and again climbed any slope. /// public class GothicJumpProvider : JumpProvider { @@ -43,6 +47,11 @@ public float Gravity set => _gravity = value; } + /// + /// The ground under the feet is too steep to jump from. Set by XriRig every frame. + /// + public bool IsTakeOffBlocked { get; set; } + protected override void Awake() { base.Awake(); @@ -57,6 +66,12 @@ protected override void Update() _isPressHandled = false; _isPressConsumed = false; } + else if (!_isPressHandled && !isJumping && IsTakeOffBlocked) + { + _isPressHandled = true; + _isPressConsumed = true; + Logger.Log("[XRI] No jump - the ground is too steep (SLIDE_ANGLE).", LogCat.VR); + } else if (!_isPressHandled && !isJumping && CanJump()) { _isPressHandled = true; diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs index 0f9cec68f..426f91db0 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs @@ -25,7 +25,7 @@ namespace Gothic.VR.Interaction.Backends.Xri { /// /// IVrRig on top of XRI's XR Origin and locomotion providers. Sits on the XR Origin GameObject next to VRPlayer. - /// Sprinting and crouching are ours, as XRI has no providers for them. + /// Sprinting and crouching are ours, as XRI has no providers for them; sliding down slopes too (XriSlopeSlide). /// Gothic logic (menu, control modes, ini settings) lives in VRPlayer and VRContextInteractionService, not here. /// public class XriRig : MonoBehaviour, IVrRig @@ -165,6 +165,7 @@ public class XriRig : MonoBehaviour, IVrRig private IVrLedgeHandler _ledgeHandler; // SetLeapVelocity: a running jump's horizontal velocity, zero = none. private Vector3 _leapVelocity; + private XriSlopeSlide _slopeSlide; public event Action Teleported; @@ -182,7 +183,8 @@ public bool IsGrounded { get { - if (_gravityProvider.isGrounded || _characterController.isGrounded) + // A slide keeps the feet on the slope, also where XRI's head-down cast misses it (steep and thin). + if (_gravityProvider.isGrounded || _characterController.isGrounded || SlopeSlide.IsSliding) _lastGroundedTime = Time.time; return Time.time - _lastGroundedTime <= _groundedGraceTime; @@ -333,6 +335,29 @@ public float StepOffset public float FadeAlpha => _screenFade != null ? _screenFade.FadeAlpha : 0f; + /// + /// HeroSlideService's slide, set every frame. Ignored while a teleport is on its way. + /// + public Vector3 SlideVelocity + { + get => SlopeSlide.Velocity; + set => SlopeSlide.Velocity = _isTeleportQueued ? Vector3.zero : value; + } + + public bool IsTakeOffBlocked + { + get => _jumpProvider.IsTakeOffBlocked; + set => _jumpProvider.IsTakeOffBlocked = value; + } + + /// + /// Created on first use: adapters on this GameObject may ask before Start. + /// + private XriSlopeSlide SlopeSlide => _slopeSlide ??= new XriSlopeSlide(_characterController) + { + LayerMask = _collidingLayers + }; + /// /// One Near-Far interactor per hand. Resolved lazily, as adapters on this GameObject ask in their Awake. /// @@ -357,6 +382,7 @@ private void Awake() // Grounded check against everything the player collides with (world, VOBs, NPCs), not only Default. _collidingLayers = GetCollidingLayers(gameObject.layer); _gravityProvider.sphereCastLayerMask = _collidingLayers; + SlopeSlide.LayerMask = _collidingLayers; _teleportationProvider.locomotionEnded += OnTeleportLocomotionEnded; @@ -388,6 +414,7 @@ private void Start() _bodyManipulator = ScriptableObject.CreateInstance(); _bodyTransformer.beforeApplyTransformations += OnBeforeApplyTransformations; _bodyTransformer.afterApplyTransformations += OnAfterApplyTransformations; + SlopeSlide.SetBodyTransformer(_bodyTransformer); } else { @@ -409,6 +436,7 @@ private void ExcludeItemsFromGround() _collidingLayers &= ~((1 << Gothic.Core.Const.Constants.VobItemLayer) | (1 << Gothic.Core.Const.Constants.VobItemNoWorldCollision)); _gravityProvider.sphereCastLayerMask = _collidingLayers; + SlopeSlide.LayerMask = _collidingLayers; } /// @@ -470,6 +498,10 @@ private void Update() UpdateClimbLock(); UpdateSprint(); UpdateCrouch(); + + // The slide moves the body down the slope: gravity's own fall speed would pile up on top of it. + if (SlopeSlide.IsSliding) + _gravityProvider.ResetFallForce(); } public void SetLeapVelocity(Vector3 velocity) @@ -533,6 +565,7 @@ private void OnBeforeApplyTransformations(XRBodyTransformer bodyTransformer) { if (!ReferenceEquals(bodyTransformer.constrainedBodyManipulator, _bodyManipulator)) bodyTransformer.constrainedBodyManipulator = _bodyManipulator; + SlopeSlide.OnBeforeMoves(Root.position); } private void OnAfterApplyTransformations(ApplyBodyTransformationsEventArgs args) @@ -686,6 +719,11 @@ private void UpdateCrouch() CameraOffset.localPosition = position; } + public bool TryGetGround(out Vector3 point, out Vector3 normal) + { + return SlopeSlide.TryGetGround(out point, out normal); + } + public void SetEyeHeightOverride(float? meters) { _eyeHeightOverride = meters; diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs new file mode 100644 index 000000000..1f4a89d6b --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs @@ -0,0 +1,139 @@ +using UnityEngine; +using UnityEngine.XR.Interaction.Toolkit.Locomotion; + +namespace Gothic.VR.Interaction.Backends.Xri +{ + /// + /// The XRI side of sliding down a slope (IVrRig.TryGetGround, IVrRig.SlideVelocity) - HeroSlideService decides, + /// this only executes. Worker of XriRig. + /// - The ground probe: one ray straight down from the CharacterController's bottom center, once per frame. A sphere + /// cast would also touch stair edges and walls beside the feet and report their steep normals. + /// - The slide is a body transformation queued after XRI's own moves (the stick, gravity): it moves the + /// CharacterController along the slope (CharacterController.Move, so walls still stop it) and takes back what the + /// stick moved up the slope in the same frame - sideways and downhill stay free. + /// The CharacterController's slopeLimit (prefab) doesn't decide anything here: Gothic's SLIDE_ANGLE does. + /// + public class XriSlopeSlide + { + // The ray starts this far above the feet (a foot sunk into the slope) and reaches this far below them: on a + // 70 deg slope the thin capsule's center hangs ~0.2 m above the ground. + private const float _probeRise = 0.3f; + private const float _probeDepth = 0.5f; + // After XRI's moves (the move provider and gravity queue at priority 0). + private const int _priority = 10; + // A larger move in one frame is a teleport, not the stick: nothing is taken back. + private const float _maxStickMove = 1f; + + private readonly CharacterController _characterController; + private readonly DelegateXRBodyTransformation _transformation; + private XRBodyTransformer _bodyTransformer; + private Vector3 _velocity; + private int _queuedFrame = -1; + private Vector3 _originBeforeMoves; + + private int _probeFrame = -1; + private bool _hasGround; + private Vector3 _groundPoint; + private Vector3 _groundNormal = Vector3.up; + + public XriSlopeSlide(CharacterController characterController) + { + _characterController = characterController; + _transformation = new DelegateXRBodyTransformation(Apply); + } + + /// + /// Layers the ground probe hits (the player's colliding layers without items). + /// + public int LayerMask { get; set; } = Physics.DefaultRaycastLayers; + + public bool IsSliding => _velocity != Vector3.zero; + + /// + /// Set every frame while sliding: queues the slide for the body transformer's next update. + /// + public Vector3 Velocity + { + get => _velocity; + set + { + _velocity = value; + if (value != Vector3.zero && _bodyTransformer != null && _queuedFrame != Time.frameCount) + { + _queuedFrame = Time.frameCount; + _bodyTransformer.QueueTransformation(_transformation, _priority); + } + } + } + + public void SetBodyTransformer(XRBodyTransformer bodyTransformer) + { + _bodyTransformer = bodyTransformer; + } + + /// + /// The origin before this update's transformations (XRBodyTransformer.beforeApplyTransformations) - what the + /// stick moved is measured from it. + /// + public void OnBeforeMoves(Vector3 origin) + { + _originBeforeMoves = origin; + } + + public bool TryGetGround(out Vector3 point, out Vector3 normal) + { + if (_probeFrame != Time.frameCount) + { + _probeFrame = Time.frameCount; + Probe(); + } + + point = _groundPoint; + normal = _groundNormal; + return _hasGround; + } + + private void Probe() + { + _hasGround = false; + _groundNormal = Vector3.up; + if (_characterController == null || !_characterController.enabled) + return; + + var controllerTransform = _characterController.transform; + var feet = controllerTransform.TransformPoint(_characterController.center) + - Vector3.up * (_characterController.height * 0.5f * controllerTransform.lossyScale.y); + if (!Physics.Raycast(feet + Vector3.up * _probeRise, Vector3.down, out var hit, _probeRise + _probeDepth, + LayerMask, QueryTriggerInteraction.Ignore)) + return; + + _hasGround = true; + _groundPoint = hit.point; + _groundNormal = hit.normal; + } + + private void Apply(XRMovableBody body) + { + var velocity = _velocity; + if (velocity == Vector3.zero) + return; + + var motion = velocity * Time.deltaTime; + var downhill = new Vector3(velocity.x, 0f, velocity.z); + if (downhill.sqrMagnitude > 0.000001f) + { + downhill.Normalize(); + var moved = body.originTransform.position - _originBeforeMoves; + moved.y = 0f; + var uphill = -Vector3.Dot(moved, downhill); + if (uphill > 0f && moved.magnitude < _maxStickMove) + motion += downhill * uphill; + } + + if (body.constrainedManipulator != null) + body.constrainedManipulator.MoveBody(motion); + else + body.originTransform.position += motion; + } + } +} diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs index b8423ddb2..223d9f386 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs @@ -221,5 +221,39 @@ void SetLedgeHandler(IVrLedgeHandler handler) void SetEyeHeightOverride(float? meters) { } + + /// + /// The ground straight under the feet (a ray down from the body's center, so stair risers and walls beside it + /// don't count), within a step below the feet. Asked per frame: backends probe once per frame. + /// Default: no ground known (no slides). + /// + bool TryGetGround(out Vector3 point, out Vector3 normal) + { + point = default; + normal = Vector3.up; + return false; + } + + /// + /// The hero slides down a slope with this world velocity (m/s), zero = no slide (HeroSlideService decides). Set + /// every frame. Meanwhile the backend moves the body with it, removes the player's own movement up the slope, + /// holds gravity's fall speed and counts the body as grounded (a slide is no fall). + /// Default: not supported, the body stands on any slope. + /// + Vector3 SlideVelocity + { + get => Vector3.zero; + set { } + } + + /// + /// The ground is too steep to jump from (SLIDE_ANGLE): a press of the jump button does nothing until released. + /// Set every frame. Default: not supported. + /// + bool IsTakeOffBlocked + { + get => false; + set { } + } } } From 31581a4fff0bd08c735921192e7ac8d0fcae4b46 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 04:26:46 +0000 Subject: [PATCH 03/31] feat: the sliding VR hero body plays S_SLIDE facing downhill and S_SLIDEB backwards, and the scripts see him standing - no footsteps, no running while he slides BS_STAND like OpenGothic (BS_NONE for the slide animations). Without S_SLIDEB the body plays S_SLIDE, without both its normal animations. Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Player/VRHeroMovement.cs | 10 +++++++ .../Adapters/Player/VrHeroLocomotion.cs | 26 +++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs index 62ba06f7b..437a91e70 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs @@ -5,6 +5,7 @@ using Gothic.Core.Models.Vm; using Gothic.Core.Services; using Gothic.Core.Services.Audio; +using Gothic.Core.Services.Movement; using Gothic.VR.Interaction.Ports; using Gothic.VR.Models; using Gothic.VR.Services; @@ -27,6 +28,7 @@ public class VRHeroMovement : MonoBehaviour [Inject] private readonly AudioService _audioService; [Inject] private readonly GroundSoundService _groundSoundService; [Inject] private readonly VRPlayerService _vrPlayerService; + [Inject] private readonly HeroSlideService _heroSlideService; // Gothic.ini footstepSounds: the hero's own steps - Gothic's RUN_ every stride of the way // walked (the VR body plays no step events; a timer stepped on while the run state lingered after a tap). @@ -200,6 +202,14 @@ private void UpdateHeroBodyState() if (props == null || !props.BodyState.IsLocomotion()) return; + // Sliding down a slope is no walking (OpenGothic: BS_NONE for S_SLIDE) - no steps, no running for the + // scripts. + if (_heroSlideService.IsSliding) + { + props.BodyState = VmGothicEnums.BodyState.BsStand; + return; + } + // Crouched = sneaking. // Lying or standing up (the VR hero body's fall camera lowers the head) isn't sneaking - an NPC asked "why // are you sneaking around" while the hero got up. diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs index 9853a165e..63edf005e 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Gothic.Core; +using Gothic.Core.Domain.Movement; using Gothic.Core.Logging; using Gothic.Core.Models.Container; using Gothic.Core.Models.Movement; @@ -18,7 +19,8 @@ namespace Gothic.VR.Adapters.Player /// Legs and torso of the VR hero body like the hero in Gothic: picks the animation and its playback speed from the /// player's velocity, the body state, the body's turn speed, crouching and swimming (VrHeroSwimPose) - idle, /// walk/run (played at the real speed - no sliding feet), walking backwards, strafing, turning on the spot, - /// jumping and falling (HeroFallService's phase), sneaking, swimming and diving. Worker of VRHeroBody + /// jumping and falling (HeroFallService's phase), sliding down slopes (HeroSlideService: S_SLIDE facing downhill, + /// S_SLIDEB backwards), sneaking, swimming and diving. Worker of VRHeroBody /// (new().Inject(), Bind per built body). A deep landing (lying, getting up) is VrHeroDownPose's. /// Publishes the body's walk/run/sneak speeds (its animations at its scale, VRPlayerService.HeroBodySpeeds) - the /// rig moves at them (VRHeroMovement), so the feet match the ground. @@ -28,6 +30,7 @@ public class VrHeroLocomotion [Inject] private readonly AnimationService _animationService; [Inject] private readonly VRPlayerService _vrPlayerService; [Inject] private readonly HeroFallService _heroFallService; + [Inject] private readonly HeroSlideService _heroSlideService; private const float _idleSpeed = 0.15f; private const float _turnAnimationSpeed = 60f; // degrees per second @@ -147,7 +150,7 @@ public void Update(NpcContainer hero, Transform body, IVrRig rig, float scale, b var isBackwards = local.z < -_backwardsShare * speed; var isTurning = Mathf.Abs(_bodyYawSpeed) >= _turnAnimationSpeed; - if (TryPlayAirAnimation(speed, isMoving)) + if (TryPlayAirAnimation(speed, isMoving) || TryPlaySlideAnimation(body.forward)) { _animator.Update(Time.deltaTime); return; @@ -294,6 +297,25 @@ private void StartTakeOff() _jumpLoop = isJumpUp && _animator.HasAnimation(_jumpUpAnimation) ? _jumpUpAnimation : _jumpAnimation; } + /// + /// S_SLIDE facing where he slides, S_SLIDEB backwards (S_SLIDE without it) - false: not sliding or the model + /// has no slide animation, the normal animations play. A landing's one-shot ends. + /// + private bool TryPlaySlideAnimation(Vector3 facing) + { + if (!_heroSlideService.IsSliding) + return false; + + var animation = _heroSlideService.GetAnimation(facing); + if (!_animator.HasAnimation(animation)) + animation = SlopeSlideDomain.SlideAnimation; + if (!_animator.HasAnimation(animation)) + return false; + + _airOneShot = null; + return _animator.Play(animation); + } + /// /// S_FALLDN, deeper than NpcFallDomain.LyingFallHeight flat: HeroFallService's pose, S_FALL on his face or /// S_FALLB on his back. From 261df31c7bd4c6dc33ea989f4c2e6006214fcc00 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 04:26:56 +0000 Subject: [PATCH 04/31] feat: NPCs and monsters slide down steep slopes too - their own guild's SLIDE_ANGLE, S_SLIDE / S_SLIDEB, off an edge into a fall NpcJumpFall gets a Sliding state (busy: the walk and fight moves wait, like for falls): ground straight under a moving NPC near the hero steeper than its SLIDE_ANGLE for 0.2 s, going down or across it, slides it down - kinematic, held on the ground below, stopped by walls. It walks on at walkable ground, stands when blocked, and falls with the slide's speed off an edge (the drop counts from there). Walking up a steep slope stays walking, so routes don't loop. Flyers never slide (NpcFallDomain.CanMove). Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/NpcJumpFall.cs | 155 +++++++++++++++++- 1 file changed, 151 insertions(+), 4 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index b88f01536..9b2829333 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -1,4 +1,5 @@ using Gothic.Core.Const; +using Gothic.Core.Domain.Movement; using Gothic.Core.Domain.Npc; using Gothic.Core.Extensions; using Gothic.Core.Logging; @@ -23,6 +24,10 @@ namespace Gothic.Core.Adapters.Npc /// Fall damage like the engine: FALLDOWN_DAMAGE per meter above FALLDOWN_HEIGHT (Species.d), minus PROT_FALL. /// - Climbing (chasing NPCs only, called by AttackPlayAni): a ledge in front between STEP_HEIGHT and JUMPMID_HEIGHT /// is climbed with the JumpUpLow/JumpUpMid animations - only if the model has them (most monsters don't). + /// - Sliding (SlopeSlideDomain, the guild's SLIDE_ANGLE): ground steeper than it, going down or across it, slides + /// the NPC down with S_SLIDE / S_SLIDEB, BS_STAND, until walkable ground (it walks on), a block, or an edge (it + /// falls). Walking up such a slope stays walking (ours - Gothic stops it like at a wall): waypoint routes over + /// steep ground don't loop between walking up and sliding down. /// Lives on the NPC (added on demand), not in an AI action: ZS_Attack_Loop clears the AI queue every ~2 s, an action /// would leave the NPC hanging in the air. /// Not saved - a loaded NPC stands on the ground anyway. @@ -63,7 +68,8 @@ private enum State None, Falling, Landing, - Climbing + Climbing, + Sliding } private NpcContainer _npc; @@ -80,6 +86,10 @@ private enum State // Thrown by a spell - lands lying and gets up. private bool _isThrown; + // Sliding down a slope. + private readonly SlopeSlideState _slide = new(); + private string _slideAnimName; + // Landing / climbing: a sequence of animations played one after another. private string[] _sequence; private float[] _sequenceDurations; @@ -163,6 +173,9 @@ private void Update() case State.Climbing: TickClimb(); break; + case State.Sliding: + TickSlide(); + break; } _previousPosition = transform.position; @@ -191,15 +204,148 @@ private bool CheckFall() if (moved.sqrMagnitude < 0.0001f) return false; - var probe = RestHeight + Rules.StepHeight + _groundProbeExtra; - if (Physics.Raycast(transform.position, Vector3.down, probe, 1 << Constants.DefaultLayer, - QueryTriggerInteraction.Ignore)) + if (TryGetGround(transform.position, out var ground)) + { + CheckSlide(ground, moved); return true; + } StartFall(moved / Mathf.Max(Time.deltaTime, 0.001f)); return true; } + private Vector3 Feet => transform.position - Vector3.up * RestHeight; + + /// + /// Ground within STEP_HEIGHT under the feet of a root at position - a ray straight down, so stair risers and + /// walls beside the NPC don't count. + /// + private bool TryGetGround(Vector3 position, out RaycastHit hit) + { + var probe = RestHeight + Rules.StepHeight + _groundProbeExtra; + return Physics.Raycast(position, Vector3.down, out hit, probe, 1 << Constants.DefaultLayer, + QueryTriggerInteraction.Ignore); + } + + /// + /// Steep ground under a moving NPC long enough: it slides - not while it walks up the slope. + /// + private void CheckSlide(RaycastHit ground, Vector3 moved) + { + if (SlopeSlideDomain.IsMovingUphill(moved, ground.normal)) + { + SlopeSlideDomain.Hold(_slide, Feet); + return; + } + + if (SlopeSlideDomain.Tick(_slide, Feet, true, ground.normal, Rules, _gravity, Time.deltaTime) == + SlopeSlideEvent.Started) + StartSlide(); + } + + private void StartSlide() + { + enabled = true; + _state = State.Sliding; + _npc.Props.BodyState = VmGothicEnums.BodyState.BsStand; + _physicsService.DisablePhysicsForNpc(_npc.PrefabProps); + _npc.PrefabProps.AnimationSystem.StopAllAnimations(); + _slideAnimName = null; + PlaySlideAnimation(); + + Logger.Log($"[NpcJumpFall] {_npc.Go.name} slides down a {_slide.GroundAngle:F0} deg slope (SLIDE_ANGLE " + + $"{Rules.SlideAngle:F0}).", LogCat.Ai); + } + + /// + /// Down the slope at the slide's speed, along walls, held on the ground below. No ground: it falls on with + /// the slide's speed (a fall from here - the slide itself is no drop). + /// + private void TickSlide() + { + if (!CanMove()) + { + SlopeSlideDomain.Hold(_slide, Feet); + EndSlide("can't move"); + return; + } + + var dt = Time.deltaTime; + var position = transform.position; + var move = _slide.Velocity * dt; + var moveH = new Vector3(move.x, 0f, move.z); + // Against a wall: the slide gets nowhere and ends as blocked. + if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, moveH.magnitude + 0.3f, + 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore)) + move = Vector3.zero; + + var next = position + move; + if (!TryGetGround(next, out var ground)) + { + var velocity = _slide.Velocity; + SlopeSlideDomain.Hold(_slide, Feet); + StopSlideAnimation(); + Logger.Log($"[NpcJumpFall] {_npc.Go.name} slides off an edge.", LogCat.Ai); + transform.position = next; + StartFall(new Vector3(velocity.x, 0f, velocity.z)); + _fallVelocityY = Mathf.Min(velocity.y, 0f); + return; + } + + transform.position = ground.point + Vector3.up * RestHeight; + var slideEvent = SlopeSlideDomain.Tick(_slide, ground.point, true, ground.normal, Rules, _gravity, dt); + if (slideEvent != SlopeSlideEvent.None) + { + EndSlide(slideEvent == SlopeSlideEvent.Blocked ? "blocked" : "walkable ground"); + return; + } + + PlaySlideAnimation(); + } + + /// + /// S_SLIDE facing downhill, S_SLIDEB backwards (S_SLIDE if the model has no S_SLIDEB) - again when the + /// direction changed or Npc_ClearAIQueue stopped it. + /// + private void PlaySlideAnimation() + { + var animationName = SlopeSlideDomain.GetAnimation(_slide.Velocity, transform.forward); + if (!HasTrack(animationName)) + animationName = SlopeSlideDomain.SlideAnimation; + if (!HasTrack(animationName)) + return; + + var animationSystem = _npc.PrefabProps.AnimationSystem; + if (animationName == _slideAnimName && animationSystem.IsPlaying(animationName)) + return; + + StopSlideAnimation(); + _slideAnimName = animationName; + animationSystem.PlayAnimation(animationName); + } + + private void StopSlideAnimation() + { + if (_slideAnimName != null) + _npc.PrefabProps.AnimationSystem.StopAnimation(_slideAnimName); + _slideAnimName = null; + } + + private void EndSlide(string reason) + { + Logger.Log($"[NpcJumpFall] {_npc.Go.name} slide ended ({reason}) after " + + $"{SlopeSlideDomain.GetSlidDistance(_slide, Feet):F1} m.", LogCat.Ai); + if (CanMove()) + { + Finish(); + return; + } + + // Died or swims: no idle animation, the death or the swimming takes over. + StopSlideAnimation(); + _state = State.None; + } + private bool IsNearHero() { var hero = _gameStateService.GothicVm?.GlobalHero as ZenKit.Daedalus.NpcInstance; @@ -607,6 +753,7 @@ private void Finish() _npc.PrefabProps.AnimationSystem.StopAnimation(_sequence[_sequenceIndex]); if (_fallAnimName != null) _npc.PrefabProps.AnimationSystem.StopAnimation(_fallAnimName); + StopSlideAnimation(); _state = State.None; _isLadder = false; From 187c47fa0de3ba9f45b846e7f1de0da2e6582f1b Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 04:27:04 +0000 Subject: [PATCH 05/31] docs: the slope slide decision record - Gothic's slide angles, no jump from steep ground, a slide is no fall, NPCs only downhill Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-11-29-slope-slide.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Docs/adr/2026-11-29-slope-slide.md diff --git a/Docs/adr/2026-11-29-slope-slide.md b/Docs/adr/2026-11-29-slope-slide.md new file mode 100644 index 000000000..0814c8517 --- /dev/null +++ b/Docs/adr/2026-11-29-slope-slide.md @@ -0,0 +1,29 @@ +# ADR: Sliding down steep slopes + +- Date: 2026-11-29 +- Technical details: the class docs of SlopeSlideDomain and HeroSlideService (Core), NpcJumpFall (Core), XriSlopeSlide and VrHeroJumpFall (VR) + +## Context + +In Gothic nobody stands on ground that is too steep: the hero and NPCs slide down it, playing the slide animation (facing downhill, or backwards), until the ground is walkable again or they slide off an edge and fall. Each guild has its own limit: humans and most monsters 45 degrees, bloodflies and demons 75, minecrawlers and swampsharks 60. A second value marks ground so close to vertical that it counts as a wall; Gothic leaves it at zero. While sliding the hero can't jump. + +In the VR game the hero stood on any slope. Worse, jumping again and again carried him up any slope, even a cliff (play test in Mroczne Tajemnice, a Gothic 1 mod). NPCs never slid either. + +## Decisions + +1. **The hero and NPCs slide on ground steeper than their guild's slide angle, with Gothic's two values.** One rule for both, the angles come from the scripts, so mods and monsters bring their own. Flying monsters never slide, like they never fall. +2. **The slide is gravity along the slope, like OpenGothic, but never faster than 6 m/s.** Gothic has no limit; in VR a long slide would get uncomfortably fast. Not chosen: a fixed slide speed (the slide would feel the same on 46 and 80 degrees). +3. **No jump from ground steeper than the slide angle, at once, also before a slide has begun.** This is the fix for climbing a slope by jumping. Not chosen: blocking the jump only while sliding (a quick jump right after landing would still work). +4. **The slope must be steep for a fifth of a second before the slide begins, and walkable for a tenth before it ends.** A single steep triangle of a rock or a mesh seam doesn't make anybody slide. Stairs don't either: only the ground straight under the feet counts, not the step edges beside them. +5. **While the hero slides, the stick can't walk him up the slope; sideways and downhill stay free.** In Gothic the player has no control at all while sliding. In VR steering sideways helps to stay on the slope and keeps the player in charge of his view. Not chosen: no stick at all (a sudden loss of control in VR), or the stick fighting the slide (he could walk up again). +6. **A slide is no fall.** Sliding down a 50 m hillside costs no hit points; only when he slides off an edge does a normal fall begin there, with its damage counted from the edge. The scripts see a standing hero while he slides (like OpenGothic), so no footsteps and no "running" for the NPCs. +7. **A slide that gets nowhere (a wall, a crevice, a rock) ends, and he stands there.** No new slide until he moved half a meter away or stood on walkable ground. Otherwise he would be stuck in the slide pose. +8. **NPCs slide when they go down or across steep ground; walking up it stays walking.** In Gothic a slope too steep to walk up stops an NPC like a wall. Our NPCs move by their animations and their routes were never built around this; a slide back down would loop with the walk up again. Not chosen: Gothic's wall for NPCs (left for later, needs the route walking to know about it). +9. **NPCs slide only near the hero (40 m), like they fall only there.** Far away the world isn't loaded under them. + +## Consequences + +- Nothing new is saved: a loaded game starts standing. +- Not checked while climbing, swimming or wading, lying after a fall, after a teleport, while sitting or using something, or while transformed into a monster: the transformed hero still stands on any slope (his monster's own angle isn't applied yet). +- The hero with no slide animation in his model (a mod) still slides, with his normal animations. +- Flat mode can feed the same rules from its own controller once it runs again. From 22ecc125214c37c035f82dec511a903cbf6603fc Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 04:32:06 +0000 Subject: [PATCH 06/31] fix: a vertical wall is never slide ground - near-vertical normals (y below 0.01) count as a wall even without SLIDE_ANGLE2 Co-Authored-By: Claude Opus 5.5 --- .../Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs index edd7e6f66..189f0a2b5 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs @@ -45,6 +45,9 @@ public static class SlopeSlideDomain /// public const float BlockedReleaseDistance = 0.5f; + // normal.y below this is a wall (about 89.4 deg), never slide ground. + private const float _wallNormalY = 0.01f; + /// /// OpenGothic MoveAlgo::testSlide: slideBegin = sin(90 - SLIDE_ANGLE), slideEnd = sin(SLIDE_ANGLE2), the ground /// slides when slideEnd < normal.y < slideBegin. @@ -52,7 +55,8 @@ public static class SlopeSlideDomain public static bool IsSlideGround(Vector3 normal, LedgeRules rules) { var slideBegin = Mathf.Min(Mathf.Cos(rules.SlideAngle * Mathf.Deg2Rad), 1f); - var slideEnd = Mathf.Sin(rules.SlideAngle2 * Mathf.Deg2Rad); + // SLIDE_ANGLE2 0 (Species.d never sets it): at least a wall, also for a float 90 deg normal (y ~ 1e-8). + var slideEnd = Mathf.Max(Mathf.Sin(rules.SlideAngle2 * Mathf.Deg2Rad), _wallNormalY); return slideEnd < normal.y && normal.y < slideBegin; } From 436cba9dd5e16106ab9f1a196da24bea08e0b085 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:23:13 +0000 Subject: [PATCH 07/31] fix: the hero's slide check no longer builds a string every frame while he fights or sits - why he isn't checked is a HeroSlideHold enum, its text only built when it changes Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Models/Movement/HeroSlideHold.cs | 54 ++++++++++++++ .../Services/Movement/HeroSlideService.cs | 74 ++++++++++++------- 2 files changed, 103 insertions(+), 25 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs new file mode 100644 index 000000000..06aa42321 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs @@ -0,0 +1,54 @@ +namespace Gothic.Core.Models.Movement +{ + /// + /// Why HeroSlideService doesn't check the hero for a slide right now (no slide, the jump allowed). An enum, not a + /// string: it's decided every frame. + /// + public enum HeroSlideHold + { + /// + /// Checked. + /// + None, + + /// + /// A hand holds a ladder or a ledge. + /// + Climbing, + + /// + /// Transformed into a monster: the puppet stands on any slope. + /// + Transformed, + + /// + /// Swimming or diving. + /// + NoGravity, + + /// + /// His own jump runs. + /// + Jumping, + + /// + /// Lying after a fall flat until he stood up. + /// + LyingAfterFall, + + /// + /// Wading or deeper in water. + /// + InWater, + + /// + /// A body state other than stand, walk, run or sneak (fighting, sitting, a mob, casting...). + /// + Busy, + + /// + /// Teleported this frame. + /// + Teleported + } +} diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs index fbdbc0984..dafa2d89f 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs @@ -30,8 +30,8 @@ public class HeroSlideService [Inject] private readonly HeroFallService _heroFallService; private readonly SlopeSlideState _state = new(); - // Why the hero isn't checked right now (logged when it changes), null = checked. - private string _holdReason; + // Why the hero isn't checked right now (logged when it changes). + private HeroSlideHold _hold; public bool IsSliding => _state.IsSliding; @@ -44,7 +44,7 @@ public class HeroSlideService /// The ground under the feet is too steep to jump from (no debounce: also before a slide begins). Without it /// the hero climbed any slope by jumping again and again. /// - public bool IsTakeOffBlocked => _holdReason == null && _state.IsSteepGround; + public bool IsTakeOffBlocked => _hold == HeroSlideHold.None && _state.IsSteepGround; public HeroSlideService() { @@ -69,13 +69,13 @@ public void Tick(in HeroFallSample sample) if (hero?.Props == null) return; - var holdReason = GetHoldReason(hero, sample); - if (holdReason != null) + var hold = GetHold(hero, sample); + if (hold != HeroSlideHold.None) { - Hold(sample.FeetPosition, holdReason); + Hold(sample.FeetPosition, hold, hero); return; } - _holdReason = null; + _hold = HeroSlideHold.None; var rules = _ledgeService.HeroRules; var feet = sample.FeetPosition; @@ -104,43 +104,67 @@ public void Tick(in HeroFallSample sample) /// public void OnTeleported(Vector3 feetPosition) { - Hold(feetPosition, "teleported"); + Hold(feetPosition, HeroSlideHold.Teleported, _npcService.GetHeroContainer()); } /// - /// Why the hero isn't checked now, null if he is. + /// Why the hero isn't checked now, None if he is. Every frame: no strings. /// - private string GetHoldReason(NpcContainer hero, in HeroFallSample sample) + private HeroSlideHold GetHold(NpcContainer hero, in HeroFallSample sample) { if (sample.IsClimbing) - return "climbing"; + return HeroSlideHold.Climbing; if (sample.IsTransformed) - return "transformed"; + return HeroSlideHold.Transformed; if (sample.Gravity <= 0f) - return "no gravity (swimming, diving)"; + return HeroSlideHold.NoGravity; if (sample.IsJumping) - return "jumping"; + return HeroSlideHold.Jumping; if (_heroFallService.IsLyingAfterFall) - return "lying after a fall"; + return HeroSlideHold.LyingAfterFall; var ai = hero.Vob?.AiHuman; if (ai != null && ai.WaterLevel != (int)ZenGineConst.WaterLevel.Normal) - return "in water"; + return HeroSlideHold.InWater; return hero.Props.BodyState is VmGothicEnums.BodyState.BsStand or VmGothicEnums.BodyState.BsWalk or VmGothicEnums.BodyState.BsRun or VmGothicEnums.BodyState.BsSneak - ? null - : $"body state {hero.Props.BodyState}"; + ? HeroSlideHold.None + : HeroSlideHold.Busy; } - private void Hold(Vector3 feet, string reason) + /// + /// Ends a running slide and logs why - the reason only when it changed, so the text is built once. + /// + private void Hold(Vector3 feet, HeroSlideHold hold, NpcContainer hero) { var speed = _state.Velocity.magnitude; - if (SlopeSlideDomain.Hold(_state, feet)) - LogEnd(reason, feet, speed); - else if (reason != _holdReason) - Logger.LogEditor($"[HeroSlide] Not checked: {reason}", LogCat.Npc); - _holdReason = reason; + var wasSliding = SlopeSlideDomain.Hold(_state, feet); + if (wasSliding || hold != _hold) + { + var reason = GetText(hold, hero); + if (wasSliding) + LogEnd(reason, feet, speed); + else + Logger.LogEditor($"[HeroSlide] Not checked: {reason}", LogCat.Npc); + } + _hold = hold; + } + + private static string GetText(HeroSlideHold hold, NpcContainer hero) + { + return hold switch + { + HeroSlideHold.Climbing => "climbing", + HeroSlideHold.Transformed => "transformed", + HeroSlideHold.NoGravity => "no gravity (swimming, diving)", + HeroSlideHold.Jumping => "jumping", + HeroSlideHold.LyingAfterFall => "lying after a fall", + HeroSlideHold.InWater => "in water", + HeroSlideHold.Busy => $"body state {hero?.Props?.BodyState}", + HeroSlideHold.Teleported => "teleported", + _ => hold.ToString() + }; } private void LogEnd(string reason, Vector3 feet, float speed) @@ -154,7 +178,7 @@ private void ResetAll() { SlopeSlideDomain.Hold(_state, Vector3.zero); _state.HasPreviousFeet = false; - _holdReason = null; + _hold = HeroSlideHold.None; } } } From 390b42fd0e1f2af2317a9a26f1e45e6df9529b98 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:23:48 +0000 Subject: [PATCH 08/31] fix: an NPC that dies or swims mid-slide gets its physics back unless dead or unconscious - fall, climb and slide all finish the same way when it can't move, without our landing or idle animations over the death Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/NpcJumpFall.cs | 45 +++++++++++-------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index 9b2829333..05cc5a1d7 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -28,6 +28,10 @@ namespace Gothic.Core.Adapters.Npc /// the NPC down with S_SLIDE / S_SLIDEB, BS_STAND, until walkable ground (it walks on), a block, or an edge (it /// falls). Walking up such a slope stays walking (ours - Gothic stops it like at a wall): waypoint routes over /// steep ground don't loop between walking up and sliding down. + /// Can't move any more (dead, unconscious, swimming - NpcFallDomain.CanMove): a fall still lands and a climb still + /// reaches its end (nobody hangs in the air), a slide ends at once (it's on the ground) - with no more of our + /// animations, the death or the swimming takes over. Dead and unconscious bodies stay kinematic (their domains + /// made them so), all others get their physics back. /// Lives on the NPC (added on demand), not in an AI action: ZS_Attack_Loop clears the AI queue every ~2 s, an action /// would leave the NPC hanging in the air. /// Not saved - a loaded NPC stands on the ground anyway. @@ -189,6 +193,10 @@ private void Update() private bool CanMove() => NpcFallDomain.CanMove(_gameStateService.GuildValues, _npc); + // NpcDeathDomain / NpcKnockoutDomain made the body kinematic: it stays so. + private bool IsDown => _npc.Props.BodyState is VmGothicEnums.BodyState.BsDead + or VmGothicEnums.BodyState.BsUnconscious; + /// /// Walked off a ledge: start falling. False if the NPC stands still or isn't checked (far from the hero, /// swimming, dead...) - then the component may go to sleep. @@ -335,15 +343,7 @@ private void EndSlide(string reason) { Logger.Log($"[NpcJumpFall] {_npc.Go.name} slide ended ({reason}) after " + $"{SlopeSlideDomain.GetSlidDistance(_slide, Feet):F1} m.", LogCat.Ai); - if (CanMove()) - { - Finish(); - return; - } - - // Died or swims: no idle animation, the death or the swimming takes over. - StopSlideAnimation(); - _state = State.None; + Finish(); } private bool IsNearHero() @@ -424,9 +424,9 @@ private void TickFall() _fallAnimName = FallPose.Front.Flight; PlayIfExists(_fallAnimName); } - else if (!_npc.PrefabProps.AnimationSystem.IsPlaying(_fallAnimName)) + else if (!_npc.PrefabProps.AnimationSystem.IsPlaying(_fallAnimName) && CanMove()) { - // Npc_ClearAIQueue stops all animations every ~2 s. + // Npc_ClearAIQueue stops all animations every ~2 s (a death's animation stays). PlayIfExists(_fallAnimName); } @@ -442,9 +442,12 @@ private void Land(float height) _npc.PrefabProps.AnimationSystem.StopAnimation(_fallAnimName); var isDeep = height > NpcFallDomain.LyingFallHeight || _isThrown; _isThrown = false; - StartSequence(State.Landing, isDeep - ? new[] { FallPose.Front.Landing, FallPose.Front.StandUp } - : new[] { "T_FALLDN_2_STAND" }); + var canMove = CanMove(); + // Can't move (died in the air, landed in water): no landing animations. + if (canMove) + StartSequence(State.Landing, isDeep + ? new[] { FallPose.Front.Landing, FallPose.Front.StandUp } + : new[] { "T_FALLDN_2_STAND" }); // NPCs' fall damage comes with the combat system, the hero's always (HeroFallService). var damage = NpcFallDomain.GetFallDamage(_gameStateService.GuildValues, _npc, height); @@ -452,7 +455,10 @@ private void Land(float height) if (isDamageOn && damage > 0) GlobalEventDispatcher.FallDamage.Invoke(_npc, damage); Logger.Log($"[NpcJumpFall] {_npc.Go.name} landed after {height:F1} m, fall damage {damage}" + - (isDamageOn || damage <= 0 ? "" : " - not applied (EnableCombatSystem off)"), LogCat.Ai); + (isDamageOn || damage <= 0 ? "" : " - not applied (EnableCombatSystem off)") + + (canMove ? "" : $" ({_npc.Props.BodyState}, no landing)"), LogCat.Ai); + if (!canMove) + Finish(); } /// @@ -739,7 +745,8 @@ private void NextInSequence() while (_sequenceIndex < _sequence.Length && _sequenceDurations[_sequenceIndex] <= 0f) _sequenceIndex++; - if (_sequenceIndex < _sequence.Length) + // Can't move any more: the move ends without our animations (the death's or swimming's play). + if (_sequenceIndex < _sequence.Length && CanMove()) _npc.PrefabProps.AnimationSystem.PlayAnimation(_sequence[_sequenceIndex]); } @@ -762,8 +769,10 @@ private void Finish() if (_npc.Props.BodyState is VmGothicEnums.BodyState.BsFall or VmGothicEnums.BodyState.BsJump or VmGothicEnums.BodyState.BsClimb) _npc.Props.BodyState = VmGothicEnums.BodyState.BsStand; - _physicsService.EnablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.PlayIdleAnimation(); + if (!IsDown) + _physicsService.EnablePhysicsForNpc(_npc.PrefabProps); + if (CanMove()) + _npc.PrefabProps.AnimationSystem.PlayIdleAnimation(); } private void PlayIfExists(string animationName) From aeba42858e2fed11d6536d52255fee16a3cc3654 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:24:18 +0000 Subject: [PATCH 09/31] fix: short walks over the same steep spot no longer add up to an NPC slide - its steep time starts again whenever it stands still, is far from the hero or can't move (a block at a wall stays) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/NpcJumpFall.cs | 12 +++++++++++- .../Domain/Movement/SlopeSlideDomain.cs | 12 ++++++++++++ .../EditMode/Movement/SlopeSlideDomainTest.cs | 19 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index 05cc5a1d7..fbe1dedab 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -203,14 +203,24 @@ private void Update() /// private bool CheckFall() { - if (!_hasPreviousPosition || RestHeight <= 0f || !CanMove() || !IsNearHero()) + if (!_hasPreviousPosition || RestHeight <= 0f) return false; + // The slide's steep time counts only while it moves over steep ground - not in bursts with breaks between. + if (!CanMove() || !IsNearHero()) + { + SlopeSlideDomain.Hold(_slide, Feet); + return false; + } + // Only NPCs that move walk off a ledge (an idle NPC on a vob that isn't loaded yet must not drop). var moved = transform.position - _previousPosition; moved.y = 0f; if (moved.sqrMagnitude < 0.0001f) + { + SlopeSlideDomain.Rest(_slide, Feet); return false; + } if (TryGetGround(transform.position, out var ground)) { diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs index 189f0a2b5..bc6656e60 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs @@ -163,6 +163,18 @@ public static bool Hold(SlopeSlideState state, Vector3 feet) return wasSliding; } + /// + /// The body stands still and isn't sliding (NPCs: no slide starts from standing): the steep time starts again + /// and the next speed is measured from here. A block stays - only moving away or walkable ground ends it, else + /// standing still at a wall would let the slide into it start again and again. + /// + public static void Rest(SlopeSlideState state, Vector3 feet) + { + state.SteepSeconds = 0f; + state.PreviousFeet = feet; + state.HasPreviousFeet = true; + } + /// /// Horizontal m between the feet and where the slide began. /// diff --git a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs index 38bdb6fea..30e04f8e8 100644 --- a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs +++ b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs @@ -183,6 +183,25 @@ public void HoldEndsTheSlide() "the steep time starts again"); } + [Test] + public void RestStartsTheSteepTimeAgain() + { + TickFor(SlopeSlideDomain.StartSeconds * 0.6f, Slope(60f)); + SlopeSlideDomain.Rest(_state, _feet); + Assert.AreEqual(SlopeSlideEvent.None, TickFor(SlopeSlideDomain.StartSeconds * 0.6f, Slope(60f)), + "two short bursts over steep ground don't add up"); + Assert.IsFalse(_state.IsSliding); + } + + [Test] + public void RestKeepsABlock() + { + TickFor(SlopeSlideDomain.StartSeconds + _dt, Slope(60f)); + Assert.AreEqual(SlopeSlideEvent.Blocked, TickFor(1f, Slope(60f), moves: false)); + SlopeSlideDomain.Rest(_state, _feet); + Assert.IsTrue(_state.IsBlocked, "standing still at the wall doesn't start the slide into it again"); + } + [Test] public void FacingDownhillSlidesForwardsElseBackwards() { From 29c03937ad85084c7d8821d62ab992618f19a8e6 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:24:41 +0000 Subject: [PATCH 10/31] fix: an NPC sliding across a slope is no longer stopped by the slope rising beside it - only near-vertical hits of its wall ray are walls, the 0.3 m look-ahead is named Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/NpcJumpFall.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index fbe1dedab..35bf0f984 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -52,6 +52,10 @@ public class NpcJumpFall : MonoBehaviour, INpcJumpFall private const float _maxFallSpeedH = 6f; private const float _outOfWorldFallHeight = 100f; private const float _groundProbeExtra = 0.1f; + // m the wall ray of a fall or slide reaches beyond this frame's move. + private const float _wallLookAhead = 0.3f; + // A slide's wall ray hit with a normal.y above this (~80 deg) is the rising slope beside it, not a wall. + private const float _slideWallMaxNormalY = 0.17f; private const float _climbMinSeconds = 0.6f; private const float _climbMaxSeconds = 2f; private const float _climbRisePart = 0.65f; @@ -292,9 +296,11 @@ private void TickSlide() var position = transform.position; var move = _slide.Velocity * dt; var moveH = new Vector3(move.x, 0f, move.z); - // Against a wall: the slide gets nowhere and ends as blocked. - if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, moveH.magnitude + 0.3f, - 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore)) + // Against a wall: the slide gets nowhere and ends as blocked. Across a slope the ray may hit the slope + // rising beside the NPC - only near-vertical hits are walls. + if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, out var wall, + moveH.magnitude + _wallLookAhead, 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore) && + wall.normal.y <= _slideWallMaxNormalY) move = Vector3.zero; var next = position + move; @@ -407,7 +413,7 @@ private void TickFall() var position = transform.position; var moveH = _fallVelocityH * dt; - if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, moveH.magnitude + 0.3f, + if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, moveH.magnitude + _wallLookAhead, 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore)) { // Against a wall: slide down it. From 463fd33551f9fda0e1408e90f2d684eb027990c9 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:25:07 +0000 Subject: [PATCH 11/31] fix: NPCs, monsters and items under the VR hero's feet no longer block his jump or start a slide - the slide's ground ray sees only the world mesh layer (Default, with the solid VOBs), like the NPCs' ground ray Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Interaction/Backends/Xri/XriRig.cs | 7 +------ .../Interaction/Backends/Xri/XriSlopeSlide.cs | 13 ++++++------- .../Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs | 3 ++- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs index 426f91db0..fb4945421 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriRig.cs @@ -353,10 +353,7 @@ public bool IsTakeOffBlocked /// /// Created on first use: adapters on this GameObject may ask before Start. /// - private XriSlopeSlide SlopeSlide => _slopeSlide ??= new XriSlopeSlide(_characterController) - { - LayerMask = _collidingLayers - }; + private XriSlopeSlide SlopeSlide => _slopeSlide ??= new XriSlopeSlide(_characterController); /// /// One Near-Far interactor per hand. Resolved lazily, as adapters on this GameObject ask in their Awake. @@ -382,7 +379,6 @@ private void Awake() // Grounded check against everything the player collides with (world, VOBs, NPCs), not only Default. _collidingLayers = GetCollidingLayers(gameObject.layer); _gravityProvider.sphereCastLayerMask = _collidingLayers; - SlopeSlide.LayerMask = _collidingLayers; _teleportationProvider.locomotionEnded += OnTeleportLocomotionEnded; @@ -436,7 +432,6 @@ private void ExcludeItemsFromGround() _collidingLayers &= ~((1 << Gothic.Core.Const.Constants.VobItemLayer) | (1 << Gothic.Core.Const.Constants.VobItemNoWorldCollision)); _gravityProvider.sphereCastLayerMask = _collidingLayers; - SlopeSlide.LayerMask = _collidingLayers; } /// diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs index 1f4a89d6b..813f083e5 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs @@ -1,3 +1,4 @@ +using Gothic.Core.Const; using UnityEngine; using UnityEngine.XR.Interaction.Toolkit.Locomotion; @@ -7,7 +8,9 @@ namespace Gothic.VR.Interaction.Backends.Xri /// The XRI side of sliding down a slope (IVrRig.TryGetGround, IVrRig.SlideVelocity) - HeroSlideService decides, /// this only executes. Worker of XriRig. /// - The ground probe: one ray straight down from the CharacterController's bottom center, once per frame. A sphere - /// cast would also touch stair edges and walls beside the feet and report their steep normals. + /// cast would also touch stair edges and walls beside the feet and report their steep normals. It sees only the + /// Default layer (the world mesh and solid VOBs, like the NPCs' ground ray): an NPC, an item or a movable under + /// the feet is no slope - no slide and no blocked jump from a barrel or a monster's back. /// - The slide is a body transformation queued after XRI's own moves (the stick, gravity): it moves the /// CharacterController along the slope (CharacterController.Move, so walls still stop it) and takes back what the /// stick moved up the slope in the same frame - sideways and downhill stay free. @@ -26,6 +29,7 @@ public class XriSlopeSlide private readonly CharacterController _characterController; private readonly DelegateXRBodyTransformation _transformation; + private readonly int _groundMask = 1 << Constants.DefaultLayer; private XRBodyTransformer _bodyTransformer; private Vector3 _velocity; private int _queuedFrame = -1; @@ -42,11 +46,6 @@ public XriSlopeSlide(CharacterController characterController) _transformation = new DelegateXRBodyTransformation(Apply); } - /// - /// Layers the ground probe hits (the player's colliding layers without items). - /// - public int LayerMask { get; set; } = Physics.DefaultRaycastLayers; - public bool IsSliding => _velocity != Vector3.zero; /// @@ -104,7 +103,7 @@ private void Probe() var feet = controllerTransform.TransformPoint(_characterController.center) - Vector3.up * (_characterController.height * 0.5f * controllerTransform.lossyScale.y); if (!Physics.Raycast(feet + Vector3.up * _probeRise, Vector3.down, out var hit, _probeRise + _probeDepth, - LayerMask, QueryTriggerInteraction.Ignore)) + _groundMask, QueryTriggerInteraction.Ignore)) return; _hasGround = true; diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs index 223d9f386..18a034845 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs @@ -224,7 +224,8 @@ void SetEyeHeightOverride(float? meters) /// /// The ground straight under the feet (a ray down from the body's center, so stair risers and walls beside it - /// don't count), within a step below the feet. Asked per frame: backends probe once per frame. + /// don't count), within a step below the feet - the world mesh only (Default layer: world and solid VOBs), not + /// NPCs, items or movables. Asked per frame: backends probe once per frame. /// Default: no ground known (no slides). /// bool TryGetGround(out Vector3 point, out Vector3 normal) From 601ea7d4dfaba5a9bae9c1936b7d6815e65d2ac0 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:26:00 +0000 Subject: [PATCH 12/31] refactor: the slide animation choice with its fallback (S_SLIDEB, else S_SLIDE, else none) lives once in SlopeSlideDomain.GetAnimation for the hero and NPCs, the names in DaedalusConst Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/NpcJumpFall.cs | 7 +++--- .../Scripts/Const/DaedalusConst.cs | 4 +++ .../Domain/Movement/SlopeSlideDomain.cs | 13 +++++----- .../Services/Movement/HeroSlideService.cs | 7 +++--- .../EditMode/Movement/SlopeSlideDomainTest.cs | 25 ++++++++++++++++--- .../Adapters/Player/VrHeroLocomotion.cs | 8 +++--- 6 files changed, 44 insertions(+), 20 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index 35bf0f984..b853b1fd5 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -333,10 +333,9 @@ private void TickSlide() /// private void PlaySlideAnimation() { - var animationName = SlopeSlideDomain.GetAnimation(_slide.Velocity, transform.forward); - if (!HasTrack(animationName)) - animationName = SlopeSlideDomain.SlideAnimation; - if (!HasTrack(animationName)) + var animationName = SlopeSlideDomain.GetAnimation(_slide.Velocity, transform.forward, + HasTrack(DaedalusConst.AniSlideBack), HasTrack(DaedalusConst.AniSlide)); + if (animationName == null) return; var animationSystem = _npc.PrefabProps.AnimationSystem; diff --git a/Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs b/Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs index 5adfa229a..da7bc2a5b 100644 --- a/Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs +++ b/Assets/Gothic-Core/Scripts/Const/DaedalusConst.cs @@ -39,6 +39,10 @@ public class DaedalusConst public const string AniSwimForward = "S_SWIMF"; public const string AniSwimBack = "S_SWIMB"; + // Sliding down a slope, facing downhill and backwards (SlopeSlideDomain.GetAnimation). + public const string AniSlide = "S_SLIDE"; + public const string AniSlideBack = "S_SLIDEB"; + // Ammunition an NPC shoots when its inventory names none of the bow's/crossbow's munition (G1, G2). public static readonly string[] FallbackArrowInstances = { "ItAmArrow", "ItRw_Arrow" }; public static readonly string[] FallbackBoltInstances = { "ItAmBolt", "ItRw_Bolt" }; diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs index bc6656e60..e44556568 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs @@ -1,3 +1,4 @@ +using Gothic.Core.Const; using Gothic.Core.Models.Movement; using UnityEngine; @@ -18,9 +19,6 @@ namespace Gothic.Core.Domain.Movement /// public static class SlopeSlideDomain { - public const string SlideAnimation = "S_SLIDE"; - public const string SlideBackwardsAnimation = "S_SLIDEB"; - /// /// Seconds the ground must be steep in a row before the slide begins. /// @@ -90,13 +88,16 @@ public static bool IsMovingUphill(Vector3 moved, Vector3 normal) /// /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards (OpenGothic - /// MoveAlgo::slideDir). + /// MoveAlgo::slideDir) - S_SLIDE if the model has no S_SLIDEB, null if it has neither (its normal animations + /// play). The caller says which of them its model has (the hero's animator, an NPC's MDS). /// - public static string GetAnimation(Vector3 velocity, Vector3 facing) + public static string GetAnimation(Vector3 velocity, Vector3 facing, bool hasBackwards, bool hasForward) { velocity.y = 0f; facing.y = 0f; - return Vector3.Dot(velocity, facing) < 0f ? SlideBackwardsAnimation : SlideAnimation; + if (hasBackwards && Vector3.Dot(velocity, facing) < 0f) + return DaedalusConst.AniSlideBack; + return hasForward ? DaedalusConst.AniSlide : null; } /// diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs index dafa2d89f..b1d6bb681 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs @@ -53,11 +53,12 @@ public HeroSlideService() } /// - /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards. + /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards - null if the body's model + /// has neither (SlopeSlideDomain.GetAnimation). /// - public string GetAnimation(Vector3 facing) + public string GetAnimation(Vector3 facing, bool hasBackwards, bool hasForward) { - return SlopeSlideDomain.GetAnimation(_state.Velocity, facing); + return SlopeSlideDomain.GetAnimation(_state.Velocity, facing, hasBackwards, hasForward); } /// diff --git a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs index 30e04f8e8..b13d8fd14 100644 --- a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs +++ b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs @@ -1,3 +1,4 @@ +using Gothic.Core.Const; using Gothic.Core.Domain.Movement; using Gothic.Core.Models.Movement; using NUnit.Framework; @@ -206,9 +207,27 @@ public void RestKeepsABlock() public void FacingDownhillSlidesForwardsElseBackwards() { var downhill = new Vector3(0f, -1f, 1f); - Assert.AreEqual(SlopeSlideDomain.SlideAnimation, SlopeSlideDomain.GetAnimation(downhill, Vector3.forward)); - Assert.AreEqual(SlopeSlideDomain.SlideBackwardsAnimation, - SlopeSlideDomain.GetAnimation(downhill, Vector3.back)); + Assert.AreEqual(DaedalusConst.AniSlide, + SlopeSlideDomain.GetAnimation(downhill, Vector3.forward, true, true)); + Assert.AreEqual(DaedalusConst.AniSlideBack, + SlopeSlideDomain.GetAnimation(downhill, Vector3.back, true, true)); + } + + [Test] + public void ModelWithoutSlideBackwardsSlidesForwardsAlsoBackwards() + { + var downhill = new Vector3(0f, -1f, 1f); + Assert.AreEqual(DaedalusConst.AniSlide, + SlopeSlideDomain.GetAnimation(downhill, Vector3.back, false, true)); + } + + [Test] + public void ModelWithoutSlideAnimationsGetsNone() + { + var downhill = new Vector3(0f, -1f, 1f); + Assert.IsNull(SlopeSlideDomain.GetAnimation(downhill, Vector3.forward, true, false), + "S_SLIDEB alone isn't used facing downhill"); + Assert.IsNull(SlopeSlideDomain.GetAnimation(downhill, Vector3.back, false, false)); } [Test] diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs index 63edf005e..f20927145 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Gothic.Core; +using Gothic.Core.Const; using Gothic.Core.Domain.Movement; using Gothic.Core.Logging; using Gothic.Core.Models.Container; @@ -306,10 +307,9 @@ private bool TryPlaySlideAnimation(Vector3 facing) if (!_heroSlideService.IsSliding) return false; - var animation = _heroSlideService.GetAnimation(facing); - if (!_animator.HasAnimation(animation)) - animation = SlopeSlideDomain.SlideAnimation; - if (!_animator.HasAnimation(animation)) + var animation = _heroSlideService.GetAnimation(facing, _animator.HasAnimation(DaedalusConst.AniSlideBack), + _animator.HasAnimation(DaedalusConst.AniSlide)); + if (animation == null) return false; _airOneShot = null; From 8406e6e9f2e9f19ca86242e2901d4f2707c7af8c Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:26:27 +0000 Subject: [PATCH 13/31] refactor: how much of the stick's step up the slope a slide takes back is Core's rule (SlopeSlideDomain.RemoveUphill, with EditMode tests) - the XRI backend only moves the body Co-Authored-By: Claude Opus 5.5 --- .../Domain/Movement/SlopeSlideDomain.cs | 17 ++++++++++++++++ .../EditMode/Movement/SlopeSlideDomainTest.cs | 20 +++++++++++++++++++ .../Interaction/Backends/Xri/XriSlopeSlide.cs | 19 +++++++----------- 3 files changed, 44 insertions(+), 12 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs index e44556568..10b1875a1 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs @@ -86,6 +86,23 @@ public static bool IsMovingUphill(Vector3 moved, Vector3 normal) return Vector3.Dot(moved, GetDownhill(normal)) < 0f; } + /// + /// While the hero slides the stick can't walk him up the slope, sideways and downhill stay free (ours, Gothic + /// gives no control at all). moved: what the player's own movement moved the body this frame, slideVelocity: + /// the slide's. Returns the correction to add to the slide's move - zero when he didn't step uphill. + /// + public static Vector3 RemoveUphill(Vector3 moved, Vector3 slideVelocity) + { + var downhill = new Vector3(slideVelocity.x, 0f, slideVelocity.z); + if (downhill.sqrMagnitude < 0.000001f) + return Vector3.zero; + + downhill.Normalize(); + moved.y = 0f; + var uphill = -Vector3.Dot(moved, downhill); + return uphill > 0f ? downhill * uphill : Vector3.zero; + } + /// /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards (OpenGothic /// MoveAlgo::slideDir) - S_SLIDE if the model has no S_SLIDEB, null if it has neither (its normal animations diff --git a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs index b13d8fd14..8e89f4e8a 100644 --- a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs +++ b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs @@ -230,6 +230,26 @@ public void ModelWithoutSlideAnimationsGetsNone() Assert.IsNull(SlopeSlideDomain.GetAnimation(downhill, Vector3.back, false, false)); } + [Test] + public void StepsUpTheSlopeAreTakenBack() + { + var slide = new Vector3(0f, -2f, 2f); + var correction = SlopeSlideDomain.RemoveUphill(new Vector3(0.3f, 0.1f, -0.05f), slide); + Assert.AreEqual(0.05f, correction.z, 0.0001f, "the uphill part back downhill"); + Assert.AreEqual(0f, correction.x, 0.0001f, "the sideways step stays"); + Assert.AreEqual(0f, correction.y, 0.0001f, "no height"); + } + + [Test] + public void StepsSidewaysAndDownhillStayFree() + { + var slide = new Vector3(0f, -2f, 2f); + Assert.AreEqual(Vector3.zero, SlopeSlideDomain.RemoveUphill(Vector3.right * 0.1f, slide), "sideways"); + Assert.AreEqual(Vector3.zero, SlopeSlideDomain.RemoveUphill(Vector3.forward * 0.1f, slide), "downhill"); + Assert.AreEqual(Vector3.zero, SlopeSlideDomain.RemoveUphill(Vector3.back * 0.1f, Vector3.down), + "a slide straight down has no uphill"); + } + [Test] public void UphillIsAgainstTheDownhillDirection() { diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs index 813f083e5..b1800cd5a 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs @@ -1,4 +1,5 @@ using Gothic.Core.Const; +using Gothic.Core.Domain.Movement; using UnityEngine; using UnityEngine.XR.Interaction.Toolkit.Locomotion; @@ -10,10 +11,10 @@ namespace Gothic.VR.Interaction.Backends.Xri /// - The ground probe: one ray straight down from the CharacterController's bottom center, once per frame. A sphere /// cast would also touch stair edges and walls beside the feet and report their steep normals. It sees only the /// Default layer (the world mesh and solid VOBs, like the NPCs' ground ray): an NPC, an item or a movable under - /// the feet is no slope - no slide and no blocked jump from a barrel or a monster's back. + /// the feet is no slope - no slide and no blocked jump from a monster's back. /// - The slide is a body transformation queued after XRI's own moves (the stick, gravity): it moves the /// CharacterController along the slope (CharacterController.Move, so walls still stop it) and takes back what the - /// stick moved up the slope in the same frame - sideways and downhill stay free. + /// stick moved up the slope in the same frame (SlopeSlideDomain.RemoveUphill decides how much). /// The CharacterController's slopeLimit (prefab) doesn't decide anything here: Gothic's SLIDE_ANGLE does. /// public class XriSlopeSlide @@ -118,16 +119,10 @@ private void Apply(XRMovableBody body) return; var motion = velocity * Time.deltaTime; - var downhill = new Vector3(velocity.x, 0f, velocity.z); - if (downhill.sqrMagnitude > 0.000001f) - { - downhill.Normalize(); - var moved = body.originTransform.position - _originBeforeMoves; - moved.y = 0f; - var uphill = -Vector3.Dot(moved, downhill); - if (uphill > 0f && moved.magnitude < _maxStickMove) - motion += downhill * uphill; - } + var moved = body.originTransform.position - _originBeforeMoves; + moved.y = 0f; + if (moved.sqrMagnitude < _maxStickMove * _maxStickMove) + motion += SlopeSlideDomain.RemoveUphill(moved, velocity); if (body.constrainedManipulator != null) body.constrainedManipulator.MoveBody(motion); From a56c8fea0d7b33b27df51229b508a3a05ed31425 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:27:23 +0000 Subject: [PATCH 14/31] refactor: a platform must say whether there's ground under the hero and its normal (HeroFallSample) - forgotten, he'd silently never slide or be kept from jumping off steep ground Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs | 5 +++-- .../Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs index 78e415a53..fb2ccc75f 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs @@ -65,7 +65,8 @@ public readonly struct HeroFallSample /// /// Ground straight under the feet (a ray down, not the body's side contacts) - its normal decides a slide - /// (HeroSlideService). false: nothing within the platform's reach below. + /// (HeroSlideService). false: nothing within the platform's reach below. Required: a platform that left it out + /// would silently never slide and never block a jump from steep ground. /// public readonly bool HasGround; @@ -75,7 +76,7 @@ public readonly struct HeroFallSample public HeroFallSample(Vector3 feetPosition, Vector3 forward, bool isGrounded, bool isJumping, bool isClimbing, bool isTransformed, float gravity, float maxFallSpeed, float groundSnapHeight, float runSpeed, - float deltaTime, bool hasGround = false, Vector3 groundNormal = default) + float deltaTime, bool hasGround, Vector3 groundNormal) { FeetPosition = feetPosition; Forward = forward; diff --git a/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs index c99f4a49b..03a519f97 100644 --- a/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs +++ b/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs @@ -52,7 +52,7 @@ private void Tick(float feetY, bool isGrounded, bool isJumping = false, float dt { _feet = new Vector3(_feet.x, feetY, _feet.z) + _moveVelocity * dt; var sample = new HeroFallSample(_feet, _forward, isGrounded, isJumping, false, false, _gravity, - _maxFallSpeed, _groundSnapHeight, _runSpeed, dt); + _maxFallSpeed, _groundSnapHeight, _runSpeed, dt, isGrounded, Vector3.up); switch (_domain.Tick(sample, _safeHeight, out var landing)) { case HeroAirEvent.Landed: From a7beec601b494cf19a195b6c36cc7577bed99814 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:27:31 +0000 Subject: [PATCH 15/31] docs: why SLIDE_ANGLE2 is clamped instead of falling back to the human default - 0 is Gothic's own value Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs b/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs index 6c9fff20d..dc1d9d4e3 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/LedgeRules.cs @@ -67,6 +67,7 @@ public static LedgeRules FromGuildValues(GuildValuesInstance values, int guild) JumpMidHeight = Metres(values.GetJumpMidHeight(guild), defaults.JumpMidHeight), JumpUpHeight = Metres(values.GetJumpUpHeight(guild), defaults.JumpUpHeight), SlideAngle = Degrees(values.GetSlideAngle(guild), defaults.SlideAngle), + // Not Degrees(): 0 is Gothic's own value here (only vertical ground is a wall), not "unset". SlideAngle2 = Mathf.Clamp(values.GetSlideAngle2(guild), 0, 90), ClimbHeadingAngle = Degrees(values.GetClimbHeadingAngle(guild), defaults.ClimbHeadingAngle) }; From 2ccc367850b860b6a57df555d4532fd08d26cf1d Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:27:48 +0000 Subject: [PATCH 16/31] docs: the slope slide decision record - only world ground blocks the jump, an NPC's steep time starts again when it stops, what happens when an NPC can't move mid-slide Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-11-29-slope-slide.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Docs/adr/2026-11-29-slope-slide.md b/Docs/adr/2026-11-29-slope-slide.md index 0814c8517..4309beba1 100644 --- a/Docs/adr/2026-11-29-slope-slide.md +++ b/Docs/adr/2026-11-29-slope-slide.md @@ -13,8 +13,8 @@ In the VR game the hero stood on any slope. Worse, jumping again and again carri 1. **The hero and NPCs slide on ground steeper than their guild's slide angle, with Gothic's two values.** One rule for both, the angles come from the scripts, so mods and monsters bring their own. Flying monsters never slide, like they never fall. 2. **The slide is gravity along the slope, like OpenGothic, but never faster than 6 m/s.** Gothic has no limit; in VR a long slide would get uncomfortably fast. Not chosen: a fixed slide speed (the slide would feel the same on 46 and 80 degrees). -3. **No jump from ground steeper than the slide angle, at once, also before a slide has begun.** This is the fix for climbing a slope by jumping. Not chosen: blocking the jump only while sliding (a quick jump right after landing would still work). -4. **The slope must be steep for a fifth of a second before the slide begins, and walkable for a tenth before it ends.** A single steep triangle of a rock or a mesh seam doesn't make anybody slide. Stairs don't either: only the ground straight under the feet counts, not the step edges beside them. +3. **No jump from ground steeper than the slide angle, at once, also before a slide has begun.** This is the fix for climbing a slope by jumping. Only the world and solid objects count as ground here: standing on an NPC, a monster or an item never blocks the jump. Not chosen: blocking the jump only while sliding (a quick jump right after landing would still work). +4. **The slope must be steep for a fifth of a second before the slide begins, and walkable for a tenth before it ends.** A single steep triangle of a rock or a mesh seam doesn't make anybody slide. Stairs don't either: only the ground straight under the feet counts, not the step edges beside them. For NPCs the time counts only while they walk over the steep ground: when they stop, it starts again. 5. **While the hero slides, the stick can't walk him up the slope; sideways and downhill stay free.** In Gothic the player has no control at all while sliding. In VR steering sideways helps to stay on the slope and keeps the player in charge of his view. Not chosen: no stick at all (a sudden loss of control in VR), or the stick fighting the slide (he could walk up again). 6. **A slide is no fall.** Sliding down a 50 m hillside costs no hit points; only when he slides off an edge does a normal fall begin there, with its damage counted from the edge. The scripts see a standing hero while he slides (like OpenGothic), so no footsteps and no "running" for the NPCs. 7. **A slide that gets nowhere (a wall, a crevice, a rock) ends, and he stands there.** No new slide until he moved half a meter away or stood on walkable ground. Otherwise he would be stuck in the slide pose. @@ -24,6 +24,7 @@ In the VR game the hero stood on any slope. Worse, jumping again and again carri ## Consequences - Nothing new is saved: a loaded game starts standing. +- An NPC that dies, is knocked out or starts swimming mid-slide stops sliding at once. A dead or unconscious body stays as its death or knockout left it; any other gets its physics back. A fall or a climb still ends on the ground first, without the landing or idle animations. - Not checked while climbing, swimming or wading, lying after a fall, after a teleport, while sitting or using something, or while transformed into a monster: the transformed hero still stands on any slope (his monster's own angle isn't applied yet). - The hero with no slide animation in his model (a mod) still slides, with his normal animations. - Flat mode can feed the same rules from its own controller once it runs again. From 5502466380cb8a89d6cc71b0c013c9337ba20d36 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:29:12 +0000 Subject: [PATCH 17/31] style: drop VrHeroLocomotion's unused Domain.Movement using - the slide animation comes from HeroSlideService Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs index f20927145..f72ae941d 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroLocomotion.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Gothic.Core; using Gothic.Core.Const; -using Gothic.Core.Domain.Movement; using Gothic.Core.Logging; using Gothic.Core.Models.Container; using Gothic.Core.Models.Movement; From ff963735efc630d935bf0ea2360aac497abb857a Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 05:32:17 +0000 Subject: [PATCH 18/31] chore: meta files of the slope slide scripts (generated by Unity on import) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Domain/Movement/SlopeSlideDomain.cs.meta | 2 ++ .../Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs.meta | 2 ++ .../Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs.meta | 2 ++ .../Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs.meta | 2 ++ .../Scripts/Services/Movement/HeroSlideService.cs.meta | 2 ++ .../Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs.meta | 2 ++ .../Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs.meta | 2 ++ 7 files changed, 14 insertions(+) create mode 100644 Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs.meta create mode 100644 Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs.meta create mode 100644 Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs.meta diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs.meta b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs.meta new file mode 100644 index 000000000..16687b0da --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/SlopeSlideDomain.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e5003fdee9c451248a4db0b13e147a21 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs.meta new file mode 100644 index 000000000..8449705a3 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d7cd18f8c7c5aca43b70e31ae8428f5e \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs.meta new file mode 100644 index 000000000..a8b32459f --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideEvent.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fc9052bee6bc9124398f570b910b9f31 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs.meta new file mode 100644 index 000000000..e464d1a3d --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/SlopeSlideState.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c683d48cf801d5a4abd0368187d4c3b7 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs.meta new file mode 100644 index 000000000..ae142d1a9 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: dfbfd1aade0e66e48bc9f58d96fdeca5 \ No newline at end of file diff --git a/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs.meta b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs.meta new file mode 100644 index 000000000..4674530f8 --- /dev/null +++ b/Assets/Gothic-Tests/EditMode/Movement/SlopeSlideDomainTest.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6b6801f233aa21744a753fc45821ac0d \ No newline at end of file diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs.meta b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs.meta new file mode 100644 index 000000000..85e2c3ff9 --- /dev/null +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0495b2ba36390594595b200ff71e33fe \ No newline at end of file From f1a03398473f90c3f1d475ad152221400b96979d Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:02:30 +0000 Subject: [PATCH 19/31] refactor: an NPC's slide is its own worker (NpcSlopeSlide) owned by NpcJumpFall - start, tick, wall look-ahead and the hand-off into a fall; what fall, climb and slide all ask of the body (rest height, guild values, ground below, physics) is NpcMoveBody Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/NpcJumpFall.cs | 216 +++++------------- .../Scripts/Adapters/Npc/NpcMoveBody.cs | 108 +++++++++ .../Scripts/Adapters/Npc/NpcSlopeSlide.cs | 160 +++++++++++++ 3 files changed, 320 insertions(+), 164 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index b853b1fd5..71e295be0 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -1,5 +1,4 @@ using Gothic.Core.Const; -using Gothic.Core.Domain.Movement; using Gothic.Core.Domain.Npc; using Gothic.Core.Extensions; using Gothic.Core.Logging; @@ -10,7 +9,6 @@ using Gothic.Core.Services.Config; using Gothic.Core.Services.Movement; using Gothic.Core.Services.Npc; -using Gothic.Core.Services.World; using Reflex.Attributes; using UnityEngine; using Logger = Gothic.Core.Logging.Logger; @@ -24,10 +22,8 @@ namespace Gothic.Core.Adapters.Npc /// Fall damage like the engine: FALLDOWN_DAMAGE per meter above FALLDOWN_HEIGHT (Species.d), minus PROT_FALL. /// - Climbing (chasing NPCs only, called by AttackPlayAni): a ledge in front between STEP_HEIGHT and JUMPMID_HEIGHT /// is climbed with the JumpUpLow/JumpUpMid animations - only if the model has them (most monsters don't). - /// - Sliding (SlopeSlideDomain, the guild's SLIDE_ANGLE): ground steeper than it, going down or across it, slides - /// the NPC down with S_SLIDE / S_SLIDEB, BS_STAND, until walkable ground (it walks on), a block, or an edge (it - /// falls). Walking up such a slope stays walking (ours - Gothic stops it like at a wall): waypoint routes over - /// steep ground don't loop between walking up and sliding down. + /// - Sliding (NpcSlopeSlide, the guild's SLIDE_ANGLE): down or across steep ground with S_SLIDE / S_SLIDEB, until + /// walkable ground (it walks on), a block, or an edge (it falls). /// Can't move any more (dead, unconscious, swimming - NpcFallDomain.CanMove): a fall still lands and a climb still /// reaches its end (nobody hangs in the air), a slide ends at once (it's on the ground) - with no more of our /// animations, the death or the swimming takes over. Dead and unconscious bodies stay kinematic (their domains @@ -35,7 +31,9 @@ namespace Gothic.Core.Adapters.Npc /// Lives on the NPC (added on demand), not in an AI action: ZS_Attack_Loop clears the AI queue every ~2 s, an action /// would leave the NPC hanging in the air. /// Not saved - a loaded NPC stands on the ground anyway. - /// The rules live elsewhere: climbing values and the ledge probe in LedgeService, falling in NpcFallDomain. + /// The rules live elsewhere: climbing values and the ledge probe in LedgeService, falling in NpcFallDomain, sliding + /// in SlopeSlideDomain. This class keeps the state switch, the fall and the landing; the slide is NpcSlopeSlide's, + /// and what they all ask of the body (rest height, guild values, ground below, physics) NpcMoveBody's. /// Disabled while nothing happens (standing, far from the hero); Get/Wake enable it again when the NPC walks, attacks, /// is hit or pushed. /// @@ -44,18 +42,11 @@ public class NpcJumpFall : MonoBehaviour, INpcJumpFall [Inject] private readonly GameStateService _gameStateService; [Inject] private readonly ConfigService _configService; [Inject] private readonly AnimationService _animationService; - [Inject] private readonly PhysicsService _physicsService; [Inject] private readonly LedgeService _ledgeService; [Inject] private readonly NpcNavMeshService _npcNavMeshService; - private const float _gravity = 9.81f; private const float _maxFallSpeedH = 6f; private const float _outOfWorldFallHeight = 100f; - private const float _groundProbeExtra = 0.1f; - // m the wall ray of a fall or slide reaches beyond this frame's move. - private const float _wallLookAhead = 0.3f; - // A slide's wall ray hit with a normal.y above this (~80 deg) is the rising slope beside it, not a wall. - private const float _slideWallMaxNormalY = 0.17f; private const float _climbMinSeconds = 0.6f; private const float _climbMaxSeconds = 2f; private const float _climbRisePart = 0.65f; @@ -81,6 +72,8 @@ private enum State } private NpcContainer _npc; + private NpcMoveBody _body; + private NpcSlopeSlide _slide; private State _state; private Vector3 _previousPosition; private bool _hasPreviousPosition; @@ -94,10 +87,6 @@ private enum State // Thrown by a spell - lands lying and gets up. private bool _isThrown; - // Sliding down a slope. - private readonly SlopeSlideState _slide = new(); - private string _slideAnimName; - // Landing / climbing: a sequence of animations played one after another. private string[] _sequence; private float[] _sequenceDurations; @@ -131,7 +120,8 @@ public static NpcJumpFall Get(NpcContainer npc) if (!npc.Go.TryGetComponent(out var jumpFall)) jumpFall = npc.Go.AddComponent(); - jumpFall._npc = npc; + if (jumpFall._npc != npc) + jumpFall.Bind(npc); jumpFall.WakeUp(); return jumpFall; } @@ -157,6 +147,13 @@ private void Awake() this.Inject(); } + private void Bind(NpcContainer npc) + { + _npc = npc; + _body = new NpcMoveBody(npc, transform).Inject(); + _slide = new NpcSlopeSlide(_body); + } + private void Update() { if (_npc?.PrefabProps?.AnimationSystem == null) @@ -190,16 +187,11 @@ private void Update() _hasPreviousPosition = true; } - private float RestHeight => _npc.PrefabProps.AnimationSystem.RestRootHeight; - private int Guild => _npc.Instance.GetValuesGuild(); + private float RestHeight => _body.RestHeight; - private LedgeRules Rules => _ledgeService.GetRules(Guild); + private LedgeRules Rules => _body.Rules; - private bool CanMove() => NpcFallDomain.CanMove(_gameStateService.GuildValues, _npc); - - // NpcDeathDomain / NpcKnockoutDomain made the body kinematic: it stays so. - private bool IsDown => _npc.Props.BodyState is VmGothicEnums.BodyState.BsDead - or VmGothicEnums.BodyState.BsUnconscious; + private bool CanMove() => _body.CanMove(); /// /// Walked off a ledge: start falling. False if the NPC stands still or isn't checked (far from the hero, @@ -213,7 +205,7 @@ private bool CheckFall() // The slide's steep time counts only while it moves over steep ground - not in bursts with breaks between. if (!CanMove() || !IsNearHero()) { - SlopeSlideDomain.Hold(_slide, Feet); + _slide.Hold(); return false; } @@ -222,13 +214,14 @@ private bool CheckFall() moved.y = 0f; if (moved.sqrMagnitude < 0.0001f) { - SlopeSlideDomain.Rest(_slide, Feet); + _slide.Rest(); return false; } - if (TryGetGround(transform.position, out var ground)) + if (_body.TryGetGround(transform.position, out var ground)) { - CheckSlide(ground, moved); + if (_slide.TryStart(ground, moved)) + Enter(State.Sliding); return true; } @@ -236,129 +229,36 @@ private bool CheckFall() return true; } - private Vector3 Feet => transform.position - Vector3.up * RestHeight; - - /// - /// Ground within STEP_HEIGHT under the feet of a root at position - a ray straight down, so stair risers and - /// walls beside the NPC don't count. - /// - private bool TryGetGround(Vector3 position, out RaycastHit hit) - { - var probe = RestHeight + Rules.StepHeight + _groundProbeExtra; - return Physics.Raycast(position, Vector3.down, out hit, probe, 1 << Constants.DefaultLayer, - QueryTriggerInteraction.Ignore); - } - - /// - /// Steep ground under a moving NPC long enough: it slides - not while it walks up the slope. - /// - private void CheckSlide(RaycastHit ground, Vector3 moved) - { - if (SlopeSlideDomain.IsMovingUphill(moved, ground.normal)) - { - SlopeSlideDomain.Hold(_slide, Feet); - return; - } - - if (SlopeSlideDomain.Tick(_slide, Feet, true, ground.normal, Rules, _gravity, Time.deltaTime) == - SlopeSlideEvent.Started) - StartSlide(); - } - - private void StartSlide() + private void Enter(State state) { enabled = true; - _state = State.Sliding; - _npc.Props.BodyState = VmGothicEnums.BodyState.BsStand; - _physicsService.DisablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.StopAllAnimations(); - _slideAnimName = null; - PlaySlideAnimation(); - - Logger.Log($"[NpcJumpFall] {_npc.Go.name} slides down a {_slide.GroundAngle:F0} deg slope (SLIDE_ANGLE " + - $"{Rules.SlideAngle:F0}).", LogCat.Ai); + _state = state; } /// - /// Down the slope at the slide's speed, along walls, held on the ground below. No ground: it falls on with - /// the slide's speed (a fall from here - the slide itself is no drop). + /// Can't move any more: the slide ends at once (it's on the ground). Off an edge it falls on with the slide's + /// speed. /// private void TickSlide() { if (!CanMove()) { - SlopeSlideDomain.Hold(_slide, Feet); - EndSlide("can't move"); - return; - } - - var dt = Time.deltaTime; - var position = transform.position; - var move = _slide.Velocity * dt; - var moveH = new Vector3(move.x, 0f, move.z); - // Against a wall: the slide gets nowhere and ends as blocked. Across a slope the ray may hit the slope - // rising beside the NPC - only near-vertical hits are walls. - if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, out var wall, - moveH.magnitude + _wallLookAhead, 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore) && - wall.normal.y <= _slideWallMaxNormalY) - move = Vector3.zero; - - var next = position + move; - if (!TryGetGround(next, out var ground)) - { - var velocity = _slide.Velocity; - SlopeSlideDomain.Hold(_slide, Feet); - StopSlideAnimation(); - Logger.Log($"[NpcJumpFall] {_npc.Go.name} slides off an edge.", LogCat.Ai); - transform.position = next; - StartFall(new Vector3(velocity.x, 0f, velocity.z)); - _fallVelocityY = Mathf.Min(velocity.y, 0f); + _slide.Stop("can't move"); + Finish(); return; } - transform.position = ground.point + Vector3.up * RestHeight; - var slideEvent = SlopeSlideDomain.Tick(_slide, ground.point, true, ground.normal, Rules, _gravity, dt); - if (slideEvent != SlopeSlideEvent.None) + switch (_slide.Tick(out var fallVelocity)) { - EndSlide(slideEvent == SlopeSlideEvent.Blocked ? "blocked" : "walkable ground"); - return; + case SlopeSlideEvent.LostGround: + StartFall(new Vector3(fallVelocity.x, 0f, fallVelocity.z)); + _fallVelocityY = Mathf.Min(fallVelocity.y, 0f); + break; + case SlopeSlideEvent.Stopped: + case SlopeSlideEvent.Blocked: + Finish(); + break; } - - PlaySlideAnimation(); - } - - /// - /// S_SLIDE facing downhill, S_SLIDEB backwards (S_SLIDE if the model has no S_SLIDEB) - again when the - /// direction changed or Npc_ClearAIQueue stopped it. - /// - private void PlaySlideAnimation() - { - var animationName = SlopeSlideDomain.GetAnimation(_slide.Velocity, transform.forward, - HasTrack(DaedalusConst.AniSlideBack), HasTrack(DaedalusConst.AniSlide)); - if (animationName == null) - return; - - var animationSystem = _npc.PrefabProps.AnimationSystem; - if (animationName == _slideAnimName && animationSystem.IsPlaying(animationName)) - return; - - StopSlideAnimation(); - _slideAnimName = animationName; - animationSystem.PlayAnimation(animationName); - } - - private void StopSlideAnimation() - { - if (_slideAnimName != null) - _npc.PrefabProps.AnimationSystem.StopAnimation(_slideAnimName); - _slideAnimName = null; - } - - private void EndSlide(string reason) - { - Logger.Log($"[NpcJumpFall] {_npc.Go.name} slide ended ({reason}) after " + - $"{SlopeSlideDomain.GetSlidDistance(_slide, Feet):F1} m.", LogCat.Ai); - Finish(); } private bool IsNearHero() @@ -371,15 +271,13 @@ private bool IsNearHero() private void StartFall(Vector3 velocityH) { - enabled = true; - _state = State.Falling; + Enter(State.Falling); _fallVelocityH = Vector3.ClampMagnitude(velocityH, _maxFallSpeedH); _fallVelocityY = 0f; _fallStartFeetY = transform.position.y - RestHeight; _npc.Props.BodyState = VmGothicEnums.BodyState.BsFall; - _physicsService.DisablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.StopAllAnimations(); + _body.TakeOver(); _fallAnimName = "S_FALLDN"; PlayIfExists(_fallAnimName); @@ -408,12 +306,13 @@ public bool TryThrow(Vector3 velocityH, float velocityY) private void TickFall() { var dt = Time.deltaTime; - _fallVelocityY -= _gravity * dt; + _fallVelocityY -= NpcMoveBody.Gravity * dt; var position = transform.position; var moveH = _fallVelocityH * dt; - if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, moveH.magnitude + _wallLookAhead, - 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore)) + if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, + moveH.magnitude + NpcMoveBody.WallLookAhead, 1 << Constants.DefaultLayer, + QueryTriggerInteraction.Ignore)) { // Against a wall: slide down it. _fallVelocityH = Vector3.zero; @@ -503,8 +402,7 @@ public bool TryStartClimb(Vector3 direction) var height = ledge.Height; _climbFrom = position; _climbTo = ledge.StandPoint + Vector3.up * RestHeight; - _physicsService.DisablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.StopAllAnimations(); + _body.TakeOver(); transform.rotation = Quaternion.LookRotation(direction); _npc.Props.BodyState = VmGothicEnums.BodyState.BsJump; _isLadder = false; @@ -553,8 +451,7 @@ public bool TryStartLadder(Vector3 ladderStart, Vector3 ladderEnd) if (flat.sqrMagnitude > 0.0001f) transform.rotation = Quaternion.LookRotation(flat); - _physicsService.DisablePhysicsForNpc(_npc.PrefabProps); - _npc.PrefabProps.AnimationSystem.StopAllAnimations(); + _body.TakeOver(); _npc.Props.BodyState = VmGothicEnums.BodyState.BsClimb; StartSequence(State.Climbing, sequence.ToArray()); // Without the animations (other models): a plain climb at ladder speed. @@ -719,8 +616,7 @@ private void TickLadder(float t) private void StartSequence(State state, string[] animations) { - enabled = true; - _state = state; + Enter(state); _sequence = animations; _sequenceDurations = new float[animations.Length]; _stateDuration = 0f; @@ -775,7 +671,7 @@ private void Finish() _npc.PrefabProps.AnimationSystem.StopAnimation(_sequence[_sequenceIndex]); if (_fallAnimName != null) _npc.PrefabProps.AnimationSystem.StopAnimation(_fallAnimName); - StopSlideAnimation(); + _slide.StopAnimation(); _state = State.None; _isLadder = false; @@ -784,21 +680,13 @@ private void Finish() if (_npc.Props.BodyState is VmGothicEnums.BodyState.BsFall or VmGothicEnums.BodyState.BsJump or VmGothicEnums.BodyState.BsClimb) _npc.Props.BodyState = VmGothicEnums.BodyState.BsStand; - if (!IsDown) - _physicsService.EnablePhysicsForNpc(_npc.PrefabProps); + _body.Release(); if (CanMove()) _npc.PrefabProps.AnimationSystem.PlayIdleAnimation(); } - private void PlayIfExists(string animationName) - { - if (HasTrack(animationName)) - _npc.PrefabProps.AnimationSystem.PlayAnimation(animationName); - } + private void PlayIfExists(string animationName) => _body.PlayIfExists(animationName); - private bool HasTrack(string animationName) - { - return _animationService.GetTrack(animationName, _npc.Props.MdsNameBase, _npc.Props.MdsNameOverlay) != null; - } + private bool HasTrack(string animationName) => _body.HasTrack(animationName); } } diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs new file mode 100644 index 000000000..74661f9f3 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs @@ -0,0 +1,108 @@ +using Gothic.Core.Adapters.Animations; +using Gothic.Core.Const; +using Gothic.Core.Domain.Npc; +using Gothic.Core.Extensions; +using Gothic.Core.Models.Container; +using Gothic.Core.Models.Movement; +using Gothic.Core.Models.Vm; +using Gothic.Core.Services; +using Gothic.Core.Services.Movement; +using Gothic.Core.Services.Npc; +using Gothic.Core.Services.World; +using Reflex.Attributes; +using UnityEngine; + +namespace Gothic.Core.Adapters.Npc +{ + /// + /// The NPC's body as NpcJumpFall and its workers (NpcSlopeSlide, NpcLedgeClimb, NpcAnimationSequence) move it: + /// its rest height, its guild's ledge and slide values, whether it can move, its animations, the ground below. + /// Created by NpcJumpFall per NPC (new().Inject()) and shared with its workers - one place for what they all ask. + /// + public class NpcMoveBody + { + [Inject] private readonly GameStateService _gameStateService; + [Inject] private readonly AnimationService _animationService; + [Inject] private readonly PhysicsService _physicsService; + [Inject] private readonly LedgeService _ledgeService; + + /// + /// m/s^2 of a fall and a slide. + /// + public const float Gravity = 9.81f; + + /// + /// m the wall ray of a fall or slide reaches beyond this frame's move. + /// + public const float WallLookAhead = 0.3f; + + private const float _groundProbeExtra = 0.1f; + + public readonly NpcContainer Npc; + public readonly Transform Transform; + + public NpcMoveBody(NpcContainer npc, Transform transform) + { + Npc = npc; + Transform = transform; + } + + public string Name => Npc.Go.name; + + public AnimationSystem Animations => Npc.PrefabProps.AnimationSystem; + + public float RestHeight => Animations.RestRootHeight; + + public Vector3 Feet => Transform.position - Vector3.up * RestHeight; + + public LedgeRules Rules => _ledgeService.GetRules(Npc.Instance.GetValuesGuild()); + + public bool CanMove() => NpcFallDomain.CanMove(_gameStateService.GuildValues, Npc); + + /// + /// NpcDeathDomain / NpcKnockoutDomain made the body kinematic: it stays so. + /// + public bool IsDown => Npc.Props.BodyState is VmGothicEnums.BodyState.BsDead + or VmGothicEnums.BodyState.BsUnconscious; + + /// + /// Ground within STEP_HEIGHT under the feet of a root at position - a ray straight down, so stair risers and + /// walls beside the NPC don't count. + /// + public bool TryGetGround(Vector3 position, out RaycastHit hit) + { + var probe = RestHeight + Rules.StepHeight + _groundProbeExtra; + return Physics.Raycast(position, Vector3.down, out hit, probe, 1 << Constants.DefaultLayer, + QueryTriggerInteraction.Ignore); + } + + /// + /// A fall, climb or slide takes the body: no physics, none of the other animations. + /// + public void TakeOver() + { + _physicsService.DisablePhysicsForNpc(Npc.PrefabProps); + Animations.StopAllAnimations(); + } + + /// + /// The move is over: physics again - unless dead or unconscious (kinematic, as their domains left it). + /// + public void Release() + { + if (!IsDown) + _physicsService.EnablePhysicsForNpc(Npc.PrefabProps); + } + + public void PlayIfExists(string animationName) + { + if (HasTrack(animationName)) + Animations.PlayAnimation(animationName); + } + + public bool HasTrack(string animationName) + { + return _animationService.GetTrack(animationName, Npc.Props.MdsNameBase, Npc.Props.MdsNameOverlay) != null; + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs new file mode 100644 index 000000000..38b7e8756 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs @@ -0,0 +1,160 @@ +using Gothic.Core.Const; +using Gothic.Core.Domain.Movement; +using Gothic.Core.Logging; +using Gothic.Core.Models.Movement; +using Gothic.Core.Models.Vm; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.Core.Adapters.Npc +{ + /// + /// An NPC's slide down a steep slope (SlopeSlideDomain, the guild's SLIDE_ANGLE), worker of NpcJumpFall: going down + /// or across ground steeper than it slides the NPC down with S_SLIDE / S_SLIDEB, BS_STAND, until walkable ground, + /// a block, or an edge (NpcJumpFall's fall takes over with the slide's speed). Walking up such a slope stays + /// walking (ours - Gothic stops it like at a wall): waypoint routes over steep ground don't loop between walking up + /// and sliding down. + /// Moves the body itself (a wall ray ahead, held on the ground below) - NpcJumpFall decides the state. + /// + public class NpcSlopeSlide + { + // A wall ray hit with a normal.y above this (~80 deg) is the rising slope beside it, not a wall. + private const float _wallMaxNormalY = 0.17f; + + private readonly NpcMoveBody _body; + private readonly SlopeSlideState _state = new(); + private string _animationName; + + public NpcSlopeSlide(NpcMoveBody body) + { + _body = body; + } + + /// + /// Not checked (can't move, far from the hero) or walking up the slope: the steep time starts again. + /// + public void Hold() + { + SlopeSlideDomain.Hold(_state, _body.Feet); + } + + /// + /// Stands still: the steep time starts again, a block stays (SlopeSlideDomain.Rest). + /// + public void Rest() + { + SlopeSlideDomain.Rest(_state, _body.Feet); + } + + /// + /// Steep ground under a moving NPC long enough: the slide begins (the body taken, its animation playing) - not + /// while it walks up the slope. moved: its horizontal move this frame. + /// + public bool TryStart(RaycastHit ground, Vector3 moved) + { + if (SlopeSlideDomain.IsMovingUphill(moved, ground.normal)) + { + Hold(); + return false; + } + + if (SlopeSlideDomain.Tick(_state, _body.Feet, true, ground.normal, _body.Rules, + NpcMoveBody.Gravity, Time.deltaTime) != SlopeSlideEvent.Started) + return false; + + _body.Npc.Props.BodyState = VmGothicEnums.BodyState.BsStand; + _body.TakeOver(); + _animationName = null; + PlayAnimation(); + + Logger.Log($"[NpcJumpFall] {_body.Name} slides down a {_state.GroundAngle:F0} deg slope (SLIDE_ANGLE " + + $"{_body.Rules.SlideAngle:F0}).", LogCat.Ai); + return true; + } + + /// + /// Down the slope at the slide's speed, along walls, held on the ground below. None: it slides on. Stopped / + /// Blocked: it stands (logged). LostGround: off an edge, it's moved there and falls on with fallVelocity (a + /// fall from here - the slide itself is no drop). + /// + public SlopeSlideEvent Tick(out Vector3 fallVelocity) + { + fallVelocity = Vector3.zero; + var dt = Time.deltaTime; + var position = _body.Transform.position; + var move = _state.Velocity * dt; + var moveH = new Vector3(move.x, 0f, move.z); + // Against a wall: the slide gets nowhere and ends as blocked. Across a slope the ray may hit the slope + // rising beside the NPC - only near-vertical hits are walls. + if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, out var wall, + moveH.magnitude + NpcMoveBody.WallLookAhead, 1 << Constants.DefaultLayer, + QueryTriggerInteraction.Ignore) && wall.normal.y <= _wallMaxNormalY) + move = Vector3.zero; + + var next = position + move; + if (!_body.TryGetGround(next, out var ground)) + { + fallVelocity = _state.Velocity; + Hold(); + StopAnimation(); + Logger.Log($"[NpcJumpFall] {_body.Name} slides off an edge.", LogCat.Ai); + _body.Transform.position = next; + return SlopeSlideEvent.LostGround; + } + + _body.Transform.position = ground.point + Vector3.up * _body.RestHeight; + var slideEvent = SlopeSlideDomain.Tick(_state, ground.point, true, ground.normal, _body.Rules, + NpcMoveBody.Gravity, dt); + if (slideEvent != SlopeSlideEvent.None) + { + LogEnd(slideEvent == SlopeSlideEvent.Blocked ? "blocked" : "walkable ground"); + return slideEvent; + } + + PlayAnimation(); + return SlopeSlideEvent.None; + } + + /// + /// The NPC can't move any more: the slide ends at once (logged). + /// + public void Stop(string reason) + { + Hold(); + LogEnd(reason); + } + + public void StopAnimation() + { + if (_animationName != null) + _body.Animations.StopAnimation(_animationName); + _animationName = null; + } + + /// + /// S_SLIDE facing downhill, S_SLIDEB backwards (S_SLIDE if the model has no S_SLIDEB) - again when the + /// direction changed or Npc_ClearAIQueue stopped it. + /// + private void PlayAnimation() + { + var animationName = SlopeSlideDomain.GetAnimation(_state.Velocity, _body.Transform.forward, + _body.HasTrack(DaedalusConst.AniSlideBack), _body.HasTrack(DaedalusConst.AniSlide)); + if (animationName == null) + return; + + var animations = _body.Animations; + if (animationName == _animationName && animations.IsPlaying(animationName)) + return; + + StopAnimation(); + _animationName = animationName; + animations.PlayAnimation(animationName); + } + + private void LogEnd(string reason) + { + Logger.Log($"[NpcJumpFall] {_body.Name} slide ended ({reason}) after " + + $"{SlopeSlideDomain.GetSlidDistance(_state, _body.Feet):F1} m.", LogCat.Ai); + } + } +} From 7aaa011c48b029555e4eb0b612fce5290f882f88 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:04:58 +0000 Subject: [PATCH 20/31] refactor: an NPC's ledge and ladder climbs are their own worker (NpcLedgeClimb), the landing's and climbs' animations one after another NpcAnimationSequence - NpcJumpFall keeps the state switch, the fall and the landing Co-Authored-By: Claude Opus 5.5 --- .../Adapters/Npc/NpcAnimationSequence.cs | 105 ++++++ .../Scripts/Adapters/Npc/NpcJumpFall.cs | 347 ++---------------- .../Scripts/Adapters/Npc/NpcLedgeClimb.cs | 319 ++++++++++++++++ 3 files changed, 452 insertions(+), 319 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs new file mode 100644 index 000000000..047def661 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs @@ -0,0 +1,105 @@ +using UnityEngine; + +namespace Gothic.Core.Adapters.Npc +{ + /// + /// Animations played on an NPC one after another, each for its own duration - a landing (NpcJumpFall) or a climb + /// (NpcLedgeClimb). Animations the model doesn't have are skipped. Can't move any more (died, swimming): the rest + /// plays none of them (the death's or swimming's animations take over), the time still runs to the end. + /// + public class NpcAnimationSequence + { + private readonly NpcMoveBody _body; + + public NpcAnimationSequence(NpcMoveBody body) + { + _body = body; + } + + public string[] Animations { get; private set; } + + /// + /// s per animation, 0 for one the model doesn't have. + /// + public float[] Durations { get; private set; } + + /// + /// The animation playing now; Animations.Length when all are done. + /// + public int Index { get; private set; } + + /// + /// s since the current animation began. + /// + public float AnimationTime { get; private set; } + + /// + /// s since the sequence began. + /// + public float Elapsed { get; private set; } + + /// + /// s the whole sequence lasts - the sum of the animations, a climb may set its own. + /// + public float Duration { get; set; } + + public bool IsDone => Elapsed >= Duration; + + /// + /// 0..1 of Duration. + /// + public float Progress => Mathf.Clamp01(Elapsed / Duration); + + public void Start(string[] animations) + { + Animations = animations; + Durations = new float[animations.Length]; + Duration = 0f; + for (var i = 0; i < animations.Length; i++) + { + Durations[i] = _body.HasTrack(animations[i]) + ? _body.Animations.GetAnimationDuration(animations[i]) + : 0f; + Duration += Durations[i]; + } + + Index = -1; + AnimationTime = 0f; + Elapsed = 0f; + Next(); + } + + public void Tick(float deltaTime) + { + Elapsed += deltaTime; + AnimationTime += deltaTime; + if (Index < Animations.Length && AnimationTime >= Durations[Index]) + Next(); + } + + /// + /// Stops the animation playing now - the sequence is over. + /// + public void Stop() + { + if (Animations != null && Index >= 0 && Index < Animations.Length) + _body.Animations.StopAnimation(Animations[Index]); + Animations = null; + } + + private void Next() + { + if (Index >= 0 && Index < Animations.Length) + _body.Animations.StopAnimation(Animations[Index]); + + Index++; + AnimationTime = 0f; + while (Index < Animations.Length && Durations[Index] <= 0f) + Index++; + + // Can't move any more: the move ends without our animations (the death's or swimming's play). + if (Index < Animations.Length && _body.CanMove()) + _body.Animations.PlayAnimation(Animations[Index]); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index 71e295be0..df362b8f1 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -7,8 +7,6 @@ using Gothic.Core.Models.Vm; using Gothic.Core.Services; using Gothic.Core.Services.Config; -using Gothic.Core.Services.Movement; -using Gothic.Core.Services.Npc; using Reflex.Attributes; using UnityEngine; using Logger = Gothic.Core.Logging.Logger; @@ -16,12 +14,12 @@ namespace Gothic.Core.Adapters.Npc { /// - /// V1: NPCs fall off ledges and climb onto ledges like the engine. + /// V1: NPCs fall off ledges, climb onto ledges and slide down steep slopes like the engine. /// - Falling: no ground within STEP_HEIGHT below the feet -> S_FALLDN (S_FALL when deeper), the direction and speed /// of the run are kept (no steering in the air), landing T_FALLDN_2_STAND or T_FALL_2_FALLEN + T_FALLEN_2_STAND. /// Fall damage like the engine: FALLDOWN_DAMAGE per meter above FALLDOWN_HEIGHT (Species.d), minus PROT_FALL. - /// - Climbing (chasing NPCs only, called by AttackPlayAni): a ledge in front between STEP_HEIGHT and JUMPMID_HEIGHT - /// is climbed with the JumpUpLow/JumpUpMid animations - only if the model has them (most monsters don't). + /// - Climbing (NpcLedgeClimb): a chasing NPC climbs a ledge in front between STEP_HEIGHT and JUMPMID_HEIGHT with + /// the JumpUpLow/JumpUpMid animations (only if the model has them), a NavMesh ladder link with the ladder ones. /// - Sliding (NpcSlopeSlide, the guild's SLIDE_ANGLE): down or across steep ground with S_SLIDE / S_SLIDEB, until /// walkable ground (it walks on), a block, or an edge (it falls). /// Can't move any more (dead, unconscious, swimming - NpcFallDomain.CanMove): a fall still lands and a climb still @@ -32,8 +30,9 @@ namespace Gothic.Core.Adapters.Npc /// would leave the NPC hanging in the air. /// Not saved - a loaded NPC stands on the ground anyway. /// The rules live elsewhere: climbing values and the ledge probe in LedgeService, falling in NpcFallDomain, sliding - /// in SlopeSlideDomain. This class keeps the state switch, the fall and the landing; the slide is NpcSlopeSlide's, - /// and what they all ask of the body (rest height, guild values, ground below, physics) NpcMoveBody's. + /// in SlopeSlideDomain. This class keeps the state switch, the fall and the landing; its workers do the rest: the + /// slide NpcSlopeSlide, the climbs NpcLedgeClimb, the landing's and climbs' animations NpcAnimationSequence, what + /// they all ask of the body (rest height, guild values, ground below, physics) NpcMoveBody. /// Disabled while nothing happens (standing, far from the hero); Get/Wake enable it again when the NPC walks, attacks, /// is hit or pushed. /// @@ -41,22 +40,9 @@ public class NpcJumpFall : MonoBehaviour, INpcJumpFall { [Inject] private readonly GameStateService _gameStateService; [Inject] private readonly ConfigService _configService; - [Inject] private readonly AnimationService _animationService; - [Inject] private readonly LedgeService _ledgeService; - [Inject] private readonly NpcNavMeshService _npcNavMeshService; private const float _maxFallSpeedH = 6f; private const float _outOfWorldFallHeight = 100f; - private const float _climbMinSeconds = 0.6f; - private const float _climbMaxSeconds = 2f; - private const float _climbRisePart = 0.65f; - private const float _ladderSpeed = 1.5f; - private const float _ladderExtraSeconds = 0.6f; - // HUMANS.MDS: one climb cycle t_Ladder_S0_2_S1 (frames 15-45), down = the same played backwards (aliases R). - private static readonly string[] _ladderUp = { "T_LADDER_STAND_2_S0", "T_LADDER_S0_2_S1", "T_LADDER_S1_2_STAND" }; - private static readonly string[] _ladderDown = { "T_LADDER_STAND_2_S1", "T_LADDER_S1_2_S0", "T_LADDER_S0_2_STAND" }; - // Fallback if the climb cycle doesn't lift the root bone itself (0.9 climbed a few cycles too many). - private const float _ladderMetersPerCycle = 1.2f; // Unloaded vobs (bridges, platforms) far from the hero have no colliders yet - nobody falls through them there. private const float _fallCheckMaxHeroDistance = 40f; // Standing (or far from the hero) this long: the component sleeps until Get/Wake. @@ -74,6 +60,8 @@ private enum State private NpcContainer _npc; private NpcMoveBody _body; private NpcSlopeSlide _slide; + private NpcAnimationSequence _sequence; + private NpcLedgeClimb _climb; private State _state; private Vector3 _previousPosition; private bool _hasPreviousPosition; @@ -87,30 +75,6 @@ private enum State // Thrown by a spell - lands lying and gets up. private bool _isThrown; - // Landing / climbing: a sequence of animations played one after another. - private string[] _sequence; - private float[] _sequenceDurations; - private int _sequenceIndex; - private float _sequenceTime; - private float _stateTime; - private float _stateDuration; - private Vector3 _climbFrom; - private Vector3 _climbTo; - // Ladders: step to the ladder during the first animation, change height only during the climb cycles, step off - // during the last one (start/end as parts of the whole climb). - private bool _isLadder; - private static bool _hasLoggedLadderCycle; - private Vector3 _ladderColumn; - private float _ladderRiseStart; - private float _ladderRiseEnd; - // The climb animations lift the root bone themselves (pose offset): per animation the NPC's base height, so each - // one starts where the previous one ended - no double lift ("hiccup"). Null: no usable root lift (plain lerp). - private float[] _ladderBases; - private float[] _ladderBlendIns; - // What's left to the ladder's end after the last animation - spread over the whole climb. - private float _ladderEndError; - private const float _ladderMaxEndError = 1.5f; - public bool IsBusy => _state != State.None; public static NpcJumpFall Get(NpcContainer npc) @@ -152,6 +116,8 @@ private void Bind(NpcContainer npc) _npc = npc; _body = new NpcMoveBody(npc, transform).Inject(); _slide = new NpcSlopeSlide(_body); + _sequence = new NpcAnimationSequence(_body); + _climb = new NpcLedgeClimb(_body, _sequence).Inject(); } private void Update() @@ -171,12 +137,13 @@ private void Update() TickFall(); break; case State.Landing: - TickSequence(); - if (_stateTime >= _stateDuration) + _sequence.Tick(Time.deltaTime); + if (_sequence.IsDone) Finish(); break; case State.Climbing: - TickClimb(); + if (_climb.Tick()) + Finish(); break; case State.Sliding: TickSlide(); @@ -189,8 +156,6 @@ private void Update() private float RestHeight => _body.RestHeight; - private LedgeRules Rules => _body.Rules; - private bool CanMove() => _body.CanMove(); /// @@ -279,7 +244,7 @@ private void StartFall(Vector3 velocityH) _body.TakeOver(); _fallAnimName = "S_FALLDN"; - PlayIfExists(_fallAnimName); + _body.PlayIfExists(_fallAnimName); Logger.Log($"[NpcJumpFall] {_npc.Go.name} falls (speed {_fallVelocityH.magnitude:F1} m/s).", LogCat.Ai); } @@ -336,12 +301,12 @@ private void TickFall() { _npc.PrefabProps.AnimationSystem.StopAnimation(_fallAnimName); _fallAnimName = FallPose.Front.Flight; - PlayIfExists(_fallAnimName); + _body.PlayIfExists(_fallAnimName); } else if (!_npc.PrefabProps.AnimationSystem.IsPlaying(_fallAnimName) && CanMove()) { // Npc_ClearAIQueue stops all animations every ~2 s (a death's animation stays). - PlayIfExists(_fallAnimName); + _body.PlayIfExists(_fallAnimName); } if (fallen > _outOfWorldFallHeight) @@ -359,9 +324,12 @@ private void Land(float height) var canMove = CanMove(); // Can't move (died in the air, landed in water): no landing animations. if (canMove) - StartSequence(State.Landing, isDeep + { + _sequence.Start(isDeep ? new[] { FallPose.Front.Landing, FallPose.Front.StandUp } : new[] { "T_FALLDN_2_STAND" }); + Enter(State.Landing); + } // NPCs' fall damage comes with the combat system, the hero's always (HeroFallService). var damage = NpcFallDomain.GetFallDamage(_gameStateService.GuildValues, _npc, height); @@ -380,35 +348,10 @@ private void Land(float height) /// public bool TryStartClimb(Vector3 direction) { - if (IsBusy || RestHeight <= 0f || !CanMove()) + if (IsBusy || RestHeight <= 0f || !CanMove() || !_climb.TryStartLedge(direction)) return false; - direction.y = 0f; - if (direction.sqrMagnitude < 0.0001f) - return false; - direction.Normalize(); - - var position = transform.position; - var ledge = _ledgeService.ProbeNpcClimb(position, RestHeight, direction, Rules); - if (ledge.Band is not (LedgeBand.Low or LedgeBand.Mid)) - return false; - - var sequence = ledge.Band == LedgeBand.Low - ? new[] { "T_STAND_2_JUMPUPLOW", "S_JUMPUPLOW", "T_JUMPUPLOW_2_STAND" } - : new[] { "T_STAND_2_JUMPUPMID", "S_JUMPUPMID", "T_JUMPUPMID_2_STAND" }; - if (!HasTrack(sequence[0])) - return false; - - var height = ledge.Height; - _climbFrom = position; - _climbTo = ledge.StandPoint + Vector3.up * RestHeight; - _body.TakeOver(); - transform.rotation = Quaternion.LookRotation(direction); - _npc.Props.BodyState = VmGothicEnums.BodyState.BsJump; - _isLadder = false; - StartSequence(State.Climbing, sequence); - - Logger.Log($"[NpcJumpFall] {_npc.Go.name} climbs a {height:F2} m ledge.", LogCat.Ai); + Enter(State.Climbing); return true; } @@ -420,55 +363,8 @@ public bool TryStartLadder(Vector3 ladderStart, Vector3 ladderEnd) if (IsBusy || RestHeight <= 0f || !CanMove()) return false; - var isUp = ladderEnd.y > ladderStart.y; - var names = isUp ? _ladderUp : _ladderDown; - var cycles = Mathf.Max(1, Mathf.RoundToInt(GetLadderClimbHeight(ladderStart, ladderEnd) / - GetLadderMetersPerCycle())); - var sequence = new System.Collections.Generic.List { names[0] }; - for (var i = 0; i < cycles; i++) - sequence.Add(names[1]); - sequence.Add(names[2]); - - _climbFrom = transform.position; - _climbTo = ladderEnd + Vector3.up * RestHeight; - _isLadder = true; - Vector3 flat; - if (_npcNavMeshService.TryGetLadderStance(ladderStart, ladderEnd, out var column, out var facing)) - { - // In front of the rungs, looking at them - up and down at the same spot (like the engine). - _ladderColumn = new Vector3(column.x, 0f, column.z); - flat = facing; - } - else - { - var middle = (ladderStart + ladderEnd) * 0.5f; - _ladderColumn = new Vector3(middle.x, 0f, middle.z); - var bottom = isUp ? ladderStart : ladderEnd; - var top = isUp ? ladderEnd : ladderStart; - flat = top - bottom; - } - flat.y = 0f; - if (flat.sqrMagnitude > 0.0001f) - transform.rotation = Quaternion.LookRotation(flat); - - _body.TakeOver(); - _npc.Props.BodyState = VmGothicEnums.BodyState.BsClimb; - StartSequence(State.Climbing, sequence.ToArray()); - // Without the animations (other models): a plain climb at ladder speed. - if (_stateDuration <= _climbMinSeconds) - { - _stateDuration = Mathf.Abs(ladderEnd.y - ladderStart.y) / _ladderSpeed + _ladderExtraSeconds; - _ladderRiseStart = 0.1f; - _ladderRiseEnd = 0.9f; - } - else - { - _ladderRiseStart = Mathf.Clamp01(_sequenceDurations[0] / _stateDuration); - _ladderRiseEnd = Mathf.Clamp(1f - _sequenceDurations[^1] / _stateDuration, _ladderRiseStart + 0.01f, 1f); - } - PrepareLadderBases(); - - Logger.Log($"[NpcJumpFall] {_npc.Go.name} takes a ladder ({ladderStart.y:F1} -> {ladderEnd.y:F1}).", LogCat.Ai); + _climb.StartLadder(ladderStart, ladderEnd); + Enter(State.Climbing); return true; } @@ -482,200 +378,17 @@ public bool IsSafeDropAhead(Vector3 direction) direction); } - private void TickClimb() - { - TickSequence(); - - var t = Mathf.Clamp01(_stateTime / _stateDuration); - if (_isLadder) - { - TickLadder(t); - return; - } - - // Up first, then forward onto the ledge. - var rise = Mathf.Clamp01(t / _climbRisePart); - var forward = Mathf.Clamp01((t - _climbRisePart * 0.5f) / (1f - _climbRisePart * 0.5f)); - var horizontal = Vector3.Lerp(new Vector3(_climbFrom.x, 0f, _climbFrom.z), new Vector3(_climbTo.x, 0f, _climbTo.z), forward); - transform.position = new Vector3(horizontal.x, Mathf.Lerp(_climbFrom.y, _climbTo.y, rise), horizontal.z); - - if (t >= 1f) - Finish(); - } - - /// - /// Height the climb cycles have to cover: the whole ladder minus what getting on and off lift already. - /// - private float GetLadderClimbHeight(Vector3 ladderStart, Vector3 ladderEnd) - { - var height = Mathf.Abs(ladderEnd.y - ladderStart.y); - var transitions = Mathf.Abs(RootHeightChange(_ladderUp[0])) + Mathf.Abs(RootHeightChange(_ladderUp[2])); - return transitions < height * 0.5f ? height - transitions : height; - } - - /// - /// One t_Ladder_S0_2_S1 cycle lifts the root this far in HUMANS.MDS (fallback if the track has no root lift). - /// - private float GetLadderMetersPerCycle() - { - var perCycle = Mathf.Abs(RootHeightChange(_ladderUp[1])); - if (!_hasLoggedLadderCycle) - { - _hasLoggedLadderCycle = true; - Logger.Log($"[NpcJumpFall] Ladder cycle lifts {perCycle:F2} m (getting on " + - $"{RootHeightChange(_ladderUp[0]):F2}, off {RootHeightChange(_ladderUp[2]):F2}).", LogCat.Ai); - } - return perCycle > 0.2f ? perCycle : _ladderMetersPerCycle; - } - - private float RootHeightChange(string animation) => - _animationService.GetRootHeightChange(animation, _npc.Props.MdsNameBase, _npc.Props.MdsNameOverlay); - - /// - /// base[i] + firstOffset[i] = base[i-1] + lastOffset[i-1]: every animation continues at the height the previous - /// one left the body. Starts at the NPC's own height. - /// - private void PrepareLadderBases() - { - _ladderBases = null; - if (_sequence == null || _sequence.Length == 0) - return; - - var bases = new float[_sequence.Length]; - var blendIns = new float[_sequence.Length]; - var baseY = _climbFrom.y; - float? previousLast = null; - for (var i = 0; i < _sequence.Length; i++) - { - if (_sequenceDurations[i] <= 0f || - !_animationService.TryGetRootHeightOffsets(_sequence[i], _npc.Props.MdsNameBase, - _npc.Props.MdsNameOverlay, out var first, out var last)) - { - bases[i] = baseY; - continue; - } - - if (previousLast != null) - baseY += previousLast.Value - first; - bases[i] = baseY; - blendIns[i] = _animationService.GetTrack(_sequence[i], _npc.Props.MdsNameBase, - _npc.Props.MdsNameOverlay)?.BlendIn ?? 0f; - previousLast = last; - } - - if (previousLast == null) - return; - var endError = _climbTo.y - (baseY + previousLast.Value); - if (Mathf.Abs(endError) > _ladderMaxEndError) - { - Logger.LogWarning($"[NpcJumpFall] Ladder root lift doesn't fit ({endError:F2} m off) - plain climb.", - LogCat.Ai); - return; - } - - _ladderBases = bases; - _ladderBlendIns = blendIns; - _ladderEndError = endError; - } - - /// - /// Base height of the running animation. While it blends in, the pose offset still blends from the previous - /// animation's - the base moves along, so the body doesn't hop. - /// - private float GetLadderBaseY(float t) - { - var index = Mathf.Clamp(_sequenceIndex, 0, _ladderBases.Length - 1); - var baseY = _ladderBases[index]; - if (index > 0 && _ladderBlendIns[index] > 0f) - baseY = Mathf.Lerp(_ladderBases[index - 1], baseY, Mathf.Clamp01(_sequenceTime / _ladderBlendIns[index])); - return baseY + _ladderEndError * t; - } - - /// - /// Onto the ladder (first animation), up/down along it (climb cycles), off it (last animation). - /// - private void TickLadder(float t) - { - var fromFlat = new Vector3(_climbFrom.x, 0f, _climbFrom.z); - var toFlat = new Vector3(_climbTo.x, 0f, _climbTo.z); - Vector3 horizontal; - if (t < _ladderRiseStart) - horizontal = Vector3.Lerp(fromFlat, _ladderColumn, t / _ladderRiseStart); - else if (t <= _ladderRiseEnd) - horizontal = _ladderColumn; - else - horizontal = Vector3.Lerp(_ladderColumn, toFlat, (t - _ladderRiseEnd) / Mathf.Max(1f - _ladderRiseEnd, 0.001f)); - - var rise = Mathf.Clamp01((t - _ladderRiseStart) / (_ladderRiseEnd - _ladderRiseStart)); - var y = _ladderBases != null ? GetLadderBaseY(t) : Mathf.Lerp(_climbFrom.y, _climbTo.y, rise); - transform.position = new Vector3(horizontal.x, y, horizontal.z); - - if (t >= 1f) - Finish(); - } - - private void StartSequence(State state, string[] animations) - { - Enter(state); - _sequence = animations; - _sequenceDurations = new float[animations.Length]; - _stateDuration = 0f; - for (var i = 0; i < animations.Length; i++) - { - _sequenceDurations[i] = HasTrack(animations[i]) - ? _npc.PrefabProps.AnimationSystem.GetAnimationDuration(animations[i]) - : 0f; - _stateDuration += _sequenceDurations[i]; - } - - // Ledges: short; ladders (more than 3 animations) take as long as their climb cycles. - if (state == State.Climbing && animations.Length <= 3) - _stateDuration = Mathf.Clamp(_stateDuration, _climbMinSeconds, _climbMaxSeconds); - - _sequenceIndex = -1; - _sequenceTime = 0f; - _stateTime = 0f; - NextInSequence(); - } - - private void TickSequence() - { - _stateTime += Time.deltaTime; - _sequenceTime += Time.deltaTime; - if (_sequenceIndex < _sequence.Length && _sequenceTime >= _sequenceDurations[_sequenceIndex]) - NextInSequence(); - } - - private void NextInSequence() - { - if (_sequenceIndex >= 0 && _sequenceIndex < _sequence.Length) - _npc.PrefabProps.AnimationSystem.StopAnimation(_sequence[_sequenceIndex]); - - _sequenceIndex++; - _sequenceTime = 0f; - while (_sequenceIndex < _sequence.Length && _sequenceDurations[_sequenceIndex] <= 0f) - _sequenceIndex++; - - // Can't move any more: the move ends without our animations (the death's or swimming's play). - if (_sequenceIndex < _sequence.Length && CanMove()) - _npc.PrefabProps.AnimationSystem.PlayAnimation(_sequence[_sequenceIndex]); - } - private void Finish() { - // Ladder: off it exactly at its end point (the base height + last pose offset left it mid-air/inside). - if (_isLadder && _state == State.Climbing) - transform.position = _climbTo; + if (_state == State.Climbing) + _climb.End(); - if (_sequence != null && _sequenceIndex >= 0 && _sequenceIndex < _sequence.Length) - _npc.PrefabProps.AnimationSystem.StopAnimation(_sequence[_sequenceIndex]); + _sequence.Stop(); if (_fallAnimName != null) _npc.PrefabProps.AnimationSystem.StopAnimation(_fallAnimName); _slide.StopAnimation(); _state = State.None; - _isLadder = false; - _sequence = null; _fallAnimName = null; if (_npc.Props.BodyState is VmGothicEnums.BodyState.BsFall or VmGothicEnums.BodyState.BsJump or VmGothicEnums.BodyState.BsClimb) @@ -684,9 +397,5 @@ private void Finish() if (CanMove()) _npc.PrefabProps.AnimationSystem.PlayIdleAnimation(); } - - private void PlayIfExists(string animationName) => _body.PlayIfExists(animationName); - - private bool HasTrack(string animationName) => _body.HasTrack(animationName); } } diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs new file mode 100644 index 000000000..f53c31af5 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs @@ -0,0 +1,319 @@ +using System.Collections.Generic; +using Gothic.Core.Logging; +using Gothic.Core.Models.Movement; +using Gothic.Core.Models.Vm; +using Gothic.Core.Services.Movement; +using Gothic.Core.Services.Npc; +using Reflex.Attributes; +using UnityEngine; +using Logger = Gothic.Core.Logging.Logger; + +namespace Gothic.Core.Adapters.Npc +{ + /// + /// An NPC's climbs, worker of NpcJumpFall (new().Inject()) - NpcJumpFall decides the state, this moves the body + /// along the climb's animations (NpcAnimationSequence). + /// - Ledges (chasing NPCs only, called by AttackPlayAni): a ledge in front between STEP_HEIGHT and JUMPMID_HEIGHT + /// (LedgeService.ProbeNpcClimb) is climbed with the JumpUpLow/JumpUpMid animations - only if the model has them + /// (most monsters don't). Up first, then forward onto the ledge. + /// - Ladders (a NavMesh ladder link): onto the ladder, as many climb cycles as its height takes, off it - the + /// animations' own root lift carries the body where they have one, else a plain climb. + /// + public class NpcLedgeClimb + { + [Inject] private readonly AnimationService _animationService; + [Inject] private readonly LedgeService _ledgeService; + [Inject] private readonly NpcNavMeshService _npcNavMeshService; + + private const float _climbMinSeconds = 0.6f; + private const float _climbMaxSeconds = 2f; + private const float _climbRisePart = 0.65f; + private const float _ladderSpeed = 1.5f; + private const float _ladderExtraSeconds = 0.6f; + // HUMANS.MDS: one climb cycle t_Ladder_S0_2_S1 (frames 15-45), down = the same played backwards (aliases R). + private static readonly string[] _ladderUp = + { "T_LADDER_STAND_2_S0", "T_LADDER_S0_2_S1", "T_LADDER_S1_2_STAND" }; + private static readonly string[] _ladderDown = + { "T_LADDER_STAND_2_S1", "T_LADDER_S1_2_S0", "T_LADDER_S0_2_STAND" }; + // Fallback if the climb cycle doesn't lift the root bone itself (0.9 climbed a few cycles too many). + private const float _ladderMetersPerCycle = 1.2f; + private const float _ladderMaxEndError = 1.5f; + + private static bool _hasLoggedLadderCycle; + + private readonly NpcMoveBody _body; + private readonly NpcAnimationSequence _sequence; + + private Vector3 _climbFrom; + private Vector3 _climbTo; + // Ladders: step to the ladder during the first animation, change height only during the climb cycles, step off + // during the last one (start/end as parts of the whole climb). + private bool _isLadder; + private Vector3 _ladderColumn; + private float _ladderRiseStart; + private float _ladderRiseEnd; + // The climb animations lift the root bone themselves (pose offset): per animation the NPC's base height, so each + // one starts where the previous one ended - no double lift ("hiccup"). Null: no usable root lift (plain lerp). + private float[] _ladderBases; + private float[] _ladderBlendIns; + // What's left to the ladder's end after the last animation - spread over the whole climb. + private float _ladderEndError; + + public NpcLedgeClimb(NpcMoveBody body, NpcAnimationSequence sequence) + { + _body = body; + _sequence = sequence; + } + + private Transform Transform => _body.Transform; + + /// + /// A chasing NPC runs into a ledge: climb it if it's higher than a step and not higher than JUMPMID_HEIGHT. + /// true: the climb began. + /// + public bool TryStartLedge(Vector3 direction) + { + direction.y = 0f; + if (direction.sqrMagnitude < 0.0001f) + return false; + direction.Normalize(); + + var position = Transform.position; + var restHeight = _body.RestHeight; + var ledge = _ledgeService.ProbeNpcClimb(position, restHeight, direction, _body.Rules); + if (ledge.Band is not (LedgeBand.Low or LedgeBand.Mid)) + return false; + + var animations = ledge.Band == LedgeBand.Low + ? new[] { "T_STAND_2_JUMPUPLOW", "S_JUMPUPLOW", "T_JUMPUPLOW_2_STAND" } + : new[] { "T_STAND_2_JUMPUPMID", "S_JUMPUPMID", "T_JUMPUPMID_2_STAND" }; + if (!_body.HasTrack(animations[0])) + return false; + + _climbFrom = position; + _climbTo = ledge.StandPoint + Vector3.up * restHeight; + _body.TakeOver(); + Transform.rotation = Quaternion.LookRotation(direction); + _body.Npc.Props.BodyState = VmGothicEnums.BodyState.BsJump; + _isLadder = false; + _sequence.Start(animations); + // Ledges are short. + _sequence.Duration = Mathf.Clamp(_sequence.Duration, _climbMinSeconds, _climbMaxSeconds); + + Logger.Log($"[NpcJumpFall] {_body.Name} climbs a {ledge.Height:F2} m ledge.", LogCat.Ai); + return true; + } + + /// + /// The NavMesh path goes over a ladder link: climb it from start to end (up or down). + /// + public void StartLadder(Vector3 ladderStart, Vector3 ladderEnd) + { + var isUp = ladderEnd.y > ladderStart.y; + var names = isUp ? _ladderUp : _ladderDown; + var cycles = Mathf.Max(1, Mathf.RoundToInt(GetLadderClimbHeight(ladderStart, ladderEnd) / + GetLadderMetersPerCycle())); + var animations = new List { names[0] }; + for (var i = 0; i < cycles; i++) + animations.Add(names[1]); + animations.Add(names[2]); + + _climbFrom = Transform.position; + _climbTo = ladderEnd + Vector3.up * _body.RestHeight; + _isLadder = true; + Vector3 flat; + if (_npcNavMeshService.TryGetLadderStance(ladderStart, ladderEnd, out var column, out var facing)) + { + // In front of the rungs, looking at them - up and down at the same spot (like the engine). + _ladderColumn = new Vector3(column.x, 0f, column.z); + flat = facing; + } + else + { + var middle = (ladderStart + ladderEnd) * 0.5f; + _ladderColumn = new Vector3(middle.x, 0f, middle.z); + var bottom = isUp ? ladderStart : ladderEnd; + var top = isUp ? ladderEnd : ladderStart; + flat = top - bottom; + } + flat.y = 0f; + if (flat.sqrMagnitude > 0.0001f) + Transform.rotation = Quaternion.LookRotation(flat); + + _body.TakeOver(); + _body.Npc.Props.BodyState = VmGothicEnums.BodyState.BsClimb; + _sequence.Start(animations.ToArray()); + // Ladders take as long as their climb cycles - one of a single cycle (three animations) is timed like a + // ledge. + if (animations.Count <= 3) + _sequence.Duration = Mathf.Clamp(_sequence.Duration, _climbMinSeconds, _climbMaxSeconds); + // Without the animations (other models): a plain climb at ladder speed. + if (_sequence.Duration <= _climbMinSeconds) + { + _sequence.Duration = Mathf.Abs(ladderEnd.y - ladderStart.y) / _ladderSpeed + _ladderExtraSeconds; + _ladderRiseStart = 0.1f; + _ladderRiseEnd = 0.9f; + } + else + { + var durations = _sequence.Durations; + _ladderRiseStart = Mathf.Clamp01(durations[0] / _sequence.Duration); + _ladderRiseEnd = Mathf.Clamp(1f - durations[^1] / _sequence.Duration, _ladderRiseStart + 0.01f, 1f); + } + PrepareLadderBases(); + + Logger.Log($"[NpcJumpFall] {_body.Name} takes a ladder ({ladderStart.y:F1} -> {ladderEnd.y:F1}).", + LogCat.Ai); + } + + /// + /// One frame of the climb. true: it's over (NpcJumpFall finishes it). + /// + public bool Tick() + { + _sequence.Tick(Time.deltaTime); + + var t = _sequence.Progress; + if (_isLadder) + { + TickLadder(t); + return t >= 1f; + } + + // Up first, then forward onto the ledge. + var rise = Mathf.Clamp01(t / _climbRisePart); + var forward = Mathf.Clamp01((t - _climbRisePart * 0.5f) / (1f - _climbRisePart * 0.5f)); + var horizontal = Vector3.Lerp(new Vector3(_climbFrom.x, 0f, _climbFrom.z), + new Vector3(_climbTo.x, 0f, _climbTo.z), forward); + Transform.position = new Vector3(horizontal.x, Mathf.Lerp(_climbFrom.y, _climbTo.y, rise), horizontal.z); + return t >= 1f; + } + + /// + /// The climb is over (or cut short): a ladder leaves the body exactly at its end point (the base height + last + /// pose offset left it mid-air/inside). + /// + public void End() + { + if (_isLadder) + Transform.position = _climbTo; + _isLadder = false; + } + + /// + /// Height the climb cycles have to cover: the whole ladder minus what getting on and off lift already. + /// + private float GetLadderClimbHeight(Vector3 ladderStart, Vector3 ladderEnd) + { + var height = Mathf.Abs(ladderEnd.y - ladderStart.y); + var transitions = Mathf.Abs(RootHeightChange(_ladderUp[0])) + Mathf.Abs(RootHeightChange(_ladderUp[2])); + return transitions < height * 0.5f ? height - transitions : height; + } + + /// + /// One t_Ladder_S0_2_S1 cycle lifts the root this far in HUMANS.MDS (fallback if the track has no root lift). + /// + private float GetLadderMetersPerCycle() + { + var perCycle = Mathf.Abs(RootHeightChange(_ladderUp[1])); + if (!_hasLoggedLadderCycle) + { + _hasLoggedLadderCycle = true; + Logger.Log($"[NpcJumpFall] Ladder cycle lifts {perCycle:F2} m (getting on " + + $"{RootHeightChange(_ladderUp[0]):F2}, off {RootHeightChange(_ladderUp[2]):F2}).", LogCat.Ai); + } + return perCycle > 0.2f ? perCycle : _ladderMetersPerCycle; + } + + private float RootHeightChange(string animation) + { + var props = _body.Npc.Props; + return _animationService.GetRootHeightChange(animation, props.MdsNameBase, props.MdsNameOverlay); + } + + /// + /// base[i] + firstOffset[i] = base[i-1] + lastOffset[i-1]: every animation continues at the height the previous + /// one left the body. Starts at the NPC's own height. + /// + private void PrepareLadderBases() + { + _ladderBases = null; + var animations = _sequence.Animations; + if (animations == null || animations.Length == 0) + return; + + var props = _body.Npc.Props; + var durations = _sequence.Durations; + var bases = new float[animations.Length]; + var blendIns = new float[animations.Length]; + var baseY = _climbFrom.y; + float? previousLast = null; + for (var i = 0; i < animations.Length; i++) + { + if (durations[i] <= 0f || + !_animationService.TryGetRootHeightOffsets(animations[i], props.MdsNameBase, props.MdsNameOverlay, + out var first, out var last)) + { + bases[i] = baseY; + continue; + } + + if (previousLast != null) + baseY += previousLast.Value - first; + bases[i] = baseY; + blendIns[i] = _animationService.GetTrack(animations[i], props.MdsNameBase, props.MdsNameOverlay) + ?.BlendIn ?? 0f; + previousLast = last; + } + + if (previousLast == null) + return; + var endError = _climbTo.y - (baseY + previousLast.Value); + if (Mathf.Abs(endError) > _ladderMaxEndError) + { + Logger.LogWarning($"[NpcJumpFall] Ladder root lift doesn't fit ({endError:F2} m off) - plain climb.", + LogCat.Ai); + return; + } + + _ladderBases = bases; + _ladderBlendIns = blendIns; + _ladderEndError = endError; + } + + /// + /// Base height of the running animation. While it blends in, the pose offset still blends from the previous + /// animation's - the base moves along, so the body doesn't hop. + /// + private float GetLadderBaseY(float t) + { + var index = Mathf.Clamp(_sequence.Index, 0, _ladderBases.Length - 1); + var baseY = _ladderBases[index]; + if (index > 0 && _ladderBlendIns[index] > 0f) + baseY = Mathf.Lerp(_ladderBases[index - 1], baseY, + Mathf.Clamp01(_sequence.AnimationTime / _ladderBlendIns[index])); + return baseY + _ladderEndError * t; + } + + /// + /// Onto the ladder (first animation), up/down along it (climb cycles), off it (last animation). + /// + private void TickLadder(float t) + { + var fromFlat = new Vector3(_climbFrom.x, 0f, _climbFrom.z); + var toFlat = new Vector3(_climbTo.x, 0f, _climbTo.z); + Vector3 horizontal; + if (t < _ladderRiseStart) + horizontal = Vector3.Lerp(fromFlat, _ladderColumn, t / _ladderRiseStart); + else if (t <= _ladderRiseEnd) + horizontal = _ladderColumn; + else + horizontal = Vector3.Lerp(_ladderColumn, toFlat, + (t - _ladderRiseEnd) / Mathf.Max(1f - _ladderRiseEnd, 0.001f)); + + var rise = Mathf.Clamp01((t - _ladderRiseStart) / (_ladderRiseEnd - _ladderRiseStart)); + var y = _ladderBases != null ? GetLadderBaseY(t) : Mathf.Lerp(_climbFrom.y, _climbTo.y, rise); + Transform.position = new Vector3(horizontal.x, y, horizontal.z); + } + } +} From e8ea4bcffb8f658ac8e04bab699f5b70e306848f Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:05:56 +0000 Subject: [PATCH 21/31] refactor: HeroFallSample is HeroBodySample - one frame's measurement of the hero's body feeds his falls and his slides alike Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Domain/Movement/HeroAirborneDomain.cs | 8 ++++---- .../Movement/{HeroFallSample.cs => HeroBodySample.cs} | 4 ++-- .../{HeroFallSample.cs.meta => HeroBodySample.cs.meta} | 0 .../Scripts/Services/Movement/HeroFallService.cs | 4 ++-- .../Scripts/Services/Movement/HeroSlideService.cs | 4 ++-- .../EditMode/Movement/HeroAirborneDomainTest.cs | 2 +- .../Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs | 2 +- Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) rename Assets/Gothic-Core/Scripts/Models/Movement/{HeroFallSample.cs => HeroBodySample.cs} (97%) rename Assets/Gothic-Core/Scripts/Models/Movement/{HeroFallSample.cs.meta => HeroBodySample.cs.meta} (100%) diff --git a/Assets/Gothic-Core/Scripts/Domain/Movement/HeroAirborneDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Movement/HeroAirborneDomain.cs index b78d4cdd3..523eee36f 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Movement/HeroAirborneDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Movement/HeroAirborneDomain.cs @@ -5,7 +5,7 @@ namespace Gothic.Core.Domain.Movement { /// - /// The hero's airborne phases from per-frame measurements (HeroFallSample): jump, fall, fall flat, landing, and + /// The hero's airborne phases from per-frame measurements (HeroBodySample): jump, fall, fall flat, landing, and /// the drop of each landing - from the highest point of the phase down to the landing point (like OpenGothic, which /// derives it from the impact speed: a jump on flat ground adds only its own small height). Pure rules, no Unity /// objects - worker of HeroFallService, which decides what is ignored (water, climbing, teleports) and what a @@ -17,11 +17,11 @@ namespace Gothic.Core.Domain.Movement /// below where it started; a jump only deeper than the guild's FALLDOWN_HEIGHT (5 m human) below its take-off, /// like OpenGothic - the jump's own rise doesn't count, and a jump down a steep slope lands on his feet. A jump /// stays a jump (its pose in the air, the jump's landing) until that deep. - /// - A jump taken at running speed (HeroFallSample.RunSpeed) is Gothic's running jump (IsRunningJump), the + /// - A jump taken at running speed (HeroBodySample.RunSpeed) is Gothic's running jump (IsRunningJump), the /// platform makes it the leap. /// - No fall without real falling: off the ground (beyond the platform's grounded grace) the hero falls only when /// moving down faster than FallSpeed and deeper below the top than the platform's ground snap - /// (HeroFallSample.GroundSnapHeight) - stairs, slopes and lifts stay walking. + /// (HeroBodySample.GroundSnapHeight) - stairs, slopes and lifts stay walking. /// public class HeroAirborneDomain { @@ -95,7 +95,7 @@ public class HeroAirborneDomain /// he falls flat (0 or less: LyingFallHeight). Returns what changed; landing is set for HeroAirEvent.Landed /// only. /// - public HeroAirEvent Tick(in HeroFallSample sample, float safeHeight, out HeroLanding landing) + public HeroAirEvent Tick(in HeroBodySample sample, float safeHeight, out HeroLanding landing) { landing = default; _jumpLyingDepth = safeHeight > 0f ? safeHeight : NpcFallDomain.LyingFallHeight; diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs similarity index 97% rename from Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs rename to Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs index fb2ccc75f..5ad42524a 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs @@ -7,7 +7,7 @@ namespace Gothic.Core.Models.Movement /// platform (VR: the rig port IVrRig, with its grounded grace time). Platform-neutral: the rules don't know where /// it comes from. /// - public readonly struct HeroFallSample + public readonly struct HeroBodySample { /// /// Position of the feet (world, m). @@ -74,7 +74,7 @@ public readonly struct HeroFallSample public float FeetY => FeetPosition.y; - public HeroFallSample(Vector3 feetPosition, Vector3 forward, bool isGrounded, bool isJumping, bool isClimbing, + public HeroBodySample(Vector3 feetPosition, Vector3 forward, bool isGrounded, bool isJumping, bool isClimbing, bool isTransformed, float gravity, float maxFallSpeed, float groundSnapHeight, float runSpeed, float deltaTime, bool hasGround, Vector3 groundNormal) { diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs.meta similarity index 100% rename from Assets/Gothic-Core/Scripts/Models/Movement/HeroFallSample.cs.meta rename to Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs.meta diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs index ff430fd88..ea7a6c26d 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs @@ -104,7 +104,7 @@ public HeroFallService() /// /// One frame's measurement of the player's body. Called every frame by the platform, also on the ground. /// - public void Tick(in HeroFallSample sample) + public void Tick(in HeroBodySample sample) { UpdateLandingLock(); @@ -171,7 +171,7 @@ public void OnTeleported(Vector3 feetPosition) /// Why the hero isn't tracked now, None if he is. A drawn weapon or a VR melee fight keeps him tracked: like /// Gothic the hero stays BS_STAND / BS_WALK / BS_RUN / BS_SNEAK then (no BS_FIGHT is set for him). /// - private static HeroFallHold GetHold(NpcContainer hero, in HeroFallSample sample) + private static HeroFallHold GetHold(NpcContainer hero, in HeroBodySample sample) { if (sample.IsClimbing) return HeroFallHold.Climbing; diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs index b1d6bb681..5c7ee851a 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs @@ -64,7 +64,7 @@ public string GetAnimation(Vector3 facing, bool hasBackwards, bool hasForward) /// /// One frame's measurement of the player's body (the same sample HeroFallService gets). /// - public void Tick(in HeroFallSample sample) + public void Tick(in HeroBodySample sample) { var hero = _npcService.GetHeroContainer(); if (hero?.Props == null) @@ -111,7 +111,7 @@ public void OnTeleported(Vector3 feetPosition) /// /// Why the hero isn't checked now, None if he is. Every frame: no strings. /// - private HeroSlideHold GetHold(NpcContainer hero, in HeroFallSample sample) + private HeroSlideHold GetHold(NpcContainer hero, in HeroBodySample sample) { if (sample.IsClimbing) return HeroSlideHold.Climbing; diff --git a/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs index 03a519f97..4c8a65547 100644 --- a/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs +++ b/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs @@ -51,7 +51,7 @@ public void SetUp() private void Tick(float feetY, bool isGrounded, bool isJumping = false, float dt = _dt) { _feet = new Vector3(_feet.x, feetY, _feet.z) + _moveVelocity * dt; - var sample = new HeroFallSample(_feet, _forward, isGrounded, isJumping, false, false, _gravity, + var sample = new HeroBodySample(_feet, _forward, isGrounded, isJumping, false, false, _gravity, _maxFallSpeed, _groundSnapHeight, _runSpeed, dt, isGrounded, Vector3.up); switch (_domain.Tick(sample, _safeHeight, out var landing)) { diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs index a47a26d2f..6ce10e2f3 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs @@ -74,7 +74,7 @@ private void Update() UpdateHorizontalVelocity(feet); var hasGround = _rig.TryGetGround(out _, out var groundNormal); - var sample = new HeroFallSample(feet, GetFacing(), _rig.IsGrounded, _rig.IsJumping, _rig.IsClimbing, + var sample = new HeroBodySample(feet, GetFacing(), _rig.IsGrounded, _rig.IsJumping, _rig.IsClimbing, _vrSpellTransformService != null && _vrSpellTransformService.IsTransformed, _rig.Gravity, _rig.MaxFallSpeed, _rig.GroundSnapHeight, _vrPlayerService.HeroSpeeds.RunThreshold, Time.deltaTime, hasGround, groundNormal); diff --git a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs index 18a034845..80b55570b 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Ports/IVrRig.cs @@ -48,7 +48,7 @@ public interface IVrRig /// /// How far in m the backend pulls the player down to the ground per frame (slopes, stairs) - a smaller drop is - /// no fall for the hero (HeroFallSample). Default: 0, for backends without snapping. + /// no fall for the hero (HeroBodySample). Default: 0, for backends without snapping. /// float GroundSnapHeight => 0f; From 4f5e69f27da3032f45d1919af60b8fd6883e9ea3 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:07:06 +0000 Subject: [PATCH 22/31] refactor: one Core entry point for the hero's body each frame (HeroBodyService.Tick) - the fall, then the slide, decided in Core; the platform applies what it returns (HeroBodyResult: slide velocity, take-off blocked) and the two services' Tick and OnTeleported are internal Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Models/Movement/HeroBodyResult.cs | 26 ++++++++++++ .../Scripts/Models/Movement/HeroBodySample.cs | 2 +- .../Scripts/ReflexProjectInstaller.cs | 1 + .../Services/Movement/HeroBodyService.cs | 41 +++++++++++++++++++ .../Services/Movement/HeroFallService.cs | 12 +++--- .../Services/Movement/HeroSlideService.cs | 12 +++--- .../Scripts/Adapters/Player/VrHeroJumpFall.cs | 23 +++++------ 7 files changed, 93 insertions(+), 24 deletions(-) create mode 100644 Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs create mode 100644 Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs new file mode 100644 index 000000000..0f0ff9b44 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +namespace Gothic.Core.Models.Movement +{ + /// + /// What the platform applies to the hero's body after a frame of HeroBodyService.Tick (VR: the rig port IVrRig). + /// + public readonly struct HeroBodyResult + { + /// + /// World m/s down the slope the body slides with, zero = no slide (HeroSlideService). + /// + public readonly Vector3 SlideVelocity; + + /// + /// The ground is too steep to jump from: the platform refuses the take-off (HeroSlideService). + /// + public readonly bool IsTakeOffBlocked; + + public HeroBodyResult(Vector3 slideVelocity, bool isTakeOffBlocked) + { + SlideVelocity = slideVelocity; + IsTakeOffBlocked = isTakeOffBlocked; + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs index 5ad42524a..ec750baa6 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodySample.cs @@ -3,7 +3,7 @@ namespace Gothic.Core.Models.Movement { /// - /// One frame's measurement of the player's body for HeroFallService.Tick and HeroSlideService.Tick, given by the + /// One frame's measurement of the player's body for HeroBodyService.Tick (his falls and his slides), given by the /// platform (VR: the rig port IVrRig, with its grounded grace time). Platform-neutral: the rules don't know where /// it comes from. /// diff --git a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs index a9408b796..91afb7b74 100644 --- a/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs +++ b/Assets/Gothic-Core/Scripts/ReflexProjectInstaller.cs @@ -148,6 +148,7 @@ public void InstallBindings(ContainerBuilder containerBuilder) containerBuilder.AddSingleton(typeof(LedgeService)); containerBuilder.AddSingleton(typeof(HeroFallService)); containerBuilder.AddSingleton(typeof(HeroSlideService)); + containerBuilder.AddSingleton(typeof(HeroBodyService)); // Misc containerBuilder.AddSingleton(typeof(AudioService)); diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs new file mode 100644 index 000000000..4df28d6c7 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs @@ -0,0 +1,41 @@ +using Gothic.Core.Models.Movement; +using Reflex.Attributes; +using UnityEngine; + +namespace Gothic.Core.Services.Movement +{ + /// + /// The one entry point for the hero's body each frame: the platform measures it (HeroBodySample - VR: + /// VrHeroJumpFall from the rig port), calls Tick and applies the result. The order of the rules is decided here, + /// not per platform: + /// 1. HeroFallService - jumps, falls, fall damage, the lying landing. + /// 2. HeroSlideService - slides down steep slopes, no take-off from them. After the fall: a landing on a steep + /// slope is a landing, the slide begins after it (and reads the landing's lying lock). + /// The platform still reads the two services' state for its body (HeroFallService.Phase / IsRunningJump, + /// HeroSlideService.IsSliding) - it only never ticks them itself. + /// + public class HeroBodyService + { + [Inject] private readonly HeroFallService _heroFallService; + [Inject] private readonly HeroSlideService _heroSlideService; + + /// + /// One frame's measurement of the player's body. Called every frame by the platform, also on the ground. + /// + public HeroBodyResult Tick(in HeroBodySample sample) + { + _heroFallService.Tick(sample); + _heroSlideService.Tick(sample); + return new HeroBodyResult(_heroSlideService.Velocity, _heroSlideService.IsTakeOffBlocked); + } + + /// + /// The player was teleported: a fall or slide measured so far ends there. + /// + public void OnTeleported(Vector3 feetPosition) + { + _heroFallService.OnTeleported(feetPosition); + _heroSlideService.OnTeleported(feetPosition); + } + } +} diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs index ea7a6c26d..98a7bc896 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroFallService.cs @@ -18,7 +18,8 @@ namespace Gothic.Core.Services.Movement /// /// The hero's jumps and falls like the engine's: BS_JUMP / BS_FALL while in the air, fall damage at the landing /// (always, also without the combat system), lying and getting up after a fall flat. The platform measures (VR: - /// the rig port, VrHeroJumpFall) and calls Tick every frame; the phases come from HeroAirborneDomain. + /// the rig port, VrHeroJumpFall) and HeroBodyService ticks this every frame, before the slide; the phases come + /// from HeroAirborneDomain. /// Pose and damage are separate rules: /// - Pose: S_FALLDN as soon as he falls; a fall deeper than NpcFallDomain.LyingFallHeight (2 m, like NPCs), a jump /// deeper than FALLDOWN_HEIGHT below its take-off (like OpenGothic), falls flat (FallPose: on his face, on @@ -97,14 +98,15 @@ public HeroFallService() { GlobalEventDispatcher.LoadGameStart.AddListener(ResetAll); GlobalEventDispatcher.WorldSceneLoaded.AddListener(ResetAll); - // The landing's lock is timed by Tick, which only the platform calls - a dead hero doesn't get up. + // The landing's lock is timed by Tick, which only the platform's frames call - a dead hero doesn't get up. GlobalEventDispatcher.HeroDied.AddListener(_ => Unlock()); } /// - /// One frame's measurement of the player's body. Called every frame by the platform, also on the ground. + /// One frame's measurement of the player's body - every frame, also on the ground. Only HeroBodyService + /// calls it (it decides the order with the slide). /// - public void Tick(in HeroBodySample sample) + internal void Tick(in HeroBodySample sample) { UpdateLandingLock(); @@ -157,7 +159,7 @@ public void Tick(in HeroBodySample sample) /// The player was teleported (thumbstick, Marvin, AI_Teleport, spawn, loading, ledge/ladder exits): whatever /// fall ran is dropped, a new one starts at the target. A lying landing's lock ends - he arrives standing. /// - public void OnTeleported(Vector3 feetPosition) + internal void OnTeleported(Vector3 feetPosition) { Unlock(); var hero = _npcService.GetHeroContainer(); diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs index 5c7ee851a..22544e247 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs @@ -14,8 +14,9 @@ namespace Gothic.Core.Services.Movement /// /// The hero slides down slopes steeper than his SLIDE_ANGLE like in Gothic (SlopeSlideDomain) - and can't jump off /// such ground (IsTakeOffBlocked, OpenGothic Npc::tryJump: no jump while sliding). The platform measures the ground - /// straight under the feet and calls Tick every frame (VR: VrHeroJumpFall, from the rig port); it moves the body - /// with Velocity and removes the player's own steps up the slope meanwhile. + /// straight under the feet (VR: VrHeroJumpFall, from the rig port) and HeroBodyService ticks this every frame, + /// after the fall; the platform moves the body with Velocity and takes back the player's own steps up the slope + /// meanwhile (SlopeSlideDomain.RemoveUphill). /// - A slide is no fall: the body stays on the ground (the platform counts it as grounded), no fall damage. Off an /// edge the slide ends and HeroFallService's normal fall begins from there. /// - Body state: BS_STAND while sliding (OpenGothic: BS_NONE for S_SLIDE/S_SLIDEB) - VR: VRHeroMovement. @@ -62,9 +63,10 @@ public string GetAnimation(Vector3 facing, bool hasBackwards, bool hasForward) } /// - /// One frame's measurement of the player's body (the same sample HeroFallService gets). + /// One frame's measurement of the player's body (the same sample HeroFallService gets, after it). Only + /// HeroBodyService calls it. /// - public void Tick(in HeroBodySample sample) + internal void Tick(in HeroBodySample sample) { var hero = _npcService.GetHeroContainer(); if (hero?.Props == null) @@ -103,7 +105,7 @@ public void Tick(in HeroBodySample sample) /// /// The player was teleported: a slide ends there. /// - public void OnTeleported(Vector3 feetPosition) + internal void OnTeleported(Vector3 feetPosition) { Hold(feetPosition, HeroSlideHold.Teleported, _npcService.GetHeroContainer()); } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs index 6ce10e2f3..4ddc6761e 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VrHeroJumpFall.cs @@ -11,11 +11,11 @@ namespace Gothic.VR.Adapters.Player { /// - /// Feeds the hero's jumps and falls (HeroFallService: body state, fall damage, lying landing) and his slides - /// down slopes (HeroSlideService) from the VR rig port: feet height, grounded (with the rig's grace time), the - /// ground under the feet, jumping, climbing, gravity, ground snap, the speed he runs from - /// (VrHeroSpeeds.RunThreshold), teleports - and hands the slide back to the rig (its velocity, no take-off from - /// steep ground). Measures only - the rules are in Core. Sits next to VRPlayer (added by + /// Feeds the hero's body (HeroBodyService: his jumps and falls - body state, fall damage, lying landing - and his + /// slides down slopes) from the VR rig port: feet height, grounded (with the rig's grace time), the ground under + /// the feet, jumping, climbing, gravity, ground snap, the speed he runs from (VrHeroSpeeds.RunThreshold), + /// teleports - and hands the result back to the rig (the slide's velocity, no take-off from steep ground). + /// Measures only - the rules and their order are in Core. Sits next to VRPlayer (added by /// VRContextInteractionService). /// A running jump (HeroFallService.IsRunningJump, the sprint) is a long leap at T_RUNL_2_JUMP's forward speed /// (VrHeroSpeeds.RunJump) in the direction of the run, until he lands, grabs or is teleported @@ -24,7 +24,7 @@ namespace Gothic.VR.Adapters.Player public class VrHeroJumpFall : MonoBehaviour { [Inject] private readonly HeroFallService _heroFallService; - [Inject] private readonly HeroSlideService _heroSlideService; + [Inject] private readonly HeroBodyService _heroBodyService; [Inject] private readonly VRSpellTransformService _vrSpellTransformService; [Inject] private readonly VRPlayerService _vrPlayerService; @@ -78,11 +78,9 @@ private void Update() _vrSpellTransformService != null && _vrSpellTransformService.IsTransformed, _rig.Gravity, _rig.MaxFallSpeed, _rig.GroundSnapHeight, _vrPlayerService.HeroSpeeds.RunThreshold, Time.deltaTime, hasGround, groundNormal); - // The fall first: a landing on a steep slope is a landing, the slide begins after it. - _heroFallService.Tick(sample); - _heroSlideService.Tick(sample); - _rig.SlideVelocity = _heroSlideService.Velocity; - _rig.IsTakeOffBlocked = _heroSlideService.IsTakeOffBlocked; + var result = _heroBodyService.Tick(sample); + _rig.SlideVelocity = result.SlideVelocity; + _rig.IsTakeOffBlocked = result.IsTakeOffBlocked; UpdateLeap(); } @@ -155,8 +153,7 @@ private void OnTeleported(Vector3 feetPosition) _lastFeet = feetPosition; _horizontalVelocity = Vector3.zero; EndLeap("teleported"); - _heroFallService.OnTeleported(feetPosition); - _heroSlideService.OnTeleported(feetPosition); + _heroBodyService.OnTeleported(feetPosition); _rig.SlideVelocity = Vector3.zero; } } From 64584c354bd54b505835d0272b3b7c5a95451bf6 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:08:43 +0000 Subject: [PATCH 23/31] docs: a map of the hero and NPC movement (Docs/hero-movement.md) - who calls whom for speeds, jumps and falls, fall damage, the lying landing, slides and climbs, where the rules live, the ADRs; pointers from architecture.md and ledge-climbing.md, and stateless Domain rule sets may be static Co-Authored-By: Claude Opus 5.5 --- Docs/architecture.md | 4 ++- Docs/hero-movement.md | 82 ++++++++++++++++++++++++++++++++++++++++++ Docs/ledge-climbing.md | 1 + 3 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 Docs/hero-movement.md diff --git a/Docs/architecture.md b/Docs/architecture.md index a2e44992d..73a0ff2aa 100644 --- a/Docs/architecture.md +++ b/Docs/architecture.md @@ -140,7 +140,8 @@ working. | Adapters | `Adapters/` | MonoBehaviours bridging Unity and services | no rules, the only layer with Unity lifecycle | Dependency rules. Domain and Services share a rank and may use each other: a Domain class is a worker owned by a -Service (`new XDomain().Inject()`). +Service (`new XDomain().Inject()`). A stateless rule set in Domain may be a static class instead, its state passed in +(`SlopeSlideDomain`: shared by a service and an adapter, nothing to inject, tested directly). 1. Nothing outside `Adapters/` uses the `Adapters` namespace. Plain data classes there (`NpcProperties`, `InteractiveProperties`) belong in `Models/`. When a service must create an adapter, it injects a factory @@ -164,6 +165,7 @@ removed from the baseline. Rule 5 is enforced by the asmdef references. | change NPC AI or fights | see the map in `Docs/npc-ai.md` | | change VR melee (swings, fists, block, stab finish) | see the map in `Docs/vr-melee.md` | | change VR bows/crossbows (draw, shot, reload) | see the map in `Docs/vr-ranged.md` | +| change how the hero or NPCs jump, fall, slide, climb or how fast the hero moves | see the map in `Docs/hero-movement.md` | | change world lights, lightmaps, fires, indoor sky | see the map in `Docs/world-lighting.md` | | add a rule about an NPC, item or VOB | a property on its model or an extension in `Extensions/` | | add a use case with state (loading, saving, dialogs) | a service in `Services//`, registered in `ReflexProjectInstaller` | diff --git a/Docs/hero-movement.md b/Docs/hero-movement.md new file mode 100644 index 000000000..ebe88da6b --- /dev/null +++ b/Docs/hero-movement.md @@ -0,0 +1,82 @@ +# Hero and NPC movement + +A map of the code that moves the hero's and the NPCs' bodies beyond walking: speeds, jumps and falls, fall damage, the +lying landing, slides down steep slopes, ledges and ladders. Gothic's values come from the scripts (`GIL_VALUES` of +the guild: `STEP_HEIGHT`, `SLIDE_ANGLE`, `FALLDOWN_HEIGHT`, ...), so mods and monsters bring their own. Core paths are +under `Assets/Gothic-Core/Scripts/`, VR paths under `Assets/Gothic-VR/Scripts/`. + +Decisions: `Docs/adr/2026-11-29-hero-speed-from-animations.md`, `Docs/adr/2026-11-29-hero-jump-fall.md`, +`Docs/adr/2026-11-29-slope-slide.md`, for ledges `Docs/adr/2026-10-28-vr-ledge-climbing.md`. + +## The hero, each frame + +1. `VrHeroJumpFall` (VR adapter, next to VRPlayer) measures the body from the rig port `IVrRig`: feet, grounded, + jumping, climbing, gravity, ground snap, the ground straight under the feet (`IVrRig.TryGetGround`), the run speed + (`VrHeroSpeeds.RunThreshold`). That is one `HeroBodySample` (`Models/Movement/`). +2. It calls `Services/Movement/HeroBodyService.Tick` - the only entry point. It decides the order: + - `HeroFallService` first: the phases from `Domain/Movement/HeroAirborneDomain` (jump, fall, fall flat, + landing, running jump), BS_JUMP / BS_FALL, fall damage at the landing (`NpcFallDomain.GetFallDamage`, raised as + `GlobalEventDispatcher.FallDamage`, applied by `FightService`), the lying landing's timeline + (`HeroLanding.StandUpStart / StandUpEnd`), `GlobalEventDispatcher.HeroLanded`. + - `HeroSlideService` second: `Domain/Movement/SlopeSlideDomain` on a `SlopeSlideState` - slide or not, its speed, + no take-off from steep ground. +3. It applies the returned `HeroBodyResult` to the rig: `IVrRig.SlideVelocity`, `IVrRig.IsTakeOffBlocked`. A running + jump (`HeroFallService.IsRunningJump`) becomes `IVrRig.SetLeapVelocity`. + +Teleports go to `HeroBodyService.OnTeleported`. The services' own `Tick` and `OnTeleported` are internal: a platform +never ticks them itself (Flat would feed the same `HeroBodySample`). + +## The hero's VR body and rig + +| Class | Owns | +|---|---| +| `Adapters/Player/VRHeroMovement` | the only writer of the rig's speeds (land speeds, water's and a transformation's wishes via `VRPlayerService.SetHeroSpeedOverride`), BS_STAND / BS_WALK / BS_RUN / BS_SNEAK - BS_STAND while sliding | +| `Services/VRPlayerService.HeroSpeeds` | the land speeds: the body's animation speeds (`HeroBodySpeeds`), else the rig's own (`IVrRig.DefaultMoveSpeed` / `DefaultRunSpeed`) | +| `Adapters/Player/VrHeroLocomotion` (worker of VRHeroBody) | the body's walk/run/sneak, jump and fall animations, S_SLIDE / S_SLIDEB; measures the loops' speeds | +| `Adapters/Player/VrHeroDownPose` (worker of VRHeroBody) | lying and getting up, following HeroFallService's times (`DownReason`, `VrHeroDownAnimations`) | +| `Adapters/Player/VRSwimDive` | BS_SWIM / BS_DIVE, the water's speed wish | +| `Interaction/Backends/Xri/XriRig` | `IVrRig` on XRI: grounded grace, ground snap, gravity, leap | +| `Interaction/Backends/Xri/XriSlopeSlide` (worker of XriRig) | the ground ray (Default layer only), the slide as a body transformation, `SlopeSlideDomain.RemoveUphill` on the stick | +| `Interaction/Backends/Xri/GothicJumpProvider` | the jump's rise, refuses the take-off when blocked, ledge jumps | + +## NPCs + +`Adapters/Npc/NpcJumpFall` (added to the NPC on demand, asleep while nothing happens, only within 40 m of the hero) +keeps the state switch, the fall and the landing. AI code reaches it through `Domain/Npc/INpcJumpFallFactory`: +`NpcChaseMovement` (climb, ladder, safe drop ahead), `AbstractWalkAnimationAction2` (ladders on a route), +`SpellHitDomain` (Windfist's throw). Its plain workers in `Adapters/Npc/`: + +| Class | Owns | +|---|---| +| `NpcMoveBody` | what all of them ask of the body: rest height, guild rules, can it move, ground below, physics on/off, tracks | +| `NpcSlopeSlide` | the slide: start (not uphill), wall look-ahead, held on the ground, off an edge into NpcJumpFall's fall | +| `NpcLedgeClimb` | ledge climbs (`LedgeService.ProbeNpcClimb`) and ladders (NavMesh links, root lift per animation) | +| `NpcAnimationSequence` | animations one after another for a landing or a climb | + +The rules: `Domain/Npc/NpcFallDomain` (can it move, fall damage, safe height, lying depth), `SlopeSlideDomain` +(shared with the hero), `LedgeService` / `LedgeProbeDomain`, `FallPose` (HUMANS.MDS fall sets). + +## Ledges and ladders (the hero) + +The hero's ledge climbing in VR has its own map: `Docs/ledge-climbing.md`. Its Gothic values (`LedgeRules`, also +`SLIDE_ANGLE` / `SLIDE_ANGLE2` for slides) come from `LedgeService.HeroRules` / `GetRules(guild)`. + +## Where does my change go? + +| You want to change ... | Put it into | +|---|---| +| when a jump or fall starts, falls flat, lands | `HeroAirborneDomain` (with `HeroAirborneDomainTest`) | +| fall damage | `NpcFallDomain.GetFallDamage` (hero and NPCs) | +| when the hero isn't tracked / doesn't slide | `HeroFallService.GetHold` / `HeroSlideService.GetHold` | +| which ground slides, how fast, debounce, blocks | `SlopeSlideDomain` (with `SlopeSlideDomainTest`) | +| the order of the hero's rules per frame | `HeroBodyService` | +| what the VR rig does with a slide or jump | `XriSlopeSlide`, `GothicJumpProvider`, `XriRig` - executing only | +| the hero's speeds | `VRHeroMovement` / `VRPlayerService.HeroSpeeds` (`VrHeroSpeeds`, `VRConstants.Movement`) | +| an NPC's fall, landing, climb or slide | `NpcJumpFall` and its worker for that move | + +## Pitfalls + +- Nothing here is saved: a loaded game starts standing on the ground. +- Ground for slides and the jump block is the Default layer only (world and solid VOBs) - an NPC or item under the + feet is no slope. NPCs' ground rays use the same layer. +- `SlopeSlideDomain` is a static class: a stateless rule set shared by a service and an adapter, its state passed in. diff --git a/Docs/ledge-climbing.md b/Docs/ledge-climbing.md index 3cd8fe987..43765028a 100644 --- a/Docs/ledge-climbing.md +++ b/Docs/ledge-climbing.md @@ -3,6 +3,7 @@ The VR player climbs exactly the ledges Gothic's hero can climb: by gripping the lip and pulling up, by a comfort fade, or by teleporting onto the top. XRI backend only. Why it's built this way: Docs/adr/2026-10-28-vr-ledge-climbing.md. +Jumps, falls, slides down slopes, NPC climbs and the hero's speeds around it: Docs/hero-movement.md. ## Gothic's rules (Core) From ed4c62e0c4e9808aee7878fc7cea009fd9b4b162 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:09:01 +0000 Subject: [PATCH 24/31] docs: the slope slide decision record names HeroBodyService (the fall before the slide, decided in Core), NpcSlopeSlide and the movement map Co-Authored-By: Claude Opus 5.5 --- Docs/adr/2026-11-29-slope-slide.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Docs/adr/2026-11-29-slope-slide.md b/Docs/adr/2026-11-29-slope-slide.md index 4309beba1..a742bdfe1 100644 --- a/Docs/adr/2026-11-29-slope-slide.md +++ b/Docs/adr/2026-11-29-slope-slide.md @@ -1,7 +1,7 @@ # ADR: Sliding down steep slopes - Date: 2026-11-29 -- Technical details: the class docs of SlopeSlideDomain and HeroSlideService (Core), NpcJumpFall (Core), XriSlopeSlide and VrHeroJumpFall (VR) +- Technical details: the class docs of SlopeSlideDomain, HeroSlideService and HeroBodyService (Core), NpcJumpFall and NpcSlopeSlide (Core), XriSlopeSlide and VrHeroJumpFall (VR); the map of the movement code: Docs/hero-movement.md ## Context @@ -27,4 +27,5 @@ In the VR game the hero stood on any slope. Worse, jumping again and again carri - An NPC that dies, is knocked out or starts swimming mid-slide stops sliding at once. A dead or unconscious body stays as its death or knockout left it; any other gets its physics back. A fall or a climb still ends on the ground first, without the landing or idle animations. - Not checked while climbing, swimming or wading, lying after a fall, after a teleport, while sitting or using something, or while transformed into a monster: the transformed hero still stands on any slope (his monster's own angle isn't applied yet). - The hero with no slide animation in his model (a mod) still slides, with his normal animations. -- Flat mode can feed the same rules from its own controller once it runs again. +- The fall is checked before the slide each frame, in Core (HeroBodyService): a landing on a steep slope is a landing, the slide begins after it. A platform only measures the body and applies the result. +- Flat mode can feed the same rules from its own controller once it runs again, through the same entry point. From a959d3f59835c532c0c9b54abdc076eb246a3fbc Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:11:55 +0000 Subject: [PATCH 25/31] chore: meta files of the NPC movement workers and HeroBodyService (generated by Unity on import) Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/NpcAnimationSequence.cs.meta | 2 ++ Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs.meta | 2 ++ Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs.meta | 2 ++ Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs.meta | 2 ++ .../Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs.meta | 2 ++ .../Scripts/Services/Movement/HeroBodyService.cs.meta | 2 ++ 6 files changed, 12 insertions(+) create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs.meta create mode 100644 Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs.meta diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs.meta new file mode 100644 index 000000000..128931628 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 942fe2213bb48d1469cd59dbcc163b97 \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs.meta new file mode 100644 index 000000000..e8babaf78 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e14f7828e3f9a6143be54faa354fdedf \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs.meta new file mode 100644 index 000000000..dfcbbb182 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2f1ccd6e4cccfbf40919246e924d11eb \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs.meta b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs.meta new file mode 100644 index 000000000..2be840289 --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d178c864e4e3e644c94526dc7b8adfcd \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs.meta b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs.meta new file mode 100644 index 000000000..5b9dd7bca --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroBodyResult.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e1fedd2eda3b1c146a0ff488575df9ff \ No newline at end of file diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs.meta b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs.meta new file mode 100644 index 000000000..4cb1a37bc --- /dev/null +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0a8301b387e36e54589ab0d78d90e013 \ No newline at end of file From 5066d03c4392e84fde76ff99091055e775244629 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:33:31 +0000 Subject: [PATCH 26/31] docs: CLAUDE.md allows a stateless Domain rule set as a static class with its state passed in, like Docs/architecture.md - one rule, stated the same in both places Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index e4f3c782d..81119a20e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -52,7 +52,7 @@ Gothic.Core with engine, services, domain logic Within Core, responsibility is further split into layers: **Model** (data) ← **Domain** (business logic) ⇄ **Service** (orchestration) ← **Adapter** (Unity integration). Arrows point to what a layer may use: - Models only use Models. -- Domain and Services are one rank and may use each other. Domain classes are workers owned by a Service, created via `new XDomain().Inject()` (not registered in Reflex), and may `[Inject]` Services. +- Domain and Services are one rank and may use each other. Domain classes are workers owned by a Service, created via `new XDomain().Inject()` (not registered in Reflex), and may `[Inject]` Services - or, for a stateless rule set, a static class with its state passed in (see `Docs/architecture.md`). - Nothing below Adapters uses Adapters. Principles, dependency rules and "where does my code go": `Docs/architecture.md`. From 83f3583e01058f9cab5a664f325efb55a862fd6d Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:35:53 +0000 Subject: [PATCH 27/31] fix: the hero's slide rules all in Core - BS_STAND while sliding is HeroSlideService's (TryGetLocomotionBodyState, VRHeroMovement asks), no slide starts in the air (HeroSlideHold.Airborne while the fall's phase isn't Grounded: a drop onto a steep slope lands first), and a missing hero ends a running slide (NoHero) so the rig keeps no slide velocity Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Models/Movement/HeroSlideHold.cs | 12 +++++++- .../Services/Movement/HeroBodyService.cs | 5 ++-- .../Services/Movement/HeroSlideService.cs | 28 +++++++++++++++++-- .../Scripts/Adapters/Player/VRHeroMovement.cs | 8 +++--- Docs/adr/2026-11-29-slope-slide.md | 2 +- Docs/hero-movement.md | 5 ++-- 6 files changed, 47 insertions(+), 13 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs index 06aa42321..34d00de6c 100644 --- a/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs +++ b/Assets/Gothic-Core/Scripts/Models/Movement/HeroSlideHold.cs @@ -31,6 +31,11 @@ public enum HeroSlideHold /// Jumping, + /// + /// In the air without his own jump (HeroFallService's phase isn't Grounded): the fall lands first. + /// + Airborne, + /// /// Lying after a fall flat until he stood up. /// @@ -49,6 +54,11 @@ public enum HeroSlideHold /// /// Teleported this frame. /// - Teleported + Teleported, + + /// + /// No hero (or his properties) right now - a slide running ends. + /// + NoHero } } diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs index 7a9ab2a8e..ab5f709e8 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroBodyService.cs @@ -10,10 +10,11 @@ namespace Gothic.Core.Services.Movement /// not per platform: /// 1. HeroFallService - jumps, falls, fall damage, the lying landing. /// 2. HeroSlideService - slides down steep slopes, no take-off from them. After the fall: a landing on a steep - /// slope is a landing, the slide begins after it (and reads the landing's lying lock). + /// slope is a landing, the slide begins after it (it reads the fall's phase and the landing's lying lock). /// The result carries the fall's event of the frame (HeroAirEvent: JumpStarted starts the VR leap). The platform /// still reads the two services' state for its body (HeroFallService.Phase / IsRunningJump / TakeOffVelocity, - /// HeroSlideService.IsSliding) - it only never ticks them itself. + /// HeroSlideService.IsSliding, the body state while sliding: HeroSlideService.TryGetLocomotionBodyState) - it + /// only never ticks them itself. /// public class HeroBodyService { diff --git a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs index 22544e247..7022524ca 100644 --- a/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Movement/HeroSlideService.cs @@ -19,9 +19,11 @@ namespace Gothic.Core.Services.Movement /// meanwhile (SlopeSlideDomain.RemoveUphill). /// - A slide is no fall: the body stays on the ground (the platform counts it as grounded), no fall damage. Off an /// edge the slide ends and HeroFallService's normal fall begins from there. - /// - Body state: BS_STAND while sliding (OpenGothic: BS_NONE for S_SLIDE/S_SLIDEB) - VR: VRHeroMovement. + /// - Body state: BS_STAND while sliding (OpenGothic: BS_NONE for S_SLIDE/S_SLIDEB), decided here - the platform + /// asks TryGetLocomotionBodyState before it sets walk/run/sneak (VR: VRHeroMovement). /// Not checked (no slide, the jump allowed): climbing, transformed (the puppet stands on any slope - its own guild - /// isn't applied), no gravity or water, in the air, lying after a fall flat, down or busy (sitting, mobs). + /// isn't applied), no gravity or water, in the air (HeroFallService's phase not Grounded), lying after a fall + /// flat, down or busy (sitting, mobs), no hero. /// Not saved: a loaded game starts standing. /// public class HeroSlideService @@ -53,6 +55,17 @@ public HeroSlideService() GlobalEventDispatcher.WorldSceneLoaded.AddListener(ResetAll); } + /// + /// The body state the scripts see for the hero's walking while Core decides it - false: the platform's own + /// walk/run/sneak counts. BS_STAND while he slides: no footsteps, no running for the NPCs' perceptions. A + /// platform asks this before it sets BS_WALK / BS_RUN / BS_SNEAK. + /// + public bool TryGetLocomotionBodyState(out VmGothicEnums.BodyState bodyState) + { + bodyState = VmGothicEnums.BodyState.BsStand; + return _state.IsSliding; + } + /// /// S_SLIDE when the body faces where it slides, S_SLIDEB when it slides backwards - null if the body's model /// has neither (SlopeSlideDomain.GetAnimation). @@ -70,7 +83,11 @@ internal void Tick(in HeroBodySample sample) { var hero = _npcService.GetHeroContainer(); if (hero?.Props == null) + { + // No slide velocity left behind for the platform to keep applying. + Hold(sample.FeetPosition, HeroSlideHold.NoHero, null); return; + } var hold = GetHold(hero, sample); if (hold != HeroSlideHold.None) @@ -123,6 +140,9 @@ private HeroSlideHold GetHold(NpcContainer hero, in HeroBodySample sample) return HeroSlideHold.NoGravity; if (sample.IsJumping) return HeroSlideHold.Jumping; + // Off a low ledge above a steep slope: the fall lands first (its damage counted), the slide after it. + if (_heroFallService.Phase != HeroAirPhase.Grounded) + return HeroSlideHold.Airborne; if (_heroFallService.IsLyingAfterFall) return HeroSlideHold.LyingAfterFall; @@ -154,7 +174,7 @@ private void Hold(Vector3 feet, HeroSlideHold hold, NpcContainer hero) _hold = hold; } - private static string GetText(HeroSlideHold hold, NpcContainer hero) + private string GetText(HeroSlideHold hold, NpcContainer hero) { return hold switch { @@ -162,10 +182,12 @@ private static string GetText(HeroSlideHold hold, NpcContainer hero) HeroSlideHold.Transformed => "transformed", HeroSlideHold.NoGravity => "no gravity (swimming, diving)", HeroSlideHold.Jumping => "jumping", + HeroSlideHold.Airborne => $"in the air ({_heroFallService.Phase})", HeroSlideHold.LyingAfterFall => "lying after a fall", HeroSlideHold.InWater => "in water", HeroSlideHold.Busy => $"body state {hero?.Props?.BodyState}", HeroSlideHold.Teleported => "teleported", + HeroSlideHold.NoHero => "no hero", _ => hold.ToString() }; } diff --git a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs index 00a75ac84..cde365b98 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Player/VRHeroMovement.cs @@ -202,11 +202,11 @@ private void UpdateHeroBodyState() if (props == null || !props.BodyState.IsLocomotion()) return; - // Sliding down a slope is no walking (OpenGothic: BS_NONE for S_SLIDE) - no steps, no running for the - // scripts. - if (_heroSlideService.IsSliding) + // Core decides while it overrides the walking (BS_STAND while sliding down a slope) - no steps, no + // running for the scripts. + if (_heroSlideService.TryGetLocomotionBodyState(out var coreBodyState)) { - props.BodyState = VmGothicEnums.BodyState.BsStand; + props.BodyState = coreBodyState; return; } diff --git a/Docs/adr/2026-11-29-slope-slide.md b/Docs/adr/2026-11-29-slope-slide.md index a742bdfe1..a95a00933 100644 --- a/Docs/adr/2026-11-29-slope-slide.md +++ b/Docs/adr/2026-11-29-slope-slide.md @@ -27,5 +27,5 @@ In the VR game the hero stood on any slope. Worse, jumping again and again carri - An NPC that dies, is knocked out or starts swimming mid-slide stops sliding at once. A dead or unconscious body stays as its death or knockout left it; any other gets its physics back. A fall or a climb still ends on the ground first, without the landing or idle animations. - Not checked while climbing, swimming or wading, lying after a fall, after a teleport, while sitting or using something, or while transformed into a monster: the transformed hero still stands on any slope (his monster's own angle isn't applied yet). - The hero with no slide animation in his model (a mod) still slides, with his normal animations. -- The fall is checked before the slide each frame, in Core (HeroBodyService): a landing on a steep slope is a landing, the slide begins after it. A platform only measures the body and applies the result. +- The fall is checked before the slide each frame, in Core (HeroBodyService): a landing on a steep slope is a landing, the slide begins after it, and no slide begins while he is in the air. A platform only measures the body and applies the result; the standing body state while sliding is Core's too, the platform asks for it before it sets walking or running. - Flat mode can feed the same rules from its own controller once it runs again, through the same entry point. diff --git a/Docs/hero-movement.md b/Docs/hero-movement.md index 75bf8faa0..c32ea4603 100644 --- a/Docs/hero-movement.md +++ b/Docs/hero-movement.md @@ -31,7 +31,7 @@ never ticks them itself (Flat would feed the same `HeroBodySample`). | Class | Owns | |---|---| -| `Adapters/Player/VRHeroMovement` | the only writer of the rig's speeds (land speeds, water's and a transformation's wishes via `VRHeroSpeedService.SetHeroSpeedOverride`), BS_STAND / BS_WALK / BS_RUN / BS_SNEAK - BS_STAND while sliding | +| `Adapters/Player/VRHeroMovement` | the only writer of the rig's speeds (land speeds, water's and a transformation's wishes via `VRHeroSpeedService.SetHeroSpeedOverride`), BS_STAND / BS_WALK / BS_RUN / BS_SNEAK - while sliding the one Core decides (`HeroSlideService.TryGetLocomotionBodyState`: BS_STAND) | | `Services/VRHeroSpeedService` (PlayerScope) | the land speeds (`HeroSpeeds`): the body's animation speeds (`HeroBodySpeeds`), else the rig's own (`IVrRig.DefaultMoveSpeed` / `DefaultRunSpeed`), the speed potion (`IsHeroSpeedBoosted`); the overrides (`HeroSpeedOverride`, water first, `GetOverrideSpeeds`) | | `Adapters/Player/VrHeroLocomotion` (worker of VRHeroBody) | the body's walk/run/sneak, jump and fall animations, S_SLIDE / S_SLIDEB; measures the loops' speeds | | `Adapters/Player/VrHeroDownPose` (worker of VRHeroBody) | lying and getting up, following HeroFallService's times (`DownReason`, `VrHeroDownAnimations`); a teleport (`IVrRig.Teleported`) ends the lying | @@ -68,7 +68,8 @@ The hero's ledge climbing in VR has its own map: `Docs/ledge-climbing.md`. Its G |---|---| | when a jump or fall starts, falls flat, lands | `HeroAirborneDomain` (with `HeroAirborneDomainTest`) | | fall damage | `NpcFallDomain.GetFallDamage` (hero and NPCs) | -| when the hero isn't tracked / doesn't slide | `HeroFallService.GetHold` / `HeroSlideService.GetHold` | +| when the hero isn't tracked / doesn't slide | `HeroFallService.GetHold` / `HeroSlideService.GetHold` (`HeroSlideHold`) | +| the body state the scripts see while he slides | `HeroSlideService.TryGetLocomotionBodyState` | | which ground slides, how fast, debounce, blocks | `SlopeSlideDomain` (with `SlopeSlideDomainTest`) | | the order of the hero's rules per frame | `HeroBodyService` | | what the VR rig does with a slide or jump | `XriSlopeSlide`, `GothicJumpProvider`, `XriRig` - executing only | From 125e95e06dbb44ea39cc4e0651167ed660f11b3b Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:36:10 +0000 Subject: [PATCH 28/31] fix: XriSlopeSlide isn't sliding without a body transformer - nothing would move the body, but XriRig counted him grounded and held his gravity Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs index b1800cd5a..c0b2c5553 100644 --- a/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs +++ b/Assets/Gothic-VR/Scripts/Interaction/Backends/Xri/XriSlopeSlide.cs @@ -47,7 +47,11 @@ public XriSlopeSlide(CharacterController characterController) _transformation = new DelegateXRBodyTransformation(Apply); } - public bool IsSliding => _velocity != Vector3.zero; + /// + /// A slide is queued for the body - never without a body transformer (nothing would move it, but the rig would + /// count the hero as grounded and hold his gravity). + /// + public bool IsSliding => _velocity != Vector3.zero && _bodyTransformer != null; /// /// Set every frame while sliding: queues the slide for the body transformer's next update. From b656225291ac34b067f7ef6cf2512b2cd92da081 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:37:29 +0000 Subject: [PATCH 29/31] fix: one wall test for an NPC's fall and slide (NpcMoveBody.IsWallAhead, near-vertical hits only) - a falling NPC no longer stops its run at a slope rising ahead but lands on it; NpcSlopeSlide logs as [NpcSlide] Co-Authored-By: Claude Opus 5.5 --- .../Scripts/Adapters/Npc/NpcJumpFall.cs | 6 ++---- .../Scripts/Adapters/Npc/NpcMoveBody.cs | 14 ++++++++++++++ .../Scripts/Adapters/Npc/NpcSlopeSlide.cs | 15 +++++---------- Docs/hero-movement.md | 4 ++-- 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs index c8e9f16df..37c93daa1 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcJumpFall.cs @@ -275,11 +275,9 @@ private void TickFall() var position = transform.position; var moveH = _fallVelocityH * dt; - if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, - moveH.magnitude + NpcMoveBody.WallLookAhead, 1 << Constants.DefaultLayer, - QueryTriggerInteraction.Ignore)) + if (_body.IsWallAhead(position, moveH)) { - // Against a wall: slide down it. + // Against a wall: slide down it. A slope rising ahead is no wall - the fall lands on it. _fallVelocityH = Vector3.zero; moveH = Vector3.zero; } diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs index 74661f9f3..6b709879e 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs @@ -37,6 +37,8 @@ public class NpcMoveBody public const float WallLookAhead = 0.3f; private const float _groundProbeExtra = 0.1f; + // A wall ray hit with a normal.y above this (~80 deg) is a slope rising ahead or beside, not a wall. + private const float _wallMaxNormalY = 0.17f; public readonly NpcContainer Npc; public readonly Transform Transform; @@ -76,6 +78,18 @@ public bool TryGetGround(Vector3 position, out RaycastHit hit) QueryTriggerInteraction.Ignore); } + /// + /// A wall in the way of this frame's horizontal move from a root at position (WallLookAhead beyond it) - for a + /// fall and a slide alike. Only near-vertical hits are walls: a slope rising ahead or beside is no wall, the + /// move goes on until the ground ray finds it. + /// + public bool IsWallAhead(Vector3 position, Vector3 moveH) + { + return moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, out var hit, + moveH.magnitude + WallLookAhead, 1 << Constants.DefaultLayer, QueryTriggerInteraction.Ignore) && + hit.normal.y <= _wallMaxNormalY; + } + /// /// A fall, climb or slide takes the body: no physics, none of the other animations. /// diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs index 38b7e8756..b38f0b420 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs @@ -18,9 +18,6 @@ namespace Gothic.Core.Adapters.Npc /// public class NpcSlopeSlide { - // A wall ray hit with a normal.y above this (~80 deg) is the rising slope beside it, not a wall. - private const float _wallMaxNormalY = 0.17f; - private readonly NpcMoveBody _body; private readonly SlopeSlideState _state = new(); private string _animationName; @@ -67,7 +64,7 @@ public bool TryStart(RaycastHit ground, Vector3 moved) _animationName = null; PlayAnimation(); - Logger.Log($"[NpcJumpFall] {_body.Name} slides down a {_state.GroundAngle:F0} deg slope (SLIDE_ANGLE " + + Logger.Log($"[NpcSlide] {_body.Name} slides down a {_state.GroundAngle:F0} deg slope (SLIDE_ANGLE " + $"{_body.Rules.SlideAngle:F0}).", LogCat.Ai); return true; } @@ -85,10 +82,8 @@ public SlopeSlideEvent Tick(out Vector3 fallVelocity) var move = _state.Velocity * dt; var moveH = new Vector3(move.x, 0f, move.z); // Against a wall: the slide gets nowhere and ends as blocked. Across a slope the ray may hit the slope - // rising beside the NPC - only near-vertical hits are walls. - if (moveH.sqrMagnitude > 0f && Physics.Raycast(position, moveH.normalized, out var wall, - moveH.magnitude + NpcMoveBody.WallLookAhead, 1 << Constants.DefaultLayer, - QueryTriggerInteraction.Ignore) && wall.normal.y <= _wallMaxNormalY) + // rising beside the NPC - no wall (NpcMoveBody.IsWallAhead). + if (_body.IsWallAhead(position, moveH)) move = Vector3.zero; var next = position + move; @@ -97,7 +92,7 @@ public SlopeSlideEvent Tick(out Vector3 fallVelocity) fallVelocity = _state.Velocity; Hold(); StopAnimation(); - Logger.Log($"[NpcJumpFall] {_body.Name} slides off an edge.", LogCat.Ai); + Logger.Log($"[NpcSlide] {_body.Name} slides off an edge.", LogCat.Ai); _body.Transform.position = next; return SlopeSlideEvent.LostGround; } @@ -153,7 +148,7 @@ private void PlayAnimation() private void LogEnd(string reason) { - Logger.Log($"[NpcJumpFall] {_body.Name} slide ended ({reason}) after " + + Logger.Log($"[NpcSlide] {_body.Name} slide ended ({reason}) after " + $"{SlopeSlideDomain.GetSlidDistance(_state, _body.Feet):F1} m.", LogCat.Ai); } } diff --git a/Docs/hero-movement.md b/Docs/hero-movement.md index c32ea4603..53aead914 100644 --- a/Docs/hero-movement.md +++ b/Docs/hero-movement.md @@ -49,8 +49,8 @@ keeps the state switch, the fall and the landing. AI code reaches it through `Do | Class | Owns | |---|---| -| `NpcMoveBody` | what all of them ask of the body: rest height, guild rules, can it move, ground below, physics on/off, tracks | -| `NpcSlopeSlide` | the slide: start (not uphill), wall look-ahead, held on the ground, off an edge into NpcJumpFall's fall | +| `NpcMoveBody` | what all of them ask of the body: rest height, guild rules, can it move, ground below, the wall ahead of a fall or slide (near-vertical hits only), physics on/off, tracks | +| `NpcSlopeSlide` | the slide: start (not uphill), wall look-ahead, held on the ground, off an edge into NpcJumpFall's fall; logs `[NpcSlide]` | | `NpcLedgeClimb` | ledge climbs (`LedgeService.ProbeNpcClimb`) and ladders (NavMesh links, root lift per animation) | | `NpcAnimationSequence` | animations one after another for a landing or a climb | From ad4d83fee959e1f42ec333eff54a2bb2ca96ebcb Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:37:42 +0000 Subject: [PATCH 30/31] refactor: NpcJumpFall's workers (NpcMoveBody, NpcSlopeSlide, NpcLedgeClimb, NpcAnimationSequence) are internal to Core - AI code reaches NPC movement only through INpcJumpFallFactory, nothing bypasses NpcJumpFall's state switch Co-Authored-By: Claude Opus 5.5 --- Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs | 2 +- Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs | 2 +- Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs | 2 +- Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs | 2 +- Docs/hero-movement.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs index 047def661..0f6253a16 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcAnimationSequence.cs @@ -7,7 +7,7 @@ namespace Gothic.Core.Adapters.Npc /// (NpcLedgeClimb). Animations the model doesn't have are skipped. Can't move any more (died, swimming): the rest /// plays none of them (the death's or swimming's animations take over), the time still runs to the end. /// - public class NpcAnimationSequence + internal class NpcAnimationSequence { private readonly NpcMoveBody _body; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs index f53c31af5..028f1ec26 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcLedgeClimb.cs @@ -19,7 +19,7 @@ namespace Gothic.Core.Adapters.Npc /// - Ladders (a NavMesh ladder link): onto the ladder, as many climb cycles as its height takes, off it - the /// animations' own root lift carries the body where they have one, else a plain climb. /// - public class NpcLedgeClimb + internal class NpcLedgeClimb { [Inject] private readonly AnimationService _animationService; [Inject] private readonly LedgeService _ledgeService; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs index 6b709879e..a22ba4e89 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcMoveBody.cs @@ -19,7 +19,7 @@ namespace Gothic.Core.Adapters.Npc /// its rest height, its guild's ledge and slide values, whether it can move, its animations, the ground below. /// Created by NpcJumpFall per NPC (new().Inject()) and shared with its workers - one place for what they all ask. /// - public class NpcMoveBody + internal class NpcMoveBody { [Inject] private readonly GameStateService _gameStateService; [Inject] private readonly AnimationService _animationService; diff --git a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs index b38f0b420..122e21807 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Npc/NpcSlopeSlide.cs @@ -16,7 +16,7 @@ namespace Gothic.Core.Adapters.Npc /// and sliding down. /// Moves the body itself (a wall ray ahead, held on the ground below) - NpcJumpFall decides the state. /// - public class NpcSlopeSlide + internal class NpcSlopeSlide { private readonly NpcMoveBody _body; private readonly SlopeSlideState _state = new(); diff --git a/Docs/hero-movement.md b/Docs/hero-movement.md index 53aead914..9ed652dcd 100644 --- a/Docs/hero-movement.md +++ b/Docs/hero-movement.md @@ -45,7 +45,7 @@ never ticks them itself (Flat would feed the same `HeroBodySample`). `Adapters/Npc/NpcJumpFall` (added to the NPC on demand, asleep while nothing happens, only within 40 m of the hero) keeps the state switch, the fall and the landing. AI code reaches it through `Domain/Npc/INpcJumpFallFactory`: `NpcChaseMovement` (climb, ladder, safe drop ahead), `AbstractWalkAnimationAction2` (ladders on a route), -`SpellHitDomain` (Windfist's throw). Its plain workers in `Adapters/Npc/`: +`SpellHitDomain` (Windfist's throw). Its plain workers in `Adapters/Npc/`, internal to Core - nothing else uses them: | Class | Owns | |---|---| From 22d68e703cde8d8e338bb420d73fedafaa8961a9 Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 29 Nov 2026 16:38:50 +0000 Subject: [PATCH 31/31] test: a slide off an edge falls from the edge (HeroAirborneDomainTest.SlideOffAnEdgeFallsFromTheEdge) - the slide counts as ground, the drop starts at the last grounded frame, the rig's grace only lowers it by a few cm; the movement map names it among the pitfalls Co-Authored-By: Claude Opus 5.5 --- .../Movement/HeroAirborneDomainTest.cs | 36 +++++++++++++++++++ Docs/hero-movement.md | 10 ++++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs b/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs index 8910e873e..5760f7623 100644 --- a/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs +++ b/Assets/Gothic-Tests/EditMode/Movement/HeroAirborneDomainTest.cs @@ -356,6 +356,42 @@ public void JumpPastFalldownHeightInOneStepLandsLying() Assert.AreEqual(6f, _landing.Height, 0.01f); } + /// + /// A slide is no fall (HeroSlideService - the platform counts the sliding hero as grounded): 2 m down a steep + /// slope and off its edge, the drop counts from the edge, not from where the slide began. The platform's + /// grounded grace after the edge (XRI: 0.12 s) only lowers that start by the few cm fallen in it. + /// + [Test] + public void SlideOffAnEdgeFallsFromTheEdge() + { + Stand(10f); + // Down a 60 deg slope at 6 m/s, on the ground: 3 m/s across, 5.2 m/s down. + _moveVelocity = Vector3.forward * 3f; + var y = 10f; + while (y > 8f) + { + y = Mathf.Max(y - 5.2f * _dt, 8f); + Tick(y, true); + } + Assert.AreEqual(HeroAirPhase.Grounded, _domain.Phase); + + // Off the edge: the slide has ended, the grace still reports ground, then the fall 4 m down. + var velocityY = 0f; + for (var time = 0f; time < 0.12f; time += _dt) + { + velocityY -= _gravity * _dt; + y += velocityY * _dt; + Tick(y, true); + } + FallTo(y, 4f, velocityY); + + Assert.AreEqual(0, _teleports); + Assert.AreEqual(1, _falls); + Assert.AreEqual(1, _landings); + Assert.IsTrue(_landing.IsLying); + Assert.AreEqual(4f, _landing.Height, 0.1f); + } + [Test] public void SteppingOffASmallEdgeIsNoLanding() { diff --git a/Docs/hero-movement.md b/Docs/hero-movement.md index 9ed652dcd..be25fc45d 100644 --- a/Docs/hero-movement.md +++ b/Docs/hero-movement.md @@ -15,9 +15,9 @@ Decisions: `Docs/adr/2026-11-29-hero-speed-from-animations.md`, `Docs/adr/2026-1 (`VrHeroSpeeds.RunThreshold`). That is one `HeroBodySample` (`Models/Movement/`). 2. It calls `Services/Movement/HeroBodyService.Tick` - the only entry point. It decides the order: - `HeroFallService` first: the phases from `Domain/Movement/HeroAirborneDomain` (jump, fall, fall flat, - landing, running jump and its `TakeOffVelocity`), BS_JUMP / BS_FALL, fall damage at the landing (`NpcFallDomain.GetFallDamage`, raised as - `GlobalEventDispatcher.FallDamage`, applied by `FightService`), the lying landing's timeline - (`HeroLanding.StandUpStart / StandUpEnd`), `GlobalEventDispatcher.HeroLanded`. + landing, running jump and its `TakeOffVelocity`), BS_JUMP / BS_FALL, fall damage at the landing + (`NpcFallDomain.GetFallDamage`, raised as `GlobalEventDispatcher.FallDamage`, applied by `FightService`), the + lying landing's timeline (`HeroLanding.StandUpStart / StandUpEnd`), `GlobalEventDispatcher.HeroLanded`. - `HeroSlideService` second: `Domain/Movement/SlopeSlideDomain` on a `SlopeSlideState` - slide or not, its speed, no take-off from steep ground. 3. It applies the returned `HeroBodyResult` to the rig: `IVrRig.SlideVelocity`, `IVrRig.IsTakeOffBlocked`. Its @@ -81,4 +81,8 @@ The hero's ledge climbing in VR has its own map: `Docs/ledge-climbing.md`. Its G - Nothing here is saved: a loaded game starts standing on the ground. - Ground for slides and the jump block is the Default layer only (world and solid VOBs) - an NPC or item under the feet is no slope. NPCs' ground rays use the same layer. +- A slide off an edge falls from the edge: the platform counts the sliding hero as grounded, so the fall starts at + the last grounded frame - a few cm lower by the rig's grounded grace + (`HeroAirborneDomainTest.SlideOffAnEdgeFallsFromTheEdge`). No slide starts while the fall's phase isn't Grounded + (`HeroSlideHold.Airborne`). - `SlopeSlideDomain` is a static class: a stateless rule set shared by a service and an adapter, its state passed in.