From f5d23ce49e1f8b3573be465b95ed2ed2cb8950e5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 4 Dec 2026 23:22:18 +0100 Subject: [PATCH] Fix all 6 60 FPS Soul Pass findings and add permanent regression tests --- client/ArenaRenderer.cs | 139 +++++++--- client/InventoryGridControl.cs | 20 +- client/Main.cs | 52 ++++ client/TerrainRenderer.cs | 33 ++- client/VehicleAssetCache.cs | 131 ++++++++-- client/VehicleVisualInstance.cs | 180 ++++++++----- client/tests/Smoke.cs | 170 +++++++++++++ src/RustToDust.Core/MatchRules.cs | 75 ++---- src/RustToDust.Core/SpectatorRing.cs | 27 +- src/RustToDust.Core/TerrainField.cs | 268 +++++++++++++++++--- src/RustToDust.Ymir/ArenaSession.cs | 127 ++++------ tests/RustToDust.Tests/DetectionLosTests.cs | 144 +++++++++++ 12 files changed, 1046 insertions(+), 320 deletions(-) diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index b92468e..91862ca 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -28,6 +28,8 @@ public partial class ArenaRenderer : Node3D public MeshInstance3D? LaserMesh; public SpectatorStance? LastHaloStance; public bool LastLaserVisible; + public float RigDtAccum; + public int RigSkipFrames; } private sealed class DropVisualEntry @@ -178,30 +180,80 @@ public partial class ArenaRenderer : Node3D { ClearChildren(_staticGroup); + // Bucket cover ruins into 4 world quadrants so frustum culling still culls off-screen quadrants + // while collapsing 36 individual MeshInstance3D draw calls down to <= 4. + var quadArrays = new SurfaceTool[4]; for (int i = 0; i < state.ArenaCoverBoxes.Count; i++) { var b = state.ArenaCoverBoxes[i]; - var mesh = new MeshInstance3D + int qIdx = (b.X >= 0f ? 1 : 0) | (b.Z >= 0f ? 2 : 0); + var st = quadArrays[qIdx]; + if (st is null) { - Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) }, - MaterialOverride = _coverMat, - Position = new Vector3(b.X, b.Y, b.Z) - }; - _staticGroup.AddChild(mesh); + st = new SurfaceTool(); + st.Begin(Mesh.PrimitiveType.Triangles); + quadArrays[qIdx] = st; + } + AppendBoxToSurfaceTool(st, new Vector3(b.X, b.Y, b.Z), new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f)); } - for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) + for (int q = 0; q < 4; q++) { - var b = state.ArenaBoundaryBoxes[i]; - var mesh = new MeshInstance3D + if (quadArrays[q] is null) continue; + quadArrays[q].GenerateNormals(); + _staticGroup.AddChild(new MeshInstance3D { - Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) }, - MaterialOverride = _bermMat, - Position = new Vector3(b.X, b.Y, b.Z), - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off - }; - _staticGroup.AddChild(mesh); + Name = $"CoverQuad_{q}", + Mesh = quadArrays[q].Commit(), + MaterialOverride = _coverMat + }); } + + if (state.ArenaBoundaryBoxes.Count > 0) + { + var bermSt = new SurfaceTool(); + bermSt.Begin(Mesh.PrimitiveType.Triangles); + for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) + { + var b = state.ArenaBoundaryBoxes[i]; + AppendBoxToSurfaceTool(bermSt, new Vector3(b.X, b.Y, b.Z), new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f)); + } + bermSt.GenerateNormals(); + _staticGroup.AddChild(new MeshInstance3D + { + Name = "BoundaryBerms", + Mesh = bermSt.Commit(), + MaterialOverride = _bermMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }); + } + } + + private static void AppendBoxToSurfaceTool(SurfaceTool st, Vector3 center, Vector3 size) + { + Vector3 h = size * 0.5f; + Vector3 p000 = center + new Vector3(-h.X, -h.Y, -h.Z); + Vector3 p100 = center + new Vector3( h.X, -h.Y, -h.Z); + Vector3 p110 = center + new Vector3( h.X, h.Y, -h.Z); + Vector3 p010 = center + new Vector3(-h.X, h.Y, -h.Z); + Vector3 p001 = center + new Vector3(-h.X, -h.Y, h.Z); + Vector3 p101 = center + new Vector3( h.X, -h.Y, h.Z); + Vector3 p111 = center + new Vector3( h.X, h.Y, h.Z); + Vector3 p011 = center + new Vector3(-h.X, h.Y, h.Z); + + // +Z, -Z, +X, -X, +Y, -Y (outward CCW in Godot right-handed coords) + AddQuad(st, p001, p101, p111, p011); + AddQuad(st, p100, p000, p010, p110); + AddQuad(st, p101, p100, p110, p111); + AddQuad(st, p000, p001, p011, p010); + AddQuad(st, p011, p111, p110, p010); + AddQuad(st, p000, p100, p101, p001); + } + + private static void AddQuad(SurfaceTool st, Vector3 a, Vector3 b, Vector3 c, Vector3 d) + { + st.AddVertex(a); st.AddVertex(b); st.AddVertex(c); + st.AddVertex(a); st.AddVertex(c); st.AddVertex(d); } private void ClearDynamicVisuals() @@ -318,22 +370,29 @@ public partial class ArenaRenderer : Node3D vis.Visual.Root.Rotation = new Vector3(0f, c.Yaw, 0f); } - bool useStaticLod = false; - bool castShadows = true; - if (hasCam && !c.IsPlayer) - { - float distSq = pos.DistanceSquaredTo(camPos); - useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f; - castShadows = distSq <= 150f * 150f; - } - vis.Visual.SetLodState(useStaticLod, castShadows); + float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; + bool castShadows = !hasCam || c.IsPlayer || distSq <= 115f * 115f; + vis.Visual.SetLodState(useStaticLod: false, castShadows); - if (!useStaticLod) + vis.Visual.SyncMountedGear(c.Grid); + if (!hasCam || c.IsPlayer || distSq <= 130f * 130f) { - vis.Visual.SyncMountedGear(c.Grid); + vis.RigDtAccum = 0f; + vis.RigSkipFrames = 0; VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, dt); - vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel); } + else + { + vis.RigDtAccum += dt; + vis.RigSkipFrames++; + if (vis.RigSkipFrames >= 3) + { + VehicleRigAnimator.Update(vis.Visual, c, vel, vis.Visual.Root.Basis, vis.RigDtAccum); + vis.RigDtAccum = 0f; + vis.RigSkipFrames = 0; + } + } + vis.Visual.SyncDamageAndHeat(c.Grid, _debris, vel); } } @@ -399,13 +458,18 @@ public partial class ArenaRenderer : Node3D vis.Visual.Root.Rotation = new Vector3(0f, s.Yaw, 0f); } + vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel); + bool useStaticLod = false; bool castShadows = true; if (hasCam) { float distSq = specPos.DistanceSquaredTo(camPos); - useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f; - castShadows = distSq <= 150f * 150f; + castShadows = distSq <= 115f * 115f; + if (s.Stance == SpectatorStance.Neutral && !vis.Visual.HasAnyStrippedCell) + { + useStaticLod = vis.Visual.IsStaticLod ? distSq > 126f * 126f : distSq > 130f * 130f; + } } vis.Visual.SetLodState(useStaticLod, castShadows); @@ -447,7 +511,6 @@ public partial class ArenaRenderer : Node3D vis.Visual.SyncMountedGear(s.Grid); VehicleRigAnimator.Update(vis.Visual, in rigInput, vis.Visual.Root.Basis); - vis.Visual.SyncDamageAndHeat(s.Grid, _debris, vel); } // Status halo @@ -611,9 +674,17 @@ public partial class ArenaRenderer : Node3D } if (d.Module is not null) { - float bob = MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f; - entry.Node.Position = new Vector3(d.X, entry.BaseY + bob, d.Z); - entry.Node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f); + bool visDrop = !hasCam || new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos) <= 240f * 240f; + if (entry.Node.Visible != visDrop) + { + entry.Node.Visible = visDrop; + } + if (visDrop) + { + float bob = MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f; + entry.Node.Position = new Vector3(d.X, entry.BaseY + bob, d.Z); + entry.Node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f); + } } else { @@ -629,7 +700,7 @@ public partial class ArenaRenderer : Node3D { float d2 = new Vector3(d.X, entry.BaseY, d.Z).DistanceSquaredTo(camPos); useFarLod = cv.IsStaticLod ? d2 > 126f * 126f : d2 > 130f * 130f; - castShadows = d2 <= 150f * 150f; + castShadows = d2 <= 95f * 95f; } cv.SetLodState(useFarLod, castShadows); } diff --git a/client/InventoryGridControl.cs b/client/InventoryGridControl.cs index 15a3456..8597b16 100644 --- a/client/InventoryGridControl.cs +++ b/client/InventoryGridControl.cs @@ -59,6 +59,7 @@ public partial class InventoryGridControl : Control private float[,] _hitPulse = new float[0, 0]; private int _lastSelectedCargoIndex = int.MinValue; + private string? _lastSelectedCargoId; private int _lastMountedSig = int.MinValue; private Vector2I? _hoveredCell; private bool _thermalEnabled; @@ -115,6 +116,9 @@ public partial class InventoryGridControl : Control } public float ThermalBlend => _thermalBlend; + internal int LabelsDrawCount => _labelsOverlay.DrawCount; + internal string? GetLastDrawnLabel(string hardpointId) => + _labelsOverlay.LastDrawnTags.TryGetValue(hardpointId, out string? tag) ? tag : null; public void SetThermalInstant(bool enabled) { @@ -216,11 +220,15 @@ public partial class InventoryGridControl : Control _grid = grid; _spec = grid.Spec; _selectedCargoIndex = selectedCargoIndex; + string? selectedCargoId = selectedCargoIndex >= 0 && selectedCargoIndex < grid.Cargo.Count + ? grid.Cargo[selectedCargoIndex].Id + : null; if (gridIdentityChanged) { EnsureBackingBuffers(grid); _lastSelectedCargoIndex = selectedCargoIndex; + _lastSelectedCargoId = selectedCargoId; _lastMountedSig = ComputeMountedSignature(grid); SnapshotTemperatures(grid); PackDataTexture(grid); @@ -233,9 +241,12 @@ public partial class InventoryGridControl : Control bool dataChanged = DetectHits(grid); int mountedSig = ComputeMountedSignature(grid); - if (_lastSelectedCargoIndex != selectedCargoIndex || _lastMountedSig != mountedSig) + if (_lastSelectedCargoIndex != selectedCargoIndex || + !string.Equals(_lastSelectedCargoId, selectedCargoId, StringComparison.Ordinal) || + _lastMountedSig != mountedSig) { _lastSelectedCargoIndex = selectedCargoIndex; + _lastSelectedCargoId = selectedCargoId; _lastMountedSig = mountedSig; dataChanged = true; } @@ -245,7 +256,6 @@ public partial class InventoryGridControl : Control if (dataChanged) { PackDataTexture(grid); - _labelsOverlay.QueueRedraw(); } if (tempChanged) { @@ -254,6 +264,7 @@ public partial class InventoryGridControl : Control } if (dataChanged || tempChanged) { + _labelsOverlay.QueueRedraw(); FlushTextures(); } } @@ -730,11 +741,15 @@ public partial class InventoryGridControl : Control private sealed partial class LabelsOverlay : Control { private readonly InventoryGridControl _owner; + public int DrawCount { get; private set; } + public readonly Dictionary LastDrawnTags = new(StringComparer.Ordinal); public LabelsOverlay(InventoryGridControl owner) => _owner = owner; public override void _Draw() { + DrawCount++; + LastDrawnTags.Clear(); var grid = _owner._grid; if (grid is null) return; @@ -755,6 +770,7 @@ public partial class InventoryGridControl : Control string tag = mounted is not null ? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°" : hp.Kind.ToString()[..3].ToUpperInvariant(); + LastDrawnTags[hp.Id] = tag; Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight; col.A = alpha; diff --git a/client/Main.cs b/client/Main.cs index 079399d..e9c6bce 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -88,8 +88,59 @@ public partial class Main : Node3D } Reset(_seed); + if (_perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1" && _session is not null) + { + SetupPerfCombatScenario(_session); + } _perfLastFrameTick = Stopwatch.GetTimestamp(); _perfLastDirtyRebakes = _terrain.DirtyRebakes; + TerrainRenderer.PerfBakeTileMs = 0; + TerrainRenderer.PerfBakeTileCalls = 0; + VehicleVisualInstance.PerfDamageHeatMs = 0; + VehicleVisualInstance.PerfMaterialDupCount = 0; + } + + private void SetupPerfCombatScenario(ArenaSession session) + { + var p = session.State.Player; + float fwdX = MathF.Sin(p.Yaw); + float fwdZ = MathF.Cos(p.Yaw); + float rightX = -fwdZ; + float rightZ = fwdX; + + for (int i = 1; i <= 8 && i < session.State.Contenders.Count; i++) + { + float dist = 65f + (i % 4) * 11f; + float lat = (i - 4.5f) * 11f; + float tx = p.X + fwdX * dist + rightX * lat; + float tz = p.Z + fwdZ * dist + rightZ * lat; + session.SetContenderPose(session.State.Contenders[i].Id, tx, tz, p.Yaw + MathF.PI); + } + + for (int i = 0; i < 6 && i < session.State.Spectators.Spectators.Count; i++) + { + var s = session.State.Spectators.Spectators[i]; + float dist = 78f + (i % 3) * 12f; + float lat = (i - 2.5f) * 16f; + float sx = p.X + fwdX * dist + rightX * lat; + float sz = p.Z + fwdZ * dist + rightZ * lat; + session.SetSpectatorPose(s.Id, sx, sz, p.Yaw + MathF.PI); + session.State.Spectators.OnSpectatorDamaged(s, p.Id); + } + + var aimTarget = session.State.Contenders[1]; + _scriptedInput = new PlayerInput( + Throttle: 0.4f, + Steer: 0f, + AimWorldX: aimTarget.X, + AimWorldZ: aimTarget.Z, + Fire: true, + InteractPickup: false, + Brake: false); + + _arena.Sync(session, _elapsedSeconds, 0f); + UpdateCamera(1f); + _hud.Sync(session); } public override void _ExitTree() @@ -343,6 +394,7 @@ public partial class Main : Node3D GD.Print($"TimePhysicsProcessMs: avg={Avg(_perfTimePhysicsProcess):F2}"); GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}"); GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / _perfPhysicsTicks:F2} ai={ArenaSession.PerfAiMs / _perfPhysicsTicks:F2} drive={ArenaSession.PerfDriveMs / _perfPhysicsTicks:F2} world={ArenaSession.PerfWorldMs / _perfPhysicsTicks:F2} sync={ArenaSession.PerfBodySyncMs / _perfPhysicsTicks:F2} detect={ArenaSession.PerfDetectMs / _perfPhysicsTicks:F2} weapons={ArenaSession.PerfWeaponsMs / _perfPhysicsTicks:F2}"); + GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} tracers={_session?.State.Tracers.Count ?? 0}"); foreach (var kv in _arena.AssetCache.Vehicles) { int tris = 0; diff --git a/client/TerrainRenderer.cs b/client/TerrainRenderer.cs index ca03e2f..7f3c8ec 100644 --- a/client/TerrainRenderer.cs +++ b/client/TerrainRenderer.cs @@ -54,6 +54,8 @@ public partial class TerrainRenderer : Node3D public int BakedTileCount { get; private set; } public int DirtyRebakes { get; private set; } + public static double PerfBakeTileMs; + public static int PerfBakeTileCalls; public override void _Ready() { @@ -117,28 +119,41 @@ public partial class TerrainRenderer : Node3D const int totalTiles = TerrainField.TileGridCount * TerrainField.TileGridCount; - // 1. Always bake uninitialized tiles immediately + // 1. Always bake uninitialized tiles and structural/crater dirty tiles immediately + ulong structuralMask = terrain.StructuralDirtyTileMask; for (int tz = 0; tz < TerrainField.TileGridCount; tz++) { for (int tx = 0; tx < TerrainField.TileGridCount; tx++) { var tile = _tiles[tx, tz]; int version = terrain.TileVersions[tx, tz]; - if (tile.BakedVersion < 0 && tile.BakedVersion != version) + bool isUninitialized = tile.BakedVersion < 0 && tile.BakedVersion != version; + ulong bit = 1UL << (tz * TerrainField.TileGridCount + tx); + bool isStructuralDirty = (structuralMask & bit) != 0UL && tile.BakedVersion != version; + if (isUninitialized || isStructuralDirty) { BakeTile(tx, tz, tile, terrain); - BakedTileCount++; + if (isUninitialized) + { + BakedTileCount++; + } + else + { + DirtyRebakes++; + } tile.BakedVersion = version; + terrain.ClearStructuralDirtyTile(tx, tz); } } } - // 2. Budget dynamic tile rebakes (tracks/craters) to <= 2 per Sync in round-robin order + // 2. Budget remaining passive dynamic tile rebakes (tracks/scorch) to <= 2 per Sync in round-robin order int rebakedThisSync = 0; bool anyRemainingDirty = false; + int startCursor = _rebakeCursor; for (int step = 0; step < totalTiles; step++) { - int idx = (_rebakeCursor + step) % totalTiles; + int idx = (startCursor + step) % totalTiles; int tx = idx % TerrainField.TileGridCount; int tz = idx / TerrainField.TileGridCount; var tile = _tiles[tx, tz]; @@ -169,7 +184,7 @@ public partial class TerrainRenderer : Node3D public void UpdateTileLod(Vector3 camPos) { const float nearRadiusSq = 240f * 240f; - const float shadowRadiusSq = 220f * 220f; + const float shadowRadiusSq = 155f * 155f; for (int tz = 0; tz < TerrainField.TileGridCount; tz++) { for (int tx = 0; tx < TerrainField.TileGridCount; tx++) @@ -334,6 +349,7 @@ public partial class TerrainRenderer : Node3D private void BakeTile(int tx, int tz, TileNode tile, TerrainField terrain) { + long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; ClearCanvasChildren(tile.HeightCanvas); ClearCanvasChildren(tile.AlbedoCanvas); @@ -393,6 +409,11 @@ public partial class TerrainRenderer : Node3D tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; tile.AlbedoViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; + if (t0 != 0) + { + PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; + PerfBakeTileCalls++; + } } private static Polygon2D CreateClearQuad(Color color, Shader clearShader, ImageTexture whiteTex) diff --git a/client/VehicleAssetCache.cs b/client/VehicleAssetCache.cs index 4b8fcbb..a917e63 100644 --- a/client/VehicleAssetCache.cs +++ b/client/VehicleAssetCache.cs @@ -62,6 +62,7 @@ public sealed class VehicleAssetCache : IDisposable public required string Id { get; init; } public required string GlbPath { get; init; } public required Node3D SceneTemplate { get; init; } + public required ArrayMesh BakedDropMesh { get; init; } public required Vector3 Size { get; init; } public required float MinY { get; init; } public required Vector3 LocalModelForward { get; init; } @@ -444,7 +445,7 @@ public sealed class VehicleAssetCache : IDisposable // C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false); ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true); - ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f); + ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f, targetMinY: minY); return new VehicleTemplate { @@ -489,6 +490,7 @@ public sealed class VehicleAssetCache : IDisposable ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax); MergeGearSubMeshes(sceneRoot, gearId); + ArrayMesh bakedDropMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false, bakeVertexColor: false); Vector3 localFwd = new Vector3(0f, 0f, 1f); return new GearTemplate @@ -496,6 +498,7 @@ public sealed class VehicleAssetCache : IDisposable Id = gearId, GlbPath = glbPath, SceneTemplate = sceneRoot, + BakedDropMesh = bakedDropMesh, Size = bMax - bMin, MinY = bMin.Y, LocalModelForward = localFwd @@ -733,7 +736,8 @@ public sealed class VehicleAssetCache : IDisposable } } - // A. Merge static non-detachable sub-meshes per rigid articulated parent + // A. Merge static non-detachable sub-meshes per rigid articulated parent, and collapse PaintTag==0 surfaces on protected structural meshes + var mergedProtectedMeshes = new HashSet(); foreach (var (rigidParent, items) in staticGroups) { if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi)) @@ -748,6 +752,7 @@ public sealed class VehicleAssetCache : IDisposable { parentMi.MaterialOverride = null; parentMi.Mesh = merged; + mergedProtectedMeshes.Add(parentMi); for (int i = 0; i < items.Count; i++) { ReparentChildrenAndRemove(items[i].Mi); @@ -773,6 +778,26 @@ public sealed class VehicleAssetCache : IDisposable } } + for (int i = 0; i < allMeshes.Count; i++) + { + MeshInstance3D mi = allMeshes[i]; + if (GodotObject.IsInstanceValid(mi) && + protectedNodes.Contains(mi) && + !mergedProtectedMeshes.Contains(mi) && + CanMergeMeshInstance(mi) && + mi.Mesh is not null && + mi.Mesh.GetSurfaceCount() > 1) + { + var single = new List<(MeshInstance3D, Transform3D)>(1) { (mi, Transform3D.Identity) }; + ArrayMesh? collapsed = BuildMergedArrayMesh(single); + if (collapsed is not null && collapsed.GetSurfaceCount() < mi.Mesh.GetSurfaceCount()) + { + mi.MaterialOverride = null; + mi.Mesh = collapsed; + } + } + } + // Prune empty non-protected grouping nodes left behind PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes); @@ -844,7 +869,7 @@ public sealed class VehicleAssetCache : IDisposable PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, keptNodes); } - private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false) + private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false, bool bakeVertexColor = true) { var allMeshes = new List(); CollectAllMeshInstances(sceneRoot, allMeshes); @@ -859,7 +884,7 @@ public sealed class VehicleAssetCache : IDisposable } } - return BuildMergedArrayMesh(items, coarseMaterials) ?? new ArrayMesh(); + return BuildMergedArrayMesh(items, coarseMaterials, bakeVertexColor) ?? new ArrayMesh(); } private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet protectedNodes) @@ -895,7 +920,12 @@ public sealed class VehicleAssetCache : IDisposable int Transparency, int CullMode); - private static bool TryGetMaterialValueKey(Material mat, bool coarse, out StandardMatKey key) + private static bool TryGetMaterialValueKey( + Material mat, + bool coarse, + bool bakeVertexColor, + out StandardMatKey key, + out Color vertexTint) { if (mat is StandardMaterial3D sm && sm.AlbedoTexture is null && @@ -908,14 +938,16 @@ public sealed class VehicleAssetCache : IDisposable int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1 : (mName.Contains("signal") || mName.Contains("orange")) ? 2 : 0; - float colorScale = coarse ? 6f : 255f; - float pbrScale = coarse ? 2f : 100f; + bool useVCol = bakeVertexColor && paintTag == 0; + vertexTint = useVCol ? sm.AlbedoColor : Colors.White; + float colorScale = coarse ? 2f : 32f; + float pbrScale = coarse ? 0f : 4f; key = new StandardMatKey( paintTag, - (int)MathF.Round(sm.AlbedoColor.R * colorScale), - (int)MathF.Round(sm.AlbedoColor.G * colorScale), - (int)MathF.Round(sm.AlbedoColor.B * colorScale), - (int)MathF.Round(sm.AlbedoColor.A * 10f), + useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.R * colorScale), + useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.G * colorScale), + useVCol ? 0 : (int)MathF.Round(sm.AlbedoColor.B * colorScale), + useVCol ? 10 : (int)MathF.Round(sm.AlbedoColor.A * 10f), (int)MathF.Round(sm.Metallic * pbrScale), (int)MathF.Round(sm.Roughness * pbrScale), sm.EmissionEnabled, @@ -928,16 +960,21 @@ public sealed class VehicleAssetCache : IDisposable return true; } key = default; + vertexTint = Colors.White; return false; } private sealed class MaterialSurfaceBucket { public required Material? Material; - public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf)> Sources = new(); + public bool UsesVertexColor; + public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf, Color VertexTint)> Sources = new(); } - private static ArrayMesh? BuildMergedArrayMesh(List<(MeshInstance3D Mi, Transform3D RelXf)> items, bool coarseMaterials = false) + private static ArrayMesh? BuildMergedArrayMesh( + List<(MeshInstance3D Mi, Transform3D RelXf)> items, + bool coarseMaterials = false, + bool bakeVertexColor = true) { if (items.Count == 0) { @@ -946,7 +983,7 @@ public sealed class VehicleAssetCache : IDisposable var buckets = new List(); var bucketByMatId = new Dictionary(); - var bucketByMatVal = new Dictionary(); + var bucketByMatVal = new Dictionary<(StandardMatKey Key, bool UseVCol), MaterialSurfaceBucket>(); MaterialSurfaceBucket? nullMatBucket = null; for (int i = 0; i < items.Count; i++) @@ -966,6 +1003,7 @@ public sealed class VehicleAssetCache : IDisposable } Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s); MaterialSurfaceBucket bucket; + Color vTint = Colors.White; if (mat is null) { nullMatBucket ??= new MaterialSurfaceBucket { Material = null }; @@ -975,12 +1013,21 @@ public sealed class VehicleAssetCache : IDisposable } bucket = nullMatBucket; } - else if (TryGetMaterialValueKey(mat, coarseMaterials, out var matKey)) + else if (TryGetMaterialValueKey(mat, coarseMaterials, bakeVertexColor, out var matKey, out vTint)) { - if (!bucketByMatVal.TryGetValue(matKey, out bucket!)) + bool useVCol = bakeVertexColor && matKey.PaintTag == 0; + if (!bucketByMatVal.TryGetValue((matKey, useVCol), out bucket!)) { - bucket = new MaterialSurfaceBucket { Material = mat }; - bucketByMatVal[matKey] = bucket; + Material bucketMat = mat; + if (useVCol && mat is StandardMaterial3D sm) + { + var vcMat = (StandardMaterial3D)sm.Duplicate(); + vcMat.AlbedoColor = Colors.White; + vcMat.VertexColorUseAsAlbedo = true; + bucketMat = vcMat; + } + bucket = new MaterialSurfaceBucket { Material = bucketMat, UsesVertexColor = useVCol }; + bucketByMatVal[(matKey, useVCol)] = bucket; buckets.Add(bucket); } } @@ -994,7 +1041,7 @@ public sealed class VehicleAssetCache : IDisposable buckets.Add(bucket); } } - bucket.Sources.Add((mesh, s, relXf)); + bucket.Sources.Add((mesh, s, relXf, vTint)); } } @@ -1011,14 +1058,14 @@ public sealed class VehicleAssetCache : IDisposable bool anyTangent = false; bool anyUv = false; bool anyUv2 = false; - bool anyColor = false; + bool anyColor = bucket.UsesVertexColor; int totalVerts = 0; int totalIndices = 0; - var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, int VertCount, int IndexCount)>(bucket.Sources.Count); + var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, Color VTint, int VertCount, int IndexCount)>(bucket.Sources.Count); for (int s = 0; s < bucket.Sources.Count; s++) { - var (mesh, surfIdx, relXf) = bucket.Sources[s]; + var (mesh, surfIdx, relXf, vTint) = bucket.Sources[s]; var arr = mesh.SurfaceGetArrays(surfIdx); if (arr.Count <= (int)Mesh.ArrayType.Vertex || arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array) @@ -1045,7 +1092,7 @@ public sealed class VehicleAssetCache : IDisposable totalVerts += verts.Length; totalIndices += idxCount; - cachedArrays.Add((arr, relXf, verts.Length, idxCount)); + cachedArrays.Add((arr, relXf, vTint, verts.Length, idxCount)); } if (totalVerts == 0 || totalIndices == 0) @@ -1065,7 +1112,7 @@ public sealed class VehicleAssetCache : IDisposable int iOffset = 0; for (int c = 0; c < cachedArrays.Count; c++) { - var (arr, relXf, vCount, idxCount) = cachedArrays[c]; + var (arr, relXf, vTint, vCount, idxCount) = cachedArrays[c]; Vector3[] srcVerts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array(); bool flipWinding = relXf.Basis.Determinant() < 0f; Basis normBasis = relXf.Basis.Inverse().Transposed(); @@ -1140,11 +1187,20 @@ public sealed class VehicleAssetCache : IDisposable { if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) { - Array.Copy(arr[(int)Mesh.ArrayType.Color].AsColorArray(), 0, outColors, vOffset, vCount); + Color[] srcC = arr[(int)Mesh.ArrayType.Color].AsColorArray(); + if (bucket.UsesVertexColor) + { + for (int v = 0; v < vCount; v++) outColors[vOffset + v] = srcC[v] * vTint; + } + else + { + Array.Copy(srcC, 0, outColors, vOffset, vCount); + } } else { - for (int v = 0; v < vCount; v++) outColors[vOffset + v] = Colors.White; + Color fill = bucket.UsesVertexColor ? vTint : Colors.White; + for (int v = 0; v < vCount; v++) outColors[vOffset + v] = fill; } } @@ -1199,7 +1255,7 @@ public sealed class VehicleAssetCache : IDisposable return outMesh.GetSurfaceCount() > 0 ? outMesh : null; } - private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize) + private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize, float targetMinY) { var outMesh = new ArrayMesh(); float invCell = 1f / MathF.Max(0.02f, cellSize); @@ -1223,6 +1279,9 @@ public sealed class VehicleAssetCache : IDisposable bool hasNorm = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array; Vector3[]? norms = hasNorm ? arr[(int)Mesh.ArrayType.Normal].AsVector3Array() : null; + bool hasColor = arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray; + Color[]? colors = hasColor ? arr[(int)Mesh.ArrayType.Color].AsColorArray() : null; + bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array; int[]? indices = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null; int triVertCount = indices is not null ? indices.Length : verts.Length; @@ -1231,7 +1290,9 @@ public sealed class VehicleAssetCache : IDisposable var vertToCellIdx = new int[verts.Length]; var accumPos = new List(verts.Length / 2 + 16); var accumNorm = norms is not null ? new List(verts.Length / 2 + 16) : null; + var accumColor = colors is not null ? new List(verts.Length / 2 + 16) : null; var counts = new List(verts.Length / 2 + 16); + var cellMinY = new List(verts.Length / 2 + 16); for (int v = 0; v < verts.Length; v++) { @@ -1247,13 +1308,17 @@ public sealed class VehicleAssetCache : IDisposable cellToNewIdx[key] = ci; accumPos.Add(p); if (accumNorm is not null) accumNorm.Add(norms![v]); + if (accumColor is not null) accumColor.Add(colors![v]); counts.Add(1); + cellMinY.Add(p.Y); } else { accumPos[ci] += p; if (accumNorm is not null) accumNorm[ci] += norms![v]; + if (accumColor is not null) accumColor[ci] += colors![v]; counts[ci]++; + if (p.Y < cellMinY[ci]) cellMinY[ci] = p.Y; } vertToCellIdx[v] = ci; } @@ -1287,20 +1352,30 @@ public sealed class VehicleAssetCache : IDisposable var outVerts = new Vector3[accumPos.Count]; Vector3[]? outNorms = accumNorm is not null ? new Vector3[accumPos.Count] : null; + Color[]? outColors = accumColor is not null ? new Color[accumPos.Count] : null; for (int i = 0; i < accumPos.Count; i++) { - outVerts[i] = accumPos[i] / counts[i]; + Vector3 avg = accumPos[i] / counts[i]; + // Preserve exact ground-contacting vertex minY so far LOD ChassisDrops never float or sink + float y = cellMinY[i] <= targetMinY + 0.08f ? cellMinY[i] : avg.Y; + if (y < targetMinY) y = targetMinY; + outVerts[i] = new Vector3(avg.X, y, avg.Z); if (outNorms is not null) { Vector3 n = accumNorm![i]; outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up; } + if (outColors is not null) + { + outColors[i] = accumColor![i] / counts[i]; + } } var newArr = new Godot.Collections.Array(); newArr.Resize((int)Mesh.ArrayType.Max); newArr[(int)Mesh.ArrayType.Vertex] = outVerts; if (outNorms is not null) newArr[(int)Mesh.ArrayType.Normal] = outNorms; + if (outColors is not null) newArr[(int)Mesh.ArrayType.Color] = outColors; newArr[(int)Mesh.ArrayType.Index] = outIndices.ToArray(); int newSurf = outMesh.GetSurfaceCount(); diff --git a/client/VehicleVisualInstance.cs b/client/VehicleVisualInstance.cs index 24caff7..8e36ae1 100644 --- a/client/VehicleVisualInstance.cs +++ b/client/VehicleVisualInstance.cs @@ -73,6 +73,8 @@ public sealed class VehicleVisualInstance private readonly VehicleAssetCache _cache; private readonly VehicleAssetCache.VehicleTemplate _template; private readonly Dictionary _hardpoints = new(StringComparer.Ordinal); + private readonly List _hardpointList = new(); + private readonly List<(int X, int Y)> _activeCells = new(); private readonly Dictionary _joints = new(StringComparer.Ordinal); private readonly Dictionary _namedNodes = new(StringComparer.Ordinal); private readonly Dictionary _restLocalByName = new(StringComparer.Ordinal); @@ -83,23 +85,30 @@ public sealed class VehicleVisualInstance private readonly HashSet _shearedHardpoints = new(StringComparer.Ordinal); private readonly VehicleRigAnimator.RigState _rigState = new(); + private readonly VehicleVisualRole _role; private readonly string _chassisId; private MeshInstance3D? _lodStaticMesh; private bool _isStaticLod; private bool _castShadows = true; + private bool _hasAnyStrippedCell; + + public static double PerfDamageHeatMs; + public static int PerfMaterialDupCount; private VehicleVisualInstance( VehicleAssetCache cache, VehicleAssetCache.VehicleTemplate template, Node3D root, Node3D modelRoot, - string chassisId) + string chassisId, + VehicleVisualRole role) { _cache = cache; _template = template; Root = root; ModelRoot = modelRoot; _chassisId = chassisId; + _role = role; int w = template.Package.GridWidth; int h = template.Package.GridHeight; @@ -124,6 +133,7 @@ public sealed class VehicleVisualInstance public IReadOnlyDictionary Joints => _joints; public int BoundHardpointCount => _hardpoints.Count; public bool IsStaticLod => _isStaticLod; + public bool HasAnyStrippedCell => _hasAnyStrippedCell; public void SetLodState(bool useStaticLod, bool castShadows) { @@ -146,6 +156,10 @@ public sealed class VehicleVisualInstance } return; } + if (_hasAnyStrippedCell) + { + useStaticLod = false; + } if (_isStaticLod != useStaticLod) { _isStaticLod = useStaticLod; @@ -197,7 +211,7 @@ public sealed class VehicleVisualInstance }; ApplyRoleTint(dropMesh, role); root.AddChild(dropMesh); - return new VehicleVisualInstance(cache, template, root, dropMesh, chassisId); + return new VehicleVisualInstance(cache, template, root, dropMesh, chassisId, role); } if (template.SceneTemplate.Duplicate() is not Node3D modelRoot) @@ -223,7 +237,7 @@ public sealed class VehicleVisualInstance } root.AddChild(lodMesh); - var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId) + var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId, role) { _lodStaticMesh = lodMesh }; @@ -315,12 +329,14 @@ public sealed class VehicleVisualInstance throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing anchor node '{rec.AnchorId}'."); } - _hardpoints[hp.Id] = new BoundHardpoint + var bh = new BoundHardpoint { Spec = hp, AnchorInfo = anchorInfo, AnchorNode = anchorNode }; + _hardpoints[hp.Id] = bh; + _hardpointList.Add(bh); } // Apply role palette tinting to painted hull meshes before binding per-cell damage clones @@ -332,6 +348,16 @@ public sealed class VehicleVisualInstance // Bind detachable exterior armor/shroud parts to their (CellX, CellY) int w = pkg.GridWidth; int h = pkg.GridHeight; + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + if (spec.IsActive(x, y)) + { + _activeCells.Add((x, y)); + } + } + } foreach (var dp in _template.DetachableParts) { if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h) @@ -415,81 +441,84 @@ public sealed class VehicleVisualInstance /// public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity) { - int w = Math.Min(grid.Spec.Width, _template.Package.GridWidth); - int h = Math.Min(grid.Spec.Height, _template.Package.GridHeight); + long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position; // 1. Part-by-cell detachment & cell scorch/heat tinting - for (int y = 0; y < h; y++) + for (int c = 0; c < _activeCells.Count; c++) { - for (int x = 0; x < w; x++) + var (x, y) = _activeCells[c]; + float armor = grid.Armor[x, y]; + var parts = _cellParts[x, y]; + if (!_strippedCells[x, y] && armor <= 0.01f) { - if (!grid.Spec.IsActive(x, y)) - { - continue; - } - - float armor = grid.Armor[x, y]; - var parts = _cellParts[x, y]; - if (!_strippedCells[x, y] && armor <= 0.01f) - { - _strippedCells[x, y] = true; - for (int i = 0; i < parts.Count; i++) - { - var pb = parts[i]; - if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node)) - { - pb.Detached = true; - debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true); - } - } - continue; - } - - if (parts.Count == 0) - { - continue; - } - - float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); - float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f); - float heatGlow = Math.Clamp((grid.Temperature[x, y] - 65f) / 110f, 0f, 1f); - float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f; - - if (dmgFrac < 0.25f && heatGlow < 0.05f) - { - continue; - } - + _strippedCells[x, y] = true; + _hasAnyStrippedCell = true; for (int i = 0; i < parts.Count; i++) { var pb = parts[i]; - if (pb.Detached || !GodotObject.IsInstanceValid(pb.Node)) + if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node)) { - continue; + pb.Detached = true; + pb.Node.Visible = true; + debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true); } - if (MathF.Abs(pb.LastTintScore - tintScore) < 0.5f) - { - continue; - } - pb.LastTintScore = tintScore; - ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow); } + continue; + } + + if (parts.Count == 0) + { + continue; + } + + float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); + float temp = grid.Temperature[x, y]; + if (armor > maxArmor * 0.75f && temp < 70.5f) + { + continue; + } + + float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f); + float heatGlow = Math.Clamp((temp - 65f) / 110f, 0f, 1f); + float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f; + + if (dmgFrac < 0.25f && heatGlow < 0.05f) + { + continue; + } + + for (int i = 0; i < parts.Count; i++) + { + var pb = parts[i]; + if (pb.Detached || !GodotObject.IsInstanceValid(pb.Node)) + { + continue; + } + if (MathF.Abs(pb.LastTintScore - tintScore) < 0.5f) + { + continue; + } + pb.LastTintScore = tintScore; + ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow); } } // 2. Hardpoint shear & mounted gear heat glow - foreach (var bh in _hardpoints.Values) + for (int i = 0; i < _hardpointList.Count; i++) { + var bh = _hardpointList[i]; if (!_shearedHardpoints.Contains(bh.Spec.Id) && !grid.IsHardpointOperational(bh.Spec)) { _shearedHardpoints.Add(bh.Spec.Id); + _hasAnyStrippedCell = true; if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) { Node3D sheared = bh.GearNode; bh.GearNode = null; bh.MountedModuleId = null; bh.GearHeatMaterials.Clear(); + sheared.Visible = true; debris.SpawnDetachedPart(sheared, blastOrigin, vehicleVelocity, impulseScale: 1.15f, applyScorch: true); } continue; @@ -510,11 +539,22 @@ public sealed class VehicleVisualInstance for (int m = 0; m < bh.GearHeatMaterials.Count; m++) { StandardMaterial3D gm = bh.GearHeatMaterials[m]; - gm.EmissionEnabled = heatFrac > 0.02f; - gm.Emission = new Color(1.0f, 0.34f, 0.08f); - gm.EmissionEnergyMultiplier = heatFrac * 2.2f; + bool wantEmit = heatFrac > 0.02f; + if (gm.EmissionEnabled != wantEmit || wantEmit) + { + gm.EmissionEnabled = wantEmit; + if (wantEmit) + { + gm.Emission = new Color(1.0f, 0.34f, 0.08f); + gm.EmissionEnergyMultiplier = heatFrac * 2.2f; + } + } } } + if (t0 != 0) + { + PerfDamageHeatMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; + } } public static Node3D CreateStandaloneGearVisual(VehicleAssetCache cache, ModuleSpec mod) @@ -522,13 +562,13 @@ public sealed class VehicleVisualInstance var list = new List(); GearVisualRecipe recipe = ResolveGearRecipe(mod); var template = cache.GetOrLoadGear(recipe.GearGlbId); - if (template.SceneTemplate.Duplicate() is not Node3D node) + var node = new MeshInstance3D { - return new Node3D { Name = $"Gear_{mod.Id}" }; - } - node.Name = $"GearDrop_{mod.Id}"; - node.Scale = recipe.VariantScale; - node.Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f); + Name = $"GearDrop_{mod.Id}", + Mesh = template.BakedDropMesh, + Scale = recipe.VariantScale, + Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f) + }; if (recipe.PaintTint.HasValue || recipe.AccentTint.HasValue) { ApplyGearVariantTint(node, recipe.PaintTint, recipe.AccentTint, list); @@ -544,9 +584,18 @@ public sealed class VehicleVisualInstance { GearVisualRecipe recipe = ResolveGearRecipe(mod); VehicleAssetCache.GearTemplate gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId); - if (gearTemplate.SceneTemplate.Duplicate() is not Node3D gearNode) + Node3D gearNode; + if (_role == VehicleVisualRole.Player) { - throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'."); + if (gearTemplate.SceneTemplate.Duplicate() is not Node3D dup) + { + throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'."); + } + gearNode = dup; + } + else + { + gearNode = new MeshInstance3D { Mesh = gearTemplate.BakedDropMesh }; } gearNode.Name = $"Mounted_{mod.Id}_{hp.Id}"; @@ -789,6 +838,7 @@ public sealed class VehicleVisualInstance StandardMaterial3D copy = src is StandardMaterial3D sm ? (StandardMaterial3D)sm.Duplicate() : new StandardMaterial3D { AlbedoColor = new Color(0.32f, 0.34f, 0.30f), Roughness = 0.6f, Metallic = 0.35f }; + PerfMaterialDupCount++; binding.Node.SetSurfaceOverrideMaterial(s, copy); binding.Materials.Add((copy, copy.AlbedoColor, copy.Roughness)); } diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index 681fda2..6d0076f 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -198,6 +198,72 @@ public partial class Smoke : Node } } + // Regression check (Finding 4): 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants) + // and passive Track throttling preserves DirtyTileMask until all tiles are baked without skipping via _rebakeCursor. + { + // Flush any lingering track rebakes first so baseline is clean + for (int flush = 0; flush < 32 && _main.Session.State.Terrain.DirtyTileMask != 0UL; flush++) + { + _main.Terrain.Sync(_main.Session.State.Terrain); + } + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + (float Qx, float Qz)[] quadrants = { (-1f, -1f), (1f, -1f), (-1f, 1f), (1f, 1f) }; + float[] qGpuBefore = new float[4]; + if (!isHeadless) + { + for (int q = 0; q < 4; q++) + { + Check(_main.Terrain.TrySampleBakedHeight(quadrants[q].Qx, quadrants[q].Qz, out qGpuBefore[q]), + $"Expected GPU readback before 4-tile boundary crater at quadrant {q}"); + } + } + + int rebakes4Before = _main.Terrain.DirtyRebakes; + _main.Session.State.Terrain.StampCrater(0f, 0f, radius: 6f, depth: 1.4f); + _main.Terrain.Sync(_main.Session.State.Terrain); // Sync#1 + Check(_main.Terrain.DirtyRebakes == rebakes4Before + 4, + $"Expected 4-tile boundary crater at (0,0) to bake all 4 tiles on Sync#1, got {_main.Terrain.DirtyRebakes - rebakes4Before}"); + Check(_main.Session.State.Terrain.StructuralDirtyTileMask == 0UL, + "Expected StructuralDirtyTileMask == 0 after Sync#1 on 4-tile boundary crater"); + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + if (!isHeadless) + { + for (int q = 0; q < 4; q++) + { + float qCpu = _main.Session.State.Terrain.SampleHeight(quadrants[q].Qx, quadrants[q].Qz); + bool ok = _main.Terrain.TrySampleBakedHeight(quadrants[q].Qx, quadrants[q].Qz, out float qGpu); + Check(ok, $"Expected GPU readback on quadrant {q} after 4-tile boundary crater"); + if (ok) + { + float qErr = MathF.Abs(qGpu - qCpu); + GD.Print($"SMOKE INFO: 4-tile crater Q{q} ({quadrants[q].Qx},{quadrants[q].Qz}) cpu={qCpu:F4}m gpu={qGpu:F4}m err={qErr:F4}m"); + Check(qErr <= 0.20f, $"4-tile crater quadrant {q} GPU error {qErr:F4}m > 0.20m"); + Check(qGpu < qGpuBefore[q] - 0.35f, $"4-tile crater quadrant {q} did not depress on Sync#1 (before={qGpuBefore[q]:F4}, after={qGpu:F4})"); + } + } + } + + // Stamp 3 passive tracks in adjacent tiles so _rebakeCursor must advance across Sync#1 and Sync#2 without skipping + int rebakesTrackBefore = _main.Terrain.DirtyRebakes; + _main.Session.State.Terrain.StampTrack(-480f, -480f, 0f, 2f, 3f); + _main.Session.State.Terrain.StampTrack(-288f, -480f, 0f, 2f, 3f); + _main.Session.State.Terrain.StampTrack(-96f, -480f, 0f, 2f, 3f); + _main.Terrain.Sync(_main.Session.State.Terrain); + Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 2, + $"Expected Sync#1 to throttle 3 passive tracks to 2 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); + Check(_main.Session.State.Terrain.DirtyTileMask != 0UL, + "Expected DirtyTileMask to stay non-zero while 1 passive track tile remains dirty"); + _main.Terrain.Sync(_main.Session.State.Terrain); + Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 3, + $"Expected Sync#2 to bake remaining 3rd passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); + Check(_main.Session.State.Terrain.DirtyTileMask == 0UL, + "Expected DirtyTileMask == 0 after all passive track tiles baked"); + } + _main.SetPhysicsProcess(true); await VerifyHudAndShadersAsync(isHeadless); @@ -409,6 +475,46 @@ public partial class Smoke : Node Check(raptorHoleScanned > 1000, $"Expected > 1000 inactive hole pixels scanned on Raptor, got {raptorHoleScanned}"); Check(raptorHoleLit == 0, $"Expected 0 lit/opaque pixels in inactive Raptor cell holes, got {raptorHoleLit}"); + // Finding 5 GPU check: LabelsOverlay redraws on temp-only change & compatibility highlights update when Cargo[0] swaps at unchanged index 0 + { + raptorGrid.Cargo.Clear(); + Check(raptorGrid.TryAddCargo(Catalog.Autocannon), "Expected Autocannon in Raptor Cargo[0]"); + vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0); + vpGrid.SetThermalInstant(false); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + int drawCountBeforeTemp = vpGrid.LabelsDrawCount; + string? tagBeforeTemp = vpGrid.GetLastDrawnLabel("hp.engine.chest"); + var cargoImgWeapon = gridVp.GetTexture().GetImage(); + + // Temp-only change (no armor hit, no mount change) + raptorGrid.InjectHardpointHeat("hp.engine.chest", 4200f); + raptorGrid.StepHeat(0.1f); + vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + int drawCountAfterTemp = vpGrid.LabelsDrawCount; + string? tagAfterTemp = vpGrid.GetLastDrawnLabel("hp.engine.chest"); + Check(drawCountAfterTemp > drawCountBeforeTemp, + $"Expected LabelsOverlay to redraw on temp-only change ({drawCountBeforeTemp} -> {drawCountAfterTemp})"); + Check(!string.Equals(tagBeforeTemp, tagAfterTemp, StringComparison.Ordinal), + $"Expected engine temp label text to update on temp-only change ('{tagBeforeTemp}' -> '{tagAfterTemp}')"); + + // Cargo[0] replacement at unchanged selectedCargoIndex == 0 (Weapon -> Radiator) + raptorGrid.Cargo[0] = Catalog.CopperRad; + vpGrid.SetGrid(raptorGrid, selectedCargoIndex: 0); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var cargoImgRad = gridVp.GetTexture().GetImage(); + int cargoDiff = CountDifferentPixels(cargoImgWeapon, cargoImgRad, 0.05f); + GD.Print($"SMOKE INFO: InventoryGrid Cargo[0] swap diff pixels={cargoDiff}, label '{tagBeforeTemp}'->'{tagAfterTemp}'"); + Check(cargoDiff > 50, + $"Expected Cargo[0] replacement at unchanged index 0 to update compatibility highlight pixels (>50), got {cargoDiff}"); + } + gridVp.QueueFree(); // GPU verification for panel_chrome.gdshader @@ -789,6 +895,27 @@ public partial class Smoke : Node } GD.Print($"SMOKE INFO: ChassisDrop max ground err={maxGroundErr:F4}m across {added.Count} chassis"); + // Also verify far LOD (BakedLodFarMesh) ChassisDrop grounding stays <= 0.05m across all 15 chassis + float maxFarGroundErr = 0f; + for (int i = 0; i < added.Count; i++) + { + var d = added[i]; + Node3D? dropNode = _main.Arena.GetNodeOrNull($"GroundDrops/Drop_{d.Id}"); + Node3D? actorNode = dropNode?.GetNodeOrNull($"Actor_{d.Chassis!.Id}"); + MeshInstance3D? dropMesh = actorNode?.GetNodeOrNull($"Model_{d.Chassis!.Id}"); + if (dropNode is not null && actorNode is not null && dropMesh is not null) + { + dropMesh.Mesh = cache.GetOrLoadVehicle(d.Chassis!.Id).BakedLodFarMesh; + float minFarWorldY = ComputeSubtreeMinWorldY(actorNode, dropNode.Position.Y); + float terrainY = _main.Session.State.Terrain.SampleHeight(d.X, d.Z); + float err = MathF.Abs(minFarWorldY - terrainY); + if (err > maxFarGroundErr) maxFarGroundErr = err; + Check(err <= 0.05f, + $"Far LOD ChassisDrop '{d.Chassis!.Id}' buried/floating: minFarWorldY={minFarWorldY:F4}m terrainY={terrainY:F4}m err={err:F4}m"); + } + } + GD.Print($"SMOKE INFO: Far LOD ChassisDrop max ground err={maxFarGroundErr:F4}m across {added.Count} chassis"); + for (int i = 0; i < added.Count; i++) { added[i].PickedUp = true; @@ -929,6 +1056,49 @@ public partial class Smoke : Node Check(sawPatron, "Expected at least one alive Patron spectator in arena"); } + // 9. Finding 3: Stripped distant rig (180m) detaches debris immediately without popping armor back on at far LOD + { + var debris = new DebrisSystem { Name = "SmokeDistantStripTest" }; + AddChild(debris); + var specGrid = Catalog.CreateWithDefaultLoadout(Catalog.Anvil); + var specVis = VehicleVisualInstance.Create(cache, "anvil", VehicleVisualRole.SpectatorPatron); + specVis.Root.Position = new Vector3(0f, 0f, 180f); + AddChild(specVis.Root); + specVis.SyncMountedGear(specGrid); + specVis.SetLodState(useStaticLod: true, castShadows: false); + Check(specVis.IsStaticLod && !specVis.ModelRoot.Visible, + "Expected intact distant rig at 180m to start in static far LOD"); + + int stripCx = -1, stripCy = -1; + for (int cy = 0; cy < specGrid.Spec.Height && stripCx < 0; cy++) + { + for (int cx = 0; cx < specGrid.Spec.Width; cx++) + { + if (specVis.CountDetachablePartsForCell(cx, cy) > 0) + { + stripCx = cx; + stripCy = cy; + break; + } + } + } + Check(stripCx >= 0, "Expected Anvil distant rig to have detachable cell parts"); + if (stripCx >= 0) + { + specGrid.Armor[stripCx, stripCy] = 0f; + } + + specVis.SyncDamageAndHeat(specGrid, debris, Vector3.Zero); + specVis.SetLodState(useStaticLod: true, castShadows: false); + Check(debris.ActiveCount >= 1, + $"Expected distant stripped rig at 180m to detach debris immediately, got {debris.ActiveCount}"); + Check(specVis.HasAnyStrippedCell && !specVis.IsStaticLod && specVis.ModelRoot.Visible, + "Expected distant stripped rig to keep ModelRoot visible without popping armor back on at far LOD"); + + specVis.Root.QueueFree(); + debris.QueueFree(); + } + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); } diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs index 927c29b..2981b61 100644 --- a/src/RustToDust.Core/MatchRules.cs +++ b/src/RustToDust.Core/MatchRules.cs @@ -103,63 +103,36 @@ namespace RustToDust.Core hasGoal = true; } - // 2. Find nearest hostile contender with actual line-of-sight (staggered every 3 ticks when tickIndex >= 0) + // 2. Find nearest hostile contender with actual live line-of-sight every tick ContenderState? target = null; float bestEnemyDistSq = 215f * 215f; - bool refreshLos = tickIndex < 0 || ((ai.Id + tickIndex) % 3 == 0); - if (refreshLos) + float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight); + for (int j = 0; j < state.Contenders.Count; j++) { - float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight); - for (int j = 0; j < state.Contenders.Count; j++) + var other = state.Contenders[j]; + if (other.Id == ai.Id || !other.Alive) { - var other = state.Contenders[j]; - if (other.Id == ai.Id || !other.Alive) - { - continue; - } - - float dx = other.X - ai.X; - float dz = other.Z - ai.Z; - float d2 = dx * dx + dz * dz; - if (d2 >= bestEnemyDistSq) - { - continue; - } - - if (hasLos is not null && - !hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z)) - { - continue; - } - - bestEnemyDistSq = d2; - target = other; - } - ai.AiTargetContenderId = target?.Id; - } - else if (ai.AiTargetContenderId is { } tid && tid >= 0 && tid < state.Contenders.Count) - { - var cached = state.Contenders[tid]; - if (cached.Alive && cached.Id != ai.Id) - { - float dx = cached.X - ai.X; - float dz = cached.Z - ai.Z; - float d2 = dx * dx + dz * dz; - if (d2 < bestEnemyDistSq) - { - bestEnemyDistSq = d2; - target = cached; - } - else - { - ai.AiTargetContenderId = null; - } - } - else - { - ai.AiTargetContenderId = null; + continue; } + + float dx = other.X - ai.X; + float dz = other.Z - ai.Z; + float d2 = dx * dx + dz * dz; + if (d2 >= bestEnemyDistSq) + { + continue; + } + + if (hasLos is not null && + !hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z)) + { + continue; + } + + bestEnemyDistSq = d2; + target = other; } + ai.AiTargetContenderId = target?.Id; // 3. Scavenge nearby upgrades when safe if (!hasGoal && ai.AiScavengeCooldown <= 0f) diff --git a/src/RustToDust.Core/SpectatorRing.cs b/src/RustToDust.Core/SpectatorRing.cs index ad163f5..f07d3bd 100644 --- a/src/RustToDust.Core/SpectatorRing.cs +++ b/src/RustToDust.Core/SpectatorRing.cs @@ -154,10 +154,6 @@ namespace RustToDust.Core { continue; } - if (tickIndex >= 0 && spec.Stance == SpectatorStance.Neutral && ((spec.Id + tickIndex) % 6 != 0)) - { - continue; - } if (hasLos is null || hasLos(spec, contender)) { @@ -245,7 +241,7 @@ namespace RustToDust.Core } // If full with a stale expired no-LOS watcher while a Neutral watcher has live LOS, rotate one slot. - if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos, tickIndex)) + if (currentCleared == allowedCleared && hasLos is not null && AnyNeutralHasLos(contender, hasLos)) { int staleIdx = FindStaleNoLosCleared(contender.Id); if (staleIdx >= 0) @@ -255,7 +251,7 @@ namespace RustToDust.Core } } - // Pass 1: Spectators with direct live LOS to the offender. + // Pass 1: Spectators with direct live LOS to the offender (nearest open-LOS watcher first). while (currentCleared < allowedCleared) { int bestIdx = -1; @@ -268,7 +264,11 @@ namespace RustToDust.Core { continue; } - if (tickIndex >= 0 && ((spec.Id + tickIndex) % 6 != 0)) + + float dx = spec.X - contender.X; + float dz = spec.Z - contender.Z; + float d2 = dx * dx + dz * dz; + if (d2 >= bestDistSq) { continue; } @@ -278,14 +278,8 @@ namespace RustToDust.Core continue; } - float dx = spec.X - contender.X; - float dz = spec.Z - contender.Z; - float d2 = dx * dx + dz * dz; - if (d2 < bestDistSq) - { - bestDistSq = d2; - bestIdx = i; - } + bestDistSq = d2; + bestIdx = i; } if (bestIdx < 0) @@ -503,13 +497,12 @@ namespace RustToDust.Core return bestIdx; } - private bool AnyNeutralHasLos(in RingContact contender, Func hasLos, int tickIndex) + private bool AnyNeutralHasLos(in RingContact contender, Func hasLos) { for (int i = 0; i < _spectators.Count; i++) { var spec = _spectators[i]; if (spec.Alive && spec.Stance == SpectatorStance.Neutral && - (tickIndex < 0 || ((spec.Id + tickIndex) % 6 == 0)) && hasLos(spec, contender)) { return true; diff --git a/src/RustToDust.Core/TerrainField.cs b/src/RustToDust.Core/TerrainField.cs index dba91a2..035e149 100644 --- a/src/RustToDust.Core/TerrainField.cs +++ b/src/RustToDust.Core/TerrainField.cs @@ -36,6 +36,9 @@ namespace RustToDust.Core public const float HalfExtent = 768f; public const int TileGridCount = 8; public const float TileSize = ArenaSize / TileGridCount; // 192m + private const int AccelGridCount = 64; + private const float AccelCellSize = ArenaSize / AccelGridCount; // 24m + private const int AccelCellCount = AccelGridCount * AccelGridCount; public const float MinWorldHeight = -18f; public const float MaxWorldHeight = 52f; public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m @@ -63,7 +66,8 @@ namespace RustToDust.Core private readonly List _brushes = new(); private readonly List _brushPrecomps = new(); private readonly List[,] _tileBrushIndices = new List[TileGridCount, TileGridCount]; - private readonly float[,] _tileMaxHeight = new float[TileGridCount, TileGridCount]; + private readonly List[] _cellBrushIndices = new List[AccelCellCount]; + private readonly float[] _cellMaxHeight = new float[AccelCellCount]; private readonly Queue _dynamicDecalSlots = new(); private int _nextBrushId = 1; @@ -78,14 +82,26 @@ namespace RustToDust.Core _tileBrushIndices[tx, tz] = new List(32); } } + for (int c = 0; c < AccelCellCount; c++) + { + _cellBrushIndices[c] = new List(4); + } } public ulong Seed { get; } public IReadOnlyList Brushes => _brushes; public int[,] TileVersions { get; } public ulong DirtyTileMask { get; private set; } + public ulong StructuralDirtyTileMask { get; private set; } - public void ClearDirtyMask() => DirtyTileMask = 0UL; + public void ClearDirtyMask() + { + DirtyTileMask = 0UL; + StructuralDirtyTileMask = 0UL; + } + + public void ClearStructuralDirtyTile(int tx, int tz) => + StructuralDirtyTileMask &= ~(1UL << (tz * TileGridCount + tx)); public IReadOnlyList GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz]; @@ -365,18 +381,19 @@ namespace RustToDust.Core { float cx = Math.Clamp(x, -HalfExtent, HalfExtent); float cz = Math.Clamp(z, -HalfExtent, HalfExtent); - WorldToTile(cx, cz, out int tx, out int tz); + WorldToAccelCell(cx, cz, out int acx, out int acz); + + var indices = _cellBrushIndices[acz * AccelGridCount + acx]; + if (indices.Count == 0) + { + return 0f; + } float h = 0f; - var indices = _tileBrushIndices[tx, tz]; for (int i = 0; i < indices.Count; i++) { int idx = indices[i]; var b = _brushes[idx]; - if (b.Kind == TerrainBrushKind.Scorch) - { - continue; - } h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz); } @@ -429,8 +446,44 @@ namespace RustToDust.Core float cx = Math.Clamp(px, -HalfExtent, HalfExtent); float cz = Math.Clamp(pz, -HalfExtent, HalfExtent); - WorldToTile(cx, cz, out int tx, out int tz); - if (py <= _tileMaxHeight[tx, tz]) + WorldToAccelCell(cx, cz, out int acx, out int acz); + float cellMax = _cellMaxHeight[acz * AccelGridCount + acx] + 0.02f; + + // Fast-skip consecutive cells strictly below the ray without sampling brushes + while (py > cellMax + 0.02f && + ct < maxDistance && + px >= -HalfExtent && px <= HalfExtent && + pz >= -HalfExtent && pz <= HalfExtent) + { + float cellMinX = -HalfExtent + acx * AccelCellSize; + float cellMaxX = cellMinX + AccelCellSize; + float cellMinZ = -HalfExtent + acz * AccelCellSize; + float cellMaxZ = cellMinZ + AccelCellSize; + float txExit = dx > 1e-6f ? (cellMaxX - px) / dx : (dx < -1e-6f ? (cellMinX - px) / dx : float.PositiveInfinity); + float tzExit = dz > 1e-6f ? (cellMaxZ - pz) / dz : (dz < -1e-6f ? (cellMinZ - pz) / dz : float.PositiveInfinity); + float tExit = MathF.Min(txExit, tzExit); + float advance = MathF.Min(tExit + 0.02f, maxDistance - ct); + if (advance <= 0.02f) + { + break; + } + float ey = py + dy * advance; + if (ey <= cellMax + 0.02f) + { + break; + } + prevT = ct + MathF.Min(tExit, maxDistance - ct); + ct += advance; + px = ox + dx * ct; + py = oy + dy * ct; + pz = oz + dz * ct; + cx = Math.Clamp(px, -HalfExtent, HalfExtent); + cz = Math.Clamp(pz, -HalfExtent, HalfExtent); + WorldToAccelCell(cx, cz, out acx, out acz); + cellMax = _cellMaxHeight[acz * AccelGridCount + acx] + 0.02f; + } + + if (py <= cellMax) { float diff = py - SampleHeight(px, pz); if (diff <= 0f) @@ -469,18 +522,6 @@ namespace RustToDust.Core } float step = ct < 160f ? 1.5f : 2.5f; - if (py > _tileMaxHeight[tx, tz] + 1.5f) - { - float farT = MathF.Min(ct + 14f, maxDistance); - float fx = Math.Clamp(ox + dx * farT, -HalfExtent, HalfExtent); - float fz = Math.Clamp(oz + dz * farT, -HalfExtent, HalfExtent); - WorldToTile(fx, fz, out int ftx, out int ftz); - float fy = oy + dy * farT; - if (ftx == tx && ftz == tz && fy > _tileMaxHeight[tx, tz] + 0.5f) - { - step = MathF.Max(step, farT - ct); - } - } t = ct + step; } @@ -608,40 +649,157 @@ namespace RustToDust.Core return brush; } - private static float GetBrushMaxPositiveHeight(in TerrainBrush b) => b.Kind switch + private static bool TryGetBrushCellBounds( + in TerrainBrush b, + in BrushPrecomp p, + int cx, int cz, + out float cellMaxPositiveHeight) { - TerrainBrushKind.DuneRidge => b.HeightDelta > 0f ? b.HeightDelta * 1.33f : 0f, - TerrainBrushKind.Mesa => b.HeightDelta > 0f ? b.HeightDelta : 0f, - TerrainBrushKind.SalvagePad or TerrainBrushKind.Road or TerrainBrushKind.Track => b.HeightDelta > 0f ? b.HeightDelta : 0f, - TerrainBrushKind.Crater => 0.33f * MathF.Abs(b.HeightDelta), - _ => 0f - }; + float minX = -HalfExtent + cx * AccelCellSize; + float maxX = minX + AccelCellSize; + float minZ = -HalfExtent + cz * AccelCellSize; + float maxZ = minZ + AccelCellSize; - private void RecomputeTileMaxHeight(int tx, int tz) + // Project all 4 cell corners into brush local (lx, lz) + float dx0 = minX - b.X, dx1 = maxX - b.X; + float dz0 = minZ - b.Z, dz1 = maxZ - b.Z; + float lx00 = dx0 * p.CosR + dz0 * p.SinR; + float lx10 = dx1 * p.CosR + dz0 * p.SinR; + float lx01 = dx0 * p.CosR + dz1 * p.SinR; + float lx11 = dx1 * p.CosR + dz1 * p.SinR; + + float lz00 = -dx0 * p.SinR + dz0 * p.CosR; + float lz10 = -dx1 * p.SinR + dz0 * p.CosR; + float lz01 = -dx0 * p.SinR + dz1 * p.CosR; + float lz11 = -dx1 * p.SinR + dz1 * p.CosR; + + float minLx = MathF.Min(MathF.Min(lx00, lx10), MathF.Min(lx01, lx11)); + float maxLx = MathF.Max(MathF.Max(lx00, lx10), MathF.Max(lx01, lx11)); + float minLz = MathF.Min(MathF.Min(lz00, lz10), MathF.Min(lz01, lz11)); + float maxLz = MathF.Max(MathF.Max(lz00, lz10), MathF.Max(lz01, lz11)); + + float absMinLx = (minLx <= 0f && maxLx >= 0f) ? 0f : MathF.Min(MathF.Abs(minLx), MathF.Abs(maxLx)); + float absMinLz = (minLz <= 0f && maxLz >= 0f) ? 0f : MathF.Min(MathF.Abs(minLz), MathF.Abs(maxLz)); + + float minU = absMinLx * p.InvRx; + float minV = absMinLz * p.InvRz; + float minR2 = minU * minU + minV * minV; + if (minR2 >= 1f) + { + cellMaxPositiveHeight = 0f; + return false; + } + + switch (b.Kind) + { + case TerrainBrushKind.DuneRidge: + { + if (b.HeightDelta <= 0f) + { + cellMaxPositiveHeight = 0f; + } + else + { + float env = 1f - minR2; + env *= env; + float ridge = MathF.Max(0f, 1f - minU * minU); + float maxAsym = MathF.Max(0f, 1f + 0.32f * (maxLx * p.InvRx)); + cellMaxPositiveHeight = b.HeightDelta * env * (0.35f + 0.65f * ridge) * maxAsym; + } + break; + } + case TerrainBrushKind.Mesa: + { + if (b.HeightDelta <= 0f) + { + cellMaxPositiveHeight = 0f; + } + else + { + float r = MathF.Sqrt(minR2); + float t = Math.Clamp((1f - r) / 0.45f, 0f, 1f); + cellMaxPositiveHeight = b.HeightDelta * t * t * (3f - 2f * t); + } + break; + } + case TerrainBrushKind.SalvagePad: + case TerrainBrushKind.Road: + case TerrainBrushKind.Track: + { + if (b.HeightDelta <= 0f) + { + cellMaxPositiveHeight = 0f; + } + else + { + float env = 1f - minR2; + cellMaxPositiveHeight = b.HeightDelta * env * env; + } + break; + } + case TerrainBrushKind.Crater: + cellMaxPositiveHeight = 0.33f * MathF.Abs(b.HeightDelta); + break; + default: + cellMaxPositiveHeight = 0f; + break; + } + + return true; + } + + private void RecomputeCellMaxHeight(int cx, int cz) { float sum = 0f; - var indices = _tileBrushIndices[tx, tz]; + int cellIdx = cz * AccelGridCount + cx; + var indices = _cellBrushIndices[cellIdx]; for (int i = 0; i < indices.Count; i++) { - sum += GetBrushMaxPositiveHeight(_brushes[indices[i]]); + int bIdx = indices[i]; + if (TryGetBrushCellBounds(_brushes[bIdx], _brushPrecomps[bIdx], cx, cz, out float h)) + { + sum += h; + } } - _tileMaxHeight[tx, tz] = Math.Min(MaxWorldHeight, sum + 0.05f); + _cellMaxHeight[cellIdx] = Math.Min(MaxWorldHeight, sum); } private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion) { - float maxPos = GetBrushMaxPositiveHeight(in brush); + bool isStructural = brush.Kind != TerrainBrushKind.Track && brush.Kind != TerrainBrushKind.Scorch; GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); for (int tz = minTz; tz <= maxTz; tz++) { for (int tx = minTx; tx <= maxTx; tx++) { _tileBrushIndices[tx, tz].Add(index); - _tileMaxHeight[tx, tz] = Math.Min(MaxWorldHeight, _tileMaxHeight[tx, tz] + maxPos + 0.05f); if (incrementTileVersion) { TileVersions[tx, tz]++; - DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + ulong bit = 1UL << (tz * TileGridCount + tx); + DirtyTileMask |= bit; + if (isStructural) + { + StructuralDirtyTileMask |= bit; + } + } + } + } + + if (brush.Kind != TerrainBrushKind.Scorch) + { + var precomp = _brushPrecomps[index]; + GetBrushAccelBounds(in brush, out int minCx, out int maxCx, out int minCz, out int maxCz); + for (int cz = minCz; cz <= maxCz; cz++) + { + for (int cx = minCx; cx <= maxCx; cx++) + { + if (TryGetBrushCellBounds(in brush, in precomp, cx, cz, out float cellMaxPos)) + { + int cellIdx = cz * AccelGridCount + cx; + _cellBrushIndices[cellIdx].Add(index); + _cellMaxHeight[cellIdx] = Math.Min(MaxWorldHeight, _cellMaxHeight[cellIdx] + cellMaxPos); + } } } } @@ -649,17 +807,51 @@ namespace RustToDust.Core private void UnregisterBrushFromTiles(int index, in TerrainBrush brush) { + bool isStructural = brush.Kind != TerrainBrushKind.Track && brush.Kind != TerrainBrushKind.Scorch; GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); for (int tz = minTz; tz <= maxTz; tz++) { for (int tx = minTx; tx <= maxTx; tx++) { _tileBrushIndices[tx, tz].Remove(index); - RecomputeTileMaxHeight(tx, tz); TileVersions[tx, tz]++; - DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + ulong bit = 1UL << (tz * TileGridCount + tx); + DirtyTileMask |= bit; + if (isStructural) + { + StructuralDirtyTileMask |= bit; + } } } + + if (brush.Kind != TerrainBrushKind.Scorch) + { + GetBrushAccelBounds(in brush, out int minCx, out int maxCx, out int minCz, out int maxCz); + for (int cz = minCz; cz <= maxCz; cz++) + { + for (int cx = minCx; cx <= maxCx; cx++) + { + int cellIdx = cz * AccelGridCount + cx; + _cellBrushIndices[cellIdx].Remove(index); + RecomputeCellMaxHeight(cx, cz); + } + } + } + } + + private static void GetBrushAccelBounds(in TerrainBrush brush, out int minCx, out int maxCx, out int minCz, out int maxCz) + { + float extent = MathF.Max(0.1f, MathF.Max(brush.RadiusX, brush.RadiusZ)) + 0.1f; + WorldToAccelCell(Math.Clamp(brush.X - extent, -HalfExtent, HalfExtent), Math.Clamp(brush.Z - extent, -HalfExtent, HalfExtent), out minCx, out minCz); + WorldToAccelCell(Math.Clamp(brush.X + extent, -HalfExtent, HalfExtent), Math.Clamp(brush.Z + extent, -HalfExtent, HalfExtent), out maxCx, out maxCz); + } + + private static void WorldToAccelCell(float x, float z, out int cx, out int cz) + { + float nx = (x + HalfExtent) / AccelCellSize; + float nz = (z + HalfExtent) / AccelCellSize; + cx = Math.Clamp((int)MathF.Floor(nx), 0, AccelGridCount - 1); + cz = Math.Clamp((int)MathF.Floor(nz), 0, AccelGridCount - 1); } private static void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz) diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 7b69638..db637cd 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -23,8 +23,6 @@ namespace RustToDust.Ymir private readonly Dictionary _spectatorBodies = new(); private readonly Dictionary _entityByStableId = new(); private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount]; - private int _stepTick; - private bool _forceFullDetectionRefresh = true; private bool _disposed; public ArenaSession(int seed = 42) @@ -88,7 +86,6 @@ namespace RustToDust.Ymir { SpawnContenderBody(c); } - _forceFullDetectionRefresh = true; } public void SetSpectatorPose(int spectatorId, float x, float z, float? yaw = null) @@ -122,7 +119,6 @@ namespace RustToDust.Ymir { SpawnSpectatorBody(index, spec); } - _forceFullDetectionRefresh = true; } public bool HasLineOfSight(float ax, float ay, float az, float bx, float by, float bz) @@ -135,17 +131,17 @@ namespace RustToDust.Ymir } Vector3 dir = delta / dist; - if (State.Terrain.Raycast( - ax, ay, az, - dir.X, dir.Y, dir.Z, - MathF.Max(0.1f, dist - 0.5f), - out _, out _, out _, out _)) + // Only static cover/boundary boxes and terrain block LOS; check fast static AABBs first. + if (IntersectsAnyStaticBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist)) { return false; } - // Only static cover/boundary boxes block LOS; dynamic vehicles do not occlude terrain/cover sightlines. - return !IntersectsAnyStaticBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist); + return !State.Terrain.Raycast( + ax, ay, az, + dir.X, dir.Y, dir.Z, + MathF.Max(0.1f, dist - 0.5f), + out _, out _, out _, out _); } private bool IntersectsAnyStaticBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist) @@ -205,7 +201,6 @@ namespace RustToDust.Ymir { ObjectDisposedException.ThrowIf(_disposed, this); - _stepTick++; State.Time += FixedDt; MatchRules.AdvanceTracers(State, FixedDt); State.Spectators.UpdateSafeRadius(State.Time); @@ -215,7 +210,7 @@ namespace RustToDust.Ymir { UpdateRingClearance(); MatchRules.ApplyPlayerInput(State, input); - MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _forceFullDetectionRefresh ? -1 : _stepTick); + MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); ApplyPhysicsDrives(); _world.Step(FixedDt, SubStepCount); @@ -233,7 +228,7 @@ namespace RustToDust.Ymir UpdateRingClearance(); long t1 = Stopwatch.GetTimestamp(); MatchRules.ApplyPlayerInput(State, input); - MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _forceFullDetectionRefresh ? -1 : _stepTick); + MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); long t2 = Stopwatch.GetTimestamp(); ApplyPhysicsDrives(); long t3 = Stopwatch.GetTimestamp(); @@ -338,7 +333,6 @@ namespace RustToDust.Ymir { SpawnContenderBody(c); } - _forceFullDetectionRefresh = true; } private void SpawnSpectatorBodies() @@ -380,7 +374,7 @@ namespace RustToDust.Ymir var c = State.Contenders[i]; contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive, c.Y, c.Grid.Spec.HalfHeight); } - State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos, _forceFullDetectionRefresh ? -1 : _stepTick); + State.Spectators.UpdateClearance(contacts, FixedDt, HasSpectatorLos); for (int i = 0; i < State.Spectators.Spectators.Count; i++) { @@ -1073,19 +1067,6 @@ namespace RustToDust.Ymir float dxC = c.X - p.X; float dzC = c.Z - p.Z; float distSqC = dxC * dxC + dzC * dzC; - int rivalPeriod = distSqC > 240f * 240f ? 6 : 3; - if (!_forceFullDetectionRefresh && ((c.Id + _stepTick) % rivalPeriod != 0)) - { - if (!mem.VisibleToPlayer && mem.HasEverBeenSeen) - { - mem.LastSeenAge += FixedDt; - } - else if (mem.VisibleToPlayer && distSqC <= 240f * 240f) - { - detectedBy++; - } - continue; - } bool playerSees = HasLineOfSight( p.X, pEyeY, p.Z, @@ -1099,12 +1080,6 @@ namespace RustToDust.Ymir mem.LastSeenX = c.X; mem.LastSeenZ = c.Z; mem.HasEverBeenSeen = true; - - if (distSqC <= 240f * 240f && - HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, p.X, pTargetY, p.Z)) - { - detectedBy++; - } } else { @@ -1115,6 +1090,12 @@ namespace RustToDust.Ymir mem.LastSeenAge += FixedDt; } } + + if (distSqC <= 240f * 240f && + HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, p.X, pTargetY, p.Z)) + { + detectedBy++; + } } for (int i = 0; i < State.Spectators.Spectators.Count; i++) @@ -1129,53 +1110,42 @@ namespace RustToDust.Ymir continue; } - bool checkLosThisTick = _forceFullDetectionRefresh || - s.Stance != SpectatorStance.Neutral || - ((s.Id + _stepTick) % 12 == 0); + bool playerSees = HasLineOfSight( + p.X, pEyeY, p.Z, + s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z); - if (checkLosThisTick) + if (playerSees) { - bool playerSees = HasLineOfSight( - p.X, pEyeY, p.Z, - s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z); - - if (playerSees) - { - mem.VisibleToPlayer = true; - mem.FaintHorizonPing = false; - mem.LastSeenAge = 0f; - mem.LastSeenX = s.X; - mem.LastSeenZ = s.Z; - mem.HasEverBeenSeen = true; - } - else - { - mem.VisibleToPlayer = false; - if (mem.HasEverBeenSeen) - { - mem.LastSeenAge += FixedDt; - } - - // Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range; - // low-signature Exemplars vanish completely when terrain-occluded. - bool horizonPing = false; - if (s.RadarSignature >= 0.9f) - { - float dx = s.X - p.X; - float dz = s.Z - p.Z; - if (dx * dx + dz * dz <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange) - { - horizonPing = HasLineOfSight( - p.X, pEyeY + 14f, p.Z, - s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z); - } - } - mem.FaintHorizonPing = horizonPing; - } + mem.VisibleToPlayer = true; + mem.FaintHorizonPing = false; + mem.LastSeenAge = 0f; + mem.LastSeenX = s.X; + mem.LastSeenZ = s.Z; + mem.HasEverBeenSeen = true; } - else if (!mem.VisibleToPlayer && mem.HasEverBeenSeen) + else { - mem.LastSeenAge += FixedDt; + mem.VisibleToPlayer = false; + if (mem.HasEverBeenSeen) + { + mem.LastSeenAge += FixedDt; + } + + // Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range; + // low-signature Exemplars vanish completely when terrain-occluded. + bool horizonPing = false; + if (s.RadarSignature >= 0.9f) + { + float dx = s.X - p.X; + float dz = s.Z - p.Z; + if (dx * dx + dz * dz <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange) + { + horizonPing = HasLineOfSight( + p.X, pEyeY + 14f, p.Z, + s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z); + } + } + mem.FaintHorizonPing = horizonPing; } if (s.Stance != SpectatorStance.Neutral && @@ -1186,7 +1156,6 @@ namespace RustToDust.Ymir } } - _forceFullDetectionRefresh = false; State.PlayerDetectedByCount = detectedBy; } diff --git a/tests/RustToDust.Tests/DetectionLosTests.cs b/tests/RustToDust.Tests/DetectionLosTests.cs index f44210c..9ac694c 100644 --- a/tests/RustToDust.Tests/DetectionLosTests.cs +++ b/tests/RustToDust.Tests/DetectionLosTests.cs @@ -420,5 +420,149 @@ namespace RustToDust.Tests Assert.True(spec.LastKnownTargetZ > spec.Z + 10f, $"Expected LastKnownTarget to point along incoming +Z direction, got Z={spec.LastKnownTargetZ:F1} vs spec.Z={spec.Z:F1}"); } + + [Fact] + public void AiContender_ImmediatelyDropsTrackingAndFiring_OnExactTickLosBreaks() + { + using var session = new ArenaSession(seed: 12); + var box = session.State.ArenaCoverBoxes[0]; + var player = session.State.Player; + var ai = session.State.Contenders[1]; + + // Move other rivals far away so only ai <-> player interaction is isolated + for (int i = 2; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(session.State.Contenders[i].Id, -680f + i * 8f, -680f); + } + + // Ensure both player and AI are low-profile ground vehicles shorter than the cover wall + if (player.Grid.Spec.IsVtol || player.Grid.Spec.HalfHeight * 2f >= box.HalfY * 2f) + { + session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 8f); + session.State.SpawnChassisDrop(box.X, box.Z - box.HalfZ - 8f, Catalog.Jackal); + Assert.True(session.State.TrySwapNearbyChassis(player.Id)); + } + if (ai.Grid.Spec.IsVtol || ai.Grid.Spec.HalfHeight * 2f >= box.HalfY * 2f) + { + session.SetContenderPose(ai.Id, box.X + 8f, box.Z - box.HalfZ - 8f); + session.State.SpawnChassisDrop(box.X + 8f, box.Z - box.HalfZ - 8f, Catalog.Jackal); + Assert.True(session.State.TrySwapNearbyChassis(ai.Id)); + } + + // Test breaking LOS across multiple step-tick phases (would catch any % 3 stagger!) + for (int phase = 0; phase < 3; phase++) + { + // Place both on the same open side of the cover box within firing range (< 165m) + session.SetContenderPose(ai.Id, box.X, box.Z - box.HalfZ - 14f, yaw: 0f); + session.SetContenderPose(player.Id, box.X + 18f, box.Z - box.HalfZ - 14f, yaw: 0f); + + // Advance `phase` ticks in open LOS; open-LOS acquisition must be immediate on tick 0! + for (int t = 0; t <= phase; t++) + { + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + Assert.Equal(player.Id, ai.AiTargetContenderId); + Assert.True(ai.FireCmd, $"Expected AI to acquire open-LOS target and fire immediately (phase={phase}, t={t})"); + } + + // Now break LOS behind the static cover wall while staying within weapon range + session.SetContenderPose(ai.Id, box.X, box.Z - box.HalfZ - 8f, yaw: 0f); + session.SetContenderPose(player.Id, box.X, box.Z + box.HalfZ + 8f, yaw: 0f); + session.State.Tracers.Clear(); + + for (int occTick = 0; occTick < 6; occTick++) + { + if (occTick > 0) + { + // Move laterally behind cover to verify AI never steers/aims toward hidden coords + session.SetContenderPose(player.Id, box.X + (occTick % 2 == 0 ? 1.5f : -1.5f), box.Z + box.HalfZ + 8f, yaw: 0f); + } + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + + Assert.Null(ai.AiTargetContenderId); + Assert.False(ai.FireCmd, $"AI leaked FireCmd on occluded tick {occTick} (phase={phase})"); + float aimToHidden = MathF.Sqrt((ai.AimX - player.X) * (ai.AimX - player.X) + (ai.AimZ - player.Z) * (ai.AimZ - player.Z)); + Assert.True(aimToHidden > 5f, $"AI aim leaked hidden player coords on occluded tick {occTick} (dist={aimToHidden:F2}m)"); + } + } + } + + [Fact] + public void PlayerDetectedByCount_StaysExactZero_UnderAsymmetricCover_NoFlicker() + { + using var session = new ArenaSession(seed: 12); + var box = session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.8f); + var player = session.State.Player; + var rival = session.State.Contenders[1]; + + // Move all other rivals and spectators far away (> 500m) so only rival <-> player is tested + for (int i = 2; i < session.State.Contenders.Count; i++) + { + session.SetContenderPose(session.State.Contenders[i].Id, -680f + i * 8f, -680f); + } + for (int i = 0; i < session.State.Spectators.Spectators.Count; i++) + { + var s = session.State.Spectators.Spectators[i]; + session.SetSpectatorPose(s.Id, (box.X >= 0f ? -1f : 1f) * 680f, (box.Z >= 0f ? -1f : 1f) * 680f); + } + + // Medium-tall player (Breaker) right next to the 5.6m bunker sees over it onto a low rival (Jackal) 40m on the far side, + // while the low rival's eye cannot see the Breaker's lower target center behind the bunker. + session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f); + session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Breaker); + Assert.True(session.State.TrySwapNearbyChassis(player.Id)); + + session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f); + session.State.SpawnChassisDrop(rival.X, rival.Z, Catalog.Jackal); + Assert.True(session.State.TrySwapNearbyChassis(rival.Id)); + + // Confirm asymmetric LOS precondition + Assert.True(session.HasLineOfSight( + player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z, + rival.X, MatchRules.GetTargetAimY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z)); + Assert.False(session.HasLineOfSight( + rival.X, MatchRules.GetObserverEyeY(rival.Y, rival.Grid.Spec.HalfHeight), rival.Z, + player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z)); + + for (int tick = 0; tick < 18; tick++) + { + // Re-pin poses each tick so drift never alters cover geometry + session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f); + session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f); + session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true)); + + Assert.True(session.State.ContenderContacts[rival.Id].VisibleToPlayer); + Assert.Equal(0, session.State.PlayerDetectedByCount); + } + } + + [Fact] + public void SpectatorRing_ClearsNearestOpenLosNeutralWatcher_OnFirstTickOutsideSafeRadius() + { + // Test every tick phase 0..5 so % 6 staggering cannot hide + for (int tickIndex = 0; tickIndex < 6; tickIndex++) + { + var ring = new SpectatorRing(seed: 42); + // Pick a spectator whose (Id + tickIndex) % 6 != 0 so % 6 staggering would have skipped it + var targetNearest = ring.Spectators.First(s => (s.Id + tickIndex) % 6 != 0); + + // Place contender just outside SafeRadius directly beside targetNearest (within 12m outside => allowedCleared = 1) + float len = MathF.Sqrt(targetNearest.X * targetNearest.X + targetNearest.Z * targetNearest.Z); + float nx = targetNearest.X / len; + float nz = targetNearest.Z / len; + float outR = ring.SafeRadius + 4f; + float cx = nx * outR; + float cz = nz * outR; + + ring.UpdateClearance( + new[] { new RingContact(0, cx, cz, true) }, + 1f / 60f, + static (_, _) => true, + tickIndex: tickIndex); + + Assert.Equal(1, ring.CountClearedFor(0)); + Assert.Equal(SpectatorStance.Cleared, targetNearest.Stance); + Assert.Equal(0, targetNearest.TargetContenderId); + } + } } }