WIP pre-reboot checkpoint

This commit is contained in:
Meta Vens 2026-12-06 00:43:46 +01:00
commit dfdccc3bd3
5 changed files with 248 additions and 19 deletions

View file

@ -520,7 +520,6 @@ public partial class Main : Node3D
42UL); 42UL);
_terrain.Visible = true; _terrain.Visible = true;
_terrain.Sync(_menuSionTerrain, _menuSionData);
_sionMap.Visible = true; _sionMap.Visible = true;
_arena.Visible = false; _arena.Visible = false;
_dropReticleMesh.Visible = false; _dropReticleMesh.Visible = false;
@ -529,6 +528,7 @@ public partial class Main : Node3D
_sionMap.EnsureBuilt(_menuSionData); _sionMap.EnsureBuilt(_menuSionData);
UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain); UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain);
_terrain.UpdateTileLod(_camera.GlobalPosition); _terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_menuSionTerrain, _menuSionData);
_sionMap.UpdateLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition);
} }
@ -877,6 +877,7 @@ public partial class Main : Node3D
_terrain.Visible = true; _terrain.Visible = true;
_terrain.InvalidateAll(); _terrain.InvalidateAll();
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(state.Terrain, state.SionMap); _terrain.Sync(state.Terrain, state.SionMap);
if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null) if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null)
@ -1340,9 +1341,9 @@ public partial class Main : Node3D
{ {
_frameEvents.Clear(); _frameEvents.Clear();
_session.DrainSimEvents(_frameEvents); _session.DrainSimEvents(_frameEvents);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain); UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain);
_terrain.UpdateTileLod(_camera.GlobalPosition); _terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
if (_mapKind == ArenaMapKind.Sion) if (_mapKind == ArenaMapKind.Sion)
{ {
_sionMap.UpdateLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition);
@ -1361,6 +1362,7 @@ public partial class Main : Node3D
} }
double toMs = 1000.0 / Stopwatch.Frequency; double toMs = 1000.0 / Stopwatch.Frequency;
long tt0 = Stopwatch.GetTimestamp(); long tt0 = Stopwatch.GetTimestamp();
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
long tt1 = Stopwatch.GetTimestamp(); long tt1 = Stopwatch.GetTimestamp();
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
@ -1418,6 +1420,7 @@ public partial class Main : Node3D
} }
else else
{ {
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha); DrainAndFanSimEvents((float)delta, alpha);

View file

@ -217,12 +217,12 @@ namespace RustToDust.Net
{ {
_hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name; _hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name;
} }
if (repairScars) ArenaMapKind prevMapKind = _session.State.MapKind;
if (repairScars && mapKind == prevMapKind)
{ {
_session.State.RepairArenaScars(); _session.State.RepairArenaScars();
_inMemoryScarsByMap.Remove(mapKind); _inMemoryScarsByMap.Remove(mapKind);
} }
ArenaMapKind prevMapKind = _session.State.MapKind;
_inMemoryScarsByMap[prevMapKind] = _session.State.ScarLedger.ToSnapshot(); _inMemoryScarsByMap[prevMapKind] = _session.State.ScarLedger.ToSnapshot();
FlushScarLedgerIfDirty(); FlushScarLedgerIfDirty();
@ -231,7 +231,20 @@ namespace RustToDust.Net
{ {
preservedScars = _session.State.ScarLedger.ToSnapshot(); preservedScars = _session.State.ScarLedger.ToSnapshot();
} }
else if (!repairScars) else if (repairScars)
{
_inMemoryScarsByMap.Remove(mapKind);
if (_persistScars)
{
string targetPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind);
if (!string.IsNullOrWhiteSpace(targetPath))
{
var emptySnap = new ArenaScarLedgerSnapshot { AssetFingerprint = GetAssetFingerprint(seed, mapKind) };
ArenaScarLedgerStore.Save(targetPath, emptySnap);
}
}
}
else
{ {
string expectedFp = GetAssetFingerprint(seed, mapKind); string expectedFp = GetAssetFingerprint(seed, mapKind);
if (_inMemoryScarsByMap.TryGetValue(mapKind, out var memScars) && if (_inMemoryScarsByMap.TryGetValue(mapKind, out var memScars) &&

View file

@ -98,6 +98,17 @@ namespace RustToDust.Ymir
public void RepairArenaScars() public void RepairArenaScars()
{ {
State.RepairArenaScars(); State.RepairArenaScars();
if (State.Terrain.IsHeightmapMode)
{
int dirtyResidentCount = _tileSync.CountDirtyResidentTiles(State.Terrain);
if (dirtyResidentCount > 0)
{
int budget = _world.FreeBodySlots >= dirtyResidentCount + 32
? dirtyResidentCount
: 4;
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: budget);
}
}
} }
public static bool IsStaticWorldStableId(ulong stableId) => public static bool IsStaticWorldStableId(ulong stableId) =>
@ -766,8 +777,9 @@ namespace RustToDust.Ymir
if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode) if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode)
{ {
Span<bool> needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; Span<bool> needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
MarkPhysicsOccupancyTiles(state, needed); Span<bool> immediate = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
tileSync.SyncNeededTiles(world, state.Terrain, needed); MarkPhysicsOccupancyTiles(state, needed, immediate);
tileSync.SyncNeededTiles(world, state.Terrain, needed, immediate);
} }
ulong boxId = StaticBoxStableIdBase; ulong boxId = StaticBoxStableIdBase;
@ -915,9 +927,13 @@ namespace RustToDust.Ymir
} }
} }
private static void MarkPhysicsOccupancyTiles(MatchState state, Span<bool> needed) private static void MarkPhysicsOccupancyTiles(MatchState state, Span<bool> needed, Span<bool> immediate = default)
{ {
needed.Clear(); needed.Clear();
if (!immediate.IsEmpty)
{
immediate.Clear();
}
var terrain = state.Terrain; var terrain = state.Terrain;
for (int i = 0; i < state.Contenders.Count; i++) for (int i = 0; i < state.Contenders.Count; i++)
{ {
@ -926,6 +942,10 @@ namespace RustToDust.Ymir
{ {
continue; continue;
} }
if (!immediate.IsEmpty)
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, immediate, c.X, c.Z, marginMeters: 0f);
}
if (c.IsHuman) if (c.IsHuman)
{ {
Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 28f); Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 28f);
@ -940,6 +960,10 @@ namespace RustToDust.Ymir
var s = state.Spectators.Spectators[i]; var s = state.Spectators.Spectators[i];
if (s.Alive && s.Stance != SpectatorStance.Neutral) if (s.Alive && s.Stance != SpectatorStance.Neutral)
{ {
if (!immediate.IsEmpty)
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, immediate, s.X, s.Z, marginMeters: 0f);
}
Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, s.X, s.Z, marginMeters: 8f); Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, s.X, s.Z, marginMeters: 8f);
} }
} }
@ -948,6 +972,10 @@ namespace RustToDust.Ymir
var pod = state.OrbitalDrop.ActivePods[i]; var pod = state.OrbitalDrop.ActivePods[i];
if (pod.Y - terrain.SampleHeight(pod.X, pod.Z) <= 80f) if (pod.Y - terrain.SampleHeight(pod.X, pod.Z) <= 80f)
{ {
if (!immediate.IsEmpty)
{
Box3DPhysicsTileSync.MarkTileRegion(terrain, immediate, pod.X, pod.Z, halfTileRadius: 0);
}
Box3DPhysicsTileSync.MarkTileRegion(terrain, needed, pod.X, pod.Z, halfTileRadius: 0); Box3DPhysicsTileSync.MarkTileRegion(terrain, needed, pod.X, pod.Z, halfTileRadius: 0);
} }
} }
@ -960,8 +988,9 @@ namespace RustToDust.Ymir
return; return;
} }
Span<bool> needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; Span<bool> needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
MarkPhysicsOccupancyTiles(State, needed); Span<bool> immediate = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
_tileSync.SyncNeededTiles(_world, State.Terrain, needed); MarkPhysicsOccupancyTiles(State, needed, immediate);
_tileSync.SyncNeededTiles(_world, State.Terrain, needed, immediate, maxNewPrefetchPerTick: 1);
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4); _tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4);
} }

