From dee2e738d8c3a810dcce8d5d436425d4e9132cdb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 5 Dec 2026 06:37:26 +0100 Subject: [PATCH] Cut 5b-2: Hybrid B centroidal GRF + 2nd-order joint mech locomotion across all 7 walkers --- client/ArenaRenderer.cs | 27 +- client/VehicleAssetCache.cs | 11 +- client/VehicleRigAnimator.cs | 806 ++++----- client/tests/Smoke.cs | 109 +- src/RustToDust.Core/GridChassis.cs | 104 +- src/RustToDust.Ymir/ArenaSession.cs | 208 ++- src/RustToDust.Ymir/WalkerLocomotion.cs | 1576 ++++++++++++++++++ tests/RustToDust.Tests/DetectionLosTests.cs | 7 +- tests/RustToDust.Tests/HybridBWalkerTests.cs | 714 ++++++++ 9 files changed, 3104 insertions(+), 458 deletions(-) create mode 100644 src/RustToDust.Ymir/WalkerLocomotion.cs create mode 100644 tests/RustToDust.Tests/HybridBWalkerTests.cs diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index 726e158..aa8c2db 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -549,7 +549,14 @@ public partial class ArenaRenderer : Node3D { vis.RigDtAccum = 0f; vis.RigSkipFrames = 0; - VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt); + if (c.Grid.Spec.IsWalker && session.TrySampleInterpolatedWalkerPose(true, c.Id, alpha, out var walkerSnap)) + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt, in walkerSnap); + } + else + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt); + } } else { @@ -557,7 +564,14 @@ public partial class ArenaRenderer : Node3D vis.RigSkipFrames++; if (vis.RigSkipFrames >= 2) { - VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum); + if (c.Grid.Spec.IsWalker && session.TrySampleInterpolatedWalkerPose(true, c.Id, alpha, out var walkerSnap)) + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum, in walkerSnap); + } + else + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum); + } vis.RigDtAccum = 0f; vis.RigSkipFrames = 0; } @@ -668,7 +682,14 @@ public partial class ArenaRenderer : Node3D IsGrounded: !s.Grid.Spec.IsVtol); vis.Visual.SyncMountedGear(s.Grid); - VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis); + if (s.Grid.Spec.IsWalker && session.TrySampleInterpolatedWalkerPose(false, s.Id, alpha, out var walkerSnap)) + { + VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis, in walkerSnap); + } + else + { + VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis); + } } vis.Visual.SubmitToPool(_partPool); diff --git a/client/VehicleAssetCache.cs b/client/VehicleAssetCache.cs index 4bf9d4f..346e3ac 100644 --- a/client/VehicleAssetCache.cs +++ b/client/VehicleAssetCache.cs @@ -567,20 +567,25 @@ public sealed class VehicleAssetCache : IDisposable private static readonly HashSet ExactStructuralNodeNames = new(StringComparer.OrdinalIgnoreCase) { - "chassis", "hull", "pelvis", "core", "trunk", "waist", "torso.pose", "aim.turret", "hull.pose", - "legl.hip", "legr.hip", "legl.shin", "legr.shin", "legl.foot", "legr.foot", + "chassis", "hull", "pelvis", "core", "trunk", "waist", "waistlug", "torso.pose", "aim.turret", "hull.pose", + "legl.hipslew", "legr.hipslew", "legl.hip", "legr.hip", "legl.hipyaw", "legr.hipyaw", + "legl.cross", "legr.cross", + "legl.shin", "legr.shin", "legl.foot", "legr.foot", "footl", "footr", "legl.upper", "legr.upper", "legl.lower", "legr.lower", "legl.ankle", "legr.ankle", "legl.thigh", "legr.thigh", "legl.cannon", "legr.cannon", "legl.oleo", "legr.oleo", "legl.oleofork", "legr.oleofork", "legl.torqueup", "legr.torqueup", "legl.torquelow", "legr.torquelow", "legl.lug", "legr.lug", "legl.ramluga0", "legl.ramluga1", "legr.ramluga0", "legr.ramluga1", "legl.recessram0", "legl.recessram1", "legr.recessram0", "legr.recessram1", + "legfl.coxa", "legfr.coxa", "legbl.coxa", "legbr.coxa", "legfl.s1", "legfr.s1", "legbl.s1", "legbr.s1", "legfl.s2", "legfr.s2", "legbl.s2", "legbr.s2", "footfl", "footfr", "footbl", "footbr", + "bone.hip_splay.fl", "bone.hip_splay.fr", "bone.hip_splay.rl", "bone.hip_splay.rr", "thigh.fl", "thigh.fr", "thigh.rl", "thigh.rr", "shin.fl", "shin.fr", "shin.rl", "shin.rr", - "ankle.fl", "ankle.fr", "ankle.rl", "ankle.rr" + "ankle.fl", "ankle.fr", "ankle.rl", "ankle.rr", + "foot.fl", "foot.fr", "foot.rl", "foot.rr" }; private static bool IsStructuralNodeName(string name) => diff --git a/client/VehicleRigAnimator.cs b/client/VehicleRigAnimator.cs index ca73f27..c0359ec 100644 --- a/client/VehicleRigAnimator.cs +++ b/client/VehicleRigAnimator.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Godot; using RustToDust.Core; +using RustToDust.Ymir; namespace RustToDust.Client; @@ -23,8 +24,9 @@ public readonly record struct VehicleRigDriveInput( /// - Wheeled: wheel spin (v / r), front-axle steering, subtle chassis suspension roll/pitch. /// - Turrets/Torsos/Arms: yaw tracking (joint.turret_yaw, joint.torso_yaw) & arm pitch. /// - VTOL: rotor spin scaled by EngineThermalPerf + lift demand, nacelle tilt with acceleration. -/// - Walkers/Mechs: procedural leg stride returning to neutral rest when stopped, Manticore tail aiming, -/// and Breaker's damped oleo strut + 2-link scissor torque links + telescoping recess rams. +/// - Walkers/Mechs: pure FK posing from Hybrid B with per-segment +/// rest-basis alignment (Q_offset), Manticore tail aiming, and Breaker's real GRF-driven +/// oleo strut + 2-link scissor torque links + telescoping recess rams. /// public static class VehicleRigAnimator { @@ -73,10 +75,27 @@ public static class VehicleRigAnimator public readonly List Rams = new(); } - public sealed class WalkerFootSample + public sealed class SegmentBinding { - public required Node3D[] ChainFromModelRoot; - public required Vector3[] LocalPoints; + public required Node3D Node; + public required Transform3D RestLocal; + public required Node3D[] IntermediateBefore; + public required Basis QOffset; + } + + public sealed class WalkerLegBinding + { + public SegmentBinding? Coxa; + public required SegmentBinding Thigh; + public required SegmentBinding Shin; + public SegmentBinding? Cannon; + public required SegmentBinding Foot; + } + + public sealed class WalkerVisualRig + { + public required WalkerGeometrySpec Geom; + public required WalkerLegBinding[] Legs; } public sealed class RigState @@ -87,15 +106,12 @@ public static class VehicleRigAnimator public float ArmPitchRad; public float RotorSpinRad; public float NacelleTiltRad; - public float StridePhaseRad; - public float StrideAmp; public float PrevForwardSpeed; - public float PrevVelY; public float ChassisPitchRad; public float ChassisRollRad; public float ElapsedSeconds; public BreakerMechRig? BreakerRig; - public List? FootSamples; + public WalkerVisualRig? WalkerRig; } public static void Update( @@ -105,6 +121,25 @@ public static class VehicleRigAnimator Basis worldBasis, float dt, bool snap = false) + { + var input = BuildContenderInput(c, velocity, dt); + Update(visual, in input, worldBasis, snap); + } + + public static void Update( + VehicleVisualInstance visual, + ContenderState c, + Vector3 velocity, + Basis worldBasis, + float dt, + in WalkerVisualSnapshot walkerSnap, + bool snap = false) + { + var input = BuildContenderInput(c, velocity, dt); + Update(visual, in input, worldBasis, in walkerSnap, snap); + } + + private static VehicleRigDriveInput BuildContenderInput(ContenderState c, Vector3 velocity, float dt) { float aimYawWorld = c.Yaw; float dx = c.AimX - c.X; @@ -125,7 +160,7 @@ public static class VehicleRigAnimator } } - var input = new VehicleRigDriveInput( + return new VehicleRigDriveInput( Velocity: velocity, Yaw: c.Yaw, AimYawWorld: aimYawWorld, @@ -136,8 +171,6 @@ public static class VehicleRigAnimator EngineThermalPerf: c.Grid.ComputeEngineThermalPerformance(), DeltaTime: dt, IsGrounded: !c.Grid.Spec.IsVtol); - - Update(visual, in input, worldBasis, snap); } public static void Update( @@ -145,6 +178,29 @@ public static class VehicleRigAnimator in VehicleRigDriveInput input, Basis worldBasis, bool snap = false) + { + UpdateCore(visual, in input, worldBasis, hasWalkerSnap: false, in DefaultSnapshot, snap); + } + + public static void Update( + VehicleVisualInstance visual, + in VehicleRigDriveInput input, + Basis worldBasis, + in WalkerVisualSnapshot walkerSnap, + bool snap = false) + { + UpdateCore(visual, in input, worldBasis, hasWalkerSnap: true, in walkerSnap, snap); + } + + private static readonly WalkerVisualSnapshot DefaultSnapshot = default; + + private static void UpdateCore( + VehicleVisualInstance visual, + in VehicleRigDriveInput input, + Basis worldBasis, + bool hasWalkerSnap, + in WalkerVisualSnapshot walkerSnap, + bool snap) { float dt = Sanitize(input.DeltaTime, 0f, 0f, 0.1f); if (!snap && dt <= 0f) @@ -170,7 +226,6 @@ public static class VehicleRigAnimator float forwardSpeed = vel.Dot(fwd); float lateralSpeed = vel.Dot(right); - float horizSpeed = MathF.Sqrt(forwardSpeed * forwardSpeed + lateralSpeed * lateralSpeed); float relYaw = MatchRules.NormalizeAngle(aimYawWorld - yaw); float aimPitchRad = Mathf.DegToRad(aimPitchDeg); @@ -194,7 +249,14 @@ public static class VehicleRigAnimator break; case MobilityKind.Walker: - UpdateWalker(visual, st, horizSpeed, forwardSpeed, vel.Y, steerCmd, relYaw, aimPitchRad, dt, blendMed); + if (hasWalkerSnap) + { + UpdateWalkerFromSnapshot(visual, st, in walkerSnap, relYaw, aimPitchRad, dt, blendMed); + } + else if (string.Equals(visual.ModelId, "manticore", StringComparison.OrdinalIgnoreCase)) + { + AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blendMed); + } break; case MobilityKind.Tracked: @@ -203,7 +265,6 @@ public static class VehicleRigAnimator } st.PrevForwardSpeed = forwardSpeed; - st.PrevVelY = vel.Y; } private static void UpdateTurretAndTorso( @@ -257,7 +318,6 @@ public static class VehicleRigAnimator float dt, float blend) { - // Determine average wheel radius from wheel joint Y height in grounded GLB float radiusSum = 0f; int radiusCount = 0; foreach (var (jid, j) in visual.Joints) @@ -296,7 +356,6 @@ public static class VehicleRigAnimator } } - // Subtle chassis suspension pitch & roll float accel = dt > 1e-4f ? (forwardSpeed - st.PrevForwardSpeed) / dt : 0f; float targetPitch = Math.Clamp(-accel * 0.0022f, -0.05f, 0.05f); float targetRoll = Math.Clamp(lateralSpeed * 0.0045f + steerCmd * MathF.Min(1f, MathF.Abs(forwardSpeed) / 14f) * 0.035f, -0.06f, 0.06f); @@ -366,196 +425,348 @@ public static class VehicleRigAnimator } } - private static void UpdateWalker( + private static void UpdateWalkerFromSnapshot( VehicleVisualInstance visual, RigState st, - float horizSpeed, - float forwardSpeed, - float velY, - float steerCmd, + in WalkerVisualSnapshot snap, float relYaw, float aimPitchRad, float dt, float blend) { - EnsureWalkerFootSamples(visual, st); - - float targetAmp = Math.Clamp(horizSpeed / 6.5f + MathF.Abs(steerCmd) * 0.32f, 0f, 1f); - st.StrideAmp += (targetAmp - st.StrideAmp) * blend; - - float strideDir = forwardSpeed >= -0.35f ? 1f : -1f; - float phaseRate = (2.8f + horizSpeed * 0.48f + MathF.Abs(steerCmd) * 1.4f) * strideDir; - st.StridePhaseRad = MathF.IEEERemainder(st.StridePhaseRad + phaseRate * dt, MathF.Tau); - - float phiL = st.StridePhaseRad; - float phiR = st.StridePhaseRad + MathF.PI; - string id = visual.ModelId.ToLowerInvariant(); - - switch (id) - { - case "breaker": - AnimateBipedLeg(visual, "LegL.Hip", "LegL.Shin", "LegL.Foot", phiL, st.StrideAmp, signX: -1f); - AnimateBipedLeg(visual, "LegR.Hip", "LegR.Shin", "LegR.Foot", phiR, st.StrideAmp, signX: -1f); - ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.024f); - StepBreakerMechanisms(visual, st, phiL, phiR, velY, dt); - ApplyWalkerFloorClearance(visual, st, "Pelvis"); - break; - - case "paladin": - AnimateBipedVehicleX(visual, "LegL.Upper", "LegL.Lower", "LegL.Ankle", phiL, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.28f, kneeForwardFlexAmp: 0.08f); - AnimateBipedVehicleX(visual, "LegR.Upper", "LegR.Lower", "LegR.Ankle", phiR, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.28f, kneeForwardFlexAmp: 0.08f); - ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.07f, rollScale: 0.020f); - ApplyWalkerFloorClearance(visual, st, "Pelvis"); - break; - - case "raptor": - AnimateBipedVehicleX(visual, "LegL.Thigh", "LegL.Shin", "LegL.Cannon", phiL, st.StrideAmp, hipAmp: 0.20f, kneeLiftAmp: 0.34f, kneeForwardFlexAmp: 0.22f); - AnimateBipedVehicleX(visual, "LegR.Thigh", "LegR.Shin", "LegR.Cannon", phiR, st.StrideAmp, hipAmp: 0.20f, kneeLiftAmp: 0.34f, kneeForwardFlexAmp: 0.22f); - ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.020f); - ApplyWalkerFloorClearance(visual, st, "Pelvis"); - break; - - case "spectre": - AnimateBipedVehicleX(visual, "LegL.Thigh", "LegL.Shin", "LegL.Cannon", phiL, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.32f, kneeForwardFlexAmp: 0f); - AnimateBipedVehicleX(visual, "LegR.Thigh", "LegR.Shin", "LegR.Cannon", phiR, st.StrideAmp, hipAmp: 0.22f, kneeLiftAmp: 0.32f, kneeForwardFlexAmp: 0f); - ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.06f, rollScale: 0.020f); - ApplyWalkerFloorClearance(visual, st, "Pelvis"); - break; - - case "kestrel": - // Kestrel leg meshes are baked under Pelvis; animate Pelvis stride bob/sway with floor clearance - ApplyPelvisBob(visual, "Pelvis", st.StridePhaseRad, st.StrideAmp, bobScale: 0.07f, rollScale: 0.024f); - ApplyWalkerFloorClearance(visual, st, "Pelvis"); - break; - - case "manticore": - AnimateManticoreLeg(visual, "LegFL.S1", "LegFL.S2", "FootFL", phiL, st.StrideAmp, isFront: true); - AnimateManticoreLeg(visual, "LegBR.S1", "LegBR.S2", "FootBR", phiL, st.StrideAmp, isFront: false); - AnimateManticoreLeg(visual, "LegFR.S1", "LegFR.S2", "FootFR", phiR, st.StrideAmp, isFront: true); - AnimateManticoreLeg(visual, "LegBL.S1", "LegBL.S2", "FootBL", phiR, st.StrideAmp, isFront: false); - ApplyPelvisBob(visual, "Hull", st.StridePhaseRad, st.StrideAmp, bobScale: 0.04f, rollScale: 0.018f); - ApplyWalkerFloorClearance(visual, st, "Hull"); - AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blend); - break; - - case "bastion": - AnimateBastionLeg(visual, "Thigh.fl", "Shin.fl", "Ankle.fl", phiL, st.StrideAmp, isFront: true); - AnimateBastionLeg(visual, "Thigh.rr", "Shin.rr", "Ankle.rr", phiL, st.StrideAmp, isFront: false); - AnimateBastionLeg(visual, "Thigh.fr", "Shin.fr", "Ankle.fr", phiR, st.StrideAmp, isFront: true); - AnimateBastionLeg(visual, "Thigh.rl", "Shin.rl", "Ankle.rl", phiR, st.StrideAmp, isFront: false); - ApplyPelvisBob(visual, "Trunk", st.StridePhaseRad, st.StrideAmp, bobScale: 0.05f, rollScale: 0.012f); - ApplyWalkerFloorClearance(visual, st, "Trunk"); - break; - } - } - - private static float SwingLift(float phase) => MathF.Max(0f, MathF.Cos(phase)); - - private static void AnimateBipedLeg( - VehicleVisualInstance visual, - string hipName, - string shinName, - string footName, - float phase, - float amp, - float signX) - { - float hipAng = MathF.Sin(phase) * 0.30f * amp; - float kneeAng = MathF.Max(0f, -MathF.Cos(phase)) * 0.38f * amp; - float footAng = -(hipAng * 0.55f + kneeAng * 0.45f); - - RotateVehicleAxis(visual, hipName, Vector3.Right, hipAng * signX); - RotateVehicleAxis(visual, shinName, Vector3.Right, kneeAng * signX); - RotateVehicleAxis(visual, footName, Vector3.Right, footAng * signX); - } - - private static void AnimateBipedVehicleX( - VehicleVisualInstance visual, - string thighName, - string shinName, - string footName, - float phase, - float amp, - float hipAmp, - float kneeLiftAmp, - float kneeForwardFlexAmp) - { - float hipAng = -MathF.Sin(phase) * hipAmp * amp; - float kneeAng = (SwingLift(phase) * kneeLiftAmp + MathF.Max(0f, MathF.Sin(phase)) * kneeForwardFlexAmp) * amp; - float footAng = -(hipAng + kneeAng); - - RotateVehicleAxis(visual, thighName, Vector3.Right, hipAng); - RotateVehicleAxis(visual, shinName, Vector3.Right, kneeAng); - RotateVehicleAxis(visual, footName, Vector3.Right, footAng); - } - - private static void AnimateManticoreLeg( - VehicleVisualInstance visual, - string s1Name, - string s2Name, - string footName, - float phase, - float amp, - bool isFront) - { - float s2Ang = -MathF.Sin(phase) * 0.22f * amp; - float liftSign = isFront ? -1f : 1f; - float s1Ang = SwingLift(phase) * 0.26f * amp * liftSign; - float footAng = -(s1Ang + s2Ang); - - RotateVehicleAxis(visual, s1Name, Vector3.Right, s1Ang); - RotateVehicleAxis(visual, s2Name, Vector3.Right, s2Ang); - RotateVehicleAxis(visual, footName, Vector3.Right, footAng); - } - - private static void AnimateBastionLeg( - VehicleVisualInstance visual, - string thighName, - string shinName, - string ankleName, - float phase, - float amp, - bool isFront) - { - float thAng; - float shAng; - if (isFront) - { - thAng = -MathF.Sin(phase) * 0.16f * amp; - shAng = SwingLift(phase) * 0.14f * amp; - } - else - { - thAng = (MathF.Max(0f, -MathF.Sin(phase)) * 0.14f + SwingLift(phase) * 0.10f) * amp; - shAng = (-MathF.Sin(phase) * 0.16f - SwingLift(phase) * 0.16f) * amp; - } - float anAng = -(thAng + shAng); - - RotateVehicleAxis(visual, thighName, Vector3.Right, thAng); - RotateVehicleAxis(visual, shinName, Vector3.Right, shAng); - RotateVehicleAxis(visual, ankleName, Vector3.Right, anAng); - } - - private static void ApplyPelvisBob( - VehicleVisualInstance visual, - string rootNodeName, - float phase, - float amp, - float bobScale, - float rollScale = 0.024f) - { - if (visual.GetNamedNode(rootNodeName) is not { } node || - !visual.TryGetRestLocal(rootNodeName, out var rest)) + var rig = st.WalkerRig ??= InitWalkerRig(visual); + if (rig is null) { return; } - float bobY = MathF.Abs(MathF.Sin(phase)) * bobScale * amp; - float swayRoll = MathF.Cos(phase) * rollScale * amp; - Basis roll = new Basis(Vector3.Back, swayRoll); - node.Transform = new Transform3D(roll * rest.Basis, rest.Origin + new Vector3(0f, bobY, 0f)); + var geom = rig.Geom; + var bodyRotSys = snap.ComRot.LengthSquared() < 1e-6f + ? System.Numerics.Quaternion.Identity + : System.Numerics.Quaternion.Normalize(snap.ComRot); + var bodyRotInv = System.Numerics.Quaternion.Conjugate(bodyRotSys); + + int count = Math.Min(rig.Legs.Length, snap.LegCount); + for (int i = 0; i < count; i++) + { + var legRig = rig.Legs[i]; + var legSpec = geom.Legs[i]; + var ang = snap.LegAngles[i]; + if (!float.IsFinite(ang.HipPitch) || !float.IsFinite(ang.HipRoll) || + !float.IsFinite(ang.KneeFlex) || !float.IsFinite(ang.HockFlex) || + !float.IsFinite(ang.AnklePitch)) + { + continue; + } + + Vector3 footNormModel = ToGodot(System.Numerics.Vector3.Transform(snap.FootNormal[i], bodyRotInv)); + footNormModel = footNormModel.LengthSquared() > 1e-6f ? footNormModel.Normalized() : Vector3.Up; + + Vector3 r0 = ToGodot(legSpec.LegRight0); + Vector3 f0 = ToGodot(legSpec.LegFwd0); + + Basis curModelBasis = Basis.Identity; + + if (snap.IsArachnidUp) + { + float coxaYaw = ang.HipRoll; + Vector3 legOut = (f0 * MathF.Cos(coxaYaw) + r0 * MathF.Sin(coxaYaw)).Normalized(); + Vector3 legRight = (r0 * MathF.Cos(coxaYaw) - f0 * MathF.Sin(coxaYaw)).Normalized(); + + if (legRig.Coxa is { } coxaSeg) + { + Basis coxaBasis = BasisFromDownAndRight(-legOut, Vector3.Up.Cross(legOut)) * coxaSeg.QOffset; + curModelBasis = ApplySegmentModelBasis(coxaSeg, curModelBasis, coxaBasis); + } + + Vector3 s1Dir = (legOut * MathF.Cos(ang.HipPitch) + Vector3.Up * MathF.Sin(ang.HipPitch)).Normalized(); + float s2Elev = ang.HipPitch - ang.KneeFlex; + Vector3 s2Dir = (legOut * MathF.Cos(s2Elev) + Vector3.Up * MathF.Sin(s2Elev)).Normalized(); + + Basis thighBasis = BasisFromDownAndRight(s1Dir, legRight) * legRig.Thigh.QOffset; + curModelBasis = ApplySegmentModelBasis(legRig.Thigh, curModelBasis, thighBasis); + + Basis shinBasis = BasisFromDownAndRight(s2Dir, legRight) * legRig.Shin.QOffset; + curModelBasis = ApplySegmentModelBasis(legRig.Shin, curModelBasis, shinBasis); + + float lat = Math.Clamp(footNormModel.Dot(legRight), -0.85f, 0.85f); + float planarMag = MathF.Sqrt(MathF.Max(0.01f, 1f - lat * lat)); + Vector3 footUp = (legRight * lat + (Vector3.Up * MathF.Cos(ang.AnklePitch) + legOut * MathF.Sin(ang.AnklePitch)) * planarMag).Normalized(); + Basis footBasis = BasisFromDownAndRight(-footUp, legRight) * legRig.Foot.QOffset; + ApplySegmentModelBasis(legRig.Foot, curModelBasis, footBasis); + } + else + { + float hipRoll = ang.HipRoll; + Vector3 legRight = (r0 * MathF.Cos(hipRoll) + Vector3.Up * MathF.Sin(hipRoll)).Normalized(); + Vector3 downTilted = (-Vector3.Up * MathF.Cos(hipRoll) + r0 * MathF.Sin(hipRoll)).Normalized(); + + Vector3 thighDir = (downTilted * MathF.Cos(ang.HipPitch) + f0 * MathF.Sin(ang.HipPitch)).Normalized(); + float shinAngle = ang.HipPitch - ang.KneeFlex; + Vector3 shinDir = (downTilted * MathF.Cos(shinAngle) + f0 * MathF.Sin(shinAngle)).Normalized(); + + Basis thighBasis = BasisFromDownAndRight(thighDir, legRight) * legRig.Thigh.QOffset; + curModelBasis = ApplySegmentModelBasis(legRig.Thigh, curModelBasis, thighBasis); + + Basis shinBasis = BasisFromDownAndRight(shinDir, legRight) * legRig.Shin.QOffset; + curModelBasis = ApplySegmentModelBasis(legRig.Shin, curModelBasis, shinBasis); + + if (snap.IsDigitigrade && legRig.Cannon is { } cannonSeg) + { + float cannonAngle = shinAngle + ang.HockFlex; + Vector3 cannonDir = (downTilted * MathF.Cos(cannonAngle) + f0 * MathF.Sin(cannonAngle)).Normalized(); + Basis cannonBasis = BasisFromDownAndRight(cannonDir, legRight) * cannonSeg.QOffset; + curModelBasis = ApplySegmentModelBasis(cannonSeg, curModelBasis, cannonBasis); + } + + float lat = Math.Clamp(footNormModel.Dot(legRight), -0.85f, 0.85f); + float planarMag = MathF.Sqrt(MathF.Max(0.01f, 1f - lat * lat)); + Vector3 footUp = (legRight * lat + (Vector3.Up * MathF.Cos(ang.AnklePitch) + f0 * MathF.Sin(ang.AnklePitch)) * planarMag).Normalized(); + Basis footBasis = BasisFromDownAndRight(-footUp, legRight) * legRig.Foot.QOffset; + ApplySegmentModelBasis(legRig.Foot, curModelBasis, footBasis); + } + } + + string id = visual.ModelId; + if (string.Equals(id, "manticore", StringComparison.OrdinalIgnoreCase)) + { + AnimateManticoreTail(visual, st, relYaw, aimPitchRad, blend); + } + else if (string.Equals(id, "breaker", StringComparison.OrdinalIgnoreCase)) + { + StepBreakerLinkages(visual, snap.LoadG[0], snap.LoadG[1], dt); + } } + private static Basis ApplySegmentModelBasis(SegmentBinding seg, Basis curBasisInModel, Basis targetBasisInModel) + { + for (int i = 0; i < seg.IntermediateBefore.Length; i++) + { + curBasisInModel *= seg.IntermediateBefore[i].Transform.Basis.Orthonormalized(); + } + Basis localBasis = curBasisInModel.Inverse() * targetBasisInModel; + seg.Node.Transform = new Transform3D(localBasis, seg.RestLocal.Origin); + return targetBasisInModel; + } + + private static WalkerVisualRig? InitWalkerRig(VehicleVisualInstance visual) + { + var geom = WalkerGeometrySpec.GetForChassis(visual.ModelId); + string id = visual.ModelId.ToLowerInvariant(); + var legs = new WalkerLegBinding[geom.LegCount]; + + for (int i = 0; i < geom.LegCount; i++) + { + string? coxaName = null; + string thighName, shinName, footName; + string? cannonName = null; + + switch (id) + { + case "breaker": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Hip"; + shinName = $"Leg{s}.Shin"; + footName = $"Leg{s}.Foot"; + break; + } + case "paladin": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Upper"; + shinName = $"Leg{s}.Lower"; + footName = $"Leg{s}.Ankle"; + break; + } + case "raptor": + case "exemplar_frame": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Thigh"; + shinName = $"Leg{s}.Shin"; + cannonName = $"Leg{s}.Cannon"; + footName = $"Foot{s}"; + break; + } + case "spectre": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Thigh"; + shinName = $"Leg{s}.Shin"; + cannonName = $"Leg{s}.Cannon"; + footName = $"Leg{s}.Ankle"; + break; + } + case "kestrel": + { + string s = i == 0 ? "L" : "R"; + thighName = $"Leg{s}.Thigh"; + shinName = $"Leg{s}.Shin"; + footName = $"Leg{s}.Foot"; + break; + } + case "manticore": + { + string q = i switch { 0 => "FL", 1 => "FR", 2 => "BL", _ => "BR" }; + coxaName = $"Leg{q}.Coxa"; + thighName = $"Leg{q}.S1"; + shinName = $"Leg{q}.S2"; + footName = $"Foot{q}"; + break; + } + case "bastion": + { + string q = i switch { 0 => "fl", 1 => "fr", 2 => "rl", _ => "rr" }; + thighName = $"Thigh.{q}"; + shinName = $"Shin.{q}"; + footName = $"Ankle.{q}"; + break; + } + default: + return null; + } + + if (visual.GetNamedNode(thighName) is not { } thighNode || + visual.GetNamedNode(shinName) is not { } shinNode || + visual.GetNamedNode(footName) is not { } footNode || + !visual.TryGetRestLocal(thighName, out var restThigh) || + !visual.TryGetRestLocal(shinName, out var restShin) || + !visual.TryGetRestLocal(footName, out var restFoot) || + !visual.TryGetRestModel(thighName, out var modelThigh) || + !visual.TryGetRestModel(shinName, out var modelShin) || + !visual.TryGetRestModel(footName, out var modelFoot)) + { + return null; + } + + Node3D? cannonNode = null; + Transform3D restCannon = Transform3D.Identity; + Transform3D modelCannon = Transform3D.Identity; + if (cannonName is not null) + { + if (visual.GetNamedNode(cannonName) is not { } cn || + !visual.TryGetRestLocal(cannonName, out restCannon) || + !visual.TryGetRestModel(cannonName, out modelCannon)) + { + return null; + } + cannonNode = cn; + } + + Node3D? coxaNode = null; + Transform3D restCoxa = Transform3D.Identity; + Transform3D modelCoxa = Transform3D.Identity; + if (coxaName is not null && + visual.GetNamedNode(coxaName) is { } cxn && + visual.TryGetRestLocal(coxaName, out restCoxa) && + visual.TryGetRestModel(coxaName, out modelCoxa)) + { + coxaNode = cxn; + } + + Vector3 dirRestThigh = (modelShin.Origin - modelThigh.Origin).Normalized(); + Vector3 shinEndOrigin = cannonNode is not null ? modelCannon.Origin : modelFoot.Origin; + Vector3 dirRestShin = (shinEndOrigin - modelShin.Origin).Normalized(); + Vector3 dirRestCannon = cannonNode is not null + ? (modelFoot.Origin - modelCannon.Origin).Normalized() + : Vector3.Down; + + Vector3 legRightRest = geom.IsArachnidUp + ? dirRestThigh.Cross(Vector3.Up).Normalized() + : ToGodot(geom.Legs[i].LegRight0); + + SegmentBinding? coxaBinding = null; + if (coxaNode is not null) + { + Vector3 rad0 = new(modelFoot.Origin.X - modelThigh.Origin.X, 0f, modelFoot.Origin.Z - modelThigh.Origin.Z); + rad0 = rad0.LengthSquared() > 1e-6f ? rad0.Normalized() : ToGodot(geom.Legs[i].LegFwd0); + Basis fCoxaRest = BasisFromDownAndRight(-rad0, Vector3.Up.Cross(rad0)); + coxaBinding = new SegmentBinding + { + Node = coxaNode, + RestLocal = restCoxa, + IntermediateBefore = BuildIntermediateChain(visual.ModelRoot, coxaNode), + QOffset = fCoxaRest.Inverse() * modelCoxa.Basis.Orthonormalized() + }; + } + + var thighBinding = new SegmentBinding + { + Node = thighNode, + RestLocal = restThigh, + IntermediateBefore = BuildIntermediateChain(coxaNode ?? visual.ModelRoot, thighNode), + QOffset = BasisFromDownAndRight(dirRestThigh, legRightRest).Inverse() * modelThigh.Basis.Orthonormalized() + }; + + var shinBinding = new SegmentBinding + { + Node = shinNode, + RestLocal = restShin, + IntermediateBefore = BuildIntermediateChain(thighNode, shinNode), + QOffset = BasisFromDownAndRight(dirRestShin, legRightRest).Inverse() * modelShin.Basis.Orthonormalized() + }; + + SegmentBinding? cannonBinding = null; + if (cannonNode is not null) + { + cannonBinding = new SegmentBinding + { + Node = cannonNode, + RestLocal = restCannon, + IntermediateBefore = BuildIntermediateChain(shinNode, cannonNode), + QOffset = BasisFromDownAndRight(dirRestCannon, legRightRest).Inverse() * modelCannon.Basis.Orthonormalized() + }; + } + + var footBinding = new SegmentBinding + { + Node = footNode, + RestLocal = restFoot, + IntermediateBefore = BuildIntermediateChain(cannonNode ?? shinNode, footNode), + QOffset = BasisFromDownAndRight(Vector3.Down, legRightRest).Inverse() * modelFoot.Basis.Orthonormalized() + }; + + legs[i] = new WalkerLegBinding + { + Coxa = coxaBinding, + Thigh = thighBinding, + Shin = shinBinding, + Cannon = cannonBinding, + Foot = footBinding + }; + } + + return new WalkerVisualRig + { + Geom = geom, + Legs = legs + }; + } + + private static Node3D[] BuildIntermediateChain(Node3D ancestorExclusive, Node3D childExclusive) + { + var list = new List(4); + for (Node? cur = childExclusive.GetParent(); cur is Node3D n3d && !ReferenceEquals(cur, ancestorExclusive); cur = cur.GetParent()) + { + list.Add(n3d); + } + list.Reverse(); + return list.ToArray(); + } + + private static Basis BasisFromDownAndRight(Vector3 downDir, Vector3 rightX) + { + Vector3 upY = -downDir.Normalized(); + Vector3 x = rightX - upY * rightX.Dot(upY); + x = x.LengthSquared() > 1e-6f ? x.Normalized() : Vector3.Right; + Vector3 z = x.Cross(upY).Normalized(); + x = upY.Cross(z).Normalized(); + return new Basis(x, upY, z); + } + + private static Vector3 ToGodot(System.Numerics.Vector3 v) => new(v.X, v.Y, v.Z); + private static void AnimateManticoreTail( VehicleVisualInstance visual, RigState st, @@ -591,12 +802,14 @@ public static class VehicleRigAnimator } } - private static void StepBreakerMechanisms( + /// + /// Steps Breaker's real oleo gas-spring struts, 2-link scissor torque knees, and telescoping recess rams + /// from real Newtonian GRF per-leg load factors (grfN / (0.5f * weightN)). + /// + public static void StepBreakerLinkages( VehicleVisualInstance visual, - RigState st, - float phiL, - float phiR, - float velY, + float leftLoadG, + float rightLoadG, float dt) { VehicleMechanismsRecord? mech = visual.Package.Mechanisms; @@ -605,15 +818,15 @@ public static class VehicleRigAnimator return; } + RigState st = visual.RigState; BreakerMechRig rig = st.BreakerRig ??= InitBreakerRig(visual, mech); if (!rig.Initialized) { return; } - float accelY = dt > 1e-4f ? Math.Clamp((velY - st.PrevVelY) / dt, -25f, 25f) : 0f; - float strideLoadL = 1.0f + 0.42f * MathF.Sin(phiL) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); - float strideLoadR = 1.0f + 0.42f * MathF.Sin(phiR) * st.StrideAmp + MathF.Max(-0.6f, accelY * 0.05f); + float strideLoadL = Math.Clamp(leftLoadG, 0f, 3.5f); + float strideLoadR = Math.Clamp(rightLoadG, 0f, 3.5f); // 1. Oleo gas-spring + asymmetric orifice damping (Brokkr mechrig.Model.strut_step) if (dt > 0f) @@ -664,7 +877,7 @@ public static class VehicleRigAnimator Vector3 bInShin = forkInShin * sb.BInOleoFork; Vector3 apexInShin = SolveScissorApex(sb.AInShin, bInShin, sb.OutInShin, sb.Arm); - Vector3 dirUp = (apexInShin - sb.AInShin); + Vector3 dirUp = apexInShin - sb.AInShin; if (dirUp.LengthSquared() > 1e-8f) { Quaternion qUp = ShortestArcQuat(sb.DirUp0InShin, dirUp.Normalized()); @@ -673,7 +886,7 @@ public static class VehicleRigAnimator } Vector3 apexInFork = forkInShin.Inverse() * apexInShin; - Vector3 dirLow = (apexInFork - sb.BInOleoFork); + Vector3 dirLow = apexInFork - sb.BInOleoFork; if (dirLow.LengthSquared() > 1e-8f) { Quaternion qLow = ShortestArcQuat(sb.DirLow0InOleoFork, dirLow.Normalized()); @@ -780,7 +993,6 @@ public static class VehicleRigAnimator foreach (var r in mech.Rams) { - // Name: "LegL.RecessRam0" -> lug "LegL.RamLugA0", oleo "LegL.Oleo", foot "LegL.Foot" string side = r.Name.StartsWith("LegR", StringComparison.Ordinal) ? "R" : "L"; char idxChar = r.Name[^1]; string lugName = $"Leg{side}.RamLugA{idxChar}"; @@ -850,190 +1062,6 @@ public static class VehicleRigAnimator j.Node.Transform = new Transform3D(delta * j.RestLocal.Basis, j.RestLocal.Origin); } - private static void RotateVehicleAxis(VehicleVisualInstance visual, string nodeName, Vector3 vehicleAxis, float angleRad) - { - if (visual.GetNamedNode(nodeName) is not { } node || - !visual.TryGetRestLocal(nodeName, out var rest)) - { - return; - } - - Vector3 axisInParent = vehicleAxis; - if (node.GetParent() is Node3D p3 && visual.TryGetRestModel(p3, out var pModel)) - { - axisInParent = (pModel.Basis.Orthonormalized().Inverse() * vehicleAxis).Normalized(); - } - Basis delta = new Basis(axisInParent, angleRad); - node.Transform = new Transform3D(delta * rest.Basis, rest.Origin); - } - - private static void EnsureWalkerFootSamples(VehicleVisualInstance visual, RigState st) - { - if (st.FootSamples is not null) - { - return; - } - - var list = new List(); - float cutoffY = visual.Template.MinY + 0.75f; - var parts = visual.StaticParts; - - for (int i = 0; i < parts.Count; i++) - { - var part = parts[i]; - if (!GodotObject.IsInstanceValid(part.Pivot)) - { - continue; - } - - // Build chain from ModelRoot -> part.Pivot - var chain = new List(); - Transform3D toModel = Transform3D.Identity; - for (Node? cur = part.Pivot; cur is Node3D n3d && !ReferenceEquals(cur, visual.ModelRoot); cur = cur.GetParent()) - { - chain.Add(n3d); - toModel = n3d.Transform * toModel; - } - chain.Reverse(); - - Aabb aabb = part.Mesh.GetAabb(); - float aabbMinY = float.PositiveInfinity; - for (int c = 0; c < 8; c++) - { - Vector3 corner = aabb.Position + new Vector3( - (c & 1) != 0 ? aabb.Size.X : 0f, - (c & 2) != 0 ? aabb.Size.Y : 0f, - (c & 4) != 0 ? aabb.Size.Z : 0f); - float wy = (toModel * corner).Y; - if (wy < aabbMinY) - { - aabbMinY = wy; - } - } - - if (aabbMinY >= cutoffY) - { - continue; - } - - var bestPts = new Vector3[FootSupportDirs.Length]; - var bestDots = new float[FootSupportDirs.Length]; - for (int d = 0; d < FootSupportDirs.Length; d++) - { - bestDots[d] = float.NegativeInfinity; - } - - bool anyVert = false; - int surfCount = part.Mesh.GetSurfaceCount(); - for (int s = 0; s < surfCount; s++) - { - var arrays = part.Mesh.SurfaceGetArrays(s); - if (arrays.Count <= (int)Mesh.ArrayType.Vertex || - arrays[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) - { - continue; - } - Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); - for (int v = 0; v < verts.Length; v++) - { - Vector3 localPt = verts[v]; - Vector3 mPt = toModel * localPt; - for (int d = 0; d < FootSupportDirs.Length; d++) - { - float score = mPt.Dot(FootSupportDirs[d]); - if (score > bestDots[d]) - { - bestDots[d] = score; - bestPts[d] = localPt; - } - } - anyVert = true; - } - } - - if (anyVert) - { - var unique = new List(FootSupportDirs.Length); - for (int d = 0; d < bestPts.Length; d++) - { - bool dup = false; - for (int u = 0; u < unique.Count; u++) - { - if ((unique[u] - bestPts[d]).LengthSquared() < 1e-6f) - { - dup = true; - break; - } - } - if (!dup) - { - unique.Add(bestPts[d]); - } - } - - list.Add(new WalkerFootSample - { - ChainFromModelRoot = chain.ToArray(), - LocalPoints = unique.ToArray() - }); - } - } - st.FootSamples = list; - } - - private static readonly Vector3[] FootSupportDirs = - { - new(0f, -1f, 0f), - new(0.45f, -1f, 0f), - new(-0.45f, -1f, 0f), - new(0f, -1f, 0.45f), - new(0f, -1f, -0.45f), - new(0.45f, -1f, 0.45f), - new(0.45f, -1f, -0.45f), - new(-0.45f, -1f, 0.45f), - new(-0.45f, -1f, -0.45f), - }; - - private static void ApplyWalkerFloorClearance(VehicleVisualInstance visual, RigState st, string rootNodeName) - { - var samples = st.FootSamples; - if (samples is null || samples.Count == 0 || visual.GetNamedNode(rootNodeName) is not { } rootNode) - { - return; - } - - float minModelY = float.PositiveInfinity; - for (int i = 0; i < samples.Count; i++) - { - var s = samples[i]; - Transform3D toModel = Transform3D.Identity; - for (int k = 0; k < s.ChainFromModelRoot.Length; k++) - { - toModel *= s.ChainFromModelRoot[k].Transform; - } - for (int p = 0; p < s.LocalPoints.Length; p++) - { - float y = (toModel * s.LocalPoints[p]).Y; - if (y < minModelY) - { - minModelY = y; - } - } - } - - float restMinY = visual.Template.MinY; - if (float.IsFinite(minModelY) && minModelY < restMinY) - { - Vector3 liftInModel = new Vector3(0f, restMinY - minModelY, 0f); - Vector3 liftInParent = liftInModel; - if (rootNode.GetParent() is Node3D p3 && visual.TryGetRestModel(p3, out var pModel)) - { - liftInParent = pModel.Basis.Orthonormalized().Inverse() * liftInModel; - } - rootNode.Transform = new Transform3D(rootNode.Transform.Basis, rootNode.Transform.Origin + liftInParent); - } - } - private static Quaternion ShortestArcQuat(Vector3 from, Vector3 to) { float dot = Math.Clamp(from.Dot(to), -1f, 1f); diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index 9b19a4c..2224d1a 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -724,7 +724,7 @@ public partial class Smoke : Node new VehicleRigDriveInput(new Vector3(0f, 0f, 6f), 0f, 0.70f, 18f, 0f, 0.8f, 0f, 1f, 1f / 60f), minRotRad: 0.001f); - // Breaker: verify oleo strut slide + scissor torque links + recess ram aiming + // Breaker: verify oleo strut slide + scissor torque links + recess ram aiming driven by Newtonian GRF load { var breakerVis = VehicleVisualInstance.Create(cache, "breaker", VehicleVisualRole.Player); Node3D? oleo = breakerVis.GetNamedNode("LegL.Oleo"); @@ -737,10 +737,13 @@ public partial class Smoke : Node Transform3D oleo0 = oleo.Transform; Transform3D sc0 = scissorUp.Transform; Transform3D ramRest = ram0.Transform; - var inp1 = new VehicleRigDriveInput(new Vector3(0f, -6f, 8f), 0f, 0.4f, 10f, 0f, 1f, 0f, 1f, 1f / 60f); - for (int s = 0; s < 10; s++) VehicleRigAnimator.Update(breakerVis, in inp1, Basis.Identity); - var inp2 = new VehicleRigDriveInput(new Vector3(0f, 3f, 8f), 0f, 0.4f, 10f, 0f, 1f, 0f, 1f, 1f / 60f); - for (int s = 0; s < 10; s++) VehicleRigAnimator.Update(breakerVis, in inp2, Basis.Identity); + Node3D? footL = breakerVis.GetNamedNode("LegL.Foot"); + if (footL is not null) + { + footL.Transform = new Transform3D(new Basis(Vector3.Right, 0.28f) * footL.Transform.Basis, footL.Transform.Origin); + } + for (int s = 0; s < 10; s++) VehicleRigAnimator.StepBreakerLinkages(breakerVis, leftLoadG: 1.85f, rightLoadG: 0.25f, dt: 1f / 60f); + for (int s = 0; s < 10; s++) VehicleRigAnimator.StepBreakerLinkages(breakerVis, leftLoadG: 0.25f, rightLoadG: 1.85f, dt: 1f / 60f); float oleoDelta = (oleo.Transform.Origin - oleo0.Origin).Length(); float scDelta = sc0.Basis.GetRotationQuaternion().AngleTo(scissorUp.Transform.Basis.GetRotationQuaternion()); @@ -920,39 +923,73 @@ public partial class Smoke : Node drops.RemoveRange(baseCount, added.Count); } - // 6. All 7 walkers stay grounded (minVertexY - restMinY >= -0.05m) and swing along +Z/-Z through a full stride cycle + // 6. All 7 walkers (including Kestrel) walk through real ArenaSession + Hybrid B FK snapshot cleanly { - var walkerChecks = new (string Id, string? FootNode, string? PelvisNode, bool CheckSagittal)[] + using var walkSession = new RustToDust.Ymir.ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert); + for (int cIdx = 1; cIdx < walkSession.State.Contenders.Count; cIdx++) { - ("raptor", "LegL.Cannon", "Pelvis", true), - ("spectre", "LegL.Cannon", "Pelvis", true), - ("manticore", "FootFL", "Hull", true), - ("bastion", "Ankle.fl", "Trunk", true), - ("breaker", "LegL.Foot", "Pelvis", true), - ("paladin", "LegL.Ankle", "Pelvis", true), - ("kestrel", null, null, false), + walkSession.SetContenderPose(cIdx, 450f + cIdx * 18f, 450f); + } + + var walkerChecks = new (string Id, string FootNode, string PelvisNode)[] + { + ("raptor", "FootL", "Pelvis"), + ("spectre", "LegL.Ankle", "Pelvis"), + ("manticore", "FootFL", "Hull"), + ("bastion", "Ankle.fl", "Trunk"), + ("breaker", "LegL.Foot", "Pelvis"), + ("paladin", "LegL.Ankle", "Pelvis"), + ("kestrel", "LegL.Foot", "Pelvis"), }; - foreach (var (wId, footNodeName, pelvisNodeName, checkSagittal) in walkerChecks) + foreach (var (wId, footNodeName, pelvisNodeName) in walkerChecks) { + var wSpec = Catalog.ChassisById[wId]; + walkSession.SetContenderPose(0, 0f, 0f, 0f); + if (walkSession.State.Player.Grid.Spec.Id != wId) + { + walkSession.State.SpawnChassisDrop(0f, 0f, wSpec); + Check(walkSession.TrySwapNearbyChassis(), $"Failed to swap walkSession player to '{wId}'"); + } + var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player); - float restMinY = vis.ComputeMinVertexY(relativeToModelRoot: true); float worstRelMinY = float.PositiveInfinity; float minFootZ = float.PositiveInfinity, maxFootZ = float.NegativeInfinity; float minFootX = float.PositiveInfinity, maxFootX = float.NegativeInfinity; - Node3D? footNode = footNodeName is not null ? vis.GetNamedNode(footNodeName) : null; - Node3D? pelvisNode = pelvisNodeName is not null ? vis.GetNamedNode(pelvisNodeName) : null; + Node3D? footNode = vis.GetNamedNode(footNodeName); + Node3D? pelvisNode = vis.GetNamedNode(pelvisNodeName); + Check(footNode is not null && pelvisNode is not null, + $"Missing FK nodes '{footNodeName}'/'{pelvisNodeName}' on walker '{wId}'"); - var walkInp = new VehicleRigDriveInput( - new Vector3(0f, 0f, 8f), 0f, 0f, 0f, 0f, 1f, 0f, 1f, 0.05f); - - for (int step = 0; step < 48; step++) + var player = walkSession.State.Player; + for (int step = 0; step < 60; step++) { - VehicleRigAnimator.Update(vis, in walkInp, Basis.Identity); - float curMinY = vis.ComputeMinVertexY(relativeToModelRoot: true); - float relMinY = curMinY - restMinY; - if (relMinY < worstRelMinY) worstRelMinY = relMinY; - Check(!float.IsNaN(curMinY), $"NaN vertex Y on walker '{wId}' step {step}"); + walkSession.Step(new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X, + AimWorldZ: player.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + + bool hasSnap = walkSession.TrySampleInterpolatedWalkerPose(true, player.Id, 1f, out var walkerSnap); + Check(hasSnap, $"Missing WalkerVisualSnapshot for '{wId}' at step {step}"); + if (!hasSnap) break; + + var (interpPos, interpRot, interpVel) = walkSession.GetInterpolatedContenderPose(player.Id, 1f); + var q = new Quaternion(interpRot.X, interpRot.Y, interpRot.Z, interpRot.W); + vis.Root.Transform = new Transform3D(new Basis(q), new Vector3(interpPos.X, interpPos.Y, interpPos.Z)); + VehicleRigAnimator.Update( + vis, + player, + new Vector3(interpVel.X, interpVel.Y, interpVel.Z), + vis.Root.Basis, + 1f / 60f, + in walkerSnap); + + float curMinWorldY = vis.ComputeMinVertexY(relativeToModelRoot: false); + Check(!float.IsNaN(curMinWorldY), $"NaN vertex Y on walker '{wId}' step {step}"); if (footNode is not null && pelvisNode is not null) { @@ -961,20 +998,24 @@ public partial class Smoke : Node if (fPos.Z > maxFootZ) maxFootZ = fPos.Z; if (fPos.X < minFootX) minFootX = fPos.X; if (fPos.X > maxFootX) maxFootX = fPos.X; + + Vector3 fInModel = TransformPointToAncestor(footNode, vis.ModelRoot, Vector3.Zero); + Vector3 fWorld = vis.Root.Transform * (vis.ModelRoot.Transform * fInModel); + float groundUnderFoot = walkSession.State.Terrain.SampleHeight(fWorld.X, fWorld.Z); + float relMinY = curMinWorldY - groundUnderFoot; + if (relMinY < worstRelMinY) worstRelMinY = relMinY; } } float zSpan = footNode is not null ? maxFootZ - minFootZ : 0f; float xSpan = footNode is not null ? maxFootX - minFootX : 0f; - GD.Print($"SMOKE INFO: Walker {wId} stride minFootY={worstRelMinY:F4}m zSpan={zSpan:F3}m xSpan={xSpan:F3}m"); - Check(worstRelMinY >= -0.05f, - $"Walker '{wId}' foot plunged below rest floor: minRelY={worstRelMinY:F4}m"); - if (checkSagittal && footNode is not null) + GD.Print($"SMOKE INFO: HybridB Walker {wId} minWorldFootRelY={worstRelMinY:F4}m zSpan={zSpan:F3}m xSpan={xSpan:F3}m"); + Check(worstRelMinY >= -0.25f, + $"Walker '{wId}' plunged below terrain: minRelY={worstRelMinY:F4}m"); + if (footNode is not null) { Check(zSpan > 0.12f, - $"Expected walker '{wId}' foot '{footNodeName}' to stride along Z > 0.12m, got {zSpan:F3}m"); - Check(xSpan < 0.03f, - $"Expected walker '{wId}' foot '{footNodeName}' to swing cleanly in sagittal plane (xSpan < 0.03m), got {xSpan:F3}m"); + $"Expected walker '{wId}' foot '{footNodeName}' to stride along Z > 0.12m through Hybrid B FK, got {zSpan:F3}m"); } vis.Root.QueueFree(); } diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs index 742154a..5c6b006 100644 --- a/src/RustToDust.Core/GridChassis.cs +++ b/src/RustToDust.Core/GridChassis.cs @@ -604,15 +604,117 @@ namespace RustToDust.Core return dropped; } + public void GetLegIntegrities(Span outLegs) + { + if (Spec.Plane == GridPlane.Coronal) + { + int legStartY = Math.Max(0, Spec.Height - 2); + int leftMaxX = Spec.Width / 2; + int rightMinX = (Spec.Width + 1) / 2; + float curL = 0f, maxL = 0f, curR = 0f, maxR = 0f; + + for (int y = legStartY; y < Spec.Height; y++) + { + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + if (x < leftMaxX) + { + curL += Armor[x, y]; + maxL += MaxArmor[x, y]; + } + else if (x >= rightMinX) + { + curR += Armor[x, y]; + maxR += MaxArmor[x, y]; + } + } + } + + if (outLegs.Length > 0) + { + outLegs[0] = maxL > 0f ? 0.25f + 0.75f * Math.Clamp(curL / maxL, 0f, 1f) : 1f; + } + if (outLegs.Length > 1) + { + outLegs[1] = maxR > 0f ? 0.25f + 0.75f * Math.Clamp(curR / maxR, 0f, 1f) : 1f; + } + for (int i = 2; i < outLegs.Length; i++) + { + outLegs[i] = 1f; + } + return; + } + + if (Spec.IsWalker) + { + int midXLeft = Spec.Width / 2; + int midXRight = (Spec.Width + 1) / 2; + int midY = Spec.Height / 2; + Span cur = stackalloc float[4]; + Span max = stackalloc float[4]; + + for (int y = 0; y < Spec.Height; y++) + { + int rowBase = y < midY ? 0 : 2; + for (int x = 0; x < Spec.Width; x++) + { + if (!Spec.IsActive(x, y)) + { + continue; + } + int legIdx; + if (x < midXLeft) + { + legIdx = rowBase; + } + else if (x >= midXRight) + { + legIdx = rowBase + 1; + } + else + { + continue; + } + cur[legIdx] += Armor[x, y]; + max[legIdx] += MaxArmor[x, y]; + } + } + + int count = Math.Min(4, outLegs.Length); + for (int i = 0; i < count; i++) + { + outLegs[i] = max[i] > 0f ? 0.25f + 0.75f * Math.Clamp(cur[i] / max[i], 0f, 1f) : 1f; + } + for (int i = 4; i < outLegs.Length; i++) + { + outLegs[i] = 1f; + } + return; + } + + outLegs.Fill(1f); + } + public float LegIntegrity { get { - if (Spec.Plane != GridPlane.Coronal) + if (!Spec.IsWalker) { return 1f; } + if (Spec.Plane == GridPlane.Dorsal) + { + Span legs = stackalloc float[4]; + GetLegIntegrities(legs); + return (legs[0] + legs[1] + legs[2] + legs[3]) * 0.25f; + } + int legStartY = Math.Max(0, Spec.Height - 2); float cur = 0f; float max = 0f; diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index f549da9..a6f9171 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -22,6 +22,8 @@ namespace RustToDust.Ymir private readonly Box3DSoaWorld _world; private readonly Dictionary _contenderBodies = new(); private readonly Dictionary _spectatorBodies = new(); + private readonly Dictionary _contenderWalkers = new(); + private readonly Dictionary _spectatorWalkers = new(); private readonly Dictionary _entityByStableId = new(); private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount]; private bool _disposed; @@ -83,6 +85,7 @@ namespace RustToDust.Ymir _world.RemoveBody(oldHandle); _contenderBodies.Remove(contenderId); } + _contenderWalkers.Remove(contenderId); if (c.Alive) { SpawnContenderBody(c); @@ -121,6 +124,7 @@ namespace RustToDust.Ymir _world.RemoveBody(oldHandle); _spectatorBodies.Remove(spectatorId); } + _spectatorWalkers.Remove(spectatorId); if (spec.Alive) { SpawnSpectatorBody(index, spec); @@ -193,6 +197,53 @@ namespace RustToDust.Ymir new Vector3(spec.VelX, spec.VelY, spec.VelZ)); } + public WalkerState? GetWalkerState(bool isContender, int id) => + isContender + ? (_contenderWalkers.TryGetValue(id, out var cw) ? cw : null) + : (_spectatorWalkers.TryGetValue(id, out var sw) ? sw : null); + + public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) + { + var dict = isContender ? _contenderWalkers : _spectatorWalkers; + if (!dict.TryGetValue(id, out var ws) || !ws.Initialized) + { + snap = default; + return false; + } + snap = WalkerVisualSnapshot.Interpolate(in ws.PrevSnap, in ws.CurrSnap, alpha); + return true; + } + + public void AddWalkerRecoilImpulse(bool isContender, int id, Vector3 shotDirWorld, float weaponDamage) + { + var dict = isContender ? _contenderWalkers : _spectatorWalkers; + if (!dict.TryGetValue(id, out var ws)) + { + return; + } + Quaternion qBody = Quaternion.Identity; + if (isContender && id >= 0 && id < State.Contenders.Count) + { + var c = State.Contenders[id]; + qBody = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW); + } + else if (!isContender && _spectatorBodies.TryGetValue(id, out var handle)) + { + var v = _world.View; + int lane = handle.Lane; + qBody = new Quaternion(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]); + } + if (qBody.LengthSquared() < 1e-6f) + { + qBody = Quaternion.Identity; + } + else + { + qBody = Quaternion.Normalize(qBody); + } + ws.AddRecoilImpulse(shotDirWorld, qBody, weaponDamage); + } + public bool HasLineOfSight(float ax, float ay, float az, float bx, float by, float bz) { var delta = new Vector3(bx - ax, by - ay, bz - az); @@ -310,6 +361,20 @@ namespace RustToDust.Ymir { State.Spectators.Spectators[i].SnapPreviousPose(); } + foreach (var ws in _contenderWalkers.Values) + { + if (ws.Initialized) + { + ws.SnapshotPrev(); + } + } + foreach (var ws in _spectatorWalkers.Values) + { + if (ws.Initialized) + { + ws.SnapshotPrev(); + } + } } public void Step(PlayerInput input) @@ -461,7 +526,10 @@ namespace RustToDust.Ymir private void SpawnContenderBody(ContenderState c) { var spec = c.Grid.Spec; - float volume = 8f * spec.HalfWidth * spec.HalfHeight * spec.HalfLength; + float physHalfH = spec.IsWalker + ? spec.HalfHeight * (spec.Plane == GridPlane.Dorsal ? 0.58f : 0.72f) + : spec.HalfHeight; + float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; float density = spec.MassKg / MathF.Max(0.1f, volume); var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); ulong stableId = ContenderStableIdBase + (ulong)c.Id; @@ -474,7 +542,7 @@ namespace RustToDust.Ymir var handle = _world.AddBox( stableId, (c.X, spawnY, c.Z), - (spec.HalfWidth, spec.HalfHeight, spec.HalfLength), + (spec.HalfWidth, physHalfH, spec.HalfLength), density, (q.X, q.Y, q.Z, q.W), friction: 0.2f, @@ -491,6 +559,17 @@ namespace RustToDust.Ymir c.VelZ = 0f; c.SnapPreviousPose(); c.ResetAimTracker(c.Yaw); + + if (spec.IsWalker) + { + var ws = new WalkerState(spec); + ws.InitializePose(new Vector3(c.X, spawnY, c.Z), q, spec.MassKg, State.Terrain); + _contenderWalkers[c.Id] = ws; + } + else + { + _contenderWalkers.Remove(c.Id); + } } private void OnContenderChassisSwapped(ContenderState c) @@ -500,6 +579,7 @@ namespace RustToDust.Ymir _world.RemoveBody(oldHandle); _contenderBodies.Remove(c.Id); } + _contenderWalkers.Remove(c.Id); if (c.Alive) { SpawnContenderBody(c); @@ -522,7 +602,10 @@ namespace RustToDust.Ymir private void SpawnSpectatorBody(int index, SpectatorState s) { var spec = s.Grid.Spec; - float volume = 8f * spec.HalfWidth * spec.HalfHeight * spec.HalfLength; + float physHalfH = spec.IsWalker + ? spec.HalfHeight * (spec.Plane == GridPlane.Dorsal ? 0.58f : 0.72f) + : spec.HalfHeight; + float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength; float density = spec.MassKg / MathF.Max(0.1f, volume); var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, s.Yaw); ulong stableId = SpectatorStableIdBase + (ulong)s.Id; @@ -532,7 +615,7 @@ namespace RustToDust.Ymir var handle = _world.AddBox( stableId, (s.X, spawnY, s.Z), - (spec.HalfWidth, spec.HalfHeight, spec.HalfLength), + (spec.HalfWidth, physHalfH, spec.HalfLength), density, (q.X, q.Y, q.Z, q.W), friction: 0.2f, @@ -549,6 +632,17 @@ namespace RustToDust.Ymir s.VelZ = 0f; s.SnapPreviousPose(); s.ResetAimTracker(s.Yaw); + + if (spec.IsWalker) + { + var ws = new WalkerState(spec); + ws.InitializePose(new Vector3(s.X, spawnY, s.Z), q, spec.MassKg, State.Terrain); + _spectatorWalkers[s.Id] = ws; + } + else + { + _spectatorWalkers.Remove(s.Id); + } } private void UpdateRingClearance() @@ -628,6 +722,40 @@ namespace RustToDust.Ymir continue; } + if (c.Grid.Spec.IsWalker) + { + if (!_contenderWalkers.TryGetValue(c.Id, out var ws)) + { + ws = new WalkerState(c.Grid.Spec); + ws.InitializePose(pos, q, mass, State.Terrain); + _contenderWalkers[c.Id] = ws; + } + + var wFwd = Vector3.Transform(Vector3.UnitZ, q); + wFwd.Y = 0f; + wFwd = wFwd.LengthSquared() < 1e-4f ? Vector3.UnitZ : Vector3.Normalize(wFwd); + float wMaxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed) * c.Grid.LegIntegrity; + Vector3 desiredHorizVel = wFwd * (c.ThrottleCmd * wMaxSpeed); + float wTargetYawVel = -c.SteerCmd * c.Grid.ComputeTurnRate(); + + if (MathF.Abs(c.ThrottleCmd) > 0.05f) + { + for (int m = 0; m < c.Grid.Mounted.Count; m++) + { + var mod = c.Grid.Mounted[m]; + if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f) + { + c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * FixedDt); + } + } + } + + WalkerLocomotion.StepWalker( + ws, c.Grid, State.Terrain, view, lane, mass, + pos, q, vel, angVel, desiredHorizVel, wTargetYawVel, c.BrakeCmd, FixedDt); + continue; + } + ComputeTerrainSupport( pos, q, vel, angVel, mass, c.Grid.Spec, out Vector3 supportForce, @@ -763,6 +891,30 @@ namespace RustToDust.Ymir continue; } + Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero; + float desiredYaw = s.Stance == SpectatorStance.Neutral + ? MathF.Atan2(-pos.X, -pos.Z) + : MathF.Atan2(aimX - pos.X, aimZ - pos.Z); + var forward = Vector3.Transform(Vector3.UnitZ, q); + float currentYaw = MathF.Atan2(forward.X, forward.Z); + float yawErr = MatchRules.NormalizeAngle(desiredYaw - currentYaw); + float targetSpecYawVel = Math.Clamp(yawErr * 3f, -5f, 5f); + + if (s.Grid.Spec.IsWalker) + { + if (!_spectatorWalkers.TryGetValue(s.Id, out var ws)) + { + ws = new WalkerState(s.Grid.Spec); + ws.InitializePose(pos, q, mass, State.Terrain); + _spectatorWalkers[s.Id] = ws; + } + + WalkerLocomotion.StepWalker( + ws, s.Grid, State.Terrain, view, lane, mass, + pos, q, vel, angVel, desiredVel, targetSpecYawVel, brakeCmd: false, FixedDt); + continue; + } + ComputeTerrainSupport( pos, q, vel, angVel, mass, s.Grid.Spec, out Vector3 supportForce, @@ -770,23 +922,15 @@ namespace RustToDust.Ymir out Vector3 terrainNormal, out _); - Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero; Vector3 horizVel = new Vector3(vel.X, 0f, vel.Z); Vector3 force = supportForce + (desiredVel - horizVel) * (mass * 4.5f); - float desiredYaw = s.Stance == SpectatorStance.Neutral - ? MathF.Atan2(-pos.X, -pos.Z) - : MathF.Atan2(aimX - pos.X, aimZ - pos.Z); - var forward = Vector3.Transform(Vector3.UnitZ, q); - float currentYaw = MathF.Atan2(forward.X, forward.Z); - float yawErr = MatchRules.NormalizeAngle(desiredYaw - currentYaw); - float hx = view.Size0[lane]; float hz = view.Size2[lane]; float iy = mass * (hx * hx + hz * hz) / 3f; Vector3 torque = ComputeRightingTorque(s.Grid.Spec, q, up, angVel, mass, terrainNormal, supportTorque, terrainBlend: 0.7f); - torque.Y = iy * (Math.Clamp(yawErr * 3f, -5f, 5f) - angVel.Y) * 8f; + torque.Y = iy * (targetSpecYawVel - angVel.Y) * 8f; view.ForceX[lane] = force.X; view.ForceY[lane] = force.Y; @@ -1013,13 +1157,9 @@ namespace RustToDust.Ymir Vector3 supportTorque, float terrainBlend) { - bool isWalker = spec.IsWalker; - float blend = isWalker ? MathF.Min(terrainBlend, 0.30f) : terrainBlend; - Vector3 desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, blend)); + Vector3 desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, terrainBlend)); - float maxDesiredTiltRad = isWalker - ? MathF.PI / 15f // 12 degrees target cap so dynamic overshoot stays <= 15-20 deg - : MathF.PI * 38f / 180f; // 38 degrees max slope alignment so cliff walls don't back-flip vehicles + const float maxDesiredTiltRad = MathF.PI * 38f / 180f; // 38 degrees max slope alignment so cliff walls don't back-flip vehicles { float dotY = Math.Clamp(desiredUp.Y, -1f, 1f); if (MathF.Acos(dotY) > maxDesiredTiltRad) @@ -1049,10 +1189,10 @@ namespace RustToDust.Ymir float maxFoot = MathF.Max(spec.HalfWidth, spec.HalfLength); float iTilt = MathF.Max(1f, (spec.HalfHeight * spec.HalfHeight + maxFoot * maxFoot) / 3f); - float rightingGain = (isWalker ? 48f : 28f) * iTilt; - float dampingGain = (isWalker ? 11f : 8.5f) * iTilt; + float rightingGain = 28f * iTilt; + float dampingGain = 8.5f * iTilt; - float tiltLimitRad = isWalker ? MathF.PI / 12f : MathF.PI * 48f / 180f; + const float tiltLimitRad = MathF.PI * 48f / 180f; float worldTiltRad = MathF.Acos(Math.Clamp(up.Y, -1f, 1f)); Vector3 arrestTorque = Vector3.Zero; if (worldTiltRad > tiltLimitRad) @@ -1070,11 +1210,11 @@ namespace RustToDust.Ymir float angOut = Vector3.Dot(new Vector3(angVel.X, 0f, angVel.Z), uprightDir); if (angOut < 0f) { - arrestTorque = uprightDir * (-angOut * mass * iTilt * (isWalker ? 28f : 18f)); + arrestTorque = uprightDir * (-angOut * mass * iTilt * 18f); } } - rightingGain *= 1f + (worldTiltRad - tiltLimitRad) * (isWalker ? 6f : 4f); + rightingGain *= 1f + (worldTiltRad - tiltLimitRad) * 4f; } return supportTorque + arrestTorque + tiltAxis * (mass * rightingGain) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * dampingGain); @@ -1111,7 +1251,6 @@ namespace RustToDust.Ymir float restTravel = isSion ? 0.22f : 0.20f; float kSpring = mass * (isSion ? 95f : 85f); float cDamp = mass * (isSion ? 12.0f : 10.5f); - float torqueScale = spec.IsWalker ? 0.12f : 1.0f; float maxPen = 0f; Span corners = stackalloc Vector3[4] @@ -1138,7 +1277,7 @@ namespace RustToDust.Ymir float fN = Math.Clamp(kSpring * penEff + bumpExtra - cDamp * vCornerN, 0f, mass * (isSion ? 42f : 65f)); Vector3 cornerForce = supportDir * fN; supportForce += cornerForce; - supportTorque += Vector3.Cross(r, cornerForce) * torqueScale; + supportTorque += Vector3.Cross(r, cornerForce); } } @@ -1219,6 +1358,10 @@ namespace RustToDust.Ymir c.VelY = vy; c.VelZ = vz; c.Speed = MathF.Sqrt(vx * vx + vz * vz); + if (_contenderWalkers.TryGetValue(c.Id, out var ws)) + { + ws.SyncBodyPoseOnly(new Vector3(c.X, c.Y, c.Z), Quaternion.Normalize(q), view.Mass[lane]); + } float stepDist = MathF.Sqrt((c.X - prevX) * (c.X - prevX) + (c.Z - prevZ) * (c.Z - prevZ)); float groundY = State.Terrain.SampleHeight(c.X, c.Z); @@ -1255,6 +1398,10 @@ namespace RustToDust.Ymir var q = new Quaternion(s.CurrRotX, s.CurrRotY, s.CurrRotZ, s.CurrRotW); var forward = Vector3.Transform(Vector3.UnitZ, q); s.Yaw = MathF.Atan2(forward.X, forward.Z); + if (_spectatorWalkers.TryGetValue(s.Id, out var ws)) + { + ws.SyncBodyPoseOnly(new Vector3(s.X, s.Y, s.Z), Quaternion.Normalize(q), view.Mass[lane]); + } } } @@ -1961,6 +2108,13 @@ namespace RustToDust.Ymir shooterGrid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput); mod.Cooldown = mod.Spec.FireCooldown; + if (shooterGrid.Spec.IsWalker) + { + bool isContenderShooter = !isSpectatorShooter; + int entityId = (int)(shooterStableId - (isContenderShooter ? ContenderStableIdBase : SpectatorStableIdBase)); + AddWalkerRecoilImpulse(isContenderShooter, entityId, baseAim, mod.Spec.WeaponDamage); + } + if (shooterContender is not null) { State.LastGunfireX = shooterPos.X; @@ -2092,6 +2246,7 @@ namespace RustToDust.Ymir _world.RemoveBody(handle); _contenderBodies.Remove(victim.Id); } + _contenderWalkers.Remove(victim.Id); if (shooterContender is not null) { @@ -2116,6 +2271,7 @@ namespace RustToDust.Ymir _world.RemoveBody(handle); _spectatorBodies.Remove(spec.Id); } + _spectatorWalkers.Remove(spec.Id); if (shooterContender is not null) { diff --git a/src/RustToDust.Ymir/WalkerLocomotion.cs b/src/RustToDust.Ymir/WalkerLocomotion.cs new file mode 100644 index 0000000..dfd2578 --- /dev/null +++ b/src/RustToDust.Ymir/WalkerLocomotion.cs @@ -0,0 +1,1576 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + [InlineArray(4)] + public struct LegArray4 + { + private T _element0; + } + + public readonly struct WalkerLegSpec + { + public WalkerLegSpec( + Vector3 hipInCom, + Vector2 restFootXZ, + float l1, + float l2, + float l3, + float ankleH, + float kneeBendSign, + bool isArachnidUp) + { + HipInCom = hipInCom; + RestFootXZ = restFootXZ; + L1 = l1; + L2 = l2; + L3 = l3; + AnkleH = ankleH; + KneeBendSign = kneeBendSign; + + if (isArachnidUp) + { + Vector3 rad = new(restFootXZ.X - hipInCom.X, 0f, restFootXZ.Y - hipInCom.Z); + LegFwd0 = rad.LengthSquared() > 1e-6f ? Vector3.Normalize(rad) : Vector3.UnitZ; + LegRight0 = Vector3.Cross(Vector3.UnitY, LegFwd0); + } + else if (MathF.Abs(restFootXZ.X - hipInCom.X) > 0.05f || MathF.Abs(restFootXZ.Y - hipInCom.Z) > 0.05f) + { + Vector3 splay = new( + (restFootXZ.X - hipInCom.X) * kneeBendSign, + 0f, + (restFootXZ.Y - hipInCom.Z) * kneeBendSign); + LegFwd0 = splay.LengthSquared() > 1e-6f ? Vector3.Normalize(splay) : Vector3.UnitZ; + LegRight0 = Vector3.Cross(Vector3.UnitY, LegFwd0); + } + else + { + LegRight0 = Vector3.UnitX; + LegFwd0 = Vector3.UnitZ; + } + + MaxLegReach = l3 > 0f ? (l1 + l2 + l3 - 0.08f) : (l1 + l2 - 0.02f); + MinLegReach = l3 > 0f ? MathF.Max(0.45f, MathF.Abs(l1 - l2) + 0.15f) : (MathF.Abs(l1 - l2) + 0.06f); + } + + public Vector3 HipInCom { get; } + public Vector2 RestFootXZ { get; } + public float L1 { get; } + public float L2 { get; } + public float L3 { get; } + public float AnkleH { get; } + public float KneeBendSign { get; } + public Vector3 LegRight0 { get; } + public Vector3 LegFwd0 { get; } + public float MaxLegReach { get; } + public float MinLegReach { get; } + } + + public sealed class WalkerGeometrySpec + { + public string Id { get; } + public int LegCount { get; } + public bool IsDigitigrade { get; } + public bool IsArachnidUp { get; } + public float ModelHalfHeight { get; } + public float ModelRideHeight { get; } + public float FootHalfW { get; } + public float FootHalfL { get; } + public float SwingArcHeight { get; } + public float MaxStepRadius { get; } + public readonly LegArray4 Legs; + + private WalkerGeometrySpec( + string id, + int legCount, + bool isDigitigrade, + bool isArachnidUp, + float modelHalfHeight, + float modelRideHeight, + float footHalfW, + float footHalfL, + float swingArcHeight, + float maxStepRadius, + LegArray4 legs) + { + Id = id; + LegCount = legCount; + IsDigitigrade = isDigitigrade; + IsArachnidUp = isArachnidUp; + ModelHalfHeight = modelHalfHeight; + ModelRideHeight = modelRideHeight; + FootHalfW = footHalfW; + FootHalfL = footHalfL; + SwingArcHeight = swingArcHeight; + MaxStepRadius = maxStepRadius; + Legs = legs; + } + + public static readonly WalkerGeometrySpec Breaker = BuildBreaker(); + public static readonly WalkerGeometrySpec Paladin = BuildPaladin(); + public static readonly WalkerGeometrySpec Raptor = BuildRaptor(); + public static readonly WalkerGeometrySpec Spectre = BuildSpectre(); + public static readonly WalkerGeometrySpec Kestrel = BuildKestrel(); + public static readonly WalkerGeometrySpec Manticore = BuildManticore(); + public static readonly WalkerGeometrySpec Bastion = BuildBastion(); + + public static WalkerGeometrySpec GetForChassis(string chassisId) => + chassisId.ToLowerInvariant() switch + { + "breaker" => Breaker, + "paladin" => Paladin, + "raptor" => Raptor, + "exemplar_frame" => Raptor, + "spectre" => Spectre, + "kestrel" => Kestrel, + "manticore" => Manticore, + "bastion" => Bastion, + _ => Raptor + }; + + private static WalkerGeometrySpec BuildBreaker() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.0809f, +0.2170f, 0f), new Vector2(+1.0809f, 0f), 1.3203f, 1.4396f, 0f, 0.6249f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.0809f, +0.2170f, 0f), new Vector2(-1.0809f, 0f), 1.3203f, 1.4396f, 0f, 0.6249f, +1f, false); + return new WalkerGeometrySpec("breaker", 2, false, false, 3.1456f, 2.99f, 0.55f, 0.80f, 0.58f, 1.65f, legs); + } + + private static WalkerGeometrySpec BuildPaladin() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.4853f, -0.2004f, +0.05f), new Vector2(+1.4853f, +0.05f), 1.9600f, 2.7200f, 0f, 1.0903f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.5047f, -0.1983f, +0.05f), new Vector2(-1.5047f, +0.05f), 1.9600f, 2.7200f, 0f, 1.0903f, +1f, false); + return new WalkerGeometrySpec("paladin", 2, false, false, 5.6581f, 5.52f, 0.82f, 1.20f, 0.85f, 2.60f, legs); + } + + private static WalkerGeometrySpec BuildRaptor() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.4000f, +1.1712f, 0f), new Vector2(+1.4000f, 0f), 1.9000f, 1.6000f, 1.7600f, 0.8173f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.4000f, +1.1712f, 0f), new Vector2(-1.4000f, 0f), 1.9000f, 1.6000f, 1.7600f, 0.8173f, +1f, false); + return new WalkerGeometrySpec("raptor", 2, true, false, 3.4937f, 3.52f, 0.62f, 0.95f, 0.70f, 2.40f, legs); + } + + private static WalkerGeometrySpec BuildSpectre() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.2500f, -0.0970f, +0.2227f), new Vector2(+1.2500f, +0.2227f), 1.7300f, 1.5340f, 1.8370f, 0.7385f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.2500f, -0.1199f, +0.1996f), new Vector2(-1.2500f, +0.1996f), 1.7300f, 1.5340f, 1.8370f, 0.7385f, +1f, false); + return new WalkerGeometrySpec("spectre", 2, true, false, 4.4946f, 4.52f, 0.70f, 1.05f, 0.78f, 2.55f, legs); + } + + private static WalkerGeometrySpec BuildKestrel() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.3000f, +1.3093f, 0f), new Vector2(+1.3000f, 0f), 2.5760f, 3.0621f, 0f, 0.8500f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-1.3000f, +1.3093f, 0f), new Vector2(-1.3000f, 0f), 2.6252f, 3.0551f, 0f, 0.8500f, +1f, false); + return new WalkerGeometrySpec("kestrel", 2, false, false, 4.8907f, 4.94f, 0.68f, 1.00f, 0.78f, 2.45f, legs); + } + + private static WalkerGeometrySpec BuildManticore() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+1.4200f, -2.4075f, +1.95f), new Vector2(+2.259f, +3.319f), 1.4719f, 1.7205f, 0f, 0.4625f, +1f, true); + legs[1] = new WalkerLegSpec(new Vector3(-1.4200f, -2.4075f, +1.95f), new Vector2(-2.259f, +3.319f), 1.4719f, 1.7205f, 0f, 0.4625f, +1f, true); + legs[2] = new WalkerLegSpec(new Vector3(+1.4800f, -2.3875f, -1.90f), new Vector2(+2.483f, -3.479f), 1.5819f, 1.8711f, 0f, 0.4225f, +1f, true); + legs[3] = new WalkerLegSpec(new Vector3(-1.4800f, -2.3875f, -1.90f), new Vector2(-2.483f, -3.479f), 1.5819f, 1.8711f, 0f, 0.4225f, +1f, true); + return new WalkerGeometrySpec("manticore", 4, false, true, 3.2500f, 3.28f, 0.45f, 0.55f, 0.62f, 1.65f, legs); + } + + private static WalkerGeometrySpec BuildBastion() + { + var legs = new LegArray4(); + legs[0] = new WalkerLegSpec(new Vector3(+4.2040f, -1.2643f, +4.2453f), new Vector2(+4.359f, +5.264f), 1.8041f, 1.2676f, 0f, 0.8855f, +1f, false); + legs[1] = new WalkerLegSpec(new Vector3(-4.2040f, -1.2643f, +4.2453f), new Vector2(-4.359f, +5.264f), 1.8041f, 1.2676f, 0f, 0.8855f, +1f, false); + legs[2] = new WalkerLegSpec(new Vector3(+3.6871f, -0.1774f, -4.2453f), new Vector2(+5.033f, -6.736f), 4.4637f, 0.9009f, 0f, 0.7259f, -1f, false); + legs[3] = new WalkerLegSpec(new Vector3(-3.6871f, -0.1774f, -4.2453f), new Vector2(-5.033f, -6.736f), 4.4637f, 0.9009f, 0f, 0.7259f, -1f, false); + return new WalkerGeometrySpec("bastion", 4, false, false, 4.8125f, 4.84f, 0.85f, 1.10f, 0.75f, 2.10f, legs); + } + } + + public struct WalkerLegAngles + { + public float HipPitch; + public float HipRoll; + public float KneeFlex; + public float HockFlex; + public float AnklePitch; + + public static WalkerLegAngles Lerp(in WalkerLegAngles a, in WalkerLegAngles b, float t) => new() + { + HipPitch = a.HipPitch + (b.HipPitch - a.HipPitch) * t, + HipRoll = a.HipRoll + (b.HipRoll - a.HipRoll) * t, + KneeFlex = a.KneeFlex + (b.KneeFlex - a.KneeFlex) * t, + HockFlex = a.HockFlex + (b.HockFlex - a.HockFlex) * t, + AnklePitch = a.AnklePitch + (b.AnklePitch - a.AnklePitch) * t + }; + } + + public struct WalkerVisualSnapshot + { + public int LegCount; + public float GeomScale; + public bool IsDigitigrade; + public bool IsArachnidUp; + public Vector3 ComPos; + public Quaternion ComRot; + public LegArray4 LegAngles; + public LegArray4 FootNormal; + public LegArray4 LoadG; + + public static WalkerVisualSnapshot Interpolate(in WalkerVisualSnapshot prev, in WalkerVisualSnapshot curr, float alpha) + { + float t = Math.Clamp(alpha, 0f, 1f); + Quaternion q0 = prev.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(prev.ComRot); + Quaternion q1 = curr.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(curr.ComRot); + if (Quaternion.Dot(q0, q1) < 0f) + { + q1 = -q1; + } + + WalkerVisualSnapshot res = new() + { + LegCount = curr.LegCount, + GeomScale = curr.GeomScale, + IsDigitigrade = curr.IsDigitigrade, + IsArachnidUp = curr.IsArachnidUp, + ComPos = Vector3.Lerp(prev.ComPos, curr.ComPos, t), + ComRot = Quaternion.Slerp(q0, q1, t) + }; + + for (int i = 0; i < curr.LegCount; i++) + { + res.LegAngles[i] = WalkerLegAngles.Lerp(prev.LegAngles[i], curr.LegAngles[i], t); + Vector3 n = Vector3.Lerp(prev.FootNormal[i], curr.FootNormal[i], t); + res.FootNormal[i] = n.LengthSquared() > 1e-6f ? Vector3.Normalize(n) : Vector3.UnitY; + res.LoadG[i] = prev.LoadG[i] + (curr.LoadG[i] - prev.LoadG[i]) * t; + } + return res; + } + } + + public struct WalkerJointActuator + { + public WalkerLegAngles Theta; + public WalkerLegAngles Omega; + public float RecoilHipImpulse; + public float RecoilKneeImpulse; + } + + public sealed class WalkerState + { + public const float ArenaGravity = 20f; + public const float FootFriction = 0.85f; + + public WalkerGeometrySpec Geom { get; private set; } + public float GeomScale { get; private set; } + public bool Initialized { get; private set; } + + public int StanceGroup; + public float SwingTime; + public float SwingPhase; + public float SimTime; + public bool IsAirborne; + public bool WasAirborne; + public float MaxFootSlipM; + public Vector3 LastTotalForce; + public Vector3 LastTotalTorque; + + public LegArray4 Planted; + public LegArray4 FootSole; + public LegArray4 SwingStartSole; + public LegArray4 SwingTargetSole; + public LegArray4 FootNormal; + public LegArray4 SwingStartNormal; + public LegArray4 SwingTargetNormal; + public LegArray4 LastGrfY; + public LegArray4 Actuators; + + public WalkerVisualSnapshot PrevSnap; + public WalkerVisualSnapshot CurrSnap; + + public WalkerState(ChassisSpec spec) + { + Geom = WalkerGeometrySpec.GetForChassis(spec.Id); + GeomScale = Geom.ModelHalfHeight > 1e-4f ? spec.HalfHeight / Geom.ModelHalfHeight : 1f; + } + + public void InitializePose(Vector3 comPos, Quaternion qBody, float mass, TerrainField terrain) + { + int n = Geom.LegCount; + StanceGroup = 0; + SwingTime = 0f; + SwingPhase = 0f; + SimTime = 0f; + bool anyCanReach = false; + for (int i = 0; i < n; i++) + { + Vector3 hipW = comPos + Vector3.Transform(Geom.Legs[i].HipInCom * GeomScale, qBody); + float gUnder = terrain.SampleHeight(hipW.X, hipW.Z); + float minAnkle = hipW.Y - (gUnder + Geom.Legs[i].AnkleH * GeomScale); + if (minAnkle <= Geom.Legs[i].MaxLegReach * GeomScale + 0.08f * GeomScale) + { + anyCanReach = true; + break; + } + } + IsAirborne = !anyCanReach; + WasAirborne = IsAirborne; + MaxFootSlipM = 0f; + LastTotalForce = Vector3.Zero; + LastTotalTorque = Vector3.Zero; + + for (int i = 0; i < n; i++) + { + Vector3 restLocal = new(Geom.Legs[i].RestFootXZ.X * GeomScale, 0f, Geom.Legs[i].RestFootXZ.Y * GeomScale); + Vector3 worldPos = comPos + Vector3.Transform(restLocal, qBody); + float gh = terrain.SampleHeight(worldPos.X, worldPos.Z); + Vector3 fn = SampleTerrainNormal(terrain, worldPos.X, worldPos.Z); + + FootSole[i] = new Vector3(worldPos.X, gh, worldPos.Z); + FootNormal[i] = fn; + SwingStartSole[i] = FootSole[i]; + SwingTargetSole[i] = FootSole[i]; + SwingStartNormal[i] = fn; + SwingTargetNormal[i] = fn; + Planted[i] = true; + LastGrfY[i] = (mass * ArenaGravity) / n; + + Vector3 hipWorld = comPos + Vector3.Transform(Geom.Legs[i].HipInCom * GeomScale, qBody); + Vector3 sole = FootSole[i]; + if (WalkerLocomotion.ClampSoleToReach(hipWorld, Geom.Legs[i].AnkleH * GeomScale, Geom.Legs[i].MaxLegReach * GeomScale * 0.96f, terrain, ref sole, out Vector3 clampedN)) + { + fn = clampedN; + FootSole[i] = sole; + FootNormal[i] = fn; + SwingStartSole[i] = sole; + SwingTargetSole[i] = sole; + SwingStartNormal[i] = fn; + SwingTargetNormal[i] = fn; + } + Vector3 ankleWorld = FootSole[i] + fn * (Geom.Legs[i].AnkleH * GeomScale); + WalkerLegAngles initAng = WalkerLocomotion.SolveLegTargetAngles(Geom, GeomScale, i, hipWorld, qBody, ankleWorld, fn, 0f); + Actuators[i] = new WalkerJointActuator + { + Theta = initAng, + Omega = default + }; + } + + CurrSnap = BuildSnapshot(comPos, qBody, mass); + PrevSnap = CurrSnap; + Initialized = true; + } + + public void SnapshotPrev() + { + PrevSnap = CurrSnap; + } + + public void SyncBodyPoseOnly(Vector3 comPos, Quaternion qBody, float mass) + { + CurrSnap.ComPos = comPos; + CurrSnap.ComRot = qBody; + float denom = MathF.Max(1f, 0.5f * mass * ArenaGravity); + for (int i = 0; i < Geom.LegCount; i++) + { + CurrSnap.LoadG[i] = LastGrfY[i] / denom; + } + } + + public void AddRecoilImpulse(Vector3 shotDirWorld, Quaternion qBody, float weaponDamage) + { + if (!Initialized) + { + return; + } + Vector3 shotLocal = Vector3.Transform(shotDirWorld, Quaternion.Conjugate(qBody)); + float dirSign = shotLocal.Z >= -0.2f ? 1f : -1f; + float mag = Math.Clamp(weaponDamage / 55f, 0.12f, 1.35f) * dirSign; + + int n = Geom.LegCount; + for (int i = 0; i < n; i++) + { + float weight = Planted[i] ? 1.0f : 0.25f; + ref var act = ref Actuators[i]; + act.RecoilHipImpulse -= 0.85f * mag * weight; + act.RecoilKneeImpulse += 1.25f * mag * weight; + } + } + + public WalkerVisualSnapshot BuildSnapshot(Vector3 comPos, Quaternion qBody, float mass) + { + WalkerVisualSnapshot snap = new() + { + LegCount = Geom.LegCount, + GeomScale = GeomScale, + IsDigitigrade = Geom.IsDigitigrade, + IsArachnidUp = Geom.IsArachnidUp, + ComPos = comPos, + ComRot = qBody + }; + + float denom = MathF.Max(1f, 0.5f * mass * ArenaGravity); + for (int i = 0; i < Geom.LegCount; i++) + { + snap.LegAngles[i] = Actuators[i].Theta; + snap.FootNormal[i] = FootNormal[i]; + snap.LoadG[i] = LastGrfY[i] / denom; + } + return snap; + } + + internal static Vector3 SampleTerrainNormal(TerrainField terrain, float x, float z) + { + var (nx, ny, nz) = terrain.SampleNormal(x, z); + Vector3 n = new(nx, ny, nz); + return n.LengthSquared() > 1e-6f ? Vector3.Normalize(n) : Vector3.UnitY; + } + } + + public static class WalkerLocomotion + { + private const float Gravity = WalkerState.ArenaGravity; + private const float Mu = WalkerState.FootFriction; + + public static float GetRideHeight(ChassisSpec spec) + { + var geom = WalkerGeometrySpec.GetForChassis(spec.Id); + float scale = geom.ModelHalfHeight > 1e-4f ? spec.HalfHeight / geom.ModelHalfHeight : 1f; + return geom.ModelRideHeight * scale; + } + + public static void StepWalker( + WalkerState ws, + ChassisGrid grid, + TerrainField terrain, + Box3DSoaView view, + int lane, + float mass, + Vector3 comPos, + Quaternion qBody, + Vector3 vel, + Vector3 angVel, + Vector3 desiredHorizVel, + float targetYawVel, + bool brakeCmd, + float dt) + { + if (!ws.Initialized) + { + ws.InitializePose(comPos, qBody, mass, terrain); + } + + var geom = ws.Geom; + float scale = ws.GeomScale; + int n = geom.LegCount; + ws.SimTime += dt; + + Span legIntegrities = stackalloc float[4]; + grid.GetLegIntegrities(legIntegrities); + float avgIntegrity = 0f; + bool anyLegSeverelyCrippled = false; + for (int i = 0; i < n; i++) + { + float integ = Math.Clamp(legIntegrities[i], 0.25f, 1f); + legIntegrities[i] = integ; + avgIntegrity += integ; + if (integ < 0.5f) + { + anyLegSeverelyCrippled = true; + } + } + avgIntegrity /= n; + + float desiredSpeed = MathF.Sqrt(desiredHorizVel.X * desiredHorizVel.X + desiredHorizVel.Z * desiredHorizVel.Z); + float horizSpeed = MathF.Sqrt(vel.X * vel.X + vel.Z * vel.Z); + float baseRideHeight = geom.ModelRideHeight * scale; + float walkSpeedRatio = Math.Clamp(horizSpeed / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f); + float rideHeight = baseRideHeight - 0.06f * scale * walkSpeedRatio; + Vector3 fwd = Vector3.Transform(Vector3.UnitZ, qBody); + fwd.Y = 0f; + fwd = fwd.LengthSquared() > 1e-5f ? Vector3.Normalize(fwd) : Vector3.UnitZ; + Vector3 right = Vector3.Cross(fwd, Vector3.UnitY); + Vector3 up = Vector3.Transform(Vector3.UnitY, qBody); + + Span hipWorld = stackalloc Vector3[4]; + for (int i = 0; i < n; i++) + { + hipWorld[i] = comPos + Vector3.Transform(geom.Legs[i].HipInCom * scale, qBody); + } + + // Determine airborne state before gait step so floating mechs don't drag feet on the ground + float comGroundY = terrain.SampleHeight(comPos.X, comPos.Z); + bool anyLegCanReachGround = false; + for (int i = 0; i < n; i++) + { + float maxReach = geom.Legs[i].MaxLegReach * scale; + float reachTol = ws.IsAirborne ? -0.04f * maxReach : 0.45f * scale; + float gUnderHip = terrain.SampleHeight(hipWorld[i].X, hipWorld[i].Z); + float minAnkleDist = hipWorld[i].Y - (gUnderHip + geom.Legs[i].AnkleH * scale); + if (minAnkleDist <= maxReach + reachTol) + { + anyLegCanReachGround = true; + break; + } + } + ws.WasAirborne = ws.IsAirborne; + ws.IsAirborne = !anyLegCanReachGround; + + // Landing transition: snap all feet to ground cleanly once on touchdown from air + if (ws.WasAirborne && !ws.IsAirborne) + { + for (int i = 0; i < n; i++) + { + float fx = ws.FootSole[i].X; + float fz = ws.FootSole[i].Z; + ws.FootSole[i] = new Vector3(fx, terrain.SampleHeight(fx, fz), fz); + ws.FootNormal[i] = WalkerState.SampleTerrainNormal(terrain, fx, fz); + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingStartNormal[i] = ws.FootNormal[i]; + ws.SwingTargetSole[i] = ws.FootSole[i]; + ws.SwingTargetNormal[i] = ws.FootNormal[i]; + ws.Planted[i] = true; + } + ws.SwingTime = 0f; + ws.SwingPhase = 0f; + } + + bool idleCmd = desiredSpeed < 0.10f && MathF.Abs(targetYawVel) < 0.05f; + bool stepping = !ws.IsAirborne && + (!idleCmd || horizSpeed >= 0.25f || MathF.Abs(angVel.Y) >= 0.10f); + + float overlap = n == 4 + ? (anyLegSeverelyCrippled ? 0.28f : 0.12f) + : 0.10f; + + bool anySwinging = false; + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) + { + anySwinging = true; + break; + } + } + + // 4B: Gait & Capture-Point Planner (Bug 1, 2, 3 fixed) + float swingToePitch = 0f; + if (ws.IsAirborne) + { + // Dangle feet cleanly below hips when airborne + for (int i = 0; i < n; i++) + { + ws.Planted[i] = false; + Vector3 restLocal = new(geom.Legs[i].RestFootXZ.X * scale, 0f, geom.Legs[i].RestFootXZ.Y * scale); + Vector3 nominal = comPos + Vector3.Transform(restLocal, qBody); + float targetAnkleY = hipWorld[i].Y - (geom.Legs[i].MaxLegReach * 0.88f) * scale; + float targetSoleY = MathF.Max(terrain.SampleHeight(nominal.X, nominal.Z), targetAnkleY - geom.Legs[i].AnkleH * scale); + ws.FootSole[i] = Vector3.Lerp(ws.FootSole[i], new Vector3(nominal.X, targetSoleY, nominal.Z), Math.Clamp(dt * 8f, 0f, 1f)); + ws.FootNormal[i] = Vector3.Normalize(Vector3.Lerp(ws.FootNormal[i], up, Math.Clamp(dt * 6f, 0f, 1f))); + } + ws.SwingTime = 0f; + ws.SwingPhase = 0f; + } + else if (!stepping && !anySwinging) + { + for (int i = 0; i < n; i++) + { + ws.Planted[i] = true; + } + ws.SwingTime = 0f; + ws.SwingPhase = 0f; + } + else + { + float baseDur = Math.Clamp(0.32f * MathF.Sqrt(MathF.Max(0.25f, geom.ModelHalfHeight * scale / 3.1456f)), 0.18f, 0.44f); + float speedScale = Math.Clamp(horizSpeed / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f); + float latDisturb = MathF.Abs((vel.X - desiredHorizVel.X) * right.X + (vel.Z - desiredHorizVel.Z) * right.Z); + float effectiveDur = baseDur * (1f - 0.30f * speedScale); + + // Bound step duration across all legs so stance travel stays inside physical horizontal leg reach at speed + float sprintCrouch = n == 2 ? 0.06f * speedScale * scale : 0f; + float speedForDur = MathF.Max(horizSpeed, desiredSpeed * 0.75f); + if (speedForDur > 1.0f) + { + for (int i = 0; i < n; i++) + { + float actualDy = hipWorld[i].Y - (terrain.SampleHeight(hipWorld[i].X, hipWorld[i].Z) + geom.Legs[i].AnkleH * scale); + float nominalDy = MathF.Max(0.25f * scale, MathF.Max(actualDy, (rideHeight - sprintCrouch) + geom.Legs[i].HipInCom.Y * scale - geom.Legs[i].AnkleH * scale)); + float availReach = geom.Legs[i].MaxLegReach * scale; + float maxHorizStride = MathF.Sqrt(MathF.Max(0.25f * scale * scale, availReach * availReach - nominalDy * nominalDy)); + effectiveDur = MathF.Min(effectiveDur, (0.68f * maxHorizStride) / speedForDur); + } + } + if (latDisturb > 1.1f) + { + effectiveDur = MathF.Min(effectiveDur, 0.20f); + } + effectiveDur = Math.Clamp(effectiveDur, 0.105f, 0.44f); + + ws.SwingTime += dt; + ws.SwingPhase += dt / MathF.Max(0.105f, effectiveDur); + float u = ws.SwingPhase; + + // Bug 1 Fix: On u >= 1.0f, plant swinging group, flip _stanceGroup, IMMEDIATELY reset _swingTime = 0 & u = 0, + // snapshot _swingStartSole/_swingStartNormal for the new swinging group, and NEVER evaluate swing with stale u >= 1! + if (u >= 1.0f) + { + for (int i = 0; i < n; i++) + { + if (!IsInGroup(n, i, ws.StanceGroup)) + { + float tx = ws.SwingTargetSole[i].X; + float tz = ws.SwingTargetSole[i].Z; + Vector3 tn = WalkerState.SampleTerrainNormal(terrain, tx, tz); + ws.FootSole[i] = new Vector3(tx, terrain.SampleHeight(tx, tz), tz); + ws.FootNormal[i] = tn; + ws.Planted[i] = true; + } + } + + ws.StanceGroup = 1 - ws.StanceGroup; + ws.SwingTime = 0f; + ws.SwingPhase = 0f; + u = 0f; + + if (stepping) + { + for (int i = 0; i < n; i++) + { + if (!IsInGroup(n, i, ws.StanceGroup)) + { + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingStartNormal[i] = ws.FootNormal[i]; + ws.SwingTargetSole[i] = ws.FootSole[i]; + ws.SwingTargetNormal[i] = ws.FootNormal[i]; + ws.Planted[i] = true; // Double-support overlap at u = 0 < overlap + } + else + { + ws.Planted[i] = true; + } + } + } + else + { + for (int i = 0; i < n; i++) + { + ws.Planted[i] = true; + } + } + } + else + { + for (int i = 0; i < n; i++) + { + if (IsInGroup(n, i, ws.StanceGroup)) + { + ws.Planted[i] = true; + } + else + { + bool shouldPlantOverlap = ws.Planted[i] && u < overlap; + if (ws.Planted[i] && !shouldPlantOverlap) + { + // Liftoff transition at u >= overlap: snapshot start pose cleanly + ws.SwingStartSole[i] = ws.FootSole[i]; + ws.SwingStartNormal[i] = ws.FootNormal[i]; + } + ws.Planted[i] = shouldPlantOverlap; + } + } + } + + // Update Capture-Point target & smooth C1 trajectory for non-planted swing feet + float omega0 = MathF.Sqrt(Gravity / MathF.Max(0.5f, rideHeight)); + float kCapture = 0.22f / omega0; + float uSwing = u >= overlap ? Math.Clamp((u - overlap) / MathF.Max(0.05f, 1f - overlap), 0f, 1f) : 0f; + float s = uSwing * uSwing * (3f - 2f * uSwing); + float env = MathF.Sin(MathF.PI * uSwing); + swingToePitch = 0.20f * MathF.Sin(MathF.Tau * uSwing); + + for (int i = 0; i < n; i++) + { + if (ws.Planted[i]) + { + continue; + } + + Vector3 rHip = hipWorld[i] - comPos; + Vector3 vHip = vel + Vector3.Cross(angVel, rHip); + Vector3 vHipDes = desiredHorizVel + Vector3.Cross(new Vector3(0f, targetYawVel, 0f), rHip); + + Vector2 vH = new(vHip.X, vHip.Z); + Vector2 vHDes = new(vHipDes.X, vHipDes.Z); + Vector2 vErr = vH - vHDes; + float vHDesLen = vHDes.Length(); + bool accelFromRest = false; + Vector2 dirDes = Vector2.Zero; + if (vHDesLen > 0.3f) + { + dirDes = vHDes / vHDesLen; + float vAlong = Vector2.Dot(vH, dirDes); + if (vAlong < vHDesLen) + { + // Accelerating up to target speed: avoid pulling swing target behind hip + float alongErr = Vector2.Dot(vErr, dirDes); + if (alongErr < 0f) + { + vErr -= dirDes * alongErr; + } + } + accelFromRest = vAlong < vHDesLen * 0.5f; + } + Vector2 stepOffset = vH * (effectiveDur * 0.50f) + vErr * kCapture; + if (accelFromRest) + { + stepOffset += vHDes * (0.28f * effectiveDur); + float alongStep = Vector2.Dot(stepOffset, dirDes); + if (alongStep < 0f) + { + stepOffset -= dirDes * alongStep; + } + } + + Vector3 restLocal = new(geom.Legs[i].RestFootXZ.X * scale, 0f, geom.Legs[i].RestFootXZ.Y * scale); + if (n == 2 && desiredSpeed > 0.5f) + { + restLocal.X *= 0.85f; + } + else if (n == 4 && desiredSpeed > 0.5f) + { + // Center splayed quadruped swing target modestly toward hip socket during locomotion + float centerT = 0.55f * Math.Clamp(MathF.Max(horizSpeed, desiredSpeed * 0.6f) / MathF.Max(6f, grid.Spec.MaxSpeed), 0f, 1f); + restLocal.X += (geom.Legs[i].HipInCom.X * scale - restLocal.X) * centerT; + restLocal.Z += (geom.Legs[i].HipInCom.Z * scale - restLocal.Z) * centerT; + } + Vector3 nominal = comPos + Vector3.Transform(restLocal, qBody); + + float maxStep = geom.MaxStepRadius * scale * (1f - 0.25f * (1f - legIntegrities[i])); + if (stepOffset.Length() > maxStep) + { + stepOffset = Vector2.Normalize(stepOffset) * maxStep; + } + + float tx = nominal.X + stepOffset.X; + float tz = nominal.Z + stepOffset.Y; + + // Prevent biped feet from crossing the sagittal midline + if (n == 2) + { + float minLat = 0.22f * scale; + float latFromCom = (tx - comPos.X) * right.X + (tz - comPos.Z) * right.Z; + // +X is Left (leg 0), -X is Right (leg 1); note right = Cross(fwd, UnitY) = -X in right-handed frame! + // Wait: Cross(UnitZ, UnitY) = (-1, 0, 0) = -X (Right)! So Left is negative dot with `right`, Right is positive dot with `right`! + if (i == 0 && latFromCom > -minLat) + { + float corr = -minLat - latFromCom; + tx += right.X * corr; + tz += right.Z * corr; + } + else if (i == 1 && latFromCom < minLat) + { + float corr = minLat - latFromCom; + tx += right.X * corr; + tz += right.Z * corr; + } + } + + // Keep swing target inside physical leg reach around hipWorld on terrain + Vector3 tgtSole = new(tx, terrain.SampleHeight(tx, tz), tz); + if (ClampSoleToReach(hipWorld[i], geom.Legs[i].AnkleH * scale, geom.Legs[i].MaxLegReach * scale * 0.985f, terrain, ref tgtSole, out Vector3 tgtNorm)) + { + ws.SwingTargetSole[i] = tgtSole; + ws.SwingTargetNormal[i] = tgtNorm; + } + else + { + ws.SwingTargetSole[i] = tgtSole; + ws.SwingTargetNormal[i] = WalkerState.SampleTerrainNormal(terrain, tgtSole.X, tgtSole.Z); + } + + // Bug 3 Fix: C1 clearance envelope (env == 0 at uSwing == 0 and uSwing == 1) + float sx = ws.SwingStartSole[i].X + (ws.SwingTargetSole[i].X - ws.SwingStartSole[i].X) * s; + float sz = ws.SwingStartSole[i].Z + (ws.SwingTargetSole[i].Z - ws.SwingStartSole[i].Z) * s; + float syBase = ws.SwingStartSole[i].Y + (ws.SwingTargetSole[i].Y - ws.SwingStartSole[i].Y) * s; + float arcLift = geom.SwingArcHeight * scale * env; + float groundUnder = terrain.SampleHeight(sx, sz); + float minGround = groundUnder + 0.05f * scale * env; + ws.FootSole[i] = new Vector3(sx, MathF.Max(syBase + arcLift, minGround), sz); + + // Bug 2 Fix: smooth normal blend (zero 14-deg ankle snap) + Vector3 nBlend = Vector3.Lerp(ws.SwingStartNormal[i], ws.SwingTargetNormal[i], s); + ws.FootNormal[i] = nBlend.LengthSquared() > 1e-6f ? Vector3.Normalize(nBlend) : Vector3.UnitY; + } + } + + // Clamp planted feet to MaxLegReach * geomScale (genuine terrain drag if dragged past reach) + if (!ws.IsAirborne) + { + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) + { + continue; + } + float maxReach = geom.Legs[i].MaxLegReach * scale; + Vector3 oldSole = ws.FootSole[i]; + Vector3 clampedSole = oldSole; + if (ClampSoleToReach(hipWorld[i], geom.Legs[i].AnkleH * scale, maxReach, terrain, ref clampedSole, out Vector3 clampedN)) + { + ws.FootSole[i] = clampedSole; + ws.FootNormal[i] = clampedN; + float drag = MathF.Sqrt((clampedSole.X - oldSole.X) * (clampedSole.X - oldSole.X) + + (clampedSole.Z - oldSole.Z) * (clampedSole.Z - oldSole.Z)); + if (drag > ws.MaxFootSlipM) + { + ws.MaxFootSlipM = drag; + } + } + } + } + + // 4C: Pure Newtonian Centroidal GRF Wrench (ZERO magic hull springs or righting torques!) + Vector3 terrainNormal = WalkerState.SampleTerrainNormal(terrain, comPos.X, comPos.Z); + float rawTerrainRateY = -(terrainNormal.X * vel.X + terrainNormal.Z * vel.Z) / MathF.Max(0.35f, terrainNormal.Y); + float terrainRateY = Math.Clamp(rawTerrainRateY, -12f, 11f); + float plantedYSum = 0f; + int plantedYCount = 0; + for (int i = 0; i < n; i++) + { + if (ws.Planted[i]) + { + plantedYSum += ws.FootSole[i].Y; + plantedYCount++; + } + } + float supportGroundY = plantedYCount > 0 + ? Math.Clamp(plantedYSum / plantedYCount, comGroundY - 0.03f * scale, comGroundY + 0.18f * scale) + : comGroundY; + // When sprinting uphill on traversable slopes (aheadNormal.Y >= 0.78), track rising terrain ahead so tall fast bipeds don't sink into steep dunes + float effectiveGroundY = MathF.Max(supportGroundY, comGroundY); + if (horizSpeed > 2.0f) + { + float vxDir = vel.X / horizSpeed; + float vzDir = vel.Z / horizSpeed; + float leadDist = MathF.Min(horizSpeed * 0.06f, 2.2f); + float ax = comPos.X + vxDir * leadDist; + float az = comPos.Z + vzDir * leadDist; + Vector3 aheadNorm = WalkerState.SampleTerrainNormal(terrain, ax, az); + if (aheadNorm.Y >= 0.78f) + { + float aheadH = terrain.SampleHeight(ax, az); + if (aheadH > comGroundY) + { + effectiveGroundY = MathF.Max(effectiveGroundY, (comGroundY + aheadH) * 0.5f); + } + } + } + float targetY = effectiveGroundY + rideHeight; + + float fyDes = MathF.Max(0f, + mass * Gravity + + mass * 48f * (targetY - comPos.Y) + + mass * 10.5f * (terrainRateY - vel.Y)); + float penThresh = MathF.Min(geom.ModelHalfHeight * scale, rideHeight) - 0.01f * scale; + float hullBottomPen = (comGroundY + penThresh) - comPos.Y; + if (!ws.IsAirborne && terrainNormal.Y < 0.975f && (vel.Y - terrainRateY) < 0.4f && comPos.Y <= comGroundY + geom.ModelHalfHeight * scale + 0.45f * scale) + { + fyDes = MathF.Max(fyDes, mass * Gravity); + } + + Vector3 driveFwd = fwd - terrainNormal * Vector3.Dot(fwd, terrainNormal); + driveFwd = driveFwd.LengthSquared() > 1e-5f ? Vector3.Normalize(driveFwd) : fwd; + Vector3 driveRight = right - terrainNormal * Vector3.Dot(right, terrainNormal); + driveRight = driveRight.LengthSquared() > 1e-5f ? Vector3.Normalize(driveRight) : right; + + // Steep-cliff strip (n.Y < 0.78 at COM or ahead on sprint path): prevent burrowing into Mesa cliff walls + Vector3 cliffNormal = terrainNormal; + if (desiredSpeed > 0.1f) + { + Vector3 probeDir = Vector3.Normalize(new Vector3(desiredHorizVel.X, 0f, desiredHorizVel.Z)); + float baseProbe = MathF.Max(view.Size2[lane], geom.FootHalfL * scale) + 1.5f * scale; + float farProbe = baseProbe + horizSpeed * 0.45f; + foreach (float pd in new[] { baseProbe, (baseProbe + farProbe) * 0.5f, farProbe }) + { + Vector3 aheadN = WalkerState.SampleTerrainNormal(terrain, comPos.X + probeDir.X * pd, comPos.Z + probeDir.Z * pd); + if (aheadN.Y < cliffNormal.Y) + { + cliffNormal = aheadN; + } + } + } + Vector3 effectiveDriveVel = desiredHorizVel; + // Physical grade resistance: steep uphill climbs naturally slow stride speed (prevents ski-jumping off steep dune crests) + if (terrainNormal.Y < 0.96f && terrainNormal.Y >= 0.78f && desiredSpeed > 0.1f) + { + Vector3 downhillHoriz = new(terrainNormal.X, 0f, terrainNormal.Z); + float dhLen = downhillHoriz.Length(); + if (dhLen > 1e-4f) + { + downhillHoriz /= dhLen; + float uphillComp = -Vector3.Dot(effectiveDriveVel, downhillHoriz); + if (uphillComp > 0f) + { + float gradeScale = Math.Clamp((terrainNormal.Y - 0.76f) / 0.20f, 0.25f, 1.0f); + effectiveDriveVel += downhillHoriz * (uphillComp * (1f - gradeScale)); + } + } + } + Vector3 cliffHoriz = Vector3.Zero; + bool onSteepCliff = cliffNormal.Y < 0.78f; + if (onSteepCliff) + { + cliffHoriz = new Vector3(cliffNormal.X, 0f, cliffNormal.Z); + if (cliffHoriz.LengthSquared() > 1e-4f) + { + cliffHoriz = Vector3.Normalize(cliffHoriz); + float intoCliff = Vector3.Dot(effectiveDriveVel, cliffHoriz); + if (intoCliff < 0f) + { + effectiveDriveVel -= cliffHoriz * intoCliff; + } + } + } + + float thrust = grid.ComputeDriveThrust(); + float maxSpd = MathF.Max(4f, grid.Spec.MaxSpeed); + float driveGain = MathF.Max(mass * 5.2f, (thrust / maxSpd) * 2.0f) * avgIntegrity; + float latGain = mass * 8.5f * avgIntegrity; + if (idleCmd) + { + float stopGain = mass * 16f * avgIntegrity; + driveGain = MathF.Max(driveGain, stopGain); + latGain = MathF.Max(latGain, stopGain); + } + float fwdVel = Vector3.Dot(vel, driveFwd); + float fwdDes = Vector3.Dot(effectiveDriveVel, new Vector3(driveFwd.X, 0f, driveFwd.Z)); + float latVel = Vector3.Dot(vel, driveRight); + float latDes = Vector3.Dot(effectiveDriveVel, new Vector3(driveRight.X, 0f, driveRight.Z)); + + Vector3 horizDriveForce = + new Vector3(driveFwd.X, 0f, driveFwd.Z) * ((fwdDes - fwdVel) * driveGain) + + new Vector3(driveRight.X, 0f, driveRight.Z) * ((latDes - latVel) * latGain); + + float hx = view.Size0[lane]; + float hy = MathF.Max(view.Size1[lane], geom.ModelHalfHeight * scale); + float hz = view.Size2[lane]; + float maxFoot = MathF.Max(hx, hz); + float iTilt = mass * (hy * hy + maxFoot * maxFoot) / 3f; + float iy = mass * (hx * hx + hz * hz) / 3f; + + if (!idleCmd && !brakeCmd) + { + float maxSelfDrive = MathF.Min(Mu * mass * Gravity, 0.85f * (iTilt * 28f) / MathF.Max(0.5f, rideHeight)) * avgIntegrity; + float driveMag = horizDriveForce.Length(); + if (driveMag > maxSelfDrive && driveMag > 1e-4f) + { + horizDriveForce *= maxSelfDrive / driveMag; + } + } + + if (onSteepCliff && cliffHoriz.LengthSquared() > 1e-4f) + { + float forceIntoCliff = Vector3.Dot(horizDriveForce, cliffHoriz); + if (forceIntoCliff < 0f) + { + horizDriveForce -= cliffHoriz * forceIntoCliff; + } + float velIntoCliff = Vector3.Dot(new Vector3(vel.X, 0f, vel.Z), cliffHoriz); + if (velIntoCliff < 0f) + { + horizDriveForce -= cliffHoriz * (velIntoCliff * mass * 18f); + } + } + + if (brakeCmd) + { + horizDriveForce -= new Vector3(vel.X, 0f, vel.Z) * (mass * 7f); + } + float fxDes = horizDriveForce.X; + float fzDes = horizDriveForce.Z; + + // Inertial attitude PD torque + subtle accel pitch lean + turn bank + crippled-leg limp sag + yaw PD torque + Vector3 desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.22f)); + float accelPitch = Math.Clamp((fwdDes - fwdVel) * 0.008f + fwdDes * 0.003f, -0.04f, 0.06f); + float limpLatLean = 0f; + float limpFwdLean = 0f; + if (n == 2) + { + // Leg 0 is Left (-right), Leg 1 is Right (+right); lean toward crippled side + limpLatLean = (legIntegrities[1] - legIntegrities[0]) * 0.075f; + } + else if (n == 4) + { + float leftInt = 0.5f * (legIntegrities[0] + legIntegrities[2]); + float rightInt = 0.5f * (legIntegrities[1] + legIntegrities[3]); + float frontInt = 0.5f * (legIntegrities[0] + legIntegrities[1]); + float rearInt = 0.5f * (legIntegrities[2] + legIntegrities[3]); + limpLatLean = (rightInt - leftInt) * 0.075f; + limpFwdLean = (rearInt - frontInt) * 0.065f; + } + Vector3 driveBank = new Vector3(fxDes, 0f, fzDes) / MathF.Max(1f, mass * Gravity) * 0.08f; + desiredUp = Vector3.Normalize(desiredUp + fwd * (accelPitch + limpFwdLean) - right * limpLatLean + driveBank); + + // Cap desiredUp tilt to <= 8.6 deg so free-fall off Mesa cliffs stays well within 22 deg upright margin + const float maxDesiredTiltRad = 0.150f; + float dotUp = Math.Clamp(desiredUp.Y, -1f, 1f); + if (MathF.Acos(dotUp) > maxDesiredTiltRad) + { + Vector3 horiz = new(desiredUp.X, 0f, desiredUp.Z); + float hLen = horiz.Length(); + desiredUp = hLen > 1e-4f + ? Vector3.UnitY * MathF.Cos(maxDesiredTiltRad) + (horiz / hLen) * MathF.Sin(maxDesiredTiltRad) + : Vector3.UnitY; + } + + Vector3 tiltAxis = Vector3.Cross(up, desiredUp); + Vector3 torqueDes = new( + iTilt * (tiltAxis.X * 72f - angVel.X * 14f), + iy * (targetYawVel - angVel.Y) * 8.5f, + iTilt * (tiltAxis.Z * 72f - angVel.Z * 14f)); + + // Allocate strictly across planted feet inside reach + Span weight = stackalloc float[4]; + Span capMax = stackalloc float[4]; + float weightSum = 0f; + int activeSupportCount = 0; + float sumR2 = 0f; + float footHalfW = geom.FootHalfW * scale; + float footHalfL = geom.FootHalfL * scale; + + for (int i = 0; i < n; i++) + { + ws.LastGrfY[i] = 0f; + capMax[i] = mass * Gravity * (n == 4 ? 1.45f : 1.75f) * legIntegrities[i]; + if (!ws.Planted[i]) + { + continue; + } + Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + float dist = (ankle - hipWorld[i]).Length(); + float maxLegReach = geom.Legs[i].MaxLegReach * scale; + float hardCutoff = maxLegReach + (n == 4 ? 2.40f * scale : 0.16f * scale); + if (dist > hardCutoff) + { + continue; + } + weight[i] = legIntegrities[i]; + weightSum += weight[i]; + activeSupportCount++; + Vector3 r = ws.FootSole[i] - comPos; + sumR2 += r.X * r.X + r.Z * r.Z; + } + + // Downhill steep-slope safety: never free-fall (weightSum == 0) while a planted foot is within extended reach + if (!ws.IsAirborne && weightSum <= 0f) + { + for (int i = 0; i < n; i++) + { + if (!ws.Planted[i]) + { + continue; + } + Vector3 ankle = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + float dist = (ankle - hipWorld[i]).Length(); + if (dist <= geom.Legs[i].MaxLegReach * scale * 1.25f) + { + weight[i] = legIntegrities[i]; + weightSum += weight[i]; + activeSupportCount++; + Vector3 r = ws.FootSole[i] - comPos; + sumR2 += r.X * r.X + r.Z * r.Z; + } + } + } + + Vector3 totalForce = Vector3.Zero; + Vector3 tContact = Vector3.Zero; + Vector3 totalTorque = Vector3.Zero; + + if (weightSum > 0f) + { + if (activeSupportCount >= 2 && sumR2 > 0.25f) + { + // Multi-foot support: Pure Newtonian GRF + Coulomb friction cone + chassis-local CoP + Span footForces = stackalloc Vector3[4]; + float sumRY = 0f; + Vector2 rAvg = Vector2.Zero; + + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + Vector3 r0 = ws.FootSole[i] - comPos; + sumRY += r0.Y; + rAvg.X += r0.X; + rAvg.Y += r0.Z; + } + rAvg /= activeSupportCount; + float avgRY = sumRY / activeSupportCount; + + float sumRelR2 = 0f; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + Vector3 r0 = ws.FootSole[i] - comPos; + float rx = r0.X - rAvg.X; + float rz = r0.Z - rAvg.Y; + sumRelR2 += rx * rx + rz * rz; + } + + float tauXForFy = torqueDes.X - avgRY * fzDes; + float tauZForFy = torqueDes.Z + avgRY * fxDes; + Span fyLeg = stackalloc float[4]; + Span dfyRaw = stackalloc float[4]; + float dfyScale = 1f; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float frac = weight[i] / weightSum; + float fyBase = fyDes * frac; + Vector3 r0 = ws.FootSole[i] - comPos; + float d = (-r0.Z * tauXForFy + r0.X * tauZForFy) / sumR2; + dfyRaw[i] = d; + if (d < -1e-3f) + { + float maxDrop = MathF.Max(0f, fyBase * 0.55f); + dfyScale = MathF.Min(dfyScale, maxDrop / (-d)); + } + else if (d > 1e-3f && fyBase + d > capMax[i]) + { + float maxRise = MathF.Max(0f, capMax[i] - fyBase); + dfyScale = MathF.Min(dfyScale, maxRise / d); + } + } + + float totalFyAlloc = 0f; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float frac = weight[i] / weightSum; + fyLeg[i] = Math.Clamp(fyDes * frac + dfyRaw[i] * dfyScale, 0f, capMax[i]); + totalFyAlloc += fyLeg[i]; + } + + // Uniform yaw scaling across active legs prevents unbalanced horizontal shear when one foot is lightly loaded + float sharedYawScale = 1f; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float auth = MathF.Min(1f, fyLeg[i] / MathF.Max(1f, (fyDes / activeSupportCount) * 0.45f)); + sharedYawScale = MathF.Min(sharedYawScale, auth); + } + + Vector3 momentFromCenters = Vector3.Zero; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float fy = fyLeg[i]; + float weightFrac = weight[i] / weightSum; + + Vector3 r0 = ws.FootSole[i] - comPos; + float fx = fxDes * weightFrac; + float fz = fzDes * weightFrac; + if (sumRelR2 > 0.1f) + { + float relX = r0.X - rAvg.X; + float relZ = r0.Z - rAvg.Y; + fx += (relZ / sumRelR2) * torqueDes.Y * sharedYawScale; + fz += (-relX / sumRelR2) * torqueDes.Y * sharedYawScale; + } + + // Coulomb friction cone clamp: |F_horiz| <= 0.85 * fy + float maxHoriz = Mu * fy; + float hMag = MathF.Sqrt(fx * fx + fz * fz); + if (hMag > maxHoriz && hMag > 1e-4f) + { + float cScale = maxHoriz / hMag; + fx *= cScale; + fz *= cScale; + } + + footForces[i] = new Vector3(fx, fy, fz); + momentFromCenters += Vector3.Cross(r0, footForces[i]); + ws.LastGrfY[i] = fy; + totalForce += footForces[i]; + } + + // Residual pitch/roll torque realized via physical CoP inside each foot sole in chassis-local (right, fwd) axes + Vector3 tRem = torqueDes - momentFromCenters; + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + Vector3 fLeg = footForces[i]; + float share = totalFyAlloc > 1e-3f ? fLeg.Y / totalFyAlloc : (weight[i] / weightSum); + Vector3 tShare = tRem * share; + float dRightCop = 0f; + float dFwdCop = 0f; + if (fLeg.Y > 100f) + { + dFwdCop = Math.Clamp(Vector3.Dot(tShare, right) / fLeg.Y, -footHalfL, footHalfL); + dRightCop = Math.Clamp(-Vector3.Dot(tShare, fwd) / fLeg.Y, -footHalfW, footHalfW); + } + + Vector3 pCop = ws.FootSole[i] + right * dRightCop + fwd * dFwdCop; + Vector3 tLeg = Vector3.Cross(pCop - comPos, fLeg); + float maxSpinYaw = 0.45f * Mu * fLeg.Y * MathF.Max(0.5f, scale); + float yawRem = (torqueDes.Y - momentFromCenters.Y) * share; + tLeg.Y += Math.Clamp(yawRem, -maxSpinYaw, maxSpinYaw); + tContact += tLeg; + } + } + else + { + // Single-foot support: Coulomb cone + chassis-local CoP + bounded torsional friction + for (int i = 0; i < n; i++) + { + if (weight[i] <= 0f) continue; + float frac = weight[i] / weightSum; + float fy = Math.Clamp(fyDes * frac, 0f, capMax[i]); + float fx = fxDes * frac; + float fz = fzDes * frac; + Vector3 tWant = torqueDes * frac; + + float maxHoriz = Mu * fy; + float hMag = MathF.Sqrt(fx * fx + fz * fz); + if (hMag > maxHoriz && hMag > 1e-4f) + { + float cScale = maxHoriz / hMag; + fx *= cScale; + fz *= cScale; + } + + Vector3 fLeg = new(fx, fy, fz); + Vector3 r0 = ws.FootSole[i] - comPos; + Vector3 tRem = tWant - Vector3.Cross(r0, fLeg); + float dRightCop = 0f; + float dFwdCop = 0f; + if (fy > 100f) + { + dFwdCop = Math.Clamp(Vector3.Dot(tRem, right) / fy, -footHalfL, footHalfL); + dRightCop = Math.Clamp(-Vector3.Dot(tRem, fwd) / fy, -footHalfW, footHalfW); + } + + Vector3 pCop = ws.FootSole[i] + right * dRightCop + fwd * dFwdCop; + Vector3 tLeg = Vector3.Cross(pCop - comPos, fLeg); + float maxSpinYaw = 0.45f * Mu * fy * MathF.Max(0.5f, scale); + tLeg.Y += Math.Clamp(tWant.Y - tLeg.Y, -maxSpinYaw, maxSpinYaw); + + totalForce += fLeg; + tContact += tLeg; + ws.LastGrfY[i] = fy; + } + } + + // Residual pitch/roll stabilization via support-scaled hip/torso angular-momentum authority; + // yaw torque remains 100% foot-driven. + float supportFrac = Math.Clamp(totalForce.Y / MathF.Max(1f, mass * Gravity), 0f, 1f); + float weightedIntegSum = 0f; + for (int i = 0; i < n; i++) + { + weightedIntegSum += ws.LastGrfY[i] * legIntegrities[i]; + } + float stanceIntegrity = totalForce.Y > 1e-3f ? weightedIntegSum / totalForce.Y : avgIntegrity; + Vector3 tRes = torqueDes - tContact; + float resHorizMag = MathF.Sqrt(tRes.X * tRes.X + tRes.Z * tRes.Z); + float maxHipAttitudeTorque = iTilt * 28f * supportFrac * stanceIntegrity; + float attScale = resHorizMag > maxHipAttitudeTorque && resHorizMag > 1e-4f + ? maxHipAttitudeTorque / resHorizMag + : 1f; + totalTorque = tContact + new Vector3(tRes.X * attScale, 0f, tRes.Z * attScale); + } + + // Predictive inelastic ground contact (triggers ONLY on high-speed dune/cliff slam or deep penetration, never gentle stride ripples) + float nextGroundY = terrain.SampleHeight(comPos.X + vel.X * dt, comPos.Z + vel.Z * dt); + float predPen = (nextGroundY + penThresh) - (comPos.Y + vel.Y * dt); + float effectivePen = MathF.Max(hullBottomPen, predPen); + if (effectivePen > 0f) + { + Vector3 contactNorm = WalkerState.SampleTerrainNormal(terrain, comPos.X + vel.X * dt, comPos.Z + vel.Z * dt); + float vInto = Vector3.Dot(vel, contactNorm); + if (vInto < -2.0f || hullBottomPen > 0.12f) + { + float penVel = MathF.Min(MathF.Max(0f, hullBottomPen) / dt, 4.0f); + float neededDvN = MathF.Max(0f, -vInto) + penVel; + if (neededDvN > 0f) + { + float currentAccelN = Vector3.Dot(totalForce / mass + new Vector3(0f, -Gravity, 0f), contactNorm); + float accelN = Math.Clamp(neededDvN / dt - currentAccelN, 0f, 1800f); + totalForce += contactNorm * (mass * accelN); + + // Coulomb impact friction absorbs excess grazing speed on high-speed dune/mesa hits (prevents 33 m/s ski-jumps) + Vector3 vTangent = vel - contactNorm * vInto; + float vtMag = vTangent.Length(); + if (vtMag > 0.5f && accelN > 5f) + { + float maxFricAccel = MathF.Min(vtMag / dt, Mu * accelN * 0.65f); + totalForce -= (vTangent / vtMag) * (mass * maxFricAccel); + } + } + } + } + + // Write ONLY planted-foot GRF forces & (pCop - comPos) x fLeg torques! + ws.LastTotalForce = totalForce; + ws.LastTotalTorque = totalTorque; + view.ForceX[lane] = totalForce.X; + view.ForceY[lane] = totalForce.Y; + view.ForceZ[lane] = totalForce.Z; + view.TorqueX[lane] = totalTorque.X; + view.TorqueY[lane] = totalTorque.Y; + view.TorqueZ[lane] = totalTorque.Z; + + // 4D: 2nd-Order Torque-Limited Joint Actuators (2 substeps = 1/120s, NEVER reset on liftoff/touchdown!) + float subDt = dt * 0.5f; + float limbI = MathF.Max(1f, mass * scale * scale * 0.025f); + float kpStance = limbI * 1400f; + float kpSwing = limbI * 420f; + float kdStance = limbI * (2f * 0.88f * MathF.Sqrt(1400f)); + float kdSwing = limbI * (2f * 0.88f * MathF.Sqrt(420f)); + float tauLimitBase = limbI * 460f; + float tauLimitAnkle = limbI * 340f; + + for (int i = 0; i < n; i++) + { + Vector3 ankleWorld = ws.FootSole[i] + ws.FootNormal[i] * (geom.Legs[i].AnkleH * scale); + float legToePitch = ws.Planted[i] ? 0f : swingToePitch; + WalkerLegAngles target = SolveLegTargetAngles(geom, scale, i, hipWorld[i], qBody, ankleWorld, ws.FootNormal[i], legToePitch); + + bool planted = ws.Planted[i]; + float kp = planted ? kpStance : kpSwing; + float kd = planted ? kdStance : kdSwing; + float tauMax = tauLimitBase * legIntegrities[i]; + float tauAnkleMax = tauLimitAnkle * legIntegrities[i]; + + ref var act = ref ws.Actuators[i]; + float recoilHipTorque = act.RecoilHipImpulse / MathF.Max(1e-4f, dt); + float recoilKneeTorque = act.RecoilKneeImpulse / MathF.Max(1e-4f, dt); + act.RecoilHipImpulse = 0f; + act.RecoilKneeImpulse = 0f; + + for (int sub = 0; sub < 2; sub++) + { + StepDof(ref act.Theta.HipPitch, ref act.Omega.HipPitch, target.HipPitch, kp, kd, tauMax, limbI, recoilHipTorque, subDt); + StepDof(ref act.Theta.HipRoll, ref act.Omega.HipRoll, target.HipRoll, kp, kd, tauMax, limbI, 0f, subDt); + StepDof(ref act.Theta.KneeFlex, ref act.Omega.KneeFlex, target.KneeFlex, kp, kd, tauMax, limbI, recoilKneeTorque, subDt); + if (geom.IsDigitigrade) + { + StepDof(ref act.Theta.HockFlex, ref act.Omega.HockFlex, target.HockFlex, kp, kd, tauMax, limbI, 0f, subDt); + } + else + { + act.Theta.HockFlex = 0f; + act.Omega.HockFlex = 0f; + } + StepDof(ref act.Theta.AnklePitch, ref act.Omega.AnklePitch, target.AnklePitch, kp, kd, tauAnkleMax, limbI, 0f, subDt); + } + } + + ws.CurrSnap = ws.BuildSnapshot(comPos, qBody, mass); + } + + private static void StepDof( + ref float theta, + ref float omega, + float target, + float kp, + float kd, + float tauMax, + float inertia, + float recoilTorque, + float dt) + { + float err = MatchRules.NormalizeAngle(target - theta); + float tau = Math.Clamp(kp * err - kd * omega, -tauMax, tauMax) + recoilTorque; + omega += (tau / inertia) * dt; + theta = Math.Clamp(theta + omega * dt, -2.35f, 2.35f); + } + + private static bool IsInGroup(int legCount, int legIdx, int group) + { + if (legCount == 2) + { + return legIdx == group; + } + // Quadruped diagonal gaits: group 0 = {FL(0), BR(3)}, group 1 = {FR(1), BL(2)} + bool isDiag0 = legIdx == 0 || legIdx == 3; + return group == 0 ? isDiag0 : !isDiag0; + } + + internal static bool ClampSoleToReach( + Vector3 hipWorld, + float ankleH, + float maxReach, + TerrainField terrain, + ref Vector3 sole, + out Vector3 normal) + { + normal = WalkerState.SampleTerrainNormal(terrain, sole.X, sole.Z); + Vector3 ankle = sole + normal * ankleH; + if ((ankle - hipWorld).Length() <= maxReach) + { + return false; + } + + float fx = sole.X; + float fz = sole.Z; + for (int iter = 0; iter < 3; iter++) + { + float gh = terrain.SampleHeight(fx, fz); + float dy = (gh + ankleH) - hipWorld.Y; + float maxHoriz = MathF.Sqrt(MathF.Max(0.04f, maxReach * maxReach - dy * dy)); + float dx = fx - hipWorld.X; + float dz = fz - hipWorld.Z; + float hDist = MathF.Sqrt(dx * dx + dz * dz); + if (hDist <= maxHoriz || hDist < 1e-4f) + { + break; + } + float k = maxHoriz / hDist; + fx = hipWorld.X + dx * k; + fz = hipWorld.Z + dz * k; + } + + float finalGh = terrain.SampleHeight(fx, fz); + sole = new Vector3(fx, finalGh, fz); + normal = WalkerState.SampleTerrainNormal(terrain, fx, fz); + return true; + } + + public static WalkerLegAngles SolveLegTargetAngles( + WalkerGeometrySpec geom, + float scale, + int legIdx, + Vector3 hipWorld, + Quaternion qBody, + Vector3 ankleWorld, + Vector3 footNormalWorld, + float swingToePitch) + { + var leg = geom.Legs[legIdx]; + Quaternion qInv = Quaternion.Conjugate(qBody); + Vector3 deltaLocal = Vector3.Transform(ankleWorld - hipWorld, qInv); + Vector3 footNormalLocal = Vector3.Transform(footNormalWorld, qInv); + + Vector3 r0 = leg.LegRight0; + Vector3 u0 = Vector3.UnitY; + Vector3 f0 = leg.LegFwd0; + + float dx = Vector3.Dot(deltaLocal, r0); + float dy = Vector3.Dot(deltaLocal, u0); + float dz = Vector3.Dot(deltaLocal, f0); + + if (geom.IsArachnidUp) + { + float coxaYaw = MathF.Atan2(dx, MathF.Max(0.20f * scale, dz)); + float planarOut = MathF.Sqrt(dx * dx + dz * dz); + float planarUp = dy; + float d = Math.Clamp( + MathF.Sqrt(planarOut * planarOut + planarUp * planarUp), + leg.MinLegReach * scale, + leg.MaxLegReach * scale); + float l1 = leg.L1 * scale; + float l2 = leg.L2 * scale; + float baseElev = MathF.Atan2(planarUp, MathF.Max(0.05f * scale, planarOut)); + float cosAlpha = Math.Clamp((l1 * l1 + d * d - l2 * l2) / (2f * l1 * d), -1f, 1f); + float alpha = MathF.Acos(cosAlpha); + float cosKnee = Math.Clamp((l1 * l1 + l2 * l2 - d * d) / (2f * l1 * l2), -1f, 1f); + + Vector3 legOut = f0 * MathF.Cos(coxaYaw) + r0 * MathF.Sin(coxaYaw); + float anklePitch = MathF.Atan2(Vector3.Dot(footNormalLocal, legOut), MathF.Max(0.2f, Vector3.Dot(footNormalLocal, u0))) + swingToePitch; + + return new WalkerLegAngles + { + HipPitch = baseElev + alpha, + HipRoll = coxaYaw, + KneeFlex = MathF.PI - MathF.Acos(cosKnee), + HockFlex = 0f, + AnklePitch = anklePitch + }; + } + + float hipRoll = MathF.Atan2(dx, MathF.Max(0.25f * scale, -dy)); + float planarDown = MathF.Sqrt(dx * dx + dy * dy); + float planarFwd = dz; + + if (geom.IsDigitigrade) + { + float l1 = leg.L1 * scale; + float l2 = leg.L2 * scale; + float l3 = leg.L3 * scale; + float d = Math.Clamp( + MathF.Sqrt(planarDown * planarDown + planarFwd * planarFwd), + leg.MinLegReach * scale, + leg.MaxLegReach * scale); + float basePitch = MathF.Atan2(planarFwd, MathF.Max(0.05f * scale, planarDown)); + + float crouchFrac = Math.Clamp(1f - d / (l1 + l2 + l3), 0f, 1f); + float phiC = 0.08f + 0.42f * crouchFrac; + float maxHockDist = l1 + l2 - 0.04f * scale; + float minCos = (d * d + l3 * l3 - maxHockDist * maxHockDist) / (2f * d * l3); + if (minCos > MathF.Cos(phiC)) + { + phiC = minCos >= 1f ? 0f : MathF.Acos(Math.Clamp(minCos, -1f, 1f)); + } + + float cannonAngle = basePitch + phiC; + float hockDown = d * MathF.Cos(basePitch) - l3 * MathF.Cos(cannonAngle); + float hockFwd = d * MathF.Sin(basePitch) - l3 * MathF.Sin(cannonAngle); + float dHock = Math.Clamp( + MathF.Sqrt(hockDown * hockDown + hockFwd * hockFwd), + MathF.Abs(l1 - l2) + 0.05f * scale, + l1 + l2 - 0.02f * scale); + float hockBasePitch = MathF.Atan2(hockFwd, MathF.Max(0.02f * scale, hockDown)); + float cosAlpha = Math.Clamp((l1 * l1 + dHock * dHock - l2 * l2) / (2f * l1 * dHock), -1f, 1f); + float alpha = MathF.Acos(cosAlpha); + float cosKnee = Math.Clamp((l1 * l1 + l2 * l2 - dHock * dHock) / (2f * l1 * l2), -1f, 1f); + + float hipPitch = hockBasePitch + alpha; + float kneeFlex = MathF.PI - MathF.Acos(cosKnee); + float shinAngle = hipPitch - kneeFlex; + float hockFlex = cannonAngle - shinAngle; + float anklePitch = MathF.Atan2(Vector3.Dot(footNormalLocal, f0), MathF.Max(0.2f, Vector3.Dot(footNormalLocal, u0))) + swingToePitch; + + return new WalkerLegAngles + { + HipPitch = hipPitch, + HipRoll = hipRoll, + KneeFlex = kneeFlex, + HockFlex = hockFlex, + AnklePitch = anklePitch + }; + } + else + { + float l1 = leg.L1 * scale; + float l2 = leg.L2 * scale; + float d = Math.Clamp( + MathF.Sqrt(planarDown * planarDown + planarFwd * planarFwd), + leg.MinLegReach * scale, + leg.MaxLegReach * scale); + float basePitch = MathF.Atan2(planarFwd, MathF.Max(0.05f * scale, planarDown)); + float cosAlpha = Math.Clamp((l1 * l1 + d * d - l2 * l2) / (2f * l1 * d), -1f, 1f); + float alpha = MathF.Acos(cosAlpha); + float cosKnee = Math.Clamp((l1 * l1 + l2 * l2 - d * d) / (2f * l1 * l2), -1f, 1f); + float kneeFlex = (MathF.PI - MathF.Acos(cosKnee)) * leg.KneeBendSign; + float hipPitch = basePitch + leg.KneeBendSign * alpha; + float anklePitch = MathF.Atan2(Vector3.Dot(footNormalLocal, f0), MathF.Max(0.2f, Vector3.Dot(footNormalLocal, u0))) + swingToePitch; + + return new WalkerLegAngles + { + HipPitch = hipPitch, + HipRoll = hipRoll, + KneeFlex = kneeFlex, + HockFlex = 0f, + AnklePitch = anklePitch + }; + } + } + } +} diff --git a/tests/RustToDust.Tests/DetectionLosTests.cs b/tests/RustToDust.Tests/DetectionLosTests.cs index b142bd5..485d7b4 100644 --- a/tests/RustToDust.Tests/DetectionLosTests.cs +++ b/tests/RustToDust.Tests/DetectionLosTests.cs @@ -252,8 +252,11 @@ namespace RustToDust.Tests var other = session.State.Spectators.Spectators[i]; if (other.Id != provokedSpec.Id && other.Id != clearedSpec.Id) { - float farX = (mesa.X >= 0f ? -1f : 1f) * 680f; - float farZ = (mesa.Z >= 0f ? -1f : 1f) * 680f; + // Space bystanders in a non-overlapping grid at the far corner so Box3D never stacks them into a tower peeking over the mesa + float signX = mesa.X >= 0f ? -1f : 1f; + float signZ = mesa.Z >= 0f ? -1f : 1f; + float farX = signX * (730f - (i % 8) * 16f); + float farZ = signZ * (730f - (i / 8) * 16f); session.SetSpectatorPose(other.Id, farX, farZ); } } diff --git a/tests/RustToDust.Tests/HybridBWalkerTests.cs b/tests/RustToDust.Tests/HybridBWalkerTests.cs new file mode 100644 index 0000000..0185da6 --- /dev/null +++ b/tests/RustToDust.Tests/HybridBWalkerTests.cs @@ -0,0 +1,714 @@ +using System; +using System.Diagnostics; +using System.Numerics; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; +using Xunit.Abstractions; + +namespace RustToDust.Tests +{ + public sealed class HybridBWalkerTests + { + private readonly ITestOutputHelper _output; + + public HybridBWalkerTests(ITestOutputHelper output) + { + _output = output; + } + + private static ChassisSpec MakeExemplarSpec() => + Catalog.Raptor with + { + Id = "exemplar_frame", + Name = "Exemplar Frame", + BaseCellArmor = 22f, + MassKg = 1150f, + BaseThrust = 26000f, + BaseTurnRate = 6.2f, + MaxSpeed = 40f, + HalfWidth = 0.8f, + HalfHeight = 1.55f, + HalfLength = 0.8f + }; + + [Fact] + public void HybridB_All7Mechs_WalkTurnSlopes_SmoothLiftoff_ZeroTeleports() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion, + MakeExemplarSpec() + }; + + // 1. Walk, turn, and climb slopes across all 7 mechs + exemplar_frame + foreach (var spec in specs) + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 500f + i * 16f, 500f); + } + + // Phase A: start on flat/gentle ground near origin (60 ticks) to verify honest walk slip < 8cm + session.SetContenderPose(0, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id}"); + var player = session.State.Player; + Assert.Equal(spec.Id, player.Grid.Spec.Id); + + var ws = session.GetWalkerState(true, player.Id); + Assert.NotNull(ws); + int nLegs = ws!.Geom.LegCount; + float geomScale = ws.GeomScale; + + for (int t = 0; t < 60; t++) + { + session.Step(new PlayerInput( + Throttle: 0.45f, + Steer: 0f, + AimWorldX: player.X, + AimWorldZ: player.Z + 60f, + Fire: false, + InteractPickup: false, + Brake: false)); + } + Assert.True(ws.MaxFootSlipM < 0.08f, + $"{spec.Id}: normal walk foot slip {ws.MaxFootSlipM:F4}m >= 0.08m (maxSpd={spec.MaxSpeed:F1})"); + + // Phase B: move to dune slope approach, turn & climb (180 ticks) checking liftoff teleport, C1 touchdown, omega continuity + float duneApproachX = 0f; + float duneApproachZ = 0f; + float bestScore = -1f; + foreach (var b in session.State.Terrain.Brushes) + { + if (b.Kind == TerrainBrushKind.DuneRidge && b.HeightDelta > 4f) + { + float d = MathF.Sqrt(b.X * b.X + b.Z * b.Z); + if (d > 40f && d < 280f && b.HeightDelta > bestScore) + { + bestScore = b.HeightDelta; + float dirX = -b.X / d; + float dirZ = -b.Z / d; + duneApproachX = b.X + dirX * MathF.Min(36f, b.RadiusX * 0.85f); + duneApproachZ = b.Z + dirZ * MathF.Min(36f, b.RadiusZ * 0.85f); + } + } + } + session.SetContenderPose(0, duneApproachX, duneApproachZ, MathF.Atan2(-duneApproachX, -duneApproachZ) + MathF.PI); + ws = session.GetWalkerState(true, player.Id)!; + + var prevFoot = new Vector3[nLegs]; + var prevPlanted = new bool[nLegs]; + var prevOmegaHip = new float[nLegs]; + for (int i = 0; i < nLegs; i++) + { + prevFoot[i] = ws.FootSole[i]; + prevPlanted[i] = ws.Planted[i]; + prevOmegaHip[i] = ws.Actuators[i].Omega.HipPitch; + } + + float maxDeltaFootPerTick = 0f; + float maxLiftoffDelta = 0f; + float maxOmegaJumpAtSwap = 0f; + float maxTouchdownGroundErr = 0f; + float minUpDot = 1f; + int swapCount = 0; + for (int t = 0; t < 180; t++) + { + float steer = MathF.Sin(t * 0.06f) * 0.65f; + session.Step(new PlayerInput( + Throttle: 0.85f, + Steer: steer, + AimWorldX: player.X + 40f * MathF.Sin(player.Yaw), + AimWorldZ: player.Z + 40f * MathF.Cos(player.Yaw), + Fire: false, + InteractPickup: false, + Brake: false)); + + Assert.True(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z), + $"{spec.Id}: non-finite pose at tick {t}"); + + var q = new Quaternion(player.CurrRotX, player.CurrRotY, player.CurrRotZ, player.CurrRotW); + var up = Vector3.Transform(Vector3.UnitY, q); + minUpDot = MathF.Min(minUpDot, up.Y); + + for (int i = 0; i < nLegs; i++) + { + Vector3 curFoot = ws.FootSole[i]; + float delta = (curFoot - prevFoot[i]).Length(); + if (delta > maxDeltaFootPerTick) + { + maxDeltaFootPerTick = delta; + } + + bool curPlanted = ws.Planted[i]; + if (prevPlanted[i] && !curPlanted && !ws.IsAirborne) + { + if (delta > maxLiftoffDelta) + { + maxLiftoffDelta = delta; + } + } + if (!prevPlanted[i] && curPlanted) + { + swapCount++; + float groundY = session.State.Terrain.SampleHeight(curFoot.X, curFoot.Z); + float gErr = MathF.Abs(curFoot.Y - groundY); + if (gErr > maxTouchdownGroundErr) + { + maxTouchdownGroundErr = gErr; + } + + float omegaDelta = MathF.Abs(ws.Actuators[i].Omega.HipPitch - prevOmegaHip[i]); + if (omegaDelta > maxOmegaJumpAtSwap) + { + maxOmegaJumpAtSwap = omegaDelta; + } + } + + prevFoot[i] = curFoot; + prevPlanted[i] = curPlanted; + prevOmegaHip[i] = ws.Actuators[i].Omega.HipPitch; + } + } + + float maxFootGroundSpeed = spec.MaxSpeed + MathF.Max(spec.HalfWidth, spec.HalfLength) * spec.BaseTurnRate * 0.5f; + float maxAllowedTickDelta = MathF.Max(0.55f, maxFootGroundSpeed * ArenaSession.FixedDt * 3.5f); + _output.WriteLine( + $"{spec.Id,-15} minUp={minUpDot:F3} slip={ws.MaxFootSlipM:F4}m maxFootDelta/tick={maxDeltaFootPerTick:F4}m " + + $"liftoffDelta={maxLiftoffDelta:F4}m tdGroundErr={maxTouchdownGroundErr:F5}m swapOmegaJump={maxOmegaJumpAtSwap:F3} swaps={swapCount}"); + + Assert.True(minUpDot >= 0.90f, $"{spec.Id}: unstable tilt minUpDot={minUpDot:F3}"); + Assert.True(swapCount >= 4, $"{spec.Id}: expected >= 4 gait transitions, got {swapCount}"); + Assert.True(maxLiftoffDelta <= 0.35f * MathF.Max(1f, geomScale), + $"{spec.Id}: Bug 1 liftoff teleport detected: liftoffDelta={maxLiftoffDelta:F4}m"); + Assert.True(maxDeltaFootPerTick <= maxAllowedTickDelta, + $"{spec.Id}: 1-tick foot teleport detected: maxDelta={maxDeltaFootPerTick:F4}m > {maxAllowedTickDelta:F4}m"); + Assert.True(maxTouchdownGroundErr <= 0.06f * MathF.Max(1f, geomScale), + $"{spec.Id}: non-C1 liftoff/touchdown height gap {maxTouchdownGroundErr:F4}m"); + Assert.True(maxOmegaJumpAtSwap < 12.0f, + $"{spec.Id}: discontinuous joint omega jump across swap: {maxOmegaJumpAtSwap:F3} rad/s"); + } + + // 2. Benchmark 12 simultaneous mechs CPU < 1.5 ms/tick + { + using var benchSession = new ArenaSession(seed: 99, mapKind: ArenaMapKind.Desert); + for (int i = 0; i < benchSession.State.Contenders.Count; i++) + { + var spec = specs[i % 7]; + float x = (i - 5.5f) * 28f; + float z = -80f + (i % 3) * 35f; + benchSession.SetContenderPose(i, x, z, 0f); + if (benchSession.State.Contenders[i].Grid.Spec.Id != spec.Id) + { + benchSession.State.Contenders[i].Grid.SwapChassis(spec); + benchSession.SetContenderPose(i, x, z, 0f); + } + } + + var walkers = new (ContenderState C, WalkerState Ws, int Lane)[12]; + for (int i = 0; i < 12; i++) + { + var c = benchSession.State.Contenders[i]; + c.ThrottleCmd = 0.8f; + c.SteerCmd = (i % 2 == 0 ? 0.2f : -0.2f); + walkers[i] = (c, benchSession.GetWalkerState(true, c.Id)!, benchSession.GetContenderBody(c.Id)!.Value.Lane); + } + + // Warmup JIT + for (int w = 0; w < 20; w++) + { + benchSession.Step(new PlayerInput(0.8f, 0.2f, 0f, 100f, false, false, false)); + } + + var view = benchSession.World.View; + const int benchTicks = 300; + long t0 = Stopwatch.GetTimestamp(); + for (int t = 0; t < benchTicks; t++) + { + for (int i = 0; i < 12; i++) + { + var (c, ws, lane) = walkers[i]; + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); + var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + var fwd = Vector3.Transform(Vector3.UnitZ, q); + fwd.Y = 0f; + fwd = fwd.LengthSquared() < 1e-4f ? Vector3.UnitZ : Vector3.Normalize(fwd); + WalkerLocomotion.StepWalker( + ws, c.Grid, benchSession.State.Terrain, view, lane, view.Mass[lane], + pos, q, vel, angVel, fwd * (c.ThrottleCmd * c.Grid.Spec.MaxSpeed), 0.3f, false, ArenaSession.FixedDt); + } + } + long t1 = Stopwatch.GetTimestamp(); + double msPerTick = (t1 - t0) * 1000.0 / Stopwatch.Frequency / benchTicks; + _output.WriteLine($"12-mech simultaneous WalkerLocomotion CPU: {msPerTick:F4} ms/tick"); + Assert.True(msPerTick < 1.5, $"12 simultaneous mechs CPU {msPerTick:F4} ms/tick exceeded 1.5 ms/tick budget"); + } + } + + [Fact] + public void HybridB_CrippledLeg_ReducesGrfAndTorque_InducesLimp() + { + Span legIntegrities = stackalloc float[4]; + foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion }) + { + using var session = new ArenaSession(seed: 17, mapKind: ArenaMapKind.Desert); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 450f + i * 16f, 450f); + } + session.SetContenderPose(0, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis()); + + var player = session.State.Player; + var grid = player.Grid; + + // Strip all left-leg cells (Breaker Coronal L: y>=H-2, x 0.002f, + $"{spec.Id}: expected crippled leg asymmetry to induce measurable limp roll"); + } + } + + [Fact] + public void HybridB_AirborneMech_ZeroGrfForce() + { + foreach (var spec in new[] { Catalog.Breaker, Catalog.Manticore }) + { + using var session = new ArenaSession(seed: 7, mapKind: ArenaMapKind.Desert); + session.SetContenderPose(0, 0f, 0f, 0f); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis()); + + var player = session.State.Player; + var body = session.GetContenderBody(player.Id)!.Value; + var view = session.World.View; + int lane = body.Lane; + + // 1. Direct StepWalker check with COM lifted 18m above terrain + float groundY = session.State.Terrain.SampleHeight(0f, 0f); + Vector3 liftedPos = new(view.PositionX[lane], groundY + spec.HalfHeight + 18f, view.PositionZ[lane]); + + var ws = session.GetWalkerState(true, player.Id)!; + WalkerLocomotion.StepWalker( + ws, + player.Grid, + session.State.Terrain, + view, + lane, + view.Mass[lane], + liftedPos, + new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]), + Vector3.Zero, + Vector3.Zero, + new Vector3(0f, 0f, 10f), + 0f, + false, + ArenaSession.FixedDt); + + Assert.True(ws.IsAirborne, $"{spec.Id}: expected IsAirborne == true when lifted 18m above terrain"); + Assert.Equal(Vector3.Zero, ws.LastTotalForce); + Assert.Equal(Vector3.Zero, ws.LastTotalTorque); + Assert.Equal(0f, view.ForceX[lane]); + Assert.Equal(0f, view.ForceY[lane]); + Assert.Equal(0f, view.ForceZ[lane]); + Assert.Equal(0f, view.TorqueX[lane]); + Assert.Equal(0f, view.TorqueY[lane]); + Assert.Equal(0f, view.TorqueZ[lane]); + + // 2. End-to-end ArenaSession launch into air: confirm zero GRF while airborne in real Step() + session.World.ApplyImpulse( + lane, + (0f, view.Mass[lane] * 28f, 0f), + (view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane])); + bool sawAirborneTick = false; + for (int t = 0; t < 20; t++) + { + session.Step(new PlayerInput(1f, 0f, 0f, 50f, false, false, false)); + if (ws.IsAirborne) + { + sawAirborneTick = true; + Assert.Equal(Vector3.Zero, ws.LastTotalForce); + Assert.Equal(Vector3.Zero, ws.LastTotalTorque); + } + } + Assert.True(sawAirborneTick, $"{spec.Id}: expected vertical launch to trigger airborne zero-GRF ticks"); + } + } + + [Fact] + public void HybridB_All7Mechs_ObeyDirectionalInputAtMultipleYaws_NoGooseStepNoDrift() + { + var specs = new[] + { + Catalog.Breaker, + Catalog.Paladin, + Catalog.Raptor, + Catalog.Spectre, + Catalog.Kestrel, + Catalog.Manticore, + Catalog.Bastion + }; + float[] yawsDeg = { 0f, 45f, 90f, 135f }; + + foreach (var spec in specs) + { + foreach (float yawDeg in yawsDeg) + { + float yawRad = yawDeg * MathF.PI / 180f; + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 500f + i * 16f, 500f); + } + + session.SetContenderPose(0, 0f, 0f, yawRad); + session.State.SpawnChassisDrop(0f, 0f, spec); + Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id}"); + session.SetContenderPose(0, 0f, 0f, yawRad); + var player = session.State.Player; + + // Lettle -> Wait 5 idle ticks to verify zero rest creep from dead stop + for (int t = 0; t < 5; t++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); + } + + Vector2 cmdFwd = new(MathF.Sin(yawRad), MathF.Cos(yawRad)); + Vector2 cmdRight = new(-cmdFwd.Y, cmdFwd.X); + + // 1. Hold W (Throttle = +1) for 2.0s (120 ticks) from rest + Vector2 wStart = new(player.X, player.Z); + for (int t = 0; t < 120; t++) + { + session.Step(new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X + cmdFwd.X * 50f, + AimWorldZ: player.Z + cmdFwd.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + } + float endWSpeed = player.Speed; + Vector2 wDelta = new Vector2(player.X, player.Z) - wStart; + float fwdDisp = Vector2.Dot(wDelta, cmdFwd); + float latDrift = MathF.Abs(Vector2.Dot(wDelta, cmdRight)); + Assert.True(fwdDisp >= 6.0f, + $"{spec.Id} @ {yawDeg}deg W 2.0s: fwdDisp={fwdDisp:F2}m < 6.0m (lat={latDrift:F2}m)"); + Assert.True(latDrift < 2.0f, + $"{spec.Id} @ {yawDeg}deg W 2.0s: latDrift={latDrift:F2}m >= 2.0m (fwd={fwdDisp:F2}m)"); + + // 2. Release W (Throttle = 0) for 3.0s (180 ticks): stop < 0.30 m/s within physical Coulomb limit, final 1.0s (60 ticks) drift < 0.15m + float speedAt1_2s = 0f; + float speedAt2_0s = 0f; + float timeToStop = -1f; + Vector2 finalWindowStart = Vector2.Zero; + for (int t = 0; t < 180; t++) + { + session.Step(new PlayerInput( + Throttle: 0f, + Steer: 0f, + AimWorldX: player.X + cmdFwd.X * 50f, + AimWorldZ: player.Z + cmdFwd.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + + if (timeToStop < 0f && player.Speed < 0.30f) + { + timeToStop = (t + 1) * ArenaSession.FixedDt; + } + if (t == 71) speedAt1_2s = player.Speed; + if (t == 119) + { + speedAt2_0s = player.Speed; + finalWindowStart = new Vector2(player.X, player.Z); + } + } + float finalDrift = (new Vector2(player.X, player.Z) - finalWindowStart).Length(); + float maxPhysStopSec = MathF.Max(1.2f, endWSpeed / 16.0f + 0.35f); + if (yawDeg == 0f) + { + _output.WriteLine( + $"{spec.Id,-10} maxSpd={spec.MaxSpeed:F1} endWSpd={endWSpeed:F2} " + + $"tStop={timeToStop:F2}s (limit={maxPhysStopSec:F2}s) spd@1.2s={speedAt1_2s:F3} spd@2.0s={speedAt2_0s:F3} finalDrift={finalDrift:F4}m"); + } + Assert.True(timeToStop > 0f && timeToStop <= maxPhysStopSec, + $"{spec.Id} @ {yawDeg}deg release W: tStop={timeToStop:F2}s > {maxPhysStopSec:F2}s (endWSpd={endWSpeed:F2}, @2.0s={speedAt2_0s:F3})"); + Assert.True(finalDrift < 0.15f, + $"{spec.Id} @ {yawDeg}deg release W: final 1.0s drift={finalDrift:F4}m >= 0.15m"); + + // 3. Hold S (Throttle = -1) for 1.5s (90 ticks) + Vector2 sStart = new(player.X, player.Z); + Vector2 revDir = new(MathF.Sin(player.Yaw), MathF.Cos(player.Yaw)); + for (int t = 0; t < 90; t++) + { + session.Step(new PlayerInput( + Throttle: -1f, + Steer: 0f, + AimWorldX: player.X + revDir.X * 50f, + AimWorldZ: player.Z + revDir.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + } + float revDisp = Vector2.Dot(new Vector2(player.X, player.Z) - sStart, -revDir); + Assert.True(revDisp >= 3.0f, + $"{spec.Id} @ {yawDeg}deg S 1.5s: revDisp={revDisp:F2}m < 3.0m"); + + // Settle until stopped before turning test + for (int t = 0; t < 180 && (t < 20 || player.Speed > 0.05f); t++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); + } + + // 4. Hold D (Steer = +1, Throttle = 0) for 1.5s (90 ticks) + Vector2 dStart = new(player.X, player.Z); + float prevYaw = player.Yaw; + float accumYaw = 0f; + for (int t = 0; t < 90; t++) + { + session.Step(new PlayerInput( + Throttle: 0f, + Steer: 1f, + AimWorldX: player.X, + AimWorldZ: player.Z + 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw); + prevYaw = player.Yaw; + } + float dTrans = (new Vector2(player.X, player.Z) - dStart).Length(); + // Steer = +1 turns right -> negative yaw change (-accumYaw >= 0.5 rad) + Assert.True(-accumYaw >= 0.5f, + $"{spec.Id} @ {yawDeg}deg D 1.5s: yawChange={accumYaw:F3} rad (expected <= -0.50 rad)"); + Assert.True(dTrans < 1.0f, + $"{spec.Id} @ {yawDeg}deg D 1.5s: spurious translation={dTrans:F3}m >= 1.0m"); + + if (yawDeg == 0f || yawDeg == 135f) + { + _output.WriteLine( + $"{spec.Id,-10} yaw={yawDeg,3:F0}deg: fwd={fwdDisp:F2}m lat={latDrift:F2}m " + + $"stopSpd={speedAt1_2s:F3}m/s drift={finalDrift:F4}m rev={revDisp:F2}m turn={-accumYaw:F2}rad dTrans={dTrans:F3}m"); + } + } + } + } + + [Fact] + public void HybridB_BreakerAndBastion_SionSlopeControl_ObeysInput() + { + foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion }) + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion); + for (int i = 1; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(i, 900f + i * 16f, 900f); + } + + var sion = session.State.SionMap!; + // Find a clear sloped hillside on Sion (slope ~7-18 deg, free of buildings and low wall meshes along a +/-7m corridor) + float slopeX = session.State.Player.X; + float slopeZ = session.State.Player.Z; + float slopeYaw = 0f; + bool foundSlope = false; + for (float r = 40f; r <= 560f && !foundSlope; r += 20f) + { + for (int a = 0; a < 36 && !foundSlope; a++) + { + float ang = a * (MathF.Tau / 36f); + float x = MathF.Cos(ang) * r; + float z = MathF.Sin(ang) * r; + if (sion.IsInsideAnyBuildingXz(x, z, 14f)) continue; + var (nx, ny, nz) = session.State.Terrain.SampleNormal(x, z); + if (ny <= 0.992f && ny >= 0.950f) + { + float yaw = MathF.Atan2(-nx, -nz); // uphill heading + float fx = MathF.Sin(yaw); + float fz = MathF.Cos(yaw); + float rx = -fz; + float rz = fx; + bool clear = true; + foreach (float lat in new[] { -7f, 0f, 7f }) + { + float sx = x + rx * lat; + float sz = z + rz * lat; + for (float d = 0f; d < 28f; d += 4f) + { + float ax = sx + fx * d; + float az = sz + fz * d; + float bx = sx + fx * (d + 4f); + float bz = sz + fz * (d + 4f); + if (sion.IsInsideAnyBuildingXz(ax, az, 4f) || + session.State.Terrain.SampleNormal(ax, az).Ny < 0.90f) + { + clear = false; + break; + } + float gyA = session.State.Terrain.SampleHeight(ax, az); + float gyB = session.State.Terrain.SampleHeight(bx, bz); + if (!session.HasLineOfSight(ax, gyA + 2.5f, az, bx, gyB + 2.5f, bz)) + { + clear = false; + break; + } + } + if (!clear) break; + } + if (clear) + { + slopeX = x; + slopeZ = z; + slopeYaw = yaw; + foundSlope = true; + } + } + } + } + Assert.True(foundSlope, $"{spec.Id}: failed to locate clear Sion slope test site"); + + session.SetContenderPose(0, slopeX, slopeZ, slopeYaw); + session.State.SpawnChassisDrop(slopeX, slopeZ, spec); + Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id} on Sion"); + session.SetContenderPose(0, slopeX, slopeZ, slopeYaw); + var player = session.State.Player; + + // 1. Drive forward up/along slope (2.0s) + Vector2 startPos = new(player.X, player.Z); + Vector2 fwdDir = new(MathF.Sin(slopeYaw), MathF.Cos(slopeYaw)); + var ws = session.GetWalkerState(true, player.Id)!; + float gStart = session.State.Terrain.SampleHeight(player.X, player.Z); + float startY = player.Y; + for (int t = 0; t < 120; t++) + { + session.Step(new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X + fwdDir.X * 50f, + AimWorldZ: player.Z + fwdDir.Y * 50f, + Fire: false, + InteractPickup: false, + Brake: false)); + } + float gEnd = session.State.Terrain.SampleHeight(player.X, player.Z); + float fwdDisp = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir); + int pLane = session.GetContenderBody(player.Id)!.Value.Lane; + string touchesStr = ""; + foreach (var tc in session.World.Facts.Touching) + { + if (tc.LaneA == pLane || tc.LaneB == pLane) + { + ulong other = tc.LaneA == pLane ? tc.StableIdB : tc.StableIdA; + touchesStr += $"{other},"; + } + } + _output.WriteLine( + $"{spec.Id} Sion slope ({slopeX:F1},{slopeZ:F1}) gStart={gStart:F2} startY={startY:F2} (H={spec.HalfHeight:F2}) -> " + + $"({player.X:F1},{player.Y:F2},{player.Z:F1}) gEnd={gEnd:F2} pYaw={player.Yaw:F2} fwdDisp={fwdDisp:F2}m air={ws.IsAirborne} force={ws.LastTotalForce} touching=[{touchesStr}]"); + Assert.True(fwdDisp >= 5.0f, $"{spec.Id} Sion slope W 2.0s: fwdDisp={fwdDisp:F2}m < 5.0m"); + + // 2. Turn cleanly on Sion slope (D for 1.5s) + float prevYaw = player.Yaw; + float accumYaw = 0f; + for (int t = 0; t < 90; t++) + { + session.Step(new PlayerInput(0f, 1f, player.X, player.Z + 50f, false, false, false)); + accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw); + prevYaw = player.Yaw; + } + Assert.True(-accumYaw >= 0.35f, $"{spec.Id} Sion slope D 1.5s: yawChange={accumYaw:F3} rad"); + + // 3. Release controls on slope (3.0s): must stop cleanly and NOT slide away + float speedAt1_2s = 0f; + float timeToStop = -1f; + Vector2 finalWinStart = Vector2.Zero; + for (int t = 0; t < 180; t++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false)); + if (timeToStop < 0f && player.Speed < 0.35f) timeToStop = (t + 1) * ArenaSession.FixedDt; + if (t == 71) speedAt1_2s = player.Speed; + if (t == 119) finalWinStart = new Vector2(player.X, player.Z); + } + float finalSlide = (new Vector2(player.X, player.Z) - finalWinStart).Length(); + _output.WriteLine( + $"{spec.Id,-10} Sion slope ({slopeX:F1},{slopeZ:F1}): fwd={fwdDisp:F2}m turn={-accumYaw:F2}rad " + + $"tStop={timeToStop:F2}s spd@1.2s={speedAt1_2s:F3}m/s slopeSlide={finalSlide:F4}m"); + Assert.True(timeToStop > 0f && timeToStop <= 2.0f, $"{spec.Id} Sion slope release: tStop={timeToStop:F2}s > 2.0s (spd@1.2s={speedAt1_2s:F3}m/s)"); + Assert.True(finalSlide < 0.18f, $"{spec.Id} Sion slope release: 1.0s slide={finalSlide:F4}m >= 0.18m"); + } + } + } +}