Merge remote-tracking branch 'origin/nibu/rtd-prototype' into nibu/rtd-cut11b-walker

# Conflicts:
#	src/RustToDust.Net/RemoteArenaSession.cs
#	src/RustToDust.Ymir/ArenaSession.cs
#	src/RustToDust.Ymir/WalkerLocomotion.cs
#	tests/RustToDust.Tests/CultNetMultiplayerTests.cs
This commit is contained in:
Meta Vens 2026-12-06 06:04:25 +01:00
commit c61b0b6a3b
250 changed files with 29333 additions and 4118 deletions

View file

@ -142,4 +142,39 @@ public sealed class CameraJuiceTests
float expected = 0.14f * (1f - 20f / 90f);
Assert.InRange(juice.Trauma, expected - 1e-4f, expected + 1e-4f);
}
[Fact]
public void DropPodFov_WidensTo82DegAndEasesTo58DegOnTouchdown()
{
var juice = new CameraJuiceState();
const float dt = 1f / 60f;
// 1. Freefall at max cross-zone glide speed (124 m/s) -> widens to 82..84 deg smoothly
for (int i = 0; i < 120; i++)
{
juice.Update(dt, localSpeedMps: 124f, isVtol: false, isInDropPod: true, podPhase: OrbitalPodPhase.Freefall);
}
float freefallFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg;
Assert.InRange(freefallFov, 80.0f, 85.0f);
// 2. RetroBurn -> tightens to ~76 deg
for (int i = 0; i < 90; i++)
{
juice.Update(dt, localSpeedMps: 15f, isVtol: false, isInDropPod: true, podPhase: OrbitalPodPhase.RetroBurn);
}
float retroFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg;
Assert.InRange(retroFov, 74.5f, 77.5f);
// 3. Touchdown ground release -> eases monotonically back toward 58 deg within ~1.5s
float prevFov = retroFov;
for (int i = 0; i < 90; i++)
{
juice.Update(dt, localSpeedMps: 0f, isVtol: false, isInDropPod: false);
float curFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg;
Assert.True(curFov <= prevFov + 1e-4f, $"Expected monotonic FOV release, jumped {prevFov:F3} -> {curFov:F3}");
Assert.True(prevFov - curFov < 2.0f, $"Expected smooth FOV release without discontinuity: delta={prevFov - curFov:F2}");
prevFov = curFov;
}
Assert.InRange(prevFov, 57.9f, 59.0f);
}
}

View file

@ -957,6 +957,171 @@ namespace RustToDust.Tests
Assert.True(sawBlastClimb, "Idle local client must sync _predWalker smoothly to server upward blast without stale prediction lock");
}
[Fact]
public void Cut13a_OutOfPvsHistoricalCratersSyncViaPersistentScars_AndLiveCratersEnterWithin576mBubble()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
const float histX = 700f;
const float histZ = 700f;
float baseHistH = host.Session.State.Terrain.SampleHeight(histX, histZ);
// 1. Historical out-of-PVS crater stamped before Client A joins
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(histX, histZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f);
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
host.StepOnce(nowMs += 16);
float scarredHistH = host.Session.State.Terrain.SampleHeight(histX, histZ);
Assert.True(scarredHistH < baseHistH - 1.2f);
using var clientA = new RemoteArenaSession(ep, "Scout");
Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000));
// Out-of-PVS historical crater must be present immediately via PersistentScars
Assert.Equal(scarredHistH, clientA.ViewState.Terrain.SampleHeight(histX, histZ), precision: 3);
Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9);
// 2. Live crater stamped far outside 576m bubble (-700, 100 vs open-sky ~700, 100 = ~1400m apart)
int slotA = clientA.LocalContenderId;
var sion = host.Session.State.SionMap!;
float liveX = 700f, liveZ = 100f;
for (float x = 640f; x <= 760f; x += 8f)
{
if (!sion.IsInsideAnyBuildingXz(x, liveZ, padding: 10f))
{
liveX = x;
break;
}
}
float baseLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ);
host.Session.SetContenderPose(slotA, -700f, liveZ, 0f);
host.StepOnce(nowMs += 16);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(liveX, liveZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f);
for (int t = 0; t < 10; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork();
Thread.Sleep(1);
}
float hostLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ);
Assert.True(hostLiveH < baseLiveH - 1.2f);
Assert.Equal(baseLiveH, clientA.ViewState.Terrain.SampleHeight(liveX, liveZ), precision: 3);
// 3. Client A enters 576m local geometry bubble (liveX - 450m -> dist = 450m <= 576m)
host.Session.SetContenderPose(slotA, liveX - 450f, liveZ, 0f);
Assert.True(PumpUntil(
host,
new[] { clientA },
() => MathF.Abs(clientA.ViewState.Terrain.SampleHeight(liveX, liveZ) - hostLiveH) < 0.05f,
ref nowMs,
3000),
"Client must receive live TerrainStampEvent upon entering 576m bubble before reaching _predWorld 3x3 window");
// 4. Client A steps into (liveX, liveZ) tile -> _predWorld 3x3 window matches server Box3D crater depth 1:1
host.Session.SetContenderPose(slotA, liveX - 20f, liveZ, 0f);
for (int t = 0; t < 10; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.BeginRenderFrame(1.0 / 60.0, 1f);
Thread.Sleep(1);
}
Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9);
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hostHit = host.Session.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f));
var predHit = clientA.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f));
Assert.True(hostHit.Hit && predHit.Hit);
Assert.True(MathF.Abs(hostHit.Point.Y - predHit.Point.Y) < 0.05f,
$"Expected _predWorld crater impact Y ({predHit.Point.Y:F3}m) to match server ({hostHit.Point.Y:F3}m)");
}
[Fact]
public void Cut13a_OverlappingCraters_CoalesceIdenticallyAcrossLiveHostJoinerAndPostReset()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
const float cx = -120f;
const float cz = 180f;
// Stamp 3 overlapping craters within < 0.75m (coalesce radius)
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx, cz, craterRadius: 4.0f, craterDepth: 1.1f, scorchRadius: 4.5f);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx + 0.30f, cz - 0.20f, craterRadius: 5.8f, craterDepth: 2.2f, scorchRadius: 6.0f);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx - 0.15f, cz + 0.25f, craterRadius: 3.0f, craterDepth: 0.7f, scorchRadius: 3.5f);
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
host.StepOnce(nowMs += 16);
float liveHostH = host.Session.State.Terrain.SampleHeight(cx, cz);
float liveHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
using var clientA = new RemoteArenaSession(ep, "Joiner");
Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000));
float clientJoinH = clientA.ViewState.Terrain.SampleHeight(cx, cz);
float clientJoinEdgeH = clientA.ViewState.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
Assert.True(MathF.Abs(liveHostH - clientJoinH) < 0.001f,
$"Expected liveHostH ({liveHostH:F4}) == clientJoinH ({clientJoinH:F4}) within 0.001m");
Assert.True(MathF.Abs(liveHostEdgeH - clientJoinEdgeH) < 0.001f,
$"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == clientJoinEdgeH ({clientJoinEdgeH:F4}) within 0.001m");
host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
float postResetHostH = host.Session.State.Terrain.SampleHeight(cx, cz);
float postResetHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
Assert.True(MathF.Abs(liveHostH - postResetHostH) < 0.001f,
$"Expected liveHostH ({liveHostH:F4}) == postResetHostH ({postResetHostH:F4}) within 0.001m");
Assert.True(MathF.Abs(liveHostEdgeH - postResetHostEdgeH) < 0.001f,
$"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == postResetHostEdgeH ({postResetHostEdgeH:F4}) within 0.001m");
}
[Fact]
public void RemoteArenaSession_AppliesRemoteContenderCoreHpRatioOnPvsSnapshot()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
using var client = new RemoteArenaSession(ep, "HpProbe");
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000));
int localSlot = client.LocalContenderId;
int rivalSlot = localSlot == 0 ? 1 : 0;
var serverLocal = host.Session.State.Contenders[localSlot];
var serverRival = host.Session.State.Contenders[rivalSlot];
host.Session.SetContenderPose(localSlot, 0f, 0f, 0f);
host.Session.SetContenderPose(rivalSlot, 0f, 40f, MathF.PI);
float targetHp = serverRival.Grid.MaxCoreHp * 0.42f;
serverRival.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, targetHp, serverRival.Grid.HitSequence + 1);
float expectedRatio = serverRival.Grid.CoreHp / serverRival.Grid.MaxCoreHp;
bool synced = PumpUntil(host, new[] { client }, () =>
{
if (!client.IsContenderVisible(rivalSlot)) return false;
var c = client.ViewState.Contenders[rivalSlot];
float r = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f;
return MathF.Abs(r - expectedRatio) < 0.02f;
}, ref nowMs, 2500);
var clientRival = client.ViewState.Contenders[rivalSlot];
float actualRatio = clientRival.Grid.MaxCoreHp > 0f ? clientRival.Grid.CoreHp / clientRival.Grid.MaxCoreHp : 1f;
Assert.True(synced, $"Expected remote contender {rivalSlot} CoreHpRatio ~ {expectedRatio:F3}, got {actualRatio:F3}");
// Edge case: living rival at 0.30 HP rounds 8-bit CoreHpRatio to 0, yet must remain Alive on remote client
serverRival.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0.30f, serverRival.Grid.HitSequence + 1);
Assert.True(serverRival.Alive);
bool lowHpSynced = PumpUntil(host, new[] { client }, () =>
{
var c = client.ViewState.Contenders[rivalSlot];
return c.Alive && c.Grid.CoreHp > 0f && c.Grid.CoreHp <= 0.5f;
}, ref nowMs, 2500);
Assert.True(lowHpSynced && clientRival.Alive && !clientRival.Grid.IsDestroyed && clientRival.Grid.CoreHp > 0f,
$"Expected living 0.30 HP rival to stay Alive on remote client, got Alive={clientRival.Alive}, CoreHp={clientRival.Grid.CoreHp:F3}");
}
private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) =>
CultNetRudpPacketCodec.Encode(new CultNetRudpPacket
{

View file

@ -584,5 +584,30 @@ namespace RustToDust.Tests
Assert.Equal(0, targetNearest.TargetContenderId);
}
}
[Fact]
public void DeadObserver_ClearsSpectatorContactsVisibleToPlayer()
{
using var session = new ArenaSession(seed: 12, slot0Human: true);
var player = session.State.Contenders[0];
var spec = session.State.Spectators.Spectators.First(s => s.Alive);
session.SetContenderPose(player.Id, 0f, 0f);
session.SetSpectatorPose(spec.Id, 0f, 35f);
session.State.Spectators.OnSpectatorDamaged(spec, player.Id);
session.Step();
var obs0 = session.State.GetOrCreateObserverState(0);
Assert.True(obs0.SpectatorContacts.TryGetValue(spec.Id, out var memBefore) && memBefore.VisibleToPlayer,
"Expected living observer in open LOS to mark provoked spectator VisibleToPlayer=true");
// Kill observer and step once; stale SpectatorContacts must clear VisibleToPlayer
player.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0f, player.Grid.HitSequence + 1);
Assert.False(player.Alive);
session.Step();
Assert.False(obs0.SpectatorContacts[spec.Id].VisibleToPlayer,
"Expected dead observer to clear SpectatorContacts.VisibleToPlayer");
}
}
}

View file

@ -0,0 +1,158 @@
using System;
using System.IO;
using RustToDust.Client;
using Xunit;
namespace RustToDust.Tests;
public sealed class GraphicsSettingsTests
{
[Fact]
public void Defaults_MatchExpectedBaseline()
{
var settings = new GraphicsSettings();
Assert.Equal(VfxResolutionScale.Half, settings.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, settings.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, settings.SdfgiQuality);
Assert.True(settings.BorderlessFullscreen);
Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(settings.VfxResolution));
Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(settings.VolumetricSamples));
var sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality);
Assert.True(sdfgi.Enabled);
Assert.Equal(0.8f, sdfgi.MinCellSize);
Assert.Equal(3, sdfgi.Cascades);
Assert.True(sdfgi.HalfResolution);
Assert.Equal(4, sdfgi.RayCount);
}
[Fact]
public void MissingOrCorruptJson_FallsBackToSafeDefaults()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
string missingPath = Path.Combine(tempDir, "missing.json");
var missingLoaded = GraphicsSettings.Load(missingPath);
Assert.Equal(VfxResolutionScale.Half, missingLoaded.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, missingLoaded.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, missingLoaded.SdfgiQuality);
Assert.True(missingLoaded.BorderlessFullscreen);
string corruptPath = Path.Combine(tempDir, "corrupt.json");
File.WriteAllText(corruptPath, "{ this is not valid json !!!");
var corruptLoaded = GraphicsSettings.Load(corruptPath);
Assert.Equal(VfxResolutionScale.Half, corruptLoaded.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, corruptLoaded.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, corruptLoaded.SdfgiQuality);
Assert.True(corruptLoaded.BorderlessFullscreen);
// ResetToDefaults(persist: true) must unconditionally rewrite a corrupt file even when memory equals defaults
corruptLoaded.ResetToDefaults(persist: true);
string repairedJson = File.ReadAllText(corruptPath);
Assert.DoesNotContain("not valid json", repairedJson, StringComparison.Ordinal);
var repaired = new GraphicsSettings();
Assert.True(repaired.LoadFromJson(repairedJson));
Assert.Equal(VfxResolutionScale.Half, repaired.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, repaired.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, repaired.SdfgiQuality);
Assert.True(repaired.BorderlessFullscreen);
var outOfRange = new GraphicsSettings();
Assert.True(outOfRange.LoadFromJson("""{"vfxResolutionScale":99,"volumetricSamples":42,"sdfgiQuality":77,"borderlessFullscreen":false}"""));
Assert.Equal(VfxResolutionScale.Half, outOfRange.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, outOfRange.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, outOfRange.SdfgiQuality);
Assert.False(outOfRange.BorderlessFullscreen);
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[Fact]
public void SaveAndReload_RoundtripsAllFieldsAndFiresChanged()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
string path = Path.Combine(tempDir, "graphics_settings.json");
var settings = GraphicsSettings.Load(path);
int changeEvents = 0;
settings.Changed += _ => changeEvents++;
settings.Apply(
VfxResolutionScale.Full,
VolumetricSamples.Ultra,
SdfgiQuality.High,
borderlessFullscreen: false,
persist: true);
Assert.Equal(1, changeEvents);
Assert.True(File.Exists(path));
// No-op apply must not fire duplicate Changed events
settings.Apply(
VfxResolutionScale.Full,
VolumetricSamples.Ultra,
SdfgiQuality.High,
borderlessFullscreen: false,
persist: true);
Assert.Equal(1, changeEvents);
var reloaded = GraphicsSettings.Load(path);
Assert.Equal(VfxResolutionScale.Full, reloaded.VfxResolution);
Assert.Equal(VolumetricSamples.Ultra, reloaded.VolumetricSamples);
Assert.Equal(SdfgiQuality.High, reloaded.SdfgiQuality);
Assert.False(reloaded.BorderlessFullscreen);
reloaded.ResetToDefaults(persist: true);
var afterReset = GraphicsSettings.Load(path);
Assert.Equal(VfxResolutionScale.Half, afterReset.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, afterReset.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, afterReset.SdfgiQuality);
Assert.True(afterReset.BorderlessFullscreen);
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[Fact]
public void PresetMappings_MatchSpecification()
{
Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Half));
Assert.Equal(0.75f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.ThreeQuarter));
Assert.Equal(1.00f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Full));
Assert.Equal((8, 12), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Low));
Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Medium));
Assert.Equal((16, 24), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.High));
Assert.Equal((24, 36), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Ultra));
Assert.False(GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Off).Enabled);
var balanced = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Balanced);
Assert.True(balanced.Enabled);
Assert.Equal(0.8f, balanced.MinCellSize);
Assert.Equal(3, balanced.Cascades);
Assert.True(balanced.HalfResolution);
Assert.Equal(4, balanced.RayCount);
var high = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.High);
Assert.True(high.Enabled);
Assert.Equal(0.4f, high.MinCellSize);
Assert.Equal(4, high.Cascades);
Assert.False(high.HalfResolution);
Assert.Equal(8, high.RayCount);
}
}