View file

@ -171,7 +171,12 @@ namespace RustToDust.Ymir
} }
} }
public void SyncNeededTiles(Box3DSoaWorld world, TerrainField terrain, ReadOnlySpan<bool> needed) public void SyncNeededTiles(
Box3DSoaWorld world,
TerrainField terrain,
ReadOnlySpan<bool> needed,
ReadOnlySpan<bool> immediate = default,
int maxNewPrefetchPerTick = int.MaxValue)
{ {
if (!terrain.IsHeightmapMode) if (!terrain.IsHeightmapMode)
{ {
@ -184,7 +189,8 @@ namespace RustToDust.Ymir
for (int tx = 0; tx < grid; tx++) for (int tx = 0; tx < grid; tx++)
{ {
int idx = tz * grid + tx; int idx = tz * grid + tx;
if (_residentFlags[idx] && !needed[idx]) bool keep = needed[idx] || (!immediate.IsEmpty && immediate[idx]);
if (_residentFlags[idx] && !keep)
{ {
world.RemoveBody(_residentHandles[idx]); world.RemoveBody(_residentHandles[idx]);
_residentHandles[idx] = default; _residentHandles[idx] = default;
@ -195,14 +201,37 @@ namespace RustToDust.Ymir
} }
} }
if (!immediate.IsEmpty)
{
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (immediate[idx] && !_residentFlags[idx])
{
EnsureTileResident(world, terrain, tx, tz);
}
}
}
}
int newPrefetch = 0;
for (int tz = 0; tz < grid; tz++) for (int tz = 0; tz < grid; tz++)
{ {
for (int tx = 0; tx < grid; tx++) for (int tx = 0; tx < grid; tx++)
{ {
if (newPrefetch >= maxNewPrefetchPerTick)
{
return;
}
int idx = tz * grid + tx; int idx = tz * grid + tx;
if (needed[idx] && !_residentFlags[idx]) if (needed[idx] && !_residentFlags[idx])
{ {
EnsureTileResident(world, terrain, tx, tz); if (EnsureTileResident(world, terrain, tx, tz))
{
newPrefetch++;
}
} }
} }
} }
@ -282,6 +311,29 @@ namespace RustToDust.Ymir
} }
} }
public int CountDirtyResidentTiles(TerrainField terrain)
{
if (!terrain.IsHeightmapMode)
{
return 0;
}
int grid = terrain.TileGridCount;
int count = 0;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (_residentFlags[idx] && terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx])
{
count++;
}
}
}
return count;
}
public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4) public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4)
{ {
if (!terrain.IsHeightmapMode || maxTilesPerTick <= 0) if (!terrain.IsHeightmapMode || maxTilesPerTick <= 0)
@ -291,7 +343,6 @@ namespace RustToDust.Ymir
int grid = terrain.TileGridCount; int grid = terrain.TileGridCount;
int rebuilt = 0; int rebuilt = 0;
var view = world.View;
for (int tz = 0; tz < grid; tz++) for (int tz = 0; tz < grid; tz++)
{ {
for (int tx = 0; tx < grid; tx++) for (int tx = 0; tx < grid; tx++)
@ -303,7 +354,7 @@ namespace RustToDust.Ymir
} }
if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx]) if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx])
{ {
if (view.Count >= view.Capacity - 8) if (world.FreeBodySlots < 8)
{ {
return rebuilt; return rebuilt;
} }

View file

@ -522,12 +522,23 @@ namespace RustToDust.Tests
session.Step(); session.Step();
} }
int viewCountBeforeRepair = session.World.View.Count; int freeBeforeRepair = session.World.FreeBodySlots;
Assert.True(freeBeforeRepair >= 20 + 32);
session.RepairArenaScars(); session.RepairArenaScars();
// Zero-step repair must NOT burst-allocate 20+ new Box3D heightfields in the same step // When FreeBodySlots >= dirtyResidentCount + 32, RepairArenaScars flushes all dirty resident tiles immediately on tick 0
Assert.Equal(viewCountBeforeRepair, session.World.View.Count); Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256,
$"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) after repair");
Assert.Equal(0, session.TileSync.CountDirtyResidentTiles(terrain));
// Step across ticks so incremental FlushDirtyHeightfields(maxTilesPerTick: 4) completes cleanly var (spotX, spotZ, spotBaseH) = spots[0];
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hitTick0 = session.CastWorldRayClosest(new Vector3(spotX, rayStartY, spotZ), new Vector3(0f, raySpanY, 0f));
Assert.True(hitTick0.Hit);
Assert.True(MathF.Abs(hitTick0.Point.Y - spotBaseH) < 0.05f,
$"Expected tick-0 Box3D raycast height ({hitTick0.Point.Y:F3}) to match restored base ({spotBaseH:F3})");
// Step across ticks so recycled slots remain healthy without exhausting world capacity
for (int t = 0; t < 20; t++) for (int t = 0; t < 20; t++)
{ {
session.Step(); session.Step();
@ -648,5 +659,127 @@ namespace RustToDust.Tests
} }
} }
} }
[Fact]
public void FlushDirtyHeightfields_RecycledFreeSlots_DoesNotWedgeAtHighViewCount()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
var sion = session.State.SionMap!;
float cx = -96f, cz = -96f;
bool foundSpot = false;
for (float z = -176f; z <= -16f && !foundSpot; z += 8f)
{
for (float x = -176f; x <= -16f; x += 8f)
{
if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f))
{
cx = x;
cz = z;
foundSpot = true;
break;
}
}
}
Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)");
session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 0);
// Push View.Count >= 1016, then remove those temporary bodies and step to recycle FreeBodySlots > 500
var tempHandles = new List<Box3DSoaBodyHandle>();
ulong nextId = 900_000UL;
while (session.World.View.Count < 1016 && session.World.FreeBodySlots > 0)
{
tempHandles.Add(session.World.AddStaticBox(nextId++, (0f, -500f, 0f), (0.5f, 0.5f, 0.5f)));
}
Assert.True(session.World.View.Count >= 1016, $"Expected View.Count >= 1016, got {session.World.View.Count}");
foreach (var h in tempHandles)
{
session.World.RemoveBody(h);
}
session.World.Step(1f / 60f);
Assert.True(session.World.View.Count >= 1016, $"Expected monotonic View.Count >= 1016, got {session.World.View.Count}");
Assert.True(session.World.FreeBodySlots > 500, $"Expected recycled FreeBodySlots > 500, got {session.World.FreeBodySlots}");
session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = cx,
Z = cz,
Radius = 6f,
Depth = 2.5f
});
int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4);
Assert.Equal(1, rebuilt);
float cpuH = terrain.SampleHeight(cx, cz);
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hit = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f));
Assert.True(hit.Hit);
Assert.True(MathF.Abs(hit.Point.Y - cpuH) < 0.05f,
$"Expected Box3D raycast height ({hit.Point.Y:F3}) to match CPU height ({cpuH:F3}) within 0.05 m");
}
[Fact]
public void ServerMatchHost_ResetMatch_RepairScarsOnCrossMapSwitch_ClearsTargetOnlyAndPreservesSource()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-repairswitch-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache");
string desertPath = ServerMatchHost.ResolveScarFilePath(explicitSionPath, ArenaMapKind.Sion, ArenaMapKind.Desert);
try
{
using var host = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true);
string sionFp = host.Session.State.SionMap!.AssetFingerprint;
// Stamp Sion crater
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = -120f,
Z = 180f,
Radius = 5.5f,
Depth = 1.8f
});
// Switch to Desert and stamp Desert crater
host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false);
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = 0f,
Z = 0f,
Radius = 4.5f,
Depth = 1.4f
});
// Switch back to Sion, then ResetMatch(42, Desert, repairScars: true) FROM Sion
host.ResetMatch(42, ArenaMapKind.Sion, startInLobby: false);
Assert.Single(host.Session.State.ScarLedger.Terrain);
host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false, repairScars: true);
Assert.Empty(host.Session.State.ScarLedger.Terrain);
var sionDisk = ArenaScarLedgerStore.Load(explicitSionPath, sionFp);
var desertDisk = ArenaScarLedgerStore.Load(desertPath, "desert:42");
Assert.Single(sionDisk.Terrain);
Assert.Empty(desertDisk.Terrain);
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
} }
} }