diff --git a/client/Hud.cs b/client/Hud.cs index 278f1f2..1b5a587 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -46,6 +46,8 @@ public partial class Hud : CanvasLayer private VBoxContainer _cargoList = null!; private Label _cargoHeader = null!; private Label _garageDetails = null!; + private PanelContainer _topLeftPanel = null!; + private PanelContainer _topRightPanel = null!; private PanelContainer _bottomLeftPanel = null!; private VBoxContainer _chyronBox = null!; @@ -89,7 +91,9 @@ public partial class Hud : CanvasLayer public bool IsPointerOverInteractiveHud(Vector2 screenPos) { - return _bottomLeftPanel.GetGlobalRect().HasPoint(screenPos); + return (_topLeftPanel.Visible && _topLeftPanel.GetGlobalRect().HasPoint(screenPos)) + || (_topRightPanel.Visible && _topRightPanel.GetGlobalRect().HasPoint(screenPos)) + || (_bottomLeftPanel.Visible && _bottomLeftPanel.GetGlobalRect().HasPoint(screenPos)); } public void Sync(ArenaSession session) @@ -195,6 +199,7 @@ public partial class Hud : CanvasLayer private void BuildTopLeft() { var panel = CreateStyledPanel(); + _topLeftPanel = panel; panel.AnchorLeft = 0f; panel.AnchorTop = 0f; panel.OffsetLeft = 14f; @@ -268,6 +273,7 @@ public partial class Hud : CanvasLayer private void BuildTopRightRadar() { var panel = CreateStyledPanel(); + _topRightPanel = panel; panel.AnchorLeft = 1f; panel.AnchorRight = 1f; panel.AnchorTop = 0f; @@ -679,10 +685,22 @@ public partial class Hud : CanvasLayer return center + new Vector2(rx, -fy) * scale; } + private static Vector2 ClampToRadarDisc(Vector2 center, float maxRadius, Vector2 pt) + { + Vector2 delta = pt - center; + float dist = delta.Length(); + if (dist > maxRadius && dist > 1e-4f) + { + return center + delta * (maxRadius / dist); + } + return pt; + } + public override void _Draw() { Vector2 center = Size * 0.5f; float radius = MathF.Min(Size.X, Size.Y) * 0.47f; + float maxBlipRadius = MathF.Max(4f, radius - 3f); float scale = radius / MatchState.ArenaHalfExtent; DrawCircle(center, radius, BgInner); @@ -693,7 +711,7 @@ public partial class Hud : CanvasLayer if (_state is null) return; // Safe Circle - float safePx = _state.Spectators.SafeRadius * scale; + float safePx = MathF.Min(_state.Spectators.SafeRadius * scale, maxBlipRadius); DrawArc(center, safePx, 0f, MathF.Tau, 64, OrangeCol, 1.6f); // Ground drops @@ -701,7 +719,7 @@ public partial class Hud : CanvasLayer { var d = _state.GroundDrops[i]; if (d.PickedUp) continue; - var p = WorldToRadar(center, scale, d.X, d.Z, _cameraYaw); + var p = ClampToRadarDisc(center, maxBlipRadius, WorldToRadar(center, scale, d.X, d.Z, _cameraYaw)); if (d.Chassis is not null) { DrawRect(new Rect2(p - new Vector2(2.5f, 2.5f), new Vector2(5f, 5f)), CyanCol); @@ -728,7 +746,7 @@ public partial class Hud : CanvasLayer bool live = mem!.VisibleToPlayer; float drawX = live || mem.FaintHorizonPing ? s.X : mem.LastSeenX; float drawZ = live || mem.FaintHorizonPing ? s.Z : mem.LastSeenZ; - var p = WorldToRadar(center, scale, drawX, drawZ, _cameraYaw); + var p = ClampToRadarDisc(center, maxBlipRadius, WorldToRadar(center, scale, drawX, drawZ, _cameraYaw)); float blipR = 1.6f + s.RadarSignature * 3.1f; Color col = s.Tier switch @@ -744,7 +762,7 @@ public partial class Hud : CanvasLayer if (tid >= 0 && tid < _state.Contenders.Count && _state.Contenders[tid].Alive) { var tgt = _state.Contenders[tid]; - var tp = WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw); + var tp = ClampToRadarDisc(center, maxBlipRadius, WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw)); DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f); } col = RedCol; @@ -774,7 +792,7 @@ public partial class Hud : CanvasLayer if (c.IsPlayer) { - var p = WorldToRadar(center, scale, c.X, c.Z, _cameraYaw); + var p = ClampToRadarDisc(center, maxBlipRadius, WorldToRadar(center, scale, c.X, c.Z, _cameraYaw)); var dir = new Vector2( -MathF.Sin(c.Yaw) * cosY + MathF.Cos(c.Yaw) * sinY, -(MathF.Sin(c.Yaw) * sinY + MathF.Cos(c.Yaw) * cosY)); @@ -797,12 +815,12 @@ public partial class Hud : CanvasLayer if (mem!.VisibleToPlayer) { - var p = WorldToRadar(center, scale, c.X, c.Z, _cameraYaw); + var p = ClampToRadarDisc(center, maxBlipRadius, WorldToRadar(center, scale, c.X, c.Z, _cameraYaw)); DrawCircle(p, 3.3f, OrangeCol); } else { - var p = WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, _cameraYaw); + var p = ClampToRadarDisc(center, maxBlipRadius, WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, _cameraYaw)); float alpha = Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); DrawCircle(p, 2.8f, new Color(OrangeCol.R, OrangeCol.G, OrangeCol.B, alpha)); } diff --git a/client/Main.cs b/client/Main.cs index f028ffd..8c7f53a 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -133,7 +133,15 @@ public partial class Main : Node3D Reset(_seed + 1); break; case Key.Escape: - if (DisplayServer.GetName() != "headless") + if (_hud.GarageExpanded) + { + _hud.ToggleGarage(); + if (DisplayServer.GetName() != "headless") + { + Input.MouseMode = Input.MouseModeEnum.Visible; + } + } + else if (DisplayServer.GetName() != "headless") { Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Captured ? Input.MouseModeEnum.Visible diff --git a/client/TerrainRenderer.cs b/client/TerrainRenderer.cs index 9865df1..0443ab5 100644 --- a/client/TerrainRenderer.cs +++ b/client/TerrainRenderer.cs @@ -12,8 +12,8 @@ namespace RustToDust.Client; /// public partial class TerrainRenderer : Node3D { - private const int ViewportSize = 128; - private const float InnerTexelSpan = 125.0f; // texel 1 center (1.5) .. texel 126 center (126.5) + private const int ViewportSize = 256; + private const float InnerTexelSpan = 253.0f; // texel 1 center (1.5) .. texel 254 center (254.5) private const float GutterCenterOffset = 1.5f; private const float PixelsPerMeter = InnerTexelSpan / TerrainField.TileSize; private const float HeightSpan = TerrainField.MaxWorldHeight - TerrainField.MinWorldHeight; @@ -21,6 +21,13 @@ public partial class TerrainRenderer : Node3D private static readonly Color HeightClearColor = new(BaseHeightNorm, 0.88f, 0.0f, 1.0f); private static readonly Color AlbedoClearColor = new(0.69f, 0.50f, 0.31f, 1.0f); + private static readonly Vector2[] BrushUv = + { + new(0f, 0f), + new(1f, 0f), + new(1f, 1f), + new(0f, 1f) + }; private sealed class TileNode { @@ -162,8 +169,8 @@ public partial class TerrainRenderer : Node3D var plane = new PlaneMesh { Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize), - SubdivideWidth = 40, - SubdivideDepth = 40 + SubdivideWidth = 64, + SubdivideDepth = 64 }; var mat = new ShaderMaterial { Shader = _surfaceShader }; @@ -205,6 +212,8 @@ public partial class TerrainRenderer : Node3D Disable3D = true, UseHdr2D = useHdr, TransparentBg = false, + Snap2DTransformsToPixel = false, + Snap2DVerticesToPixel = false, RenderTargetClearMode = SubViewport.ClearMode.Always, RenderTargetUpdateMode = SubViewport.UpdateMode.Disabled }; @@ -227,19 +236,9 @@ public partial class TerrainRenderer : Node3D ClearCanvasChildren(tile.HeightCanvas); ClearCanvasChildren(tile.AlbedoCanvas); - // Full-tile base clear quads - tile.HeightCanvas.AddChild(new ColorRect - { - Position = Vector2.Zero, - Size = new Vector2(ViewportSize, ViewportSize), - Color = HeightClearColor - }); - tile.AlbedoCanvas.AddChild(new ColorRect - { - Position = Vector2.Zero, - Size = new Vector2(ViewportSize, ViewportSize), - Color = AlbedoClearColor - }); + // Full-tile base clear quads (Polygon2D avoids GUI pixel snapping) + tile.HeightCanvas.AddChild(CreateClearQuad(HeightClearColor)); + tile.AlbedoCanvas.AddChild(CreateClearQuad(AlbedoClearColor)); float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; @@ -282,13 +281,7 @@ public partial class TerrainRenderer : Node3D } // 2. Albedo brush pass - var albedoQuad = new ColorRect - { - Position = new Vector2(px - rxPx, py - rzPx), - Size = new Vector2(rxPx * 2f, rzPx * 2f), - PivotOffset = new Vector2(rxPx, rzPx), - Rotation = b.RotationRad - }; + var albedoQuad = CreateOrientedQuad(px, py, rxPx, rzPx, b.RotationRad); var albedoMat = new ShaderMaterial { Shader = _brushAlbedoShader }; albedoMat.SetShaderParameter("brush_kind", kindInt); albedoMat.SetShaderParameter("brush_albedo", new Vector3(b.AlbedoR, b.AlbedoG, b.AlbedoB)); @@ -301,7 +294,42 @@ public partial class TerrainRenderer : Node3D tile.AlbedoViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; } - private static ColorRect CreateBrushQuad( + private static Polygon2D CreateClearQuad(Color color) + { + return new Polygon2D + { + Polygon = new[] + { + new Vector2(0f, 0f), + new Vector2(ViewportSize, 0f), + new Vector2(ViewportSize, ViewportSize), + new Vector2(0f, ViewportSize) + }, + Color = color + }; + } + + private static Polygon2D CreateOrientedQuad( + float px, float py, + float rxPx, float rzPx, + float rotationRad) + { + return new Polygon2D + { + Position = new Vector2(px, py), + Rotation = rotationRad, + Polygon = new[] + { + new Vector2(-rxPx, -rzPx), + new Vector2(rxPx, -rzPx), + new Vector2(rxPx, rzPx), + new Vector2(-rxPx, rzPx) + }, + Uv = BrushUv + }; + } + + private static Polygon2D CreateBrushQuad( float px, float py, float rxPx, float rzPx, float rotationRad, @@ -309,13 +337,7 @@ public partial class TerrainRenderer : Node3D int kindInt, float heightDelta) { - var quad = new ColorRect - { - Position = new Vector2(px - rxPx, py - rzPx), - Size = new Vector2(rxPx * 2f, rzPx * 2f), - PivotOffset = new Vector2(rxPx, rzPx), - Rotation = rotationRad - }; + var quad = CreateOrientedQuad(px, py, rxPx, rzPx, rotationRad); var mat = new ShaderMaterial { Shader = shader }; mat.SetShaderParameter("brush_kind", kindInt); mat.SetShaderParameter("height_delta", heightDelta); diff --git a/client/terrain_surface.gdshader b/client/terrain_surface.gdshader index 58caa86..eaf2609 100644 --- a/client/terrain_surface.gdshader +++ b/client/terrain_surface.gdshader @@ -6,8 +6,8 @@ uniform sampler2D albedo_tex : filter_linear, repeat_disable; uniform float height_min = -18.0; uniform float height_max = 52.0; uniform float tile_size = 192.0; -uniform float inner_span = 125.0; -uniform float tex_size = 128.0; +uniform float inner_span = 253.0; +uniform float tex_size = 256.0; uniform float gutter_offset = 1.5; float decode_height(float h_norm) { diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs index 5274494..6d097f0 100644 --- a/src/RustToDust.Core/MatchRules.cs +++ b/src/RustToDust.Core/MatchRules.cs @@ -250,16 +250,49 @@ namespace RustToDust.Core return; } - // Occluded behind terrain/cover: never shoot through rock! Maneuver around ridge / to higher ground. + // Occluded behind terrain/cover: never shoot through rock! Never fall back to live target.X/Z while occluded. if (!spec.HasTargetLos) { shouldFire = false; bool hasMemory = spec.TimeSinceLastSeen < SpectatorRing.TargetMemoryDuration; - float focusX = hasMemory ? spec.LastKnownTargetX : target.X; - float focusZ = hasMemory ? spec.LastKnownTargetZ : target.Z; + float focusX = spec.LastKnownTargetX; + float focusZ = spec.LastKnownTargetZ; aimX = focusX; aimZ = focusZ; + if (!hasMemory) + { + var (anchorX, anchorZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes); + float toFocusX = focusX - spec.X; + float toFocusZ = focusZ - spec.Z; + float toFocusLen = MathF.Sqrt(toFocusX * toFocusX + toFocusZ * toFocusZ); + bool hasValidFocus = (focusX != 0f || focusZ != 0f) && toFocusLen > 12f && toFocusLen < 240f; + float centerX = hasValidFocus ? focusX : anchorX; + float centerZ = hasValidFocus ? focusZ : anchorZ; + + float bestX = centerX; + float bestZ = centerZ; + float bestH = state.Terrain.SampleHeight(bestX, bestZ); + float maxBound = TerrainField.HalfExtent - 18f; + for (int k = 0; k < 4; k++) + { + float ang = spec.Id * 0.7f + k * (MathF.PI * 0.5f); + float cx = Math.Clamp(centerX + MathF.Cos(ang) * 26f, -maxBound, maxBound); + float cz = Math.Clamp(centerZ + MathF.Sin(ang) * 26f, -maxBound, maxBound); + float h = state.Terrain.SampleHeight(cx, cz); + if (h > bestH) + { + bestH = h; + bestX = cx; + bestZ = cz; + } + } + + goalX = bestX; + goalZ = bestZ; + return; + } + float fdx = focusX - spec.X; float fdz = focusZ - spec.Z; float fLen = MathF.Sqrt(fdx * fdx + fdz * fdz); diff --git a/src/RustToDust.Core/SpectatorRing.cs b/src/RustToDust.Core/SpectatorRing.cs index d1ffc5b..caab91a 100644 --- a/src/RustToDust.Core/SpectatorRing.cs +++ b/src/RustToDust.Core/SpectatorRing.cs @@ -126,17 +126,22 @@ namespace RustToDust.Core Span prevTargets = _spectators.Count <= 256 ? stackalloc int[_spectators.Count] : new int[_spectators.Count]; + Span prevTimesSinceSeen = _spectators.Count <= 256 + ? stackalloc float[_spectators.Count] + : new float[_spectators.Count]; // Keep Provoked lock while target is alive; reset Cleared to Neutral for clean re-evaluation. for (int i = 0; i < _spectators.Count; i++) { var spec = _spectators[i]; prevTargets[i] = spec.TargetContenderId ?? -1; + prevTimesSinceSeen[i] = spec.TimeSinceLastSeen; if (!spec.Alive) { spec.TargetContenderId = null; spec.HasTargetLos = false; + spec.TimeSinceLastSeen = TargetMemoryDuration + 1f; continue; } @@ -149,7 +154,7 @@ namespace RustToDust.Core spec.Stance = SpectatorStance.Neutral; spec.TargetContenderId = null; spec.HasTargetLos = false; - spec.TimeSinceLastSeen = float.PositiveInfinity; + spec.TimeSinceLastSeen = TargetMemoryDuration + 1f; } else { @@ -175,6 +180,7 @@ namespace RustToDust.Core spec.Stance = SpectatorStance.Neutral; spec.TargetContenderId = null; spec.HasTargetLos = false; + spec.TimeSinceLastSeen = TargetMemoryDuration + 1f; } } @@ -260,8 +266,9 @@ namespace RustToDust.Core float dx = spec.X - contender.X; float dz = spec.Z - contender.Z; float d2 = dx * dx + dz * dz; - bool hasMemory = prevTargets[i] == contender.Id && spec.TimeSinceLastSeen < TargetMemoryDuration; - float score = hasMemory ? d2 * 0.25f : d2; + bool hadTarget = prevTargets[i] == contender.Id; + bool hasMemory = hadTarget && prevTimesSinceSeen[i] < TargetMemoryDuration; + float score = hasMemory ? d2 * 0.2f : (hadTarget ? d2 * 0.35f : d2); if (score < bestScore) { bestScore = score; @@ -278,16 +285,19 @@ namespace RustToDust.Core chosen.Stance = SpectatorStance.Cleared; chosen.TargetContenderId = contender.Id; chosen.HasTargetLos = false; - if (prevTargets[bestIdx] == contender.Id && chosen.TimeSinceLastSeen < TargetMemoryDuration) + if (prevTargets[bestIdx] == contender.Id) { - chosen.TimeSinceLastSeen += dt; + chosen.TimeSinceLastSeen = prevTimesSinceSeen[bestIdx] + dt; } else { - chosen.LastKnownTargetX = contender.X; - chosen.LastKnownTargetY = contender.Y; - chosen.LastKnownTargetZ = contender.Z; - chosen.TimeSinceLastSeen = 0f; + float dirX = distFromCenter > 1e-3f ? contender.X / distFromCenter : 1f; + float dirZ = distFromCenter > 1e-3f ? contender.Z / distFromCenter : 0f; + float boundaryRadius = SafeRadius + 6f; + chosen.LastKnownTargetX = dirX * boundaryRadius; + chosen.LastKnownTargetY = chosen.Y; + chosen.LastKnownTargetZ = dirZ * boundaryRadius; + chosen.TimeSinceLastSeen = TargetMemoryDuration; } assigned++; } diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 6c9afff..99b3948 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -426,8 +426,24 @@ namespace RustToDust.Ymir float gripScale = groundedCorners > 0 ? (0.4f + 0.6f * (groundedCorners / 4f)) : 0.12f; Vector3 force = supportForce; + // On steep cliffs (ny < 0.74), strip inward horizontal thrust so vehicles slide along the slope instead of burrowing + Vector3 effectiveDriveFwd = driveForward; + if (groundedCorners > 0 && terrainNormal.Y < 0.74f) + { + Vector3 cliffHoriz = new Vector3(terrainNormal.X, 0f, terrainNormal.Z); + if (cliffHoriz.LengthSquared() > 1e-4f) + { + cliffHoriz = Vector3.Normalize(cliffHoriz); + float intoCliff = Vector3.Dot(effectiveDriveFwd, cliffHoriz); + if (intoCliff < 0f) + { + effectiveDriveFwd -= cliffHoriz * intoCliff; + effectiveDriveFwd.Y = MathF.Min(effectiveDriveFwd.Y, 0.25f); + } + } + } // Drive thrust along slope-aligned forward with smooth terminal velocity drag at MaxSpeed - force += driveForward * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed) * gripScale; + force += effectiveDriveFwd * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed) * gripScale; // Lateral tire / stride grip force -= driveRight * (lateralSpeed * mass * 8.5f * gripScale); @@ -457,9 +473,7 @@ namespace RustToDust.Ymir float hz = view.Size2[lane]; float iy = mass * (hx * hx + hz * hz) / 3f; - Vector3 targetUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.85f)); - Vector3 tiltAxis = Vector3.Cross(up, targetUp); - Vector3 torque = supportTorque + tiltAxis * (mass * 16f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f); + Vector3 torque = ComputeRightingTorque(c.Grid.Spec, q, up, angVel, mass, terrainNormal, supportTorque, terrainBlend: 0.85f); torque.Y = iy * (targetYawVel - angVel.Y) * 8f; view.ForceX[lane] = force.X; @@ -518,9 +532,7 @@ namespace RustToDust.Ymir float hz = view.Size2[lane]; float iy = mass * (hx * hx + hz * hz) / 3f; - Vector3 targetUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.7f)); - Vector3 tiltAxis = Vector3.Cross(up, targetUp); - Vector3 torque = supportTorque + tiltAxis * (mass * 16f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f); + 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; view.ForceX[lane] = force.X; @@ -532,6 +544,53 @@ namespace RustToDust.Ymir } } + private static Vector3 ComputeRightingTorque( + ChassisSpec spec, + Quaternion q, + Vector3 up, + Vector3 angVel, + float mass, + Vector3 terrainNormal, + Vector3 supportTorque, + float terrainBlend) + { + bool isTallRig = spec.Plane == GridPlane.Coronal || spec.Id == "manticore"; + float blend = isTallRig ? MathF.Min(terrainBlend, 0.45f) : terrainBlend; + Vector3 desiredUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, blend)); + + if (isTallRig) + { + const float maxTiltRad = MathF.PI / 12f; // 15 degrees max tilt for bipeds/quadrupeds + float dotY = Math.Clamp(desiredUp.Y, -1f, 1f); + if (MathF.Acos(dotY) > maxTiltRad) + { + Vector3 horiz = new Vector3(desiredUp.X, 0f, desiredUp.Z); + float hLen = horiz.Length(); + desiredUp = hLen > 1e-4f + ? Vector3.UnitY * MathF.Cos(maxTiltRad) + (horiz / hLen) * MathF.Sin(maxTiltRad) + : Vector3.UnitY; + } + } + + float upDot = Vector3.Dot(up, desiredUp); + Vector3 tiltAxis = Vector3.Cross(up, desiredUp); + if (upDot < 0.2f) + { + Vector3 fallbackAxis = Vector3.Transform(Vector3.UnitZ, q); + fallbackAxis.Y = 0f; + fallbackAxis = fallbackAxis.LengthSquared() > 1e-4f + ? Vector3.Normalize(fallbackAxis) + : Vector3.UnitX; + + float axisLen = tiltAxis.Length(); + Vector3 recoveryDir = axisLen > 0.15f ? tiltAxis / axisLen : fallbackAxis; + tiltAxis = recoveryDir * MathF.Max(axisLen, 1.0f); + } + + float rightingGain = isTallRig ? 28f : 16f; + return supportTorque + tiltAxis * (mass * rightingGain) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6.5f); + } + private void ComputeTerrainSupport( Vector3 pos, Quaternion q, @@ -548,12 +607,22 @@ namespace RustToDust.Ymir supportTorque = Vector3.Zero; groundedCorners = 0; + var (nx, ny, nz) = State.Terrain.SampleNormal(pos.X, pos.Z); + terrainNormal = new Vector3(nx, ny, nz); + + // Blend smoothly from pure vertical on flat ground to surface normal on steep mesa/dune slopes + float slopeBlend = Math.Clamp((0.985f - terrainNormal.Y) / 0.18f, 0f, 1f); + Vector3 supportDir = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, slopeBlend)); + float orthoScale = MathF.Max(0.35f, terrainNormal.Y); + float hx = spec.HalfWidth * 0.9f; float hz = spec.HalfLength * 0.9f; float bottomY = -spec.HalfHeight; const float restTravel = 0.20f; float kSpring = mass * 85f; float cDamp = mass * 10.5f; + float torqueScale = spec.HalfHeight > spec.HalfLength ? 0.18f : 1.0f; + float maxPen = 0f; Span corners = stackalloc Vector3[4] { @@ -572,10 +641,12 @@ namespace RustToDust.Ymir if (pen > 0f) { groundedCorners++; - float vCornerY = vel.Y + Vector3.Cross(angVel, r).Y; - float fY = Math.Clamp(kSpring * pen - cDamp * vCornerY, 0f, mass * 160f); - supportForce.Y += fY; - supportTorque += Vector3.Cross(r, new Vector3(0f, fY, 0f)); + maxPen = MathF.Max(maxPen, pen); + float vCornerN = Vector3.Dot(vel + Vector3.Cross(angVel, r), supportDir); + float fN = Math.Clamp(kSpring * (pen * orthoScale) - cDamp * vCornerN, 0f, mass * 45f); + Vector3 cornerForce = supportDir * fN; + supportForce += cornerForce; + supportTorque += Vector3.Cross(r, cornerForce) * torqueScale; } } @@ -584,11 +655,40 @@ namespace RustToDust.Ymir if (centerPen > 0f) { groundedCorners = Math.Max(groundedCorners, 1); - supportForce.Y += Math.Clamp(mass * 160f * centerPen - mass * 12f * vel.Y, 0f, mass * 140f); + maxPen = MathF.Max(maxPen, centerPen); + float vCenterN = Vector3.Dot(vel, supportDir); + float fCenter = Math.Clamp(mass * 120f * (centerPen * orthoScale) - mass * 10f * vCenterN, 0f, mass * 55f); + supportForce += supportDir * fCenter; } - var (nx, ny, nz) = State.Terrain.SampleNormal(pos.X, pos.Z); - terrainNormal = new Vector3(nx, ny, nz); + // Cap total spring + bump-stop vertical acceleration at <= 65 m/s^2 so ridge impacts never catapult vehicles skyward + float maxSpringY = mass * 65f; + if (supportForce.Y > maxSpringY && supportForce.Y > 1e-4f) + { + supportForce *= maxSpringY / supportForce.Y; + } + + // Steep-slope velocity projection / deflection: damp inward velocity when contacting terrain + if (maxPen > 0f) + { + float vn = Vector3.Dot(vel, terrainNormal); + if (vn < 0f) + { + float deflectMag = MathF.Min(-vn * mass * 30f, -vn * mass / FixedDt); + Vector3 deflectForce = terrainNormal * deflectMag; + float maxAllowableY = MathF.Max(0f, maxSpringY - supportForce.Y); + if (deflectForce.Y > maxAllowableY) + { + deflectForce.Y = maxAllowableY; + } + supportForce += deflectForce; + } + + if (maxPen > 0.35f && terrainNormal.Y < 0.85f) + { + supportForce += new Vector3(terrainNormal.X, 0f, terrainNormal.Z) * (mass * 45f * MathF.Min(maxPen, 1.5f)); + } + } } private void SyncBodiesFromWorld() diff --git a/tests/RustToDust.Tests/DetectionLosTests.cs b/tests/RustToDust.Tests/DetectionLosTests.cs index 8f2dd3c..da31233 100644 --- a/tests/RustToDust.Tests/DetectionLosTests.cs +++ b/tests/RustToDust.Tests/DetectionLosTests.cs @@ -196,5 +196,117 @@ namespace RustToDust.Tests } } } + + [Fact] + public void OccludedSpectators_DoNotLeakLiveTargetAfterMemoryExpires_FiveSeconds() + { + using var session = new ArenaSession(seed: 42); + // Shrink safe circle so the tall mesa perimeter is outside SafeRadius + session.State.Time = 360f; + session.State.Spectators.UpdateSafeRadius(session.State.Time); + + TerrainBrush mesa = default; + float bestArea = -1f; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + float area = b.RadiusX * b.RadiusZ; + if (area > bestArea) + { + bestArea = area; + mesa = b; + } + } + } + Assert.True(bestArea > 0f, "Expected at least one tall Mesa in generated terrain."); + + var player = session.State.Player; + var tourists = session.State.Spectators.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList(); + var provokedSpec = tourists[0]; + var clearedSpec = tourists[1]; + + // Place player on the side of the mesa further from center (strictly outside SafeRadius) + float xNeg = mesa.X - mesa.RadiusX - 18f; + float xPos = mesa.X + mesa.RadiusX + 18f; + bool negIsFurther = (xNeg * xNeg + mesa.Z * mesa.Z) >= (xPos * xPos + mesa.Z * mesa.Z); + float occludedX = negIsFurther ? xNeg : xPos; + float specSideX = negIsFurther ? xPos : xNeg; + + // Briefly establish visual contact for provokedSpec at initial spot, then move player behind the mesa + session.SetContenderPose(player.Id, specSideX - (negIsFurther ? 12f : -12f), mesa.Z); + session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z); + session.State.Spectators.OnSpectatorDamaged(provokedSpec, player.Id); + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + Assert.True(provokedSpec.HasTargetLos, "Expected initial LOS before player drops behind cover"); + + float provokedKnownX = provokedSpec.LastKnownTargetX; + float provokedKnownZ = provokedSpec.LastKnownTargetZ; + + // Now hide player behind the mesa and place clearedSpec on the opposite side closest to the breach + session.SetContenderPose(player.Id, occludedX, mesa.Z - 14f); + session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z - 4f); + session.SetSpectatorPose(clearedSpec.Id, specSideX, mesa.Z + 4f); + + // Verify clearedSpec gets Pass-2 Cleared assignment without LOS + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + Assert.False(provokedSpec.HasTargetLos); + Assert.Equal(SpectatorStance.Cleared, clearedSpec.Stance); + Assert.False(clearedSpec.HasTargetLos); + + float clearedInitialKnownX = clearedSpec.LastKnownTargetX; + float clearedInitialKnownZ = clearedSpec.LastKnownTargetZ; + + // Run 300 ticks (5.0s > 4.0s TargetMemoryDuration) while player moves laterally behind cover + for (int tick = 0; tick < 300; tick++) + { + float latZ = mesa.Z - 14f + (tick / 299f) * 34f; + if (tick % 10 == 0) + { + session.SetContenderPose(player.Id, occludedX, latZ); + } + + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + + Assert.False(provokedSpec.HasTargetLos, $"Provoked spectator regained unexpected LOS at tick {tick}"); + Assert.False(clearedSpec.HasTargetLos, $"Cleared spectator regained unexpected LOS at tick {tick}"); + + if (tick == 270) // 4.5s > 4.0s memory window + { + Assert.True(provokedSpec.TimeSinceLastSeen >= 4.5f, + $"Provoked TimeSinceLastSeen reset unexpectedly: {provokedSpec.TimeSinceLastSeen:F2}s"); + Assert.True(clearedSpec.TimeSinceLastSeen >= 4.5f, + $"Cleared TimeSinceLastSeen reset unexpectedly: {clearedSpec.TimeSinceLastSeen:F2}s"); + } + } + + // Neither spectator's LastKnownTarget or aim vector may track the player's new occluded position + float provokedDistToPlayer = MathF.Sqrt( + (provokedSpec.LastKnownTargetX - player.X) * (provokedSpec.LastKnownTargetX - player.X) + + (provokedSpec.LastKnownTargetZ - player.Z) * (provokedSpec.LastKnownTargetZ - player.Z)); + Assert.Equal(provokedKnownX, provokedSpec.LastKnownTargetX, precision: 3); + Assert.Equal(provokedKnownZ, provokedSpec.LastKnownTargetZ, precision: 3); + Assert.True(provokedDistToPlayer > 25f, + $"Provoked LastKnownTarget leaked live player position (dist={provokedDistToPlayer:F2}m)"); + + float clearedDistToPlayer = MathF.Sqrt( + (clearedSpec.LastKnownTargetX - player.X) * (clearedSpec.LastKnownTargetX - player.X) + + (clearedSpec.LastKnownTargetZ - player.Z) * (clearedSpec.LastKnownTargetZ - player.Z)); + Assert.Equal(clearedInitialKnownX, clearedSpec.LastKnownTargetX, precision: 3); + Assert.Equal(clearedInitialKnownZ, clearedSpec.LastKnownTargetZ, precision: 3); + Assert.True(clearedDistToPlayer > 20f, + $"Cleared LastKnownTarget leaked live player position (dist={clearedDistToPlayer:F2}m)"); + + MatchRules.ComputeSpectatorBehavior(provokedSpec, session.State, out _, out _, out float pAimX, out float pAimZ, out bool pFire); + Assert.False(pFire); + Assert.Equal(provokedKnownX, pAimX, precision: 3); + Assert.Equal(provokedKnownZ, pAimZ, precision: 3); + + MatchRules.ComputeSpectatorBehavior(clearedSpec, session.State, out _, out _, out float cAimX, out float cAimZ, out bool cFire); + Assert.False(cFire); + Assert.Equal(clearedInitialKnownX, cAimX, precision: 3); + Assert.Equal(clearedInitialKnownZ, cAimZ, precision: 3); + } } } diff --git a/tests/RustToDust.Tests/TerrainTests.cs b/tests/RustToDust.Tests/TerrainTests.cs index 95a0aa8..9cff564 100644 --- a/tests/RustToDust.Tests/TerrainTests.cs +++ b/tests/RustToDust.Tests/TerrainTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Numerics; using RustToDust.Core; using RustToDust.Ymir; using Xunit; @@ -256,5 +257,90 @@ namespace RustToDust.Tests $"Expected Road major axis to be tangential (dot ~ 0), got {radialDot:F4}"); } } + + [Theory] + [InlineData(42)] + [InlineData(101)] + public void SteepMesaAndCanyonTraversal_BuggyAndPaladin_NoTunnelingSkyLaunchOrOverturning(int seed) + { + RunSteepTerrainStress(seed, usePaladin: false); + RunSteepTerrainStress(seed, usePaladin: true); + } + + private static void RunSteepTerrainStress(int seed, bool usePaladin) + { + using var session = new ArenaSession(seed); + var player = session.State.Player; + + TerrainBrush mesa = default; + bool foundMesa = false; + for (int i = 0; i < session.State.Terrain.Brushes.Count; i++) + { + var b = session.State.Terrain.Brushes[i]; + if (b.Kind == TerrainBrushKind.Mesa && b.HeightDelta >= 22f) + { + mesa = b; + foundMesa = true; + break; + } + } + Assert.True(foundMesa, $"Expected at least one tall mesa in seed {seed}"); + + float startX = mesa.X - mesa.RadiusX - 24f; + float startZ = mesa.Z; + float yawToMesa = MathF.Atan2(mesa.X - startX, mesa.Z - startZ); + session.SetContenderPose(player.Id, startX, startZ, yawToMesa); + + if (usePaladin) + { + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Paladin); + Assert.True(session.TrySwapNearbyChassis()); + Assert.Equal(GridPlane.Coronal, player.Grid.Spec.Plane); + } + + float minBottomRel = float.PositiveInfinity; + float maxAirGap = float.NegativeInfinity; + float minUpDot = float.PositiveInfinity; + + for (int tick = 0; tick < 600; tick++) + { + float steer = MathF.Sin(tick * 0.03f) * 0.2f; + session.Step(new PlayerInput( + Throttle: 1f, + Steer: steer, + AimWorldX: mesa.X, + AimWorldZ: mesa.Z, + Fire: false, + InteractPickup: false, + Brake: false)); + + Assert.False( + float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z), + $"NaN pose at tick {tick} (seed={seed}, paladin={usePaladin})"); + + var body = session.GetContenderBody(player.Id); + Assert.True(body.HasValue, $"Expected live contender body at tick {tick} (seed={seed}, paladin={usePaladin})"); + + int lane = body!.Value.Lane; + var view = session.World.View; + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + var up = Vector3.Transform(Vector3.UnitY, q); + Assert.False(float.IsNaN(up.Y), $"NaN orientation at tick {tick}"); + + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + float bottomRel = (player.Y - player.Grid.Spec.HalfHeight) - gh; + + minBottomRel = MathF.Min(minBottomRel, bottomRel); + maxAirGap = MathF.Max(maxAirGap, bottomRel); + minUpDot = MathF.Min(minUpDot, up.Y); + } + + Assert.True(minBottomRel >= -1.2f, + $"Deep terrain tunneling detected (seed={seed}, paladin={usePaladin}): minBottomRel={minBottomRel:F2}m"); + Assert.True(maxAirGap <= 10.0f, + $"Excessive sky launch detected (seed={seed}, paladin={usePaladin}): maxAirGap={maxAirGap:F2}m"); + Assert.True(minUpDot > 0.25f, + $"Chassis overturned onto side/back (seed={seed}, paladin={usePaladin}): minUpDot={minUpDot:F3}"); + } } }