View file

@ -0,0 +1,271 @@
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using RustToDust.HbGpu;
using Xunit;
namespace RustToDust.Tests;
public sealed class HbGpuNativeTests
{
private static string RepoRoot
{
get
{
string? dir = AppContext.BaseDirectory;
while (dir is not null)
{
if (File.Exists(Path.Combine(dir, "RustToDust.slnx")))
{
return dir;
}
dir = Directory.GetParent(dir)?.FullName;
}
throw new DirectoryNotFoundException("Could not locate RustToDust.slnx from test output directory.");
}
}
[Fact]
public void NativeDllExistsAndMeetsSizeBudget()
{
if (OperatingSystem.IsWindows())
{
string dllPath = Path.Combine(AppContext.BaseDirectory, "rtd_hbgpu.dll");
Assert.True(File.Exists(dllPath), $"Expected rtd_hbgpu.dll at '{dllPath}'.");
long size = new FileInfo(dllPath).Length;
Assert.InRange(size, 100_000, 2_621_440); // < 2.5 MiB
}
string ver = HbGpuNative.GetVersionString();
Assert.Equal("15.2.0", ver);
string vertShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared);
string fragShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared);
string fragDraw = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw);
Assert.Contains("hb_gpu_dilate", vertShared);
Assert.Contains("uniform isamplerBuffer hb_gpu_atlas;", fragShared);
Assert.Contains("hb_gpu_draw", fragDraw);
}
[Fact]
public void KryptonFontAndLicensesAreCompliant()
{
string root = RepoRoot;
string fontPath = Path.Combine(root, "assets", "fonts", "Krypton.ttf");
string oflPath = Path.Combine(root, "assets", "fonts", "OFL-1.1.txt");
string hbCopyPath = Path.Combine(root, "assets", "fonts", "HARFBUZZ-COPYING.txt");
string noticesPath = Path.Combine(root, "THIRD_PARTY_NOTICES.txt");
Assert.True(File.Exists(fontPath));
Assert.True(File.Exists(oflPath));
Assert.True(File.Exists(hbCopyPath));
Assert.True(File.Exists(noticesPath));
byte[] fontBytes = File.ReadAllBytes(fontPath);
Assert.Equal(1_363_340, fontBytes.Length);
string sha = Convert.ToHexString(SHA256.HashData(fontBytes)).ToLowerInvariant();
Assert.Equal("6462cae55b336ae6ffb7c8f1932177960510a4207e65803f527b276d42c8a240", sha);
string oflText = File.ReadAllText(oflPath);
Assert.Contains("Copyright (c) 2023, GitHub", oflText);
Assert.Contains("Krypton", oflText);
}
[Fact]
public void QuadInstanceStructIs80Bytes()
{
Assert.Equal(80, Unsafe.SizeOf<HbGpuQuadInstance>());
Assert.Equal(80, Marshal.SizeOf<HbGpuQuadInstance>());
}
[Fact]
public void ShapingAndGlyphEncodingWorkAcrossKryptonAxes()
{
string fontPath = Path.Combine(RepoRoot, "assets", "fonts", "Krypton.ttf");
using var fonts = new HbGpuFontCache();
fonts.RegisterFontFromFile(0, fontPath);
RtdHbFontMetrics metrics = fonts.GetMetrics(0);
Assert.Equal(2000, metrics.Upem);
var atlas = new HbGpuAtlasAllocator();
var blobs = new HbGpuBlobCache(atlas);
var writer = new HbGpuCommandWriter();
writer.BeginFrame();
float wReg = writer.DrawTextUtf16("RAPTOR -> 142.8m", 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f);
float wBold = writer.DrawTextUtf16("CHASSIS", 10f, 80f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 700f);
float wSlnt = writer.DrawTextUtf16("SLANT", 10f, 120f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 400f, slnt: -9f);
Assert.True(wReg > 50f);
Assert.True(wBold > 20f);
Assert.True(wSlnt > 20f);
Assert.True(writer.QuadCount >= 18); // spaces omit quads, visible glyphs emit quads
Assert.True(blobs.CachedGlyphCount >= 15);
Assert.True(atlas.PersistentCursor > 0);
Assert.True(atlas.PendingChunkCount > 0);
// Space glyph encodes cleanly as empty
CachedBlob spaceBlob = blobs.GetOrEncodeGlyph(fonts, 0, 1 /* glyph or verify space */, 200, 1000, 0);
Assert.True(spaceBlob.TexelCount >= 0);
// Hot steady-state loop allocates zero managed bytes once glyphs/styles are cached
writer.BeginFrame();
atlas.ClearPending();
ReadOnlySpan<char> hotText = "RAPTOR -> 142.8m";
long before = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 64; i++)
{
writer.BeginFrame();
writer.DrawTextUtf16(hotText, 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f);
}
long after = GC.GetAllocatedBytesForCurrentThread();
Assert.Equal(0, after - before);
}
[Fact]
public void VectorPathsAndAtlasBudgetResetWork()
{
var atlas = new HbGpuAtlasAllocator();
var blobs = new HbGpuBlobCache(atlas);
CachedBlob rect = HbGpuVectorShapes.GetUnitFilledRect(blobs);
CachedBlob circle = HbGpuVectorShapes.GetUnitFilledCircle(blobs);
CachedBlob ring = HbGpuVectorShapes.GetUnitRingStroke(blobs, 24);
CachedBlob bracket = HbGpuVectorShapes.GetTargetBracketCorner(blobs, 120);
CachedBlob arrow = HbGpuVectorShapes.GetDirectionalArrow(blobs);
CachedBlob chevron = HbGpuVectorShapes.GetChevronTriangle(blobs);
CachedBlob diamond = HbGpuVectorShapes.GetDiamondBlip(blobs);
CachedBlob arc = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -2.356f, 0.785f);
Assert.True(rect.IsValid && rect.TexelCount > 2);
Assert.True(circle.IsValid && circle.TexelCount > 2);
Assert.True(ring.IsValid && ring.TexelCount > 4);
Assert.True(bracket.IsValid && bracket.TexelCount > 2);
Assert.True(arrow.IsValid && arrow.TexelCount > 2);
Assert.True(chevron.IsValid && chevron.TexelCount > 2);
Assert.True(diamond.IsValid && diamond.TexelCount > 2);
Assert.True(arc.IsValid && arc.TexelCount > 4);
Assert.True(arc.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase);
// Also test tapered line verb directly
Span<byte> lineVerb = stackalloc byte[] { (byte)HbGpuPathVerb.Line };
Span<float> lineArgs = stackalloc float[] { -400f, 0f, 20f, 400f, 0f, 60f, 1f };
CachedBlob lineBlob = blobs.GetOrEncodeStaticPath(
new VectorBlobKey(VectorShapeKind.Custom, 1, 0), 1000u, lineVerb, lineArgs);
Assert.True(lineBlob.IsValid);
// Drain uploads with zero allocations
byte[] staging = new byte[HbGpuBlobCache.ScratchShortsCapacity * sizeof(short)];
int drainedBytes = 0;
Action<uint, uint> cb = (_, len) => drainedBytes += (int)len;
int chunks = atlas.DrainChunks(staging, cb);
Assert.True(chunks >= 9);
Assert.True(drainedBytes > 0);
Assert.Equal(0, atlas.PendingChunkCount);
// Verify static arc caching (0 pending chunks and 0 B GC allocs on repeat lookup)
var staticArcKey = new VectorBlobKey(VectorShapeKind.ThermalHeatArc, 45, 1);
CachedBlob staticArc = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f);
Assert.True(staticArc.IsValid);
Assert.True(staticArc.AtlasOffset < HbGpuAtlasAllocator.DynamicBase);
atlas.ClearPending();
// Warm up cache-hit path once before measuring GC allocations
CachedBlob warmHit = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f);
Assert.Equal(staticArc.AtlasOffset, warmHit.AtlasOffset);
uint expectedOffset = staticArc.AtlasOffset;
bool allMatched = true;
long arcGcBefore = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 64; i++)
{
CachedBlob hit = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f);
if (hit.AtlasOffset != expectedOffset) allMatched = false;
}
long arcGcAfter = GC.GetAllocatedBytesForCurrentThread();
Assert.True(allMatched);
Assert.Equal(0, arcGcAfter - arcGcBefore);
Assert.Equal(0, atlas.PendingChunkCount);
// Verify dynamic ring wrap-around
for (int i = 0; i < 600; i++)
{
CachedBlob dyn = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -1.5f, 1.5f);
Assert.True(dyn.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase);
Assert.True(dyn.AtlasOffset + dyn.TexelCount <= HbGpuAtlasAllocator.TotalTexels);
atlas.ClearPending();
}
}
[Fact]
public void PersistentAtlasOverflowDoesNotResetMidFrame()
{
var atlas = new HbGpuAtlasAllocator();
var blobs = new HbGpuBlobCache(atlas);
// Fill persistent zone right up near PersistentCapacity without crossing it
short[] chunk = new short[4096 * 4]; // 4096 texels
chunk[0] = 1;
while (atlas.PersistentCursor + 4096 <= HbGpuAtlasAllocator.PersistentCapacity)
{
atlas.AllocatePersistent(chunk);
atlas.ClearPending();
}
uint epochBefore = atlas.Epoch;
uint cursorBefore = atlas.PersistentCursor;
Assert.True(cursorBefore > HbGpuAtlasAllocator.PersistentResetWatermark);
// Encode a static vector that exceeds remaining PersistentCapacity: must NOT reset mid-frame!
Span<byte> bigVerbs = stackalloc byte[64];
Span<float> bigArgs = stackalloc float[128];
int v = 0, a = 0;
bigVerbs[v++] = (byte)HbGpuPathVerb.Move;
bigArgs[a++] = 0f;
bigArgs[a++] = 0f;
for (int i = 1; i <= 30; i++)
{
float ang = i * 0.2f;
bigVerbs[v++] = (byte)HbGpuPathVerb.LineTo;
bigArgs[a++] = MathF.Cos(ang) * 400f;
bigArgs[a++] = MathF.Sin(ang) * 400f;
}
bigVerbs[v++] = (byte)HbGpuPathVerb.Close;
// First force a large remaining fill so the encoded vector overflows remaining space
uint rem = HbGpuAtlasAllocator.PersistentCapacity - atlas.PersistentCursor;
if (rem > 2)
{
atlas.AllocatePersistent(new short[(rem - 1) * 4]);
atlas.ClearPending();
}
cursorBefore = atlas.PersistentCursor;
CachedBlob overflowed = blobs.GetOrEncodeStaticPath(
new VectorBlobKey(VectorShapeKind.Custom, 999, 1),
1000u,
bigVerbs[..v],
bigArgs[..a]);
Assert.False(overflowed.IsValid);
Assert.Equal(epochBefore, atlas.Epoch);
Assert.Equal(cursorBefore, atlas.PersistentCursor);
Assert.True(blobs.IsPersistentOverflowPending);
// Next BeginFrame resets cleanly and allows encoding
Assert.True(blobs.EnsureBudgetOrReset());
Assert.Equal(epochBefore + 1, atlas.Epoch);
Assert.Equal(0u, atlas.PersistentCursor);
Assert.False(blobs.IsPersistentOverflowPending);
CachedBlob recovered = blobs.GetOrEncodeStaticPath(
new VectorBlobKey(VectorShapeKind.Custom, 999, 1),
1000u,
bigVerbs[..v],
bigArgs[..a]);
Assert.True(recovered.IsValid);
}
}

View file

@ -741,7 +741,7 @@ namespace RustToDust.Tests
var sion = session.State.SionMap!;
var sites = new System.Collections.Generic.List<(float X, float Z, float Yaw, float Ny)>();
for (float r = 60f; r <= 720f && sites.Count < 3; r += 25f)
for (float r = 60f; r <= 1350f && sites.Count < 3; r += 25f)
{
for (int a = 0; a < 48 && sites.Count < 3; a++)
{
@ -774,6 +774,22 @@ namespace RustToDust.Tests
clear = false;
break;
}
if (lat == 0f && sion.Trees is not null)
{
for (int ti = 0; ti < sion.Trees.Count; ti++)
{
var tr = sion.Trees.Trees[ti];
if (tr.TrunkRadiusM < SionTreeDestructionState.MinColliderTrunkRadiusM) continue;
float tdx = tr.X - ax;
float tdz = tr.Z - az;
if (tdx * tdx + tdz * tdz <= 4.0f * 4.0f)
{
clear = false;
break;
}
}
if (!clear) break;
}
float gyA = session.State.Terrain.SampleHeight(ax, az);
float gyB = session.State.Terrain.SampleHeight(bx, bz);
if (!session.HasLineOfSight(ax, gyA + 2.5f, az, bx, gyB + 2.5f, bz))

View file

@ -633,5 +633,204 @@ namespace RustToDust.Tests
Assert.NotNull(res.Summary);
Assert.Equal(new string('\u2022', 16), res.Summary!.Value.ServerName);
}
[Fact]
public void LobbySquadSwap_ReliableRoundTrip()
{
using var listenHost = new ListenHostArenaSession(
IPAddress.Loopback,
0,
seed: 42,
mapKind: ArenaMapKind.Desert,
startInLobby: true,
minHumansToStart: 2,
squadSize: 3);
using var remote = new RemoteArenaSession(
new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort),
"WingBuddy");
var deadline = DateTime.UtcNow.AddSeconds(3);
while (!remote.IsJoined && DateTime.UtcNow < deadline)
{
PumpListenHostAndClient(listenHost, remote);
}
Assert.True(remote.IsJoined);
int remoteId = remote.LocalContenderId;
Assert.Equal((byte)3, listenHost.LobbyState?.SquadSize);
Assert.Equal((byte)3, remote.LobbyState?.SquadSize);
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
// 1. Remote client swaps to Squad 2 -> swaps cleanly with an AI in Squad 2
Assert.True(remote.RequestLobbySquad(2));
PumpListenHostAndClient(listenHost, remote, ticks: 15);
Assert.Equal((byte)2, listenHost.LobbyState!.Slots[remoteId].SquadId);
Assert.Equal((byte)2, remote.LobbyState!.Slots[remoteId].SquadId);
// 2. Host switches SquadMode to Duos (2) -> slots regroup cleanly to 2-player squads
Assert.True(listenHost.RequestLobbyConfig(77, ArenaMapKind.Desert, 2));
PumpListenHostAndClient(listenHost, remote, ticks: 15);
Assert.Equal((byte)2, listenHost.LobbyState!.SquadSize);
Assert.Equal((byte)2, remote.LobbyState!.SquadSize);
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
// 3. Remote swaps to Squad 3, then back to Squad 0 (Host's Duo), both ready up & launch!
Assert.True(remote.RequestLobbySquad(3));
PumpListenHostAndClient(listenHost, remote, ticks: 15);
Assert.Equal((byte)3, remote.LobbyState!.Slots[remoteId].SquadId);
Assert.True(remote.RequestLobbySquad(0));
PumpListenHostAndClient(listenHost, remote, ticks: 15);
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
Assert.True(listenHost.SetLobbyReady(true));
Assert.True(remote.SetLobbyReady(true));
for (int tick = 0; tick < 340; tick++)
{
listenHost.SubmitLocalInput(default, isPhysicsTick: true);
remote.PumpNetwork();
if (listenHost.ViewState.Phase == MatchPhase.Active &&
remote.ViewState.Phase == MatchPhase.Active &&
remote.ActivePods.Count > 0)
{
break;
}
Thread.Sleep(1);
}
PumpListenHostAndClient(listenHost, remote, ticks: 10);
Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase);
Assert.Equal(MatchPhase.Active, remote.ViewState.Phase);
Assert.Equal((byte)2, listenHost.ViewState.SquadSize);
Assert.Equal((byte)2, remote.ViewState.SquadSize);
Assert.Equal(0, listenHost.ViewState.Contenders[remoteId].SquadId);
Assert.Equal(0, remote.ViewState.Contenders[remoteId].SquadId);
Assert.True(listenHost.ViewState.AreAllies(0, remoteId));
Assert.True(remote.ViewState.AreAllies(0, remoteId));
}
[Fact]
public void LobbySquadSwap_MidMatchReconnectAndLateJoin_PreservesAll12SquadIdsOutsidePvs()
{
using var host = new ServerMatchHost(
IPAddress.Loopback,
0,
seed: 42,
mapKind: ArenaMapKind.Desert,
startInLobby: true,
minHumansToStart: 1,
squadSize: 3);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
using var clientA = new RemoteArenaSession(ep, "LeaderSwap");
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var deadline = DateTime.UtcNow.AddSeconds(3);
while (!clientA.IsJoined && DateTime.UtcNow < deadline)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork(nowMs);
Thread.Sleep(2);
}
Assert.True(clientA.IsJoined);
int slotA = clientA.LocalContenderId;
Assert.Equal(0, slotA);
// Polish check: out-of-range TargetSquadId >= maxSquads (4 for SquadSize=3) must be rejected, not clamped
Assert.False(host.MovePeerToSquad(slotA, 4));
Assert.Equal((byte)0, host.Session.State.Contenders[slotA].SquadId);
// Swap Slot 0 (0 -> 2) and Slot 6 (2 -> 0) in Lobby (SquadSize = 3)
Assert.True(clientA.RequestLobbySquad(2));
for (int t = 0; t < 20; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork(nowMs);
Thread.Sleep(2);
}
Assert.Equal((byte)2, host.Session.State.Contenders[0].SquadId);
Assert.Equal((byte)0, host.Session.State.Contenders[6].SquadId);
// Launch to MatchPhase.Active
Assert.True(host.SetLobbyReady(slotA, true));
for (int tick = 0; tick < 340; tick++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork(nowMs);
if (host.Session.State.Phase == MatchPhase.Active && clientA.ViewState.Phase == MatchPhase.Active)
{
break;
}
Thread.Sleep(1);
}
Assert.Equal(MatchPhase.Active, host.Session.State.Phase);
// Position contenders far apart across Desert so non-allies (including Slot 6) are outside PVS
host.Session.SetContenderPose(0, -320f, -320f, 0f);
for (int i = 1; i < MatchState.ContenderCount; i++)
{
if (host.Session.State.AreAllies(0, i))
{
host.Session.SetContenderPose(i, -310f + i * 3f, -320f, 0f);
}
else
{
host.Session.SetContenderPose(i, 320f, 320f - i * 8f, MathF.PI);
}
}
nowMs += 16;
host.StepOnce(nowMs);
Assert.False(host.Session.IsEntityInPeerPvs(0, true, 6));
// 1. Reconnect clientA mid-match and assert ALL 12 SquadIds and AreAllies match server 12/12
Guid tokenA = clientA.ReconnectToken;
clientA.DisconnectGracefully("ReconnectSquadTest");
clientA.Dispose();
for (int t = 0; t < 20; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
Thread.Sleep(1);
}
using var clientARejoin = new RemoteArenaSession(ep, "LeaderSwap", tokenA);
deadline = DateTime.UtcNow.AddSeconds(3);
while (!clientARejoin.IsJoined && DateTime.UtcNow < deadline)
{
nowMs += 16;
host.StepOnce(nowMs);
clientARejoin.PumpNetwork(nowMs);
Thread.Sleep(2);
}
Assert.True(clientARejoin.IsJoined);
Assert.Equal(0, clientARejoin.LocalContenderId);
// 2. Late-join a fresh clientB mid-match while non-allies are outside PVS
using var clientB = new RemoteArenaSession(ep, "LateJoiner");
deadline = DateTime.UtcNow.AddSeconds(3);
while (!clientB.IsJoined && DateTime.UtcNow < deadline)
{
nowMs += 16;
host.StepOnce(nowMs);
clientARejoin.PumpNetwork(nowMs);
clientB.PumpNetwork(nowMs);
Thread.Sleep(2);
}
Assert.True(clientB.IsJoined);
var serverState = host.Session.State;
for (int i = 0; i < MatchState.ContenderCount; i++)
{
Assert.Equal(serverState.Contenders[i].SquadId, clientARejoin.ViewState.Contenders[i].SquadId);
Assert.Equal(serverState.Contenders[i].SquadId, clientB.ViewState.Contenders[i].SquadId);
for (int j = 0; j < MatchState.ContenderCount; j++)
{
Assert.Equal(serverState.AreAllies(i, j), clientARejoin.ViewState.AreAllies(i, j));
Assert.Equal(serverState.AreAllies(i, j), clientB.ViewState.AreAllies(i, j));
}
}
}
}
}

View file

@ -25,16 +25,18 @@ namespace RustToDust.Tests
[Fact]
public void HoverSlam_FlatDesertAnd30DegSionSlope_TouchdownUnder3MsAndZeroPenetration()
{
// 1. Flat Desert trajectory & cross-range steering [120m, 180m]
// 1. Flat Desert trajectory & cross-range steering
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
var player = session.State.Contenders[0];
float startX = player.X;
float startZ = player.Z;
float aimX = startX;
float aimZ = startZ + 100f;
// Steer straight across the arena center so boundary clamp does not reverse heading
float dirLen = MathF.Max(1f, MathF.Sqrt(startX * startX + startZ * startZ));
float dirX = -startX / dirLen;
float dirZ = -startZ / dirLen;
int maxTicks = 600;
int maxTicks = 1200;
float impactSpeed = -1f;
float touchTime = -1f;
float snapDiffAtTouchdown = float.NaN;
@ -50,8 +52,8 @@ namespace RustToDust.Tests
session.SetHumanInput(0, new PlayerInput(
Throttle: 1.0f,
Steer: 0f,
AimWorldX: player.X,
AimWorldZ: player.Z + 100f,
AimWorldX: player.X + dirX * 100f,
AimWorldZ: player.Z + dirZ * 100f,
Fire: false,
InteractPickup: false,
Brake: false));
@ -67,12 +69,12 @@ namespace RustToDust.Tests
}
}
Assert.True(player.IsGroundedActive, "Player pod failed to touch down within 10s on Desert");
Assert.InRange(impactSpeed, 0.5f, 2.99f);
Assert.InRange(touchTime, 5.5f, 9.5f);
Assert.True(player.IsGroundedActive, "Player pod failed to touch down within 20s on Desert");
Assert.InRange(impactSpeed, 0.5f, 2.49f);
Assert.InRange(touchTime, 12.5f, 18.0f);
float glideDist = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ));
Assert.InRange(glideDist, 120f, 180f);
Assert.True(glideDist >= 800f, $"Expected cross-arena Desert glide >= 800m, got {glideDist:F1}m");
// Verify PrevY == Y right at touchdown SnapPreviousPose() and continuous post-Step settlement (< 0.06m, zero sky pop)
Assert.True(snapDiffAtTouchdown < 1e-4f,
@ -130,7 +132,7 @@ namespace RustToDust.Tests
};
float impactSpeed = -1f;
for (int t = 0; t < 600; t++)
for (int t = 0; t < 2000; t++)
{
pod.LookForwardX = -snx;
pod.LookForwardZ = -snz;
@ -146,7 +148,7 @@ namespace RustToDust.Tests
}
Assert.True(c.IsGroundedActive, $"Pod failed to land on {slopeDeg:F1} deg Sion slope");
Assert.InRange(impactSpeed, 0.5f, 2.99f);
Assert.InRange(impactSpeed, 0.5f, 2.49f);
Assert.True(snapDiffAtTouchdown < 1e-4f);
Assert.True(MathF.Abs(c.PrevY - c.Y) < 0.06f);
AssertZeroChassisPenetration(session.State, c);
@ -167,7 +169,7 @@ namespace RustToDust.Tests
float maxGearTouchTime = 0f;
float minContenderTouchTime = float.PositiveInfinity;
for (int t = 0; t < 660; t++)
for (int t = 0; t < 2000; t++)
{
session.Step();
if (session.State.OrbitalDrop.ActivePods.Count == 0)
@ -192,7 +194,7 @@ namespace RustToDust.Tests
var state = new MatchState(seed: 42, map);
var gearTouchTimes = new List<float>();
var contenderTouchTimes = new List<float>();
for (int t = 0; t < 660; t++)
for (int t = 0; t < 2000; t++)
{
state.Time += ArenaSession.FixedDt;
state.OrbitalDrop.Step(ArenaSession.FixedDt, state.DefaultDropSurfaceQuery, (pod, _) =>
@ -246,7 +248,7 @@ namespace RustToDust.Tests
var pod = session.State.OrbitalDrop.LaunchGearPod(0, tx, tz, null, Catalog.Autocannon, session.QueryDropSurface);
bool landed = false;
for (int t = 0; t < 600; t++)
for (int t = 0; t < 1800; t++)
{
bool touched = OrbitalDropKinematics.StepPod(
pod,
@ -267,12 +269,12 @@ namespace RustToDust.Tests
Assert.False(touchSample.IsInsideSolidBuilding,
$"Target #{i} ({tx:F1},{tz:F1}) landed with IsInsideSolidBuilding=true at ({pod.X:F1},{pod.Z:F1})!");
Assert.False(touchSample.IsBuildingRoof);
Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.99f);
Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.5f);
break;
}
}
Assert.True(landed, $"Target #{i} ({tx:F1},{tz:F1}) hover-stalled!");
Assert.True(pod.FlightTime <= 9.5f, $"Target #{i} took too long: {pod.FlightTime:F2}s");
Assert.True(pod.FlightTime <= 28.0f, $"Target #{i} took too long: {pod.FlightTime:F2}s");
tested++;
}
@ -312,7 +314,7 @@ namespace RustToDust.Tests
player, 0, fr.CenterX, fr.CenterZ, 0f, session.QueryDropSurface, isRespawn: false);
roofPod.AllowFlatRoofLanding = true;
for (int t = 0; t < 600 && !player.IsGroundedActive; t++)
for (int t = 0; t < 2000 && !player.IsGroundedActive; t++)
{
session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 20f, false, false, false));
session.Step();
@ -390,15 +392,15 @@ namespace RustToDust.Tests
var state = session.State;
var player = state.Contenders[0];
// Step until Wave 0 contenders touch down (~7.5s)
for (int t = 0; t < 480 && !state.Contenders.All(c => c.IsGroundedActive); t++)
// Step until Wave 0 contenders touch down (~15s on Desert)
for (int t = 0; t < 1200 && !state.Contenders.All(c => c.IsGroundedActive); t++)
{
session.Step();
}
Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive));
// 1. Kill 11 AIs at t = 15s -> must enter WaitingForRespawnWave and match stays Active!
while (state.Time < 15f)
// 1. Kill 11 AIs at t = 20s -> must enter WaitingForRespawnWave and match stays Active!
while (state.Time < 20f)
{
session.Step();
}
@ -414,8 +416,8 @@ namespace RustToDust.Tests
Assert.True(state.Contenders[i].WaitingForRespawn);
}
// 2. Step past Wave 1 (t = 75s) + drop time -> all 11 AIs re-drop in stock Jackals with RespawnsRemaining == 0!
while (state.Time < 75.5f)
// 2. Step past Wave 1 (t = 85s) + drop time -> all 11 AIs re-drop in stock Jackals with RespawnsRemaining == 0!
while (state.Time < 85.5f)
{
session.Step();
}
@ -426,15 +428,15 @@ namespace RustToDust.Tests
Assert.Equal(0, state.Contenders[i].RespawnsRemaining);
Assert.Equal(Catalog.Jackal.Id, state.Contenders[i].Grid.Spec.Id);
}
for (int t = 0; t < 480; t++)
for (int t = 0; t < 1200; t++)
{
session.Step();
if (state.Contenders.All(c => c.IsGroundedActive)) break;
}
Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive));
// 3. Kill Player before Wave 2 (t = 120s) -> match MUST stay Active (Player.WaitingForRespawn == true)
while (state.Time < 120f)
// 3. Kill Player before Wave 2 (t = 130s) -> match MUST stay Active (Player.WaitingForRespawn == true)
while (state.Time < 130f)
{
session.Step();
}
@ -444,8 +446,8 @@ namespace RustToDust.Tests
Assert.Equal(MatchPhase.Active, state.Phase);
Assert.True(player.WaitingForRespawn);
// Step past Wave 2 (t = 155s) -> Player re-drops in stock Jackal (RespawnsRemaining == 0), RespawnCutoffReached == true!
while (state.Time < 155.5f)
// Step past Wave 2 (t = 165s) -> Player re-drops in stock Jackal (RespawnsRemaining == 0), RespawnCutoffReached == true!
while (state.Time < 165.5f)
{
session.Step();
}
@ -454,8 +456,8 @@ namespace RustToDust.Tests
Assert.Equal(ContenderLifecycle.Deploying, player.Lifecycle);
Assert.Equal(0, player.RespawnsRemaining);
// 4. Kill an AI at t = 158.1s (after Wave 2 cutoff) -> immediately Eliminated (never WaitingForRespawnWave)!
while (state.Time < 158.1f)
// 4. Kill an AI at t = 168.1s (after Wave 2 cutoff) -> immediately Eliminated (never WaitingForRespawnWave)!
while (state.Time < 168.1f)
{
session.Step();
}
@ -524,9 +526,9 @@ namespace RustToDust.Tests
Assert.True(clientIface.ActivePods.Count >= 12,
$"Expected active Wave 0 pods on RemoteArenaSession join, got {clientIface.ActivePods.Count}");
// Step through full Wave 0 orbital drop (~7.8s = 470 ticks) with steering input
// Step through full Wave 0 orbital drop (~15.1s = 905 ticks) with steering input
var simEvents = new List<ISimEvent>();
for (int t = 0; t < 480; t++)
for (int t = 0; t < 1100; t++)
{
nowMs += 16;
clientIface.SubmitLocalInput(new PlayerInput(
@ -621,9 +623,9 @@ namespace RustToDust.Tests
Assert.True(midGearPod.LastAgl < gearAgl0 - 20f && midGearPod.LastAgl > 0f,
$"Gear pod LastAgl failed to update: {gearAgl0:F2} -> {midGearPod.LastAgl:F2}");
// Step through remainder of Wave 0 + 30 settle ticks so all pods touch down across Sion PVS
// Step through remainder of Wave 0 + 30 settle ticks so all pods touch down across Sion PVS (~27.6s = 1658 ticks)
var simEvents = new List<ISimEvent>();
for (int t = 0; t < 560; t++)
for (int t = 0; t < 1900; t++)
{
nowMs += 16;
clientIface.SubmitLocalInput(new PlayerInput(
@ -690,7 +692,7 @@ namespace RustToDust.Tests
}
// 1. Land Wave 0
for (int i = 0; i < 480 && !clientIface.LocalContender.IsGroundedActive; i++)
for (int i = 0; i < 1100 && !clientIface.LocalContender.IsGroundedActive; i++)
{
PumpStep(1);
}
@ -708,8 +710,8 @@ namespace RustToDust.Tests
PumpStep(12);
Assert.Equal(ContenderLifecycle.WaitingForRespawnWave, clientIface.LocalContender.Lifecycle);
// 4. Advance past Wave 1 (75.0s) -> server resets local player to Jackal (256/256) and launches Wave 1 pod
host.Session.State.Time = 74.85f;
// 4. Advance past Wave 1 (85.0s) -> server resets local player to Jackal (256/256) and launches Wave 1 pod
host.Session.State.Time = 84.85f;
PumpStep(30);
Assert.Equal(ContenderLifecycle.Deploying, clientIface.LocalContender.Lifecycle);
@ -1019,7 +1021,7 @@ namespace RustToDust.Tests
// 2. Full Sion Wave 0 drop steering human toward sion_1365 + steep Sion terrain checks across all 12 contenders
var maxBurnStartAgl = new Dictionary<int, float>();
for (int t = 0; t < 700; t++)
for (int t = 0; t < 2200; t++)
{
var p0 = session.State.Contenders[0];
session.SetHumanInput(0, new PlayerInput(
@ -1044,7 +1046,7 @@ namespace RustToDust.Tests
maxBurnStartAgl[pod.PodId] = pod.LastAgl;
Assert.True(pod.LastAgl <= 160f, $"Wave 0 pod {pod.PodId} ignited RetroBurn at {pod.LastAgl:F1}m AGL");
}
Assert.True(pod.FlightTime <= 10.5f, $"Wave 0 pod {pod.PodId} exceeded 10.5s flight time: {pod.FlightTime:F2}s");
Assert.True(pod.FlightTime <= 34.0f, $"Wave 0 pod {pod.PodId} exceeded 34.0s flight time: {pod.FlightTime:F2}s");
}
if (session.State.OrbitalDrop.ActivePods.Count == 0 && p0.IsGroundedActive)
@ -1110,8 +1112,8 @@ namespace RustToDust.Tests
host.Session.SetContenderPose(localId, -900f, -900f, 0f);
PumpStep(5);
// Trigger Wave 1 (75.0s) so rival launches its drop pod out of observer PVS
host.Session.State.Time = 74.9f;
// Trigger Wave 1 (85.0s) so rival launches its drop pod out of observer PVS
host.Session.State.Time = 84.9f;
for (int i = 0; i < 20 && host.Session.State.Contenders[rivalId].Lifecycle != ContenderLifecycle.Deploying; i++)
{
PumpStep(1);
@ -1189,7 +1191,7 @@ namespace RustToDust.Tests
foreach (bool allowFlat in new[] { false, true })
{
foreach (float startAgl in new[] { 410f, 80f })
foreach (float startAgl in new[] { 1620f, 80f })
{
foreach (var (label, sx, sz) in startPoints)
{
@ -1209,7 +1211,7 @@ namespace RustToDust.Tests
X = sx,
Y = terrain0 + startAgl,
Z = sz,
VelY = startAgl > 200f ? OrbitalPodPreset.Contender.InitialVelY : -28f,
VelY = startAgl > 200f ? OrbitalPodPreset.GetContender(ArenaMapKind.Sion).InitialVelY : -28f,
LookForwardX = dirX,
LookForwardZ = dirZ,
SteerForwardCmd = 1f,
@ -1217,7 +1219,7 @@ namespace RustToDust.Tests
};
bool landed = false;
for (int t = 0; t < 720; t++)
for (int t = 0; t < 2200; t++)
{
float prevX = pod.X;
float prevY = pod.Y;
@ -1248,7 +1250,7 @@ namespace RustToDust.Tests
(pod.Y - prevY) * (pod.Y - prevY) +
(pod.Z - prevZ) * (pod.Z - prevZ));
maxTouchdownStep = MathF.Max(maxTouchdownStep, tdStep3D);
if (tdStep3D > 1.0f || horizStep > 1.0f)
if (tdStep3D > 1.0f || horizStep > 2.25f)
{
touchdownWarps++;
}
@ -1271,8 +1273,332 @@ namespace RustToDust.Tests
Assert.Equal(0, wallBreachFrames);
Assert.Equal(0, touchdownWarps);
Assert.True(maxHorizStep <= 1.0f, $"Horizontal warp {maxHorizStep:F3}m > 1.0m/tick");
Assert.True(maxTouchSpeed < 3.0f, $"Touchdown speed {maxTouchSpeed:F2} m/s >= 3.0 m/s");
Assert.True(maxHorizStep <= 2.25f, $"Horizontal warp {maxHorizStep:F3}m > 2.25m/tick");
Assert.True(maxTouchSpeed < 2.5f, $"Touchdown speed {maxTouchSpeed:F2} m/s >= 2.5 m/s");
}
[Fact]
public void HoverSlam_CrossZoneDrop_SionAndDesert()
{
// Large synthetic flat terrain to measure unobstructed max-burn cross-zone horizontal glide
var largeHeights = new float[17 * 17];
var largeFlat = TerrainField.LoadHeightmap(sizeMeters: 10000f, gridRes: 17, largeHeights, minY: 0f, maxY: 0f, seed: 1);
DropSurfaceSample FlatQuery(float x, float z, float footR, float refMaxY) =>
new(0f, Vector3.UnitY, false, false, false, false);
(float X, float Z) FlatClear(float x, float z, float pad) => (x, z);
foreach (var (map, minGlideM) in new[] { (ArenaMapKind.Sion, 3000f), (ArenaMapKind.Desert, 1400f) })
{
var preset = OrbitalPodPreset.GetContender(map);
var pod = new OrbitalPod
{
PodId = 100 + (int)map,
PodKind = OrbitalPodKind.Contender,
Phase = OrbitalPodPhase.Freefall,
X = 0f,
Y = preset.StartAltAgl,
Z = 0f,
VelY = preset.InitialVelY,
LookForwardX = 0f,
LookForwardZ = 1f,
SteerForwardCmd = 1.0f,
Yaw = 0f
};
float burnStartAgl = -1f;
bool touched = false;
for (int t = 0; t < 2400; t++)
{
if (OrbitalDropKinematics.StepPod(pod, ArenaSession.FixedDt, largeFlat, FlatQuery, FlatClear, out bool retroStarted, out _))
{
touched = true;
break;
}
if (retroStarted)
{
burnStartAgl = pod.Y;
}
}
Assert.True(touched, $"{map} cross-zone pod failed to touch down");
Assert.True(pod.Z >= minGlideM, $"{map} max-burn horizontal glide {pod.Z:F1}m < {minGlideM:F1}m");
Assert.True(pod.TouchdownSpeed < 2.5f, $"{map} flat touchdown speed {pod.TouchdownSpeed:F2} >= 2.5 m/s");
Assert.InRange(burnStartAgl, 8f, 160f);
Assert.Equal(0f, pod.Y, precision: 3);
_output.WriteLine($"{map} flat cross-zone: glide={pod.Z:F1}m, flight={pod.FlightTime:F2}s, retroAgl={burnStartAgl:F2}m, tdVel={pod.TouchdownSpeed:F2} m/s");
}
// +-30 deg slope hover-slam verification
float slopeTan = MathF.Tan(30f * MathF.PI / 180f); // ~0.57735
foreach (float sign in new[] { 1f, -1f })
{
const int res = 129;
const float size = 8000f;
var slopeHeights = new float[res * res];
for (int gz = 0; gz < res; gz++)
{
float wz = -size * 0.5f + (gz / (float)(res - 1)) * size;
float h = sign > 0f ? MathF.Max(0f, wz * slopeTan) : MathF.Max(0f, (1000f - wz) * slopeTan);
for (int gx = 0; gx < res; gx++)
{
slopeHeights[gz * res + gx] = h;
}
}
var slopeTerrain = TerrainField.LoadHeightmap(size, res, slopeHeights, 0f, 3000f, 2UL);
DropSurfaceSample SlopeQuery(float x, float z, float footR, float refMaxY)
{
float sy = slopeTerrain.SampleHeight(x, z);
var (nx, ny, nz) = slopeTerrain.SampleNormal(x, z);
return new DropSurfaceSample(sy, Vector3.Normalize(new Vector3(nx, ny, nz)), false, false, false, false);
}
var sionPreset = OrbitalPodPreset.GetContender(ArenaMapKind.Sion);
float startZ = -400f;
float startSurf = slopeTerrain.SampleHeight(0f, startZ);
var pod = new OrbitalPod
{
PodId = 300 + (sign > 0 ? 1 : 2),
PodKind = OrbitalPodKind.Contender,
Phase = OrbitalPodPhase.Freefall,
X = 0f,
Y = startSurf + sionPreset.StartAltAgl,
Z = startZ,
VelY = sionPreset.InitialVelY,
LookForwardX = 0f,
LookForwardZ = 1f,
SteerForwardCmd = 1.0f,
Yaw = 0f
};
float burnStartAgl = -1f;
bool touched = false;
for (int t = 0; t < 3000; t++)
{
if (OrbitalDropKinematics.StepPod(pod, ArenaSession.FixedDt, slopeTerrain, SlopeQuery, FlatClear, out bool retroStarted, out _))
{
touched = true;
break;
}
if (retroStarted)
{
burnStartAgl = pod.Y - slopeTerrain.SampleHeight(pod.X, pod.Z);
}
}
Assert.True(touched, $"Slope sign={sign} pod failed to touch down");
Assert.True(pod.TouchdownSpeed < 2.5f, $"Slope sign={sign} touchdown speed {pod.TouchdownSpeed:F2} >= 2.5 m/s");
Assert.InRange(burnStartAgl, 5f, 160f);
float endTerrain = slopeTerrain.SampleHeight(pod.X, pod.Z);
Assert.True(MathF.Abs(pod.Y - endTerrain) < 0.001f, $"Slope sign={sign} penetration/hover error {pod.Y - endTerrain:F5}m");
_output.WriteLine($"Slope sign={sign:+#;-#}: flight={pod.FlightTime:F2}s, retroAgl={burnStartAgl:F2}m, tdVel={pod.TouchdownSpeed:F2} m/s");
}
}
[Fact]
public void SquadFormation_TrioDrop_ZeroPodOverlapAndFormationVisible()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, squadSize: 3);
var state = session.State;
Assert.Equal(3, state.SquadSize);
// Verify 4 squads of 3; inter-squad anchors >= 220m apart, intra-squad pods >= 14m apart at launch
var squadGroups = state.Contenders.GroupBy(c => c.SquadId).ToList();
Assert.Equal(4, squadGroups.Count);
foreach (var grp in squadGroups)
{
var members = grp.ToList();
Assert.Equal(3, members.Count);
for (int a = 0; a < members.Count; a++)
{
for (int b = a + 1; b < members.Count; b++)
{
float d = MathF.Sqrt(
(members[a].X - members[b].X) * (members[a].X - members[b].X) +
(members[a].Z - members[b].Z) * (members[a].Z - members[b].Z));
Assert.True(d >= 14f, $"Same-squad launch separation too small: {d:F2}m");
}
}
}
// Different squad leaders >= 200m apart (anchors >= 220m, leaders +8m fwd)
for (int i = 0; i < squadGroups.Count; i++)
{
var li = state.GetSquadLeader(squadGroups[i].Key)!;
for (int j = i + 1; j < squadGroups.Count; j++)
{
var lj = state.GetSquadLeader(squadGroups[j].Key)!;
float d = MathF.Sqrt((li.X - lj.X) * (li.X - lj.X) + (li.Z - lj.Z) * (li.Z - lj.Z));
Assert.True(d >= 195f, $"Inter-squad separation too small: {d:F1}m");
}
}
// Allied persistent PVS + zero false DetectedBy from allies
Assert.True(session.IsEntityInPeerPvs(0, true, 1));
Assert.True(session.IsEntityInPeerPvs(0, true, 2));
Assert.Equal(0, state.ObserverStates[0].DetectedByCount);
// Step Wave 0 drop while player glides gently forward; track formation and touchdown separation
for (int t = 0; t < 2200; t++)
{
var p0 = state.Contenders[0];
session.SetHumanInput(0, new PlayerInput(
Throttle: 0.45f,
Steer: 0f,
AimWorldX: p0.X + MathF.Sin(p0.Yaw) * 100f,
AimWorldZ: p0.Z + MathF.Cos(p0.Yaw) * 100f,
Fire: false,
InteractPickup: false,
Brake: false));
session.Step();
if (state.Contenders.All(c => c.IsGroundedActive))
{
break;
}
}
Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive));
// Wingmen (1, 2) landed >= 12m apart from player (0) and each other, with 0 penetration
for (int a = 0; a < 3; a++)
{
AssertZeroChassisPenetration(state, state.Contenders[a]);
for (int b = a + 1; b < 3; b++)
{
float d = MathF.Sqrt(
(state.Contenders[a].X - state.Contenders[b].X) * (state.Contenders[a].X - state.Contenders[b].X) +
(state.Contenders[a].Z - state.Contenders[b].Z) * (state.Contenders[a].Z - state.Contenders[b].Z));
Assert.True(d >= 11.5f, $"Squadmates {a} & {b} landed too close: {d:F2}m");
}
}
// Verify AI allies do not target allies and friendly fire does 0 damage
var ally1 = state.Contenders[1];
float allyHpBefore = ally1.Grid.CoreHp;
session.SetContenderPose(0, 0f, 0f, 0f);
session.SetContenderPose(1, 0f, 20f, MathF.PI);
for (int t = 0; t < 30; t++)
{
session.SetHumanInput(0, new PlayerInput(0f, 0f, ally1.X, ally1.Z, Fire: true, InteractPickup: false, Brake: true));
session.Step();
Assert.False(ally1.AiTargetContenderId.HasValue && state.AreAllies(1, ally1.AiTargetContenderId.Value),
"AI wingman targeted an allied squadmate!");
}
Assert.Equal(allyHpBefore, ally1.Grid.CoreHp);
// Advance past Wave 2 cutoff and eliminate all 9 non-Squad-0 contenders -> Squad 0 wins!
state.Time = 250f;
session.Step();
Assert.True(state.OrbitalDrop.RespawnCutoffReached);
for (int i = 3; i < state.Contenders.Count; i++)
{
session.ForceEliminateContender(i);
}
MatchRules.UpdateMatchOutcome(state);
Assert.Equal(MatchPhase.Completed, state.Phase);
Assert.Equal(0, state.WinnerContenderId);
}
[Fact]
public void CorePvs_MaxDatagramCap_StrictlyUnder1152B()
{
var state = new MatchState(seed: 42, ArenaMapKind.Desert, skipInitialDrop: true, squadSize: 3);
var local = state.Contenders[0];
local.Grid.SwapChassis(Catalog.Bastion);
var contenders = new List<NetContenderState>(12);
var walkers = new List<NetWalkerEntry>(12);
var specs = new List<NetSpectatorState>(10);
for (int i = 0; i < 12; i++)
{
contenders.Add(new NetContenderState
{
SlotId = (byte)i,
Alive = true,
IsHuman = i < 3,
Lifecycle = ContenderLifecycle.Active,
Pos = new Vector3(i * 12f, 3f, -i * 6f),
Rot = Quaternion.Identity,
Vel = Vector3.Zero,
CoreHpRatio = 1f
});
walkers.Add(new NetWalkerEntry
{
IsContender = true,
EntityId = (byte)i,
Snapshot = new WalkerVisualSnapshot { LegCount = 4 }
});
}
byte[] payload = SnapshotCodec.EncodeCorePvs(
1, 10, 20, 12.5f, 0, 0, 772f, MatchPhase.Active, null, 0, 0xFFF,
local, Vector3.Zero, contenders, walkers, specs);
byte[] wire = SnapshotCodec.WrapLatest(payload, 1, 10);
Assert.True(wire.Length <= SnapshotCodec.MaxLatestDatagramBytes,
$"CorePvs wire frame {wire.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
}
[Fact]
public void SquadTrioDrop_AllSeedsAndMaps_AllLandedSquadmatesSeparatedAtLeast12Meters()
{
int[] seeds = { 1, 7, 42, 1337 };
ArenaMapKind[] maps = { ArenaMapKind.Sion, ArenaMapKind.Desert };
foreach (var mapKind in maps)
{
foreach (int seed in seeds)
{
using var session = new ArenaSession(seed: seed, mapKind: mapKind, slot0Human: false, squadSize: 3);
var state = session.State;
var tdPos = new (float X, float Z, int Tick)[MatchState.ContenderCount];
var landed = new bool[MatchState.ContenderCount];
for (int t = 0; t < 2400; t++)
{
session.Step();
for (int i = 0; i < state.Contenders.Count; i++)
{
var c = state.Contenders[i];
if (!landed[i] && c.IsGroundedActive)
{
landed[i] = true;
tdPos[i] = (c.X, c.Z, t);
}
}
if (state.Contenders.All(c => c.IsGroundedActive))
{
break;
}
}
Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive,
$"Map={mapKind} Seed={seed} contender {c.Id} failed to land"));
foreach (var grp in state.Contenders.GroupBy(c => c.SquadId))
{
var members = grp.ToList();
for (int a = 0; a < members.Count; a++)
{
for (int b = a + 1; b < members.Count; b++)
{
var ma = members[a];
var mb = members[b];
float tdDx = tdPos[ma.Id].X - tdPos[mb.Id].X;
float tdDz = tdPos[ma.Id].Z - tdPos[mb.Id].Z;
float tdDist = MathF.Sqrt(tdDx * tdDx + tdDz * tdDz);
float dx = ma.X - mb.X;
float dz = ma.Z - mb.Z;
float d = MathF.Sqrt(dx * dx + dz * dz);
Assert.True(tdDist >= 12.0f,
$"Map={mapKind} Seed={seed} Squad={grp.Key} pair ({ma.Id}@t{tdPos[ma.Id].Tick},{mb.Id}@t{tdPos[mb.Id].Tick}) touchdown too close: td={tdDist:F2}m (now={d:F2}m)");
Assert.True(d >= 12.0f,
$"Map={mapKind} Seed={seed} Squad={grp.Key} pair ({ma.Id}@t{tdPos[ma.Id].Tick},{mb.Id}@t{tdPos[mb.Id].Tick}) landed too close: now={d:F2}m (td={tdDist:F2}m)");
}
}
}
}
}
}
private static void AssertZeroChassisPenetration(MatchState state, ContenderState c)

View file

@ -979,5 +979,133 @@ namespace RustToDust.Tests
var ex = Assert.Throws<InvalidOperationException>(() => OrdnanceGraphValidator.ValidateAndFlatten(combined));
Assert.Contains("sub-spawn budget", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void AlliedPdAndHitscan_DoNotInterceptSquadmateOrdnance()
{
using var session = new ArenaSession(seed: 101, slot0Human: true, skipInitialDrop: true, squadSize: 3);
var ally0 = session.State.Contenders[0];
var ally1 = session.State.Contenders[1];
var enemy = session.State.Contenders[3];
Assert.True(session.State.AreAllies(ally0.Id, ally1.Id));
Assert.False(session.State.AreAllies(ally0.Id, enemy.Id));
IsolateContenders(session, ally0.Id, ally1.Id, enemy.Id);
// Place Ally 0 and Ally 1 nearby facing Enemy so Ally 1's PD + RailPlasmaBeam shoot across Ally 0's ordnance
session.SetContenderPose(ally0.Id, 0f, 0f, 0f);
session.SetContenderPose(ally1.Id, 16f, 16f, -0.5f);
session.SetContenderPose(enemy.Id, 0f, 80f, MathF.PI);
foreach (var c in new[] { ally0, ally1, enemy })
{
session.State.SpawnChassisDrop(c.X, c.Z, Catalog.Anvil);
Assert.True(session.State.TrySwapNearbyChassis(c.Id));
c.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon);
}
session.SetContenderPose(ally0.Id, 0f, 0f, 0f);
session.SetContenderPose(ally1.Id, 16f, 16f, -0.5f);
session.SetContenderPose(enemy.Id, 0f, 80f, MathF.PI);
var droneSpec = ProceduralWeaponGenerator.CreateDreamLoiteringDrone();
var swarmSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.HomingSwarmPod);
var railSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.RailPlasmaBeam);
Assert.True(ally0.Grid.TryMount(droneSpec.Module, "hp.weapon.siege_l"));
Assert.True(ally0.Grid.TryMount(swarmSpec.Module, "hp.weapon.siege_r"));
Assert.True(ally1.Grid.TryMount(Catalog.ImperialAegisPd, "hp.weapon.sponson_l"));
Assert.True(ally1.Grid.TryMount(railSpec.Module, "hp.weapon.siege_l"));
Assert.True(ally1.Grid.TryMount(Catalog.GoldRadiator, "hp.radiator.l"));
Assert.True(ally1.Grid.TryMount(Catalog.GoldRadiator, "hp.radiator.r"));
session.SetHumanSlot(ally1.Id, true, "Ally1");
session.SetHumanInput(ally0.Id, new PlayerInput(0f, 0f, enemy.X, enemy.Z, Fire: false, InteractPickup: false, Brake: true, AimWorldY: enemy.Y + 2f));
session.SetHumanInput(ally1.Id, new PlayerInput(0f, 0f, 0f, 25f, Fire: false, InteractPickup: false, Brake: true, AimWorldY: 12f));
session.Step();
var events = new List<ISimEvent>();
session.DrainStepEvents(events);
int allyOrdnanceSpawned = 0;
int allyOrdnanceIntercepted = 0;
int railShotsWhileAllyOrdnanceAirborne = 0;
for (int tick = 0; tick < 360; tick++)
{
Vector3? allyAirbornePos = null;
var pool = session.Ordnance.PoolSpan;
for (int i = 0; i < pool.Length; i++)
{
ref readonly var inst = ref pool[i];
if (!inst.Active || inst.IsSpectatorShooter || inst.ShooterContenderId != ally0.Id)
{
continue;
}
if (inst.Def.InterceptHp > 0f &&
inst.Def.Motion is OrdnanceMotion.LoiterOrbit or OrdnanceMotion.HomingMissile)
{
allyAirbornePos = inst.Pos;
break;
}
}
// Keep Ally 1 cool enough to continuously fire PD + RailPlasmaBeam directly at Ally 0's airborne ordnance
foreach (var mod in ally1.Grid.Mounted)
{
mod.CurrentTemp = mod.Spec.OptimalTemp;
}
session.SetHumanInput(ally0.Id, new PlayerInput(
0f, 0f,
enemy.X, enemy.Z,
Fire: tick < 5,
InteractPickup: false,
Brake: true,
AimWorldY: enemy.Y + 2f));
if (allyAirbornePos.HasValue)
{
var p = allyAirbornePos.Value;
session.SetHumanInput(ally1.Id, new PlayerInput(
0f, 0f,
p.X, p.Z,
Fire: true,
InteractPickup: false,
Brake: true,
AimWorldY: p.Y));
railShotsWhileAllyOrdnanceAirborne++;
}
else
{
session.SetHumanInput(ally1.Id, new PlayerInput(
0f, 0f,
enemy.X, enemy.Z,
Fire: false,
InteractPickup: false,
Brake: true,
AimWorldY: enemy.Y + 2f));
}
session.Step();
events.Clear();
session.DrainStepEvents(events);
foreach (var ev in events)
{
if (ev is OrdnanceNodeEvent one && !one.IsSpectatorShooter && one.ShooterId == ally0.Id)
{
if (one.Kind == (byte)OrdnanceEventKind.Spawned)
{
allyOrdnanceSpawned++;
}
else if (one.Kind == (byte)OrdnanceEventKind.Intercepted)
{
allyOrdnanceIntercepted++;
}
}
}
}
Assert.True(allyOrdnanceSpawned >= 2, $"Expected Ally 0 to spawn drone + swarm ordnance, got {allyOrdnanceSpawned}");
Assert.True(railShotsWhileAllyOrdnanceAirborne >= 10, $"Expected Ally 1 to aim RailPlasmaBeam + PD at airborne ally ordnance, got {railShotsWhileAllyOrdnanceAirborne}");
Assert.Equal(0, allyOrdnanceIntercepted);
}
}
}

View file

@ -67,8 +67,9 @@ namespace RustToDust.Tests
}
}
// 3. Step 4.5s (270 ticks) so Wave 0 gear pods touch down into GroundDrops; all 14 non-Jackal chassis exist
for (int t = 0; t < 270; t++)
// 3. Step Wave 0 gear drop duration so Wave 0 gear pods touch down into GroundDrops; all 14 non-Jackal chassis exist
int gearDropTicks = map == ArenaMapKind.Sion ? 1600 : 900;
for (int t = 0; t < gearDropTicks; t++)
{
session.Step();
}

View file

@ -18,11 +18,13 @@
<ItemGroup>
<Compile Include="..\..\client\WalkerFootstepTracker.cs" Link="Client\WalkerFootstepTracker.cs" />
<Compile Include="..\..\client\CameraJuiceState.cs" Link="Client\CameraJuiceState.cs" />
<Compile Include="..\..\client\GraphicsSettings.cs" Link="Client\GraphicsSettings.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RustToDust.Core\RustToDust.Core.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />
<ProjectReference Include="..\..\src\RustToDust.HbGpu\RustToDust.HbGpu.csproj" AdditionalProperties="HbGpuNativeConfiguration=$(YmirNativeConfiguration)" />
<ProjectReference Include="..\..\src\RustToDust.Net\RustToDust.Net.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Directory\RustToDust.Directory.csproj" />
<ProjectReference Include="$(YmirRoot)/src/Ymir.Box3D/Ymir.Box3D.csproj" AdditionalProperties="YmirNativeConfiguration=$(YmirNativeConfiguration)" />

View file

@ -1,6 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Numerics;
using RustToDust.Core;
using RustToDust.Net;
using RustToDust.Ymir;
using Xunit;
using Ymir.Box3D;
@ -16,20 +20,24 @@ namespace RustToDust.Tests
var meta = sion.Metadata;
Assert.Equal(3072f, meta.SizeMeters);
Assert.Equal(6, meta.TileGrid);
Assert.Equal(512f, meta.TileSizeMeters);
Assert.Equal(1025, meta.GridRes);
Assert.Equal(3.0f, meta.CellSizeMeters);
Assert.Equal(16, meta.TileGrid);
Assert.Equal(192f, meta.TileSizeMeters);
Assert.Equal(6145, meta.GridRes);
Assert.Equal(0.5f, meta.CellSizeMeters);
Assert.Equal("heightmap_05m.u16z", meta.HeightmapFile);
Assert.False(string.IsNullOrWhiteSpace(meta.DemAssetHash));
Assert.Contains("swisstopo", meta.Attribution, StringComparison.OrdinalIgnoreCase);
Assert.Equal(1025 * 1025, sion.Heights.Length);
Assert.Equal(6145 * 6145, sion.BaseDem.Length);
Assert.Equal(2319, sion.Buildings.Count);
Assert.Equal(36, sion.CollisionMeshes.Count);
var terrain = TerrainField.LoadHeightmap(
meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY);
var terrain = TerrainField.LoadSharedHeightmap(
meta.SizeMeters, meta.GridRes, meta.TileGrid,
sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale,
meta.MinY, meta.MaxY);
// Verify Basilique de Valere and valley buildings align cleanly with heightmap.f32 (0.00m coordinate drift)
// Verify Basilique de Valere and valley buildings align cleanly with heightmap_05m.u16z (0.00m coordinate drift)
bool foundValere = false;
int flatAlignChecked = 0;
int closeAlignCount = 0;
@ -82,16 +90,19 @@ namespace RustToDust.Tests
{
var sion = SionMapLoader.Load();
var meta = sion.Metadata;
var terrain = TerrainField.LoadHeightmap(
meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY);
var terrain = TerrainField.LoadSharedHeightmap(
meta.SizeMeters, meta.GridRes, meta.TileGrid,
sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale,
meta.MinY, meta.MaxY);
Assert.True(terrain.IsHeightmapMode);
Assert.Equal(3072f, terrain.MapSize);
Assert.Equal(1536f, terrain.MapHalfExtent);
Assert.Equal(16, terrain.TileGridCount);
// Grid vertex exactness at (-1536, -1536) and (0, 0)
Assert.Equal(sion.Heights[0], terrain.SampleHeight(-1536f, -1536f), precision: 4);
Assert.Equal(sion.Heights[512 * 1025 + 512], terrain.SampleHeight(0f, 0f), precision: 4);
Assert.Equal(sion.SampleBaseDemAtIndex(0), terrain.SampleHeight(-1536f, -1536f), precision: 4);
Assert.Equal(sion.SampleBaseDemAtIndex(3072 * 6145 + 3072), terrain.SampleHeight(0f, 0f), precision: 4);
// Plaza spawn area is flat; Valere hill rises > 100m
var (_, plazaNy, _) = terrain.SampleNormal(-60f, 360f);
@ -126,7 +137,7 @@ namespace RustToDust.Tests
Assert.Empty(state.ArenaCoverBoxes);
Assert.Equal(MatchState.SionInitialSafeRadius, state.Spectators.SafeRadius);
// Verify StaticHeightField (1) + StaticMesh (36) exist in Ymir
// Verify lazy tiled StaticHeightField (192m tiles) + StaticMesh (36) exist in Ymir
int hfCount = 0;
int meshCount = 0;
var view = session.World.View;
@ -136,8 +147,10 @@ namespace RustToDust.Tests
if (kind == Box3DSoaKind.StaticHeightField) hfCount++;
else if (kind == Box3DSoaKind.StaticMesh) meshCount++;
}
Assert.Equal(1, hfCount);
Assert.Equal(36, meshCount);
Assert.InRange(hfCount, 1, 45);
Assert.Equal(hfCount, session.TileSync.ResidentTileCount);
Assert.InRange(session.TileSync.ResidentTreeTileCount, 1, 45);
Assert.Equal(36 + session.TileSync.ResidentTreeTileCount, meshCount);
// Verify zero contenders, spectators, or drops spawned inside any building
foreach (var c in state.Contenders)
@ -225,5 +238,567 @@ namespace RustToDust.Tests
float pDisp = MathF.Sqrt((player.X - pStartX) * (player.X - pStartX) + (player.Z - pStartZ) * (player.Z - pStartZ));
Assert.True(pDisp > 5f, $"Expected player displacement > 5m on Sion after 180 ticks, got {pDisp:F2}m");
}
[Fact]
public void SionBox3DTile_CraterRebuildsLocalTileOnlyAndLeavesNeighborsIntact()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
// Tile (7, 7) spans [-192, 0) x [-192, 0); neighbor tile (8, 7) spans [0, 192) x [-192, 0).
// Pick an open-sky coordinate strictly inside tile (7, 7) away from any building footprint.
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: 1);
Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetBefore));
Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborBefore));
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hitBefore = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f));
Assert.True(hitBefore.Hit);
Assert.Equal(Box3DPhysicsTileSync.HeightfieldTileStableIdBase + (ulong)(7 * 16 + 7), hitBefore.StableId);
// Stamp crater strictly inside tile (7, 7)
session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = cx,
Z = cz,
Radius = 6f,
Depth = 2.0f
});
int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4);
Assert.Equal(1, rebuilt);
Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetAfter));
Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborAfter));
Assert.NotEqual(handleTargetBefore, handleTargetAfter);
Assert.Equal(handleNeighborBefore, handleNeighborAfter);
var hitAfter = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f));
Assert.True(hitAfter.Hit);
Assert.True(hitAfter.Point.Y < hitBefore.Point.Y - 1.2f,
$"Expected Box3D raycast impact height to drop in crater (before={hitBefore.Point.Y:F3}, after={hitAfter.Point.Y:F3})");
}
[Fact]
public void ArenaScarLedgerStore_PersistsCratersAndRubbleAcrossResetAndRepairsToLayer0()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-scar-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string scarPath = Path.Combine(tempDir, "sion_scars_test.cultcache");
try
{
const float craterX = -120f;
const float craterZ = 180f;
const float rubbleX = 140f;
const float rubbleZ = 180f;
float baseCraterH;
float baseRubbleH;
float scarredCraterH;
float scarredRubbleH;
using (var host1 = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: scarPath, persistScars: true))
{
var state1 = host1.Session.State;
baseCraterH = state1.Terrain.SampleHeight(craterX, craterZ);
baseRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ);
state1.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
state1.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Rubble,
X = rubbleX,
Z = rubbleZ,
Radius = 6.0f,
Depth = 1.2f,
Yaw = 0.4f
});
scarredCraterH = state1.Terrain.SampleHeight(craterX, craterZ);
scarredRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ);
Assert.True(scarredCraterH < baseCraterH - 1.2f);
Assert.True(scarredRubbleH > baseRubbleH + 0.6f);
// ResetMatch preserves scars in RAM & flushes to CultCache
host1.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
Assert.Equal(scarredCraterH, host1.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(scarredRubbleH, host1.Session.State.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
}
Assert.True(File.Exists(scarPath), "Expected CultCache scar file on disk after host dispose");
using (var host2 = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 44, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: scarPath, persistScars: true))
{
var state2 = host2.Session.State;
Assert.Equal(scarredCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(scarredRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
// RepairArenaScars zeroes back to Layer 0
host2.RepairArenaScars();
Assert.Equal(baseCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(baseRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
Assert.Empty(state2.ScarLedger.Terrain);
}
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[Fact]
public void ValereSlopeHits_ClassifyAsTerrainNeverStaticCover_ForHitscanAndProjectile()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
var sion = session.State.SionMap!;
// Ensure Valere hill heightfield tiles are resident so Box3D heightfields are active on the slope ray
session.TileSync.EnsureTileRegion(session.World, terrain, 113f, -211f, halfTileRadius: 1);
// Find an open-sky steep Valere slope point and an unobstructed muzzle above it (zero buildings on ray)
Vector3 muzzle = default;
Vector3 dir = default;
bool foundSlope = false;
for (float sz = -290f; sz <= -175f && !foundSlope; sz += 6f)
{
for (float sx = 40f; sx <= 185f && !foundSlope; sx += 6f)
{
if (sion.IsInsideAnyBuildingXz(sx, sz, padding: 8.0f))
{
continue;
}
float sh = terrain.SampleHeight(sx, sz);
var (nx, ny, nz) = terrain.SampleNormal(sx, sz);
if (sh < 55f || ny >= 0.88f)
{
continue;
}
Vector3 slopePt = new(sx, sh, sz);
Vector3 nrm = Vector3.Normalize(new Vector3(nx, ny, nz));
Vector3 candMuzzle = slopePt + nrm * 32f + Vector3.UnitY * 8f;
Vector3 candDir = Vector3.Normalize(slopePt - candMuzzle);
float dist = Vector3.Distance(candMuzzle, slopePt) + 5f;
if (!sion.IntersectsAnyBuildingAabb(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist) &&
terrain.Raycast(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist, out float tx, out _, out float tz, out _) &&
!sion.IsInsideAnyBuildingXz(tx, tz, padding: 2.0f))
{
muzzle = candMuzzle;
dir = candDir;
foundSlope = true;
}
}
}
Assert.True(foundSlope, "Expected open-sky steep Valere slope ray unobstructed by buildings");
session.TileSync.EnsureTileRegion(session.World, terrain, muzzle.X, muzzle.Z, halfTileRadius: 1);
var events = new List<ISimEvent>();
session.DrainStepEvents(events);
// 1. Fire hitscan directly into Valere slope
var hitscanSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.RotaryAutocannon);
session.Ordnance.FireWeapon(new OrdnanceFireRequest(
Module: new MountedModule(hitscanSpec.Module, "hp.weapon.main", 0f),
ShooterStableId: ArenaSession.ContenderStableIdBase,
ShooterContender: session.State.Contenders[0],
ShooterLabel: "Tester",
IsSpectatorShooter: false,
ShooterEntityId: 0,
ShooterPos: muzzle,
MuzzlePos: muzzle,
AimDir: dir,
AimDist: 160f,
SpreadRad: 0f,
TargetEntityStableId: 0UL,
RootDef: hitscanSpec.RootNode,
WeaponKey: hitscanSpec.Key));
// 2. Fire ballistic projectile into Valere slope
var projSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.SabotSlugCannon);
session.Ordnance.FireWeapon(new OrdnanceFireRequest(
Module: new MountedModule(projSpec.Module, "hp.weapon.main", 0f),
ShooterStableId: ArenaSession.ContenderStableIdBase,
ShooterContender: session.State.Contenders[0],
ShooterLabel: "Tester",
IsSpectatorShooter: false,
ShooterEntityId: 0,
ShooterPos: muzzle,
MuzzlePos: muzzle,
AimDir: dir,
AimDist: 160f,
SpreadRad: 0f,
TargetEntityStableId: 0UL,
RootDef: projSpec.RootNode,
WeaponKey: projSpec.Key));
var impacts = new List<HitImpactEvent>();
for (int tick = 0; tick < 60; tick++)
{
session.Step();
events.Clear();
session.DrainStepEvents(events);
foreach (var ev in events)
{
if (ev is HitImpactEvent hit)
{
impacts.Add(hit);
}
}
if (impacts.Count >= 2)
{
break;
}
}
Assert.True(impacts.Count >= 2, $"Expected >= 2 slope impacts (hitscan + projectile), got {impacts.Count}");
Assert.All(impacts, h => Assert.Equal((byte)HitTargetKind.Terrain, h.TargetKind));
}
[Fact]
public void RepairArenaScars_ManyScarredTilesRebuildIncrementallyWithoutExhaustingWorldCapacity()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
// Materialize 20 resident tiles in a 5x4 grid and crater all 20
var spots = new List<(float X, float Z, float BaseH)>();
for (int tz = 5; tz <= 8; tz++)
{
for (int tx = 5; tx <= 9; tx++)
{
float wx = -terrain.MapHalfExtent + (tx + 0.5f) * terrain.MapTileSize;
float wz = -terrain.MapHalfExtent + (tz + 0.5f) * terrain.MapTileSize;
session.TileSync.EnsureTileResident(session.World, terrain, tx, tz);
float baseH = terrain.SampleHeight(wx, wz);
spots.Add((wx, wz, baseH));
session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = wx,
Z = wz,
Radius = 5f,
Depth = 1.6f
});
}
}
// Flush all 20 cratered tiles into Box3D heightfields without evicting non-actor tiles
int flushedBeforeRepair = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 20);
Assert.Equal(20, flushedBeforeRepair);
session.World.Step(1f / 60f);
var sion = session.State.SionMap!;
var sionMeta = sion.Metadata;
(float X, float Z, float BaseH) openSpot = default;
bool foundOpenSpot = false;
foreach (var s in spots)
{
if (!sion.IsInsideAnyBuildingXz(s.X, s.Z, padding: 6f))
{
openSpot = s;
foundOpenSpot = true;
break;
}
}
Assert.True(foundOpenSpot, "Expected at least one open-sky spot among the 20 cratered tiles");
float rayStartY = sionMeta.MaxY + 25f;
float raySpanY = -(sionMeta.MaxY - sionMeta.MinY + 60f);
var hitCratered = session.CastWorldRayClosest(new Vector3(openSpot.X, rayStartY, openSpot.Z), new Vector3(0f, raySpanY, 0f));
Assert.True(hitCratered.Hit);
Assert.True(hitCratered.Point.Y < openSpot.BaseH - 1.0f,
$"Expected cratered Box3D raycast height ({hitCratered.Point.Y:F3}) well below base ({openSpot.BaseH:F3})");
int freeBeforeRepair = session.World.FreeBodySlots;
Assert.True(freeBeforeRepair >= 20 + 32);
session.RepairArenaScars();
// When FreeBodySlots >= dirtyResidentCount + 32, RepairArenaScars flushes all dirty resident tiles immediately on tick 0
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));
var hitTick0 = session.CastWorldRayClosest(new Vector3(openSpot.X, rayStartY, openSpot.Z), new Vector3(0f, raySpanY, 0f));
Assert.True(hitTick0.Hit);
Assert.True(MathF.Abs(hitTick0.Point.Y - openSpot.BaseH) < 0.05f,
$"Expected tick-0 Box3D raycast height ({hitTick0.Point.Y:F3}) to match restored base ({openSpot.BaseH:F3})");
// Step across ticks so recycled slots remain healthy without exhausting world capacity
for (int t = 0; t < 20; t++)
{
session.Step();
Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256,
$"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) at tick {t}");
}
foreach (var (wx, wz, baseH) in spots)
{
Assert.Equal(baseH, terrain.SampleHeight(wx, wz), precision: 3);
}
}
[Fact]
public void ServerMatchHost_SionDesertSion_PreservesSionScarsAndDoesNotClobberExplicitScarFile()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-mapswitch-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache");
try
{
const float craterX = -120f;
const float craterZ = 180f;
float sionBaseH;
float sionScarredH;
using (var host = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true))
{
sionBaseH = host.Session.State.Terrain.SampleHeight(craterX, craterZ);
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
sionScarredH = host.Session.State.Terrain.SampleHeight(craterX, craterZ);
Assert.True(sionScarredH < sionBaseH - 1.2f);
// Switch Sion -> Desert: Desert must NOT inherit Sion craters, nor overwrite explicitSionPath
float desertBaseH;
host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false);
Assert.Empty(host.Session.State.ScarLedger.Terrain);
desertBaseH = host.Session.State.Terrain.SampleHeight(0f, 0f);
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = 0f,
Z = 0f,
Radius = 4.5f,
Depth = 1.4f
});
float desertScarredH = host.Session.State.Terrain.SampleHeight(0f, 0f);
Assert.True(desertScarredH < desertBaseH - 0.8f);
// Switch Desert -> Sion: Sion craters must be restored cleanly!
host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
Assert.Equal(sionScarredH, host.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3);
// Verify explicitSionPath on disk still holds Sion's AssetFingerprint & crater (never clobbered by Desert)
var diskSnap = ArenaScarLedgerStore.Load(explicitSionPath, host.Session.State.SionMap!.AssetFingerprint);
Assert.Single(diskSnap.Terrain);
Assert.Equal(craterX, diskSnap.Terrain[0].X);
Assert.Equal(craterZ, diskSnap.Terrain[0].Z);
}
// Also verify LocalArenaSession & ListenHostArenaSession carry scars across rounds and Sion -> Desert -> Sion
using (var local = new LocalArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, skipInitialDrop: true))
{
local.Inner.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
local.RequestNewMatch(43, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
local.RequestNewMatch(42, ArenaMapKind.Desert);
Assert.Empty(local.ViewState.ScarLedger.Terrain);
local.RequestNewMatch(44, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
local.RepairArenaScars();
local.RequestNewMatch(45, ArenaMapKind.Sion);
Assert.Equal(sionBaseH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
}
using (var listen = new ListenHostArenaSession(IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Sion))
{
listen.Host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
listen.RequestNewMatch(43, ArenaMapKind.Desert);
Assert.Empty(listen.ViewState.ScarLedger.Terrain);
listen.RequestNewMatch(44, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, listen.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
}
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[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);
}
}
}
}
}

View file

@ -0,0 +1,453 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Numerics;
using System.Text.Json;
using RustToDust.Core;
using RustToDust.Net;
using RustToDust.Ymir;
using Xunit;
using Ymir.Box3D;
namespace RustToDust.Tests
{
public sealed class SionTreeTests
{
[Fact]
public void SionTreeCatalog_LoadsWithoutBeechExcludesBuildingsAndMatchesArbresRemarquables()
{
var sion = SionMapLoader.Load();
var catalog = sion.Trees;
Assert.InRange(catalog.Count, 500, SionTreeCatalog.MaxTrees);
Assert.False(string.IsNullOrWhiteSpace(catalog.AssetHash));
Assert.Contains($":trees:{catalog.AssetHash}", sion.AssetFingerprint, StringComparison.Ordinal);
// Check binary disk budget + tree assets directory <= 12.4 MiB
string treesBin = Path.Combine(sion.DirectoryPath, "trees_sion.bin");
string treesDir = Path.Combine(sion.DirectoryPath, "trees");
long totalBytes = new FileInfo(treesBin).Length;
foreach (var f in Directory.EnumerateFiles(treesDir, "*", SearchOption.AllDirectories))
{
totalBytes += new FileInfo(f).Length;
}
Assert.True(totalBytes <= 13_000_000L, $"Expected Sion tree assets + bin <= 12.4 MiB, got {totalBytes:N0} B");
bool hasSequoia = false;
bool hasCedrus = false;
bool hasMonumentalPlane = false;
// Planta d'en Haut Giant Sequoia: LV95 (2593636.1374, 1120075.402) -> (-513.8626, -25.402)
float seqWx = 2593636.1374f - 2594150.0f;
float seqWz = 1120050.0f - 1120075.402f;
// Pratifori / Cimetiere Lebanon Cedar: LV95 (2593522.9419, 1119968.4164) -> (-627.0581, 81.5836)
float cedWx = 2593522.9419f - 2594150.0f;
float cedWz = 1120050.0f - 1119968.4164f;
// Planta d'en Haut Monumental Avenue (Aesculus/PlatanusMonumental archetype #9): LV95 (2593619.7614, 1120373.0299)
float plaWx = 2593619.7614f - 2594150.0f;
float plaWz = 1120050.0f - 1120373.0299f;
for (int i = 0; i < catalog.Count; i++)
{
var t = catalog.Trees[i];
Assert.True((byte)t.Species <= (byte)SionTreeSpecies.PlatanusMonumental);
string spName = t.Species.ToString();
Assert.DoesNotContain("Fagus", spName, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("Beech", spName, StringComparison.OrdinalIgnoreCase);
Assert.False(sion.IsInsideAnyBuildingXz(t.X, t.Z, 0f),
$"Tree {t.TreeId} ({t.Species}) placed inside building at ({t.X:F2}, {t.Z:F2})");
Assert.InRange(t.HeightM, 4.0f, 38.0f);
Assert.InRange(t.TrunkRadiusM, 0.10f, 1.20f);
if (t.Species == SionTreeSpecies.Sequoiadendron &&
MathF.Sqrt((t.X - seqWx) * (t.X - seqWx) + (t.Z - seqWz) * (t.Z - seqWz)) < 0.25f)
{
hasSequoia = true;
}
if (t.Species == SionTreeSpecies.Cedrus &&
MathF.Sqrt((t.X - cedWx) * (t.X - cedWx) + (t.Z - cedWz) * (t.Z - cedWz)) < 0.25f)
{
hasCedrus = true;
}
if (t.Species == SionTreeSpecies.PlatanusMonumental &&
MathF.Sqrt((t.X - plaWx) * (t.X - plaWx) + (t.Z - plaWz) * (t.Z - plaWz)) < 0.25f)
{
hasMonumentalPlane = true;
}
}
Assert.True(hasSequoia, "Expected Planta d'en Haut Sequoiadendron at exact Sion coordinates");
Assert.True(hasCedrus, "Expected Lebanon Cedrus at exact Sion coordinates");
Assert.True(hasMonumentalPlane, "Expected En Ville PlatanusMonumental at exact Sion coordinates");
}
[Fact]
public void SionTreeDestruction_OrdnanceSnapsAndChars_UpdatesBox3DColliderPersistsAndHeals()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13d-tree-scar-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string scarPath = Path.Combine(tempDir, "sion_tree_scars.cultcache");
try
{
ushort targetId = 0;
SionTreePlacement targetTree = default;
bool foundTarget = false;
using (var host = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: scarPath, persistScars: true))
{
var trees = host.Session.State.SionTrees!;
var catalog = trees.Catalog;
// Pick an isolated solid tree (TrunkRadiusM >= 0.28m) with no nearby buildings/neighbors on the ray
for (int i = 0; i < catalog.Count; i++)
{
var t = catalog.Trees[i];
if (t.TrunkRadiusM < 0.28f || t.IsMonumental) continue;
if (host.Session.State.SionMap!.IsInsideAnyBuildingXz(t.X, t.Z, 12f)) continue;
targetTree = t;
targetId = t.TreeId;
foundTarget = true;
break;
}
Assert.True(foundTarget, "Expected a solid non-monumental tree outside buildings");
host.Session.TileSync.EnsureTreeTileResident(host.Session.World, trees, targetTree.Tx, targetTree.Tz);
ulong expectedStableId = Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)targetTree.TileIndex;
// Horizontal ray through the trunk must hit the Box3D tree tile mesh
var rayOrigin = new Vector3(targetTree.X - 4.0f, targetTree.Y + 1.4f, targetTree.Z);
var raySpan = new Vector3(8.0f, 0f, 0f);
var preHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.True(preHit.Hit, "Expected horizontal ray to strike solid tree trunk collider");
Assert.Equal(expectedStableId, preHit.StableId);
// Artillery blast at trunk base snaps target tree; verify outer char radius on a second tree
var hitEvents = new List<TreeStateEvent>();
int changed = trees.ApplyBlast(new Vector3(targetTree.X, targetTree.Y + 0.5f, targetTree.Z), splashRadius: 10f, blastDamage: 240f, hitEvents);
Assert.True(changed >= 1);
Assert.Equal(SionTreeState.Snapped, trees.GetState(targetId));
foreach (var ev in hitEvents)
{
host.Session.State.ScarLedger.RecordTreeState(ev.TreeId, ev.State);
}
// Flush dirty tree tiles -> Box3D collider for snapped trunk must be gone
host.Session.TileSync.FlushDirtyTreeTiles(host.Session.World, trees, maxTilesPerTick: 4);
var postHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.False(postHit.Hit && postHit.StableId == expectedStableId &&
MathF.Abs(postHit.Point.X - targetTree.X) <= targetTree.TrunkRadiusM * 1.5f,
"Expected snapped tree trunk collider to be removed from Box3D tile mesh");
// Also test outer thermal char state on a distant intact tree
ushort charId = 0;
for (int i = 0; i < catalog.Count; i++)
{
var t = catalog.Trees[i];
if (t.TreeId == targetId || trees.GetState(t.TreeId) != SionTreeState.Intact) continue;
if (t.TrunkRadiusM < 0.30f) continue;
var evs = new List<TreeStateEvent>();
// Blast 8.5m away (outside snapCore, inside charRadius = 1.35 * 9.0) with moderate heat/blast
trees.ApplyBlast(new Vector3(t.X + 8.5f, t.Y + 1.0f, t.Z), splashRadius: 9.0f, blastDamage: 60f, evs);
if (trees.GetState(t.TreeId) == SionTreeState.Charred)
{
charId = t.TreeId;
host.Session.State.ScarLedger.RecordTreeState(charId, (byte)SionTreeState.Charred);
break;
}
}
Assert.NotEqual(0, charId);
// ResetMatch must preserve both Snapped and Charred tree scars
host.ResetMatch(43, ArenaMapKind.Sion);
Assert.Equal(SionTreeState.Snapped, host.Session.State.SionTrees!.GetState(targetId));
Assert.Equal(SionTreeState.Charred, host.Session.State.SionTrees!.GetState(charId));
// RepairArenaScars restores all trees to Intact and restores Box3D trunk collider
host.RepairArenaScars();
Assert.Equal(SionTreeState.Intact, host.Session.State.SionTrees!.GetState(targetId));
Assert.Equal(SionTreeState.Intact, host.Session.State.SionTrees!.GetState(charId));
host.Session.TileSync.EnsureTreeTileResident(host.Session.World, host.Session.State.SionTrees, targetTree.Tx, targetTree.Tz);
var healedHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.True(healedHit.Hit && healedHit.StableId == expectedStableId,
"Expected repaired tree trunk collider to be restored in Box3D");
}
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[Fact]
public void SionTreeDestruction_HeavyWalkerTramplesThinTreesButNotThickOrMonumental()
{
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!;
var trees = session.State.SionTrees!;
Assert.True(Catalog.Raptor.MassKg < SionTreeDestructionState.HeavyWalkerMinMassKg,
$"Expected Raptor ({Catalog.Raptor.MassKg}kg) < HeavyWalkerMinMassKg");
Assert.True(Catalog.Bastion.MassKg >= SionTreeDestructionState.HeavyWalkerMinMassKg,
$"Expected Bastion ({Catalog.Bastion.MassKg}kg) >= HeavyWalkerMinMassKg");
SionTreePlacement thin = default;
SionTreePlacement thick = default;
bool foundThin = false, foundThick = false;
foreach (var t in sion.Trees.Trees)
{
if (!foundThin && t.TrunkRadiusM >= 0.12f && t.TrunkRadiusM < SionTreeDestructionState.WalkerTrampleMaxTrunkRadiusM &&
!sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.0f))
{
thin = t;
foundThin = true;
}
if (!foundThick && t.TrunkRadiusM >= 0.45f &&
!sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.0f))
{
thick = t;
foundThick = true;
}
if (foundThin && foundThick) break;
}
Assert.True(foundThin && foundThick);
// Light walker (Raptor < HeavyWalkerMinMassKg) placed overlapping thin tree must NOT trample it
session.SetContenderPose(0, thin.X, thin.Z, 0f);
session.State.SpawnChassisDrop(thin.X, thin.Z, Catalog.Raptor);
Assert.True(session.TrySwapNearbyChassis(0), "Expected swap to Raptor near thin tree");
session.SetContenderPose(0, thin.X, thin.Z, 0f);
session.Step();
Assert.Equal(SionTreeState.Intact, trees.GetState(thin.TreeId));
// Heavy walker (Bastion >= HeavyWalkerMinMassKg) trampling same thin (< 0.30m) tree snaps it cleanly
session.State.SpawnChassisDrop(thin.X, thin.Z, Catalog.Bastion);
Assert.True(session.TrySwapNearbyChassis(0), "Expected swap to Bastion near thin tree");
session.SetContenderPose(0, thin.X, thin.Z, 0f);
session.Step();
Assert.Equal(SionTreeState.Snapped, trees.GetState(thin.TreeId));
// Heavy walker overlapping thick (>= 0.30m) tree must NOT trample it
session.SetContenderPose(0, thick.X, thick.Z, 0f);
session.Step();
Assert.Equal(SionTreeState.Intact, trees.GetState(thick.TreeId));
}
[Fact]
public void SionTreeDestruction_FlushDirtyTreeTiles_RestoresColliderImmediatelyAfterAllTileTreesSnappedAndRepaired()
{
using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!;
var trees = session.State.SionTrees!;
// Find an active-near tile or any tile containing solid (>= 0.20m) trees clear of buildings
SionTreePlacement targetTree = default;
bool found = false;
for (int i = 0; i < sion.Trees.Count; i++)
{
var t = sion.Trees.Trees[i];
if (t.TrunkRadiusM >= SionTreeDestructionState.MinColliderTrunkRadiusM &&
!sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.5f))
{
targetTree = t;
found = true;
break;
}
}
Assert.True(found);
// Place contender 0 in the target tile so SyncNeededTreeTiles keeps it needed across Step(),
// and do NOT manually call EnsureTreeTileResident after repair.
session.SetContenderPose(0, targetTree.X + 8.0f, targetTree.Z + 8.0f, 0f);
session.TileSync.EnsureTreeTileResident(session.World, trees, targetTree.Tx, targetTree.Tz);
ulong expectedStableId = Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)targetTree.TileIndex;
var rayOrigin = new Vector3(targetTree.X - 4.0f, targetTree.Y + 1.4f, targetTree.Z);
var raySpan = new Vector3(8.0f, 0f, 0f);
Assert.Equal(expectedStableId, session.CastWorldRayClosest(rayOrigin, raySpan).StableId);
// Snap EVERY solid tree in that tile -> removes the Box3D body completely (ResidentTreeTileCount drops)
foreach (int idx in sion.Trees.GetTileTreeIndices(targetTree.Tx, targetTree.Tz))
{
var tileTree = sion.Trees.Trees[idx];
if (tileTree.TrunkRadiusM >= SionTreeDestructionState.MinColliderTrunkRadiusM)
{
trees.ApplyBlast(new Vector3(tileTree.X, tileTree.Y + 0.5f, tileTree.Z), splashRadius: 4f, blastDamage: 300f);
}
}
session.TileSync.FlushDirtyTreeTiles(session.World, trees, maxTilesPerTick: 8);
var afterSnapHit = session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.False(afterSnapHit.Hit && afterSnapHit.StableId == expectedStableId,
"Expected Box3D tree tile body to be removed when all collider trees in tile are snapped");
// RepairArenaScars() + Step() (NO manual EnsureTreeTileResident!) must immediately restore Box3D collider
session.RepairArenaScars();
var immediateHit = session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.True(immediateHit.Hit && immediateHit.StableId == expectedStableId,
$"Expected RepairArenaScars FlushDirtyTreeTiles to restore tree collider {expectedStableId}, got Hit={immediateHit.Hit} StableId={immediateHit.StableId}");
session.Step();
var stepHit = session.CastWorldRayClosest(rayOrigin, raySpan);
Assert.True(stepHit.Hit && stepHit.StableId == expectedStableId,
$"Expected tick-0 Step() to keep restored tree collider {expectedStableId}, got Hit={stepHit.Hit} StableId={stepHit.StableId}");
}
[Fact]
public void SionTreeDestruction_CumulativeBlastDamage_TwoColdStartRecoillessHitsSnapMediumTrunk()
{
var sion = SionMapLoader.Load();
var trees = new SionTreeDestructionState(sion.Trees);
SionTreePlacement med = default;
bool found = false;
foreach (var t in sion.Trees.Trees)
{
if (t.TrunkRadiusM >= 0.32f && t.TrunkRadiusM <= 0.39f)
{
med = t;
found = true;
break;
}
}
Assert.True(found, "Expected a medium ~0.35m trunk tree in Sion catalog");
// Cold-start Recoilless shell: WeaponDamage=85 * ~0.65 cold thermal scale = ~55.25 damage (< 65f one-shot core threshold)
float coldRecoillessDmg = Catalog.Recoilless.WeaponDamage * 0.65f;
var hitPoint = new Vector3(med.X + med.TrunkRadiusM, med.Y + 1.0f, med.Z);
// Hit #1: chars the tree without snapping it immediately
trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg);
Assert.Equal(SionTreeState.Charred, trees.GetState(med.TreeId));
// Hit #2: cumulative damage reaches snapThreshold (~98..105) -> cleanly snaps the trunk
trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg);
Assert.Equal(SionTreeState.Snapped, trees.GetState(med.TreeId));
// Repair clears accumulated damage so another single cold-start hit only chars again
trees.RepairAll();
Assert.Equal(SionTreeState.Intact, trees.GetState(med.TreeId));
trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg);
Assert.Equal(SionTreeState.Charred, trees.GetState(med.TreeId));
}
[Fact]
public void SionTreeDestruction_SmallArmsCannotFellOrCharMediumOakOrMonumentalSequoia()
{
var sion = SionMapLoader.Load();
var trees = new SionTreeDestructionState(sion.Trees);
SionTreePlacement oak = default;
SionTreePlacement sequoia = default;
bool foundOak = false, foundSequoia = false;
foreach (var t in sion.Trees.Trees)
{
if (!foundOak && t.Species == SionTreeSpecies.QuercusPubescens && t.TrunkRadiusM >= 0.32f)
{
oak = t;
foundOak = true;
}
if (!foundSequoia && t.Species == SionTreeSpecies.Sequoiadendron)
{
sequoia = t;
foundSequoia = true;
}
if (foundOak && foundSequoia) break;
}
Assert.True(foundOak && foundSequoia);
float mgDmg = Catalog.Mg762.WeaponDamage; // 12f (< 25f)
var oakHit = new Vector3(oak.X + oak.TrunkRadiusM, oak.Y + 1.0f, oak.Z);
var seqHit = new Vector3(sequoia.X + sequoia.TrunkRadiusM, sequoia.Y + 1.0f, sequoia.Z);
for (int i = 0; i < 30; i++)
{
trees.ApplyBlast(oakHit, splashRadius: 2.5f, blastDamage: mgDmg);
trees.ApplyBlast(seqHit, splashRadius: 2.5f, blastDamage: mgDmg);
}
Assert.Equal(SionTreeState.Intact, trees.GetState(oak.TreeId));
Assert.Equal(SionTreeState.Intact, trees.GetState(sequoia.TreeId));
}
[Fact]
public void CultNet_RemoteClientSyncsTreeScarsInPersistentSnapshotBubbleAndRepair()
{
using var host = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, persistScars: false);
var hostTrees = host.Session.State.SionTrees!;
// Snap a historical tree before client joins
var histTree = hostTrees.Catalog.Trees[0];
host.Session.State.ApplyTreeState(histTree.TreeId, SionTreeState.Snapped, recordInLedger: true);
using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "TreeTester");
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
for (int i = 0; i < 120 && !client.IsJoined; i++)
{
nowMs += 16;
host.StepOnce(nowMs);
client.BeginRenderFrame(1f / 60f, 0f);
System.Threading.Thread.Sleep(5);
}
Assert.True(client.IsJoined, "Remote client failed to join Sion ServerMatchHost");
Assert.Equal(SionTreeState.Snapped, client.ViewState.SionTrees!.GetState(histTree.TreeId));
// Find a tree near the remote client's local contender (within 576m local geometry bubble)
var local = client.LocalContender;
SionTreePlacement liveTree = default;
bool foundLive = false;
foreach (var t in hostTrees.Catalog.Trees)
{
if (t.TreeId == histTree.TreeId || t.TrunkRadiusM < 0.25f) continue;
float dx = t.X - local.X;
float dz = t.Z - local.Z;
float dist = MathF.Sqrt(dx * dx + dz * dz);
if (dist <= 500f)
{
liveTree = t;
foundLive = true;
break;
}
}
Assert.True(foundLive, "Expected a solid tree within 500m of local contender");
// Snap it via Ordnance sink on host so TreeStateEvent flows through the 576m bubble
((IOrdnanceTargetSink)host.Session).ApplyTreeImpact(
Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)liveTree.TileIndex,
new Vector3(liveTree.X, liveTree.Y + 0.5f, liveTree.Z),
splashRadius: 6.0f,
damage: 250f);
for (int i = 0; i < 60 && client.ViewState.SionTrees!.GetState(liveTree.TreeId) != SionTreeState.Snapped; i++)
{
nowMs += 16;
host.StepOnce(nowMs);
client.BeginRenderFrame(1f / 60f, 0f);
System.Threading.Thread.Sleep(5);
}
Assert.Equal(SionTreeState.Snapped, client.ViewState.SionTrees!.GetState(liveTree.TreeId));
// RepairArenaScars propagates to remote client
host.RepairArenaScars();
for (int i = 0; i < 60 && client.ViewState.SionTrees!.GetState(liveTree.TreeId) != SionTreeState.Intact; i++)
{
nowMs += 16;
host.StepOnce(nowMs);
client.BeginRenderFrame(1f / 60f, 0f);
System.Threading.Thread.Sleep(5);
}
Assert.Equal(SionTreeState.Intact, client.ViewState.SionTrees!.GetState(histTree.TreeId));
Assert.Equal(SionTreeState.Intact, client.ViewState.SionTrees!.GetState(liveTree.TreeId));
}
}
}

View file

@ -13,7 +13,7 @@ namespace RustToDust.Tests
public void Generate_ProducesDeterministicNonFlatReliefWithinBounds()
{
Assert.Equal(1536f, TerrainField.ArenaSize);
Assert.Equal(8, TerrainField.TileGridCount);
Assert.Equal(8, TerrainField.DesertTileGridCount);
Assert.Equal(192f, TerrainField.TileSize);
Assert.Equal(-18f, TerrainField.MinWorldHeight);
Assert.Equal(52f, TerrainField.MaxWorldHeight);
@ -56,7 +56,6 @@ namespace RustToDust.Tests
public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles()
{
var terrain = TerrainField.Generate(42UL, Array.Empty<ArenaBoxSpec>());
terrain.ClearDirtyMask();
// Tile (3, 3) spans X in [-192, 0), Z in [-192, 0).
// Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else.
@ -79,15 +78,15 @@ namespace RustToDust.Tests
$"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})");
// Only tile (3, 3) should have incremented from version 1 to 2
for (int tz = 0; tz < TerrainField.TileGridCount; tz++)
for (int tz = 0; tz < terrain.TileGridCount; tz++)
{
for (int tx = 0; tx < TerrainField.TileGridCount; tx++)
for (int tx = 0; tx < terrain.TileGridCount; tx++)
{
int expected = (tx == 3 && tz == 3) ? 2 : 1;
Assert.Equal(expected, terrain.TileVersions[tx, tz]);
Assert.Equal(expected, terrain.StructuralTileVersions[tx, tz]);
Assert.Equal(expected, terrain.VisualTileVersions[tx, tz]);
}
}
Assert.Equal(1UL << (3 * TerrainField.TileGridCount + 3), terrain.DirtyTileMask);
}
[Fact]

View file

@ -125,7 +125,7 @@ namespace RustToDust.Tests
// All 14 non-starter chassis launch in Wave 0 orbital gear pods and touch down into GroundDrops
var state = new MatchState(seed: 42);
for (int t = 0; t < 300; t++)
for (int t = 0; t < 900; t++)
{
state.Time += 1f / 60f;
state.OrbitalDrop.Step(1f / 60f);