using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Numerics; using System.Threading; using GameCult.Mesh; using GameCult.Networking; using RustToDust.Core; using RustToDust.Net; using RustToDust.Ymir; using Xunit; using Xunit.Abstractions; namespace RustToDust.Tests { public sealed class CultNetMultiplayerTests { private readonly ITestOutputHelper _output; public CultNetMultiplayerTests(ITestOutputHelper output) { _output = output; } [Fact] public void SnapshotCodec_WorstCase12ContendersAndWalkersAndCombatSpecs_StrictlyFitsIn1152Bytes() { var state = new MatchState(seed: 42, ArenaMapKind.Desert); var local = state.Contenders[0]; local.Grid.SwapChassis(Catalog.Bastion); // large 8x8 dorsal mech grid var contenders = new List(12); var walkers = new List(12); var specs = new List(10); for (int i = 0; i < 12; i++) { contenders.Add(new NetContenderState { SlotId = (byte)i, Alive = true, IsHuman = true, Fire = true, Brake = false, Snap = false, Pos = new Vector3(i * 10f, 3f, -i * 5f), Rot = Quaternion.Identity, Vel = new Vector3(12f, 0f, 4f), AimYaw = 0.5f, AimPitchDeg = 10f, Throttle = 1f, Steer = -0.5f, CoreHpRatio = 0.85f, MaxThermalRatio = 0.45f }); var ws = new WalkerVisualSnapshot { LegCount = 4 }; for (int l = 0; l < 4; l++) { ws.LegAngles[l] = new WalkerLegAngles { HipPitch = 0.4f, HipRoll = 0.1f, KneeFlex = -0.8f, HockFlex = 0.3f, AnklePitch = 0.2f }; ws.FootNormal[l] = Vector3.UnitY; ws.LoadG[l] = 1.2f; } walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws }); } for (int i = 0; i < 10; i++) { specs.Add(new NetSpectatorState { Id = (byte)i, Alive = true, Stance = SpectatorStance.Provoked, TargetContenderId = 0, Pos = new Vector3(100f + i * 5f, 4f, -80f), Rot = Quaternion.Identity, Vel = new Vector3(2f, 0f, -3f) }); } byte[] p1 = SnapshotCodec.EncodeCorePvs( 1, 42, 84, 1.4f, 10, 100, 450f, MatchPhase.Active, null, 2, 0xFFF, local, new Vector3(0.1f, 0.2f, 0.05f), contenders, walkers, specs); byte[] w1 = SnapshotCodec.WrapLatest(p1, 1, 1); byte[] p2 = SnapshotCodec.EncodeSpectatorOrbitHalf(1, 42, 0, Enumerable.Range(0, 28).Select(i => specs[i % specs.Count]).ToList()); byte[] w2 = SnapshotCodec.WrapLatest(p2, 1, 2); var radarList = Enumerable.Range(0, 32).Select(i => new NetRadarContact { EntityId = (byte)i, Visible = true, LastSeenX = i * 5f, LastSeenZ = -i * 5f }).ToList(); byte[] p3 = SnapshotCodec.EncodeRadarContacts(1, 42, radarList.Take(11).ToList(), radarList); byte[] w3 = SnapshotCodec.WrapLatest(p3, 1, 3); byte[] pIn = SnapshotCodec.EncodeClientInput(new ClientInputPacket(1, 99, 1234, new PlayerInput(1f, -0.5f, 10f, 20f, true, true, false, 2f, 0.5f))); byte[] wIn = SnapshotCodec.WrapLatest(pIn, 1, 4, SnapshotCodec.SchemaInputId); byte[] udp1 = EncodeRudpLatestDatagram(w1, 1); byte[] udp2 = EncodeRudpLatestDatagram(w2, 2); byte[] udp3 = EncodeRudpLatestDatagram(w3, 3); byte[] udpIn = EncodeRudpLatestDatagram(wIn, 4); _output.WriteLine($"Max frame bytes: Packet1={w1.Length}B, Packet2={w2.Length}B, Packet3={w3.Length}B, Input={wIn.Length}B"); _output.WriteLine($"Max UDP wire bytes: Packet1={udp1.Length}B, Packet2={udp2.Length}B, Packet3={udp3.Length}B, Input={udpIn.Length}B"); Assert.True(w1.Length <= SnapshotCodec.MaxLatestFrameBytes, $"Packet1 frame {w1.Length}B > {SnapshotCodec.MaxLatestFrameBytes}B"); Assert.True(w2.Length <= SnapshotCodec.MaxLatestFrameBytes, $"Packet2 frame {w2.Length}B > {SnapshotCodec.MaxLatestFrameBytes}B"); Assert.True(w3.Length <= SnapshotCodec.MaxLatestFrameBytes, $"Packet3 frame {w3.Length}B > {SnapshotCodec.MaxLatestFrameBytes}B"); Assert.True(wIn.Length <= SnapshotCodec.MaxLatestFrameBytes, $"Input frame {wIn.Length}B > {SnapshotCodec.MaxLatestFrameBytes}B"); Assert.True(udp1.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet1 UDP {udp1.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); Assert.True(udp2.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet2 UDP {udp2.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); Assert.True(udp3.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet3 UDP {udp3.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); Assert.True(udpIn.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Input UDP {udpIn.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); var decoded = SnapshotCodec.DecodeCorePvs(SnapshotCodec.Unwrap(w1).Payload.Span); Assert.Equal(12, decoded.Contenders.Count); Assert.Equal(42u, decoded.SnapshotSeq); } [Fact] public void RealUdpLoopback_TwoClientsSion_DriveFireDamageCargoAndSimEvents() { using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); using var clientA = new RemoteArenaSession(ep, "Alpha"); using var clientB = new RemoteArenaSession(ep, "Bravo"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Assert.True(PumpUntil(host, new[] { clientA, clientB }, () => clientA.IsJoined && clientB.IsJoined, ref nowMs, 3000), "Both UDP clients should join ServerMatchHost"); Assert.NotEqual(clientA.LocalContenderId, clientB.LocalContenderId); int slotA = clientA.LocalContenderId; int slotB = clientB.LocalContenderId; // Place A and B facing each other 28m apart in open Sion plaza var anchor = host.Session.State.Contenders[slotA]; host.Session.SetContenderPose(slotA, anchor.X, anchor.Z, 0f); host.Session.SetContenderPose(slotB, anchor.X, anchor.Z + 28f, MathF.PI); // Give clientB a cargo module & equip it over reliable schema channel -> verify private cargo not leaked to A! host.Session.State.Contenders[slotB].Grid.TryAddCargo(Catalog.Autocannon); host.Session.State.Contenders[slotA].Grid.TryAddCargo(Catalog.CopperRad); int cargoIdxB = host.Session.State.Contenders[slotB].Grid.Cargo.Count - 1; Assert.True(clientB.RequestEquipCargo(cargoIdxB, "hp.weapon.roof")); float startAz = clientA.LocalContender.Z; float bArmorBefore = host.Session.State.Contenders[slotB].Grid.TotalArmorRatio(); // Step 90 ticks: Client A drives forward + fires at Client B for (int t = 0; t < 90; t++) { var posB = host.Session.State.Contenders[slotB]; clientA.SubmitLocalInput(new PlayerInput(0.6f, 0f, posB.X, posB.Z, Fire: true, InteractPickup: false, Brake: false, AimWorldY: posB.Y), true); clientB.SubmitLocalInput(new PlayerInput(0f, 0f, anchor.X, anchor.Z, Fire: false, InteractPickup: false, Brake: true), true); nowMs += 16; host.StepOnce(nowMs); clientA.BeginRenderFrame(1.0 / 60.0, 1f); clientB.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } Assert.True(clientA.LocalContender.Z > startAz + 1.5f, "Client A should have advanced under Option M + server auth"); Assert.True(host.Session.State.Contenders[slotB].Grid.TotalArmorRatio() < bArmorBefore, "Client A's fire should damage Client B on server"); Assert.True(clientB.LocalContender.Grid.TotalArmorRatio() < 1.0f, "Client B should receive HitImpactEvent armor damage"); Assert.Equal(Catalog.Autocannon.Id, clientA.ViewState.Contenders[slotB].Grid.GetMountedOn("hp.weapon.roof")?.Spec.Id); Assert.Empty(clientA.ViewState.Contenders[slotB].Grid.Cargo); // Private cargo NOT leaked! Assert.True(clientA.ViewState.Tracers.Count > 0 || host.Session.State.Contenders[slotB].Grid.HitSequence > 0); } [Fact] public void AntiWallhack_PvsPayloadAudit_OccludedRivalAndExemplarOmittedUntilPvsEnter() { using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 12, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); using var clientA = new RemoteArenaSession(ep, "Alpha"); using var clientB = new RemoteArenaSession(ep, "Bravo"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Assert.True(PumpUntil(host, new[] { clientA, clientB }, () => clientA.IsJoined && clientB.IsJoined, ref nowMs, 3000)); int slotA = clientA.LocalContenderId; int slotB = clientB.LocalContenderId; // Place A and B on opposite sides of tall cover box (> 65m apart so outside proximity PVS envelope!) var box = host.Session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.3f); host.Session.SetContenderPose(slotA, box.X, box.Z - box.HalfZ - 40f, 0f); host.Session.SetContenderPose(slotB, box.X, box.Z + box.HalfZ + 40f, 0f); if (host.Session.State.ObserverStates.TryGetValue(slotA, out var obsA)) obsA.ContenderContacts.Remove(slotB); if (host.Session.State.ObserverStates.TryGetValue(slotB, out var obsB)) obsB.ContenderContacts.Remove(slotA); // Step 10 ticks so server recomputes PVS & snapshots while B also tries moving behind cover float preBClientX = clientA.ViewState.Contenders[slotB].X; float preBClientZ = clientA.ViewState.Contenders[slotB].Z; float preBServerZ = host.Session.State.Contenders[slotB].Z; for (int t = 0; t < 10; t++) { clientB.SubmitLocalInput(new PlayerInput(1f, 0f, 0f, 0f, false, false, false), true); nowMs += 16; host.StepOnce(nowMs); clientA.BeginRenderFrame(1.0 / 60.0, 1f); clientB.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } Assert.False(host.Session.IsEntityInPeerPvs(slotA, true, slotB), "Occluded rival > 65m must NOT be in Peer A PVS"); Assert.False(clientA.IsContenderVisible(slotB), "Client A must mark occluded rival invisible"); Assert.False(clientA.LocalContenderContacts.TryGetValue(slotB, out var memB) && MatchState.IsContactOnRadar(memB)); Assert.True(MathF.Abs(host.Session.State.Contenders[slotB].Z - preBServerZ) > 0.25f, "Server B actually moved behind cover"); Assert.Equal(preBClientX, clientA.ViewState.Contenders[slotB].X); Assert.Equal(preBClientZ, clientA.ViewState.Contenders[slotB].Z); // Now move B into open plaza right in front of A AND swap B's chassis while occluded -> verify PvsEnter delivers chassis & pose! host.Session.State.SpawnChassisDrop(box.X, box.Z + box.HalfZ + 40f, Catalog.Anvil); Assert.True(host.Session.TrySwapNearbyChassis(slotB)); host.Session.SetContenderPose(slotB, box.X + 18f, box.Z - box.HalfZ - 40f, 0f); for (int t = 0; t < 12; t++) { nowMs += 16; host.StepOnce(nowMs); clientA.BeginRenderFrame(1.0 / 60.0, 1f); clientB.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } Assert.True(clientA.IsContenderVisible(slotB), "Rival entering open LOS must become PVS visible"); Assert.Equal(Catalog.Anvil.Id, clientA.ViewState.Contenders[slotB].Grid.Spec.Id); } [Fact] public void OptionM_LocalPredictionMovesImmediatelyAtZeroMs_ReconcilesSmoothly_AndHardSnapsOver4m() { using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); using var client = new RemoteArenaSession(serverEp, "Predictor"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); int slot = client.LocalContenderId; host.Session.SetContenderPose(slot, 0f, 0f, 0f); for (int t = 0; t < 4; t++) { nowMs += 16; host.StepOnce(nowMs); client.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } float initialZ = client.GetInterpolatedContenderPose(slot, 1f).Pos.Z; // Drop ALL inbound snapshots temporarily while client drives 10 ticks -> Option M must predict movement immediately! client.DebugInboundLatestDropFilter = _ => true; for (int t = 0; t < 10; t++) { client.SubmitLocalInput(new PlayerInput(1f, 0f, 0f, 60f, false, false, false), true); } float predictedZ = client.GetInterpolatedContenderPose(slot, 1f).Pos.Z; Assert.True(predictedZ > initialZ + 0.10f, $"Option M must move immediately at 0ms before snapshots arrive ({initialZ:F3} -> {predictedZ:F3})"); Assert.True(client.UnackedInputCount >= 10); // Re-enable snapshots & let server process delayed packets -> verify reconciliation replays unacked & decays error smoothly client.DebugInboundLatestDropFilter = null; for (int t = 0; t < 12; t++) { nowMs += 16; host.StepOnce(nowMs); client.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } Assert.Equal(0, client.UnackedInputCount); // Force > 4.0m authoritative displacement (teleport) -> Option M MUST hard-snap residual error to zero! host.Session.SetContenderPose(slot, 45f, 45f, 0f); bool sawTeleportSnap = false; float errAtSnap = float.MaxValue; for (int t = 0; t < 10; t++) { nowMs += 16; host.StepOnce(nowMs); client.BeginRenderFrame(1.0 / 60.0, 1f); var p = client.GetInterpolatedContenderPose(slot, 1f).Pos; if (Vector2.Distance(new Vector2(p.X, p.Z), new Vector2(45f, 45f)) < 2.0f) { sawTeleportSnap = true; errAtSnap = client.CurrentPredictionError.Length(); break; } Thread.Sleep(1); } Assert.True(sawTeleportSnap, "Client should receive >4m teleport snapshot"); Assert.True(errAtSnap < 0.001f, $"Expected >4m teleport to hard-snap prediction error to zero, got {errAtSnap:F4}m"); var snappedPos = client.GetInterpolatedContenderPose(slot, 1f).Pos; Assert.InRange(Vector2.Distance(new Vector2(snappedPos.X, snappedPos.Z), new Vector2(45f, 45f)), 0f, 1.5f); } [Fact] public void OptionL1_DisconnectAndTimeoutHandBackToAi_AndReconnectTokenReclaimsExactSlot() { using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); var clientA = new RemoteArenaSession(serverEp, "Nomad"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); int originalSlot = clientA.LocalContenderId; Guid token = clientA.ReconnectToken; Assert.NotEqual(Guid.Empty, token); Assert.True(host.Session.State.Contenders[originalSlot].IsHuman); // 1. Graceful disconnect -> IsHuman flips to false (AI takes over surviving chassis) clientA.DisconnectGracefully("BRB"); clientA.Dispose(); for (int t = 0; t < 35; t++) { nowMs += 16; host.StepOnce(nowMs); Thread.Sleep(1); } Assert.False(host.Session.State.Contenders[originalSlot].IsHuman, "Graceful disconnect must hand slot back to AI"); Assert.Equal(0, host.ConnectedHumanCount); // 2. Reconnect presenting matching ReconnectToken -> reclaims exact same slot! using var clientAReconnect = new RemoteArenaSession(serverEp, "Nomad", token); Assert.True(PumpUntil(host, new[] { clientAReconnect }, () => clientAReconnect.IsJoined, ref nowMs, 3000)); Assert.Equal(originalSlot, clientAReconnect.LocalContenderId); Assert.True(host.Session.State.Contenders[originalSlot].IsHuman); // 3. Simulate > 5000ms silence (timeout) -> server releases slot back to AI cleanly! nowMs += ServerMatchHost.IdleTimeoutMs + 250; host.StepOnce(nowMs); Assert.False(host.Session.State.Contenders[originalSlot].IsHuman, "5s silence timeout must hand slot back to AI"); Assert.Equal(0, host.ConnectedHumanCount); } [Fact] public void Cut5cFix1_Sion30mAcrossBuilding_OmitsOccludedRivalFromInitialStateCorePvsAndEvents() { using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); // Pick a solid Sion Old Town building ~30m wide and place contender 0 & 1 on opposite sides BEFORE client B joins! var sion = host.Session.State.SionMap!; var terrain = host.Session.State.Terrain; float halfH = Catalog.Jackal.HalfHeight; SionBuildingAabb? chosen = null; float z1 = 0f, z2 = 0f; for (int i = 0; i < sion.Buildings.Count; i++) { var b = sion.Buildings[i]; if (b.Class != "Gebaeude Einzelhaus" || b.HalfX < 6f || b.HalfZ < 6f || (b.RoofY - b.GroundY) < 9f || MathF.Abs(b.CenterX) > 600f || MathF.Abs(b.CenterZ) > 600f) continue; float candZ1 = b.CenterZ - b.HalfZ - 5f; float candZ2 = b.CenterZ + b.HalfZ + 5f; if (MathF.Abs(candZ2 - candZ1) > 48f) continue; if (sion.IsInsideAnyBuildingXz(b.CenterX, candZ1, 3.5f) || sion.IsInsideAnyBuildingXz(b.CenterX, candZ2, 3.5f)) continue; float y1 = terrain.SampleHeight(b.CenterX, candZ1) + halfH + 0.15f; float y2 = terrain.SampleHeight(b.CenterX, candZ2) + halfH + 0.15f; if (!host.Session.HasLineOfSight(b.CenterX, MatchRules.GetObserverEyeY(y1, halfH), candZ1, b.CenterX, MatchRules.GetTargetAimY(y2, halfH), candZ2)) { chosen = b; z1 = candZ1; z2 = candZ2; break; } } Assert.NotNull(chosen); var building = chosen!.Value; using var clientA = new RemoteArenaSession(ep, "Alpha"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); int slotA = clientA.LocalContenderId; // Place A on side 1, and pick an AI/B slot on side 2 (~30m away across the building) BEFORE clientB joins int slotB = (slotA + 1) % MatchState.ContenderCount; host.Session.SetContenderPose(slotA, building.CenterX, z1, 0f); host.Session.SetContenderPose(slotB, building.CenterX, z2, MathF.PI); host.Session.State.SpawnChassisDrop(building.CenterX, z2 + 2f, Catalog.Anvil); host.StepOnce(nowMs += 16); // Re-place B after step and join B while A & B are ~30m apart across the building host.Session.SetContenderPose(slotA, building.CenterX, z1, 0f); host.Session.SetContenderPose(slotB, building.CenterX, z2, MathF.PI); host.StepOnce(nowMs += 16); Assert.False(host.Session.IsEntityInPeerPvs(slotA, true, slotB), "Occluded rival 30m across Sion building must NOT be in Peer A PVS (no 65m blind bypass)"); using var clientB = new RemoteArenaSession(ep, "Bravo"); Assert.True(PumpUntil(host, new[] { clientA, clientB }, () => clientB.IsJoined, ref nowMs, 3000)); int realSlotB = clientB.LocalContenderId; // Verify InitialMatchStateDto omits occluded rival at ~30m across Sion building: // Retire clientA, pin slotA at z1 and slotB at z2, then reconnect clientA with its token! Guid tokenA = clientA.ReconnectToken; clientA.DisconnectGracefully("RejoinTest"); clientA.Dispose(); for (int t = 0; t < 35; t++) { host.Session.SetContenderPose(slotA, building.CenterX, z1, 0f); host.Session.SetContenderPose(realSlotB, building.CenterX, z2, MathF.PI); nowMs += 16; host.StepOnce(nowMs); clientB.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } using var clientARejoin = new RemoteArenaSession(ep, "Alpha", tokenA); Assert.True(PumpUntil(host, new[] { clientARejoin, clientB }, () => clientARejoin.IsJoined, ref nowMs, 3000)); Assert.Equal(slotA, clientARejoin.LocalContenderId); Assert.False(clientARejoin.IsContenderVisible(realSlotB), "Occluded rival 30m across building must not be visible in InitialMatchStateDto"); Assert.Equal(0f, clientARejoin.ViewState.Contenders[realSlotB].X); Assert.Equal(0f, clientARejoin.ViewState.Contenders[realSlotB].Z); // Re-pin & test live events while occluded behind building host.Session.SetContenderPose(slotA, building.CenterX, z1, 0f); host.Session.SetContenderPose(realSlotB, building.CenterX, z2, MathF.PI); if (host.Session.State.ObserverStates.TryGetValue(slotA, out var obsA)) obsA.ContenderContacts.Remove(realSlotB); int dropsBefore = clientARejoin.ViewState.GroundDrops.Count(d => !d.PickedUp && Vector2.Distance(new Vector2(d.X, d.Z), new Vector2(building.CenterX, z2)) < 12f); host.Session.State.SpawnChassisDrop(building.CenterX, z2 + 3f, Catalog.Paladin); int hitsBefore = clientARejoin.ViewState.HitEvents.Count; int tracersBefore = clientARejoin.ViewState.Tracers.Count; for (int t = 0; t < 10; t++) { clientARejoin.SubmitLocalInput(new PlayerInput(0f, 0f, building.CenterX, z1 - 10f, false, false, false), true); clientB.SubmitLocalInput(new PlayerInput(0f, 0f, building.CenterX + 3f, z2 + 6f, Fire: true, false, false, AimWorldY: terrain.SampleHeight(building.CenterX + 3f, z2 + 6f)), true); nowMs += 16; host.StepOnce(nowMs); clientARejoin.BeginRenderFrame(1.0 / 60.0, 1f); clientB.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } Assert.False(host.Session.IsEntityInPeerPvs(slotA, true, realSlotB)); Assert.False(clientARejoin.IsContenderVisible(realSlotB)); int dropsAfter = clientARejoin.ViewState.GroundDrops.Count(d => !d.PickedUp && Vector2.Distance(new Vector2(d.X, d.Z), new Vector2(building.CenterX, z2)) < 12f); Assert.Equal(dropsBefore, dropsAfter); // Any HitImpactEvent or ShotFiredEvent from occluded B behind the building must NOT leak B's coordinates to A! for (int i = tracersBefore; i < clientARejoin.ViewState.Tracers.Count; i++) { var tr = clientARejoin.ViewState.Tracers[i]; Assert.True(Vector2.Distance(new Vector2(tr.StartX, tr.StartZ), new Vector2(building.CenterX, z2)) > 5f, "Occluded ShotFiredEvent must not leak rival shooter coords"); } for (int i = hitsBefore; i < clientARejoin.ViewState.HitEvents.Count; i++) { var he = clientARejoin.ViewState.HitEvents[i]; Assert.True(Vector2.Distance(new Vector2(he.SourceX, he.SourceZ), new Vector2(building.CenterX, z2)) > 5f, "Occluded HitImpactEvent must scrub SourceX/Y/Z if shooter not in PVS"); } } [Fact] public void Cut5cFix2_WalkerGaitClock_ChassisSwapSink_AndSpectatorWalkerSync() { using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); var serverEp = new IPEndPoint(IPAddress.Loopback, host.BoundPort); // Real 120ms RTT UDP delay proxy (60ms uplink + 60ms downlink) using var proxyToClient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp) { Blocking = false }; using var proxyToServer = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp) { Blocking = false }; proxyToClient.Bind(new IPEndPoint(IPAddress.Loopback, 0)); proxyToServer.Bind(new IPEndPoint(IPAddress.Loopback, 0)); var proxyEp = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)proxyToClient.LocalEndPoint!).Port); var uplink = new Queue<(long DeliverMs, byte[] Data)>(); var downlink = new Queue<(long DeliverMs, byte[] Data)>(); EndPoint? clientRemoteEp = null; void PumpProxy(long tMs, int oneWayMs) { var buf = new byte[4096]; while (proxyToClient.Available > 0) { EndPoint from = new IPEndPoint(IPAddress.Any, 0); int n = proxyToClient.ReceiveFrom(buf, ref from); clientRemoteEp = from; uplink.Enqueue((tMs + oneWayMs, buf.AsSpan(0, n).ToArray())); } while (proxyToServer.Available > 0) { EndPoint from = new IPEndPoint(IPAddress.Any, 0); int n = proxyToServer.ReceiveFrom(buf, ref from); downlink.Enqueue((tMs + oneWayMs, buf.AsSpan(0, n).ToArray())); } while (uplink.Count > 0 && uplink.Peek().DeliverMs <= tMs) { proxyToServer.SendTo(uplink.Dequeue().Data, serverEp); } while (downlink.Count > 0 && downlink.Peek().DeliverMs <= tMs && clientRemoteEp is not null) { proxyToClient.SendTo(downlink.Dequeue().Data, clientRemoteEp); } } using var client = new RemoteArenaSession(proxyEp, "Walker"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var deadline = DateTimeOffset.UtcNow.AddMilliseconds(4000); while (DateTimeOffset.UtcNow < deadline && !client.IsJoined) { nowMs += 16; PumpProxy(nowMs, 60); host.StepOnce(nowMs); PumpProxy(nowMs, 60); client.PumpNetwork(nowMs); Thread.Sleep(2); } Assert.True(client.IsJoined); int slot = client.LocalContenderId; // a) Swap local contender to Paladin (biped walker), walk 2.0s @ 120ms simulated RTT host.Session.SetContenderPose(slot, 0f, 0f, 0f); host.Session.State.SpawnChassisDrop(0f, 0f, Catalog.Paladin); Assert.True(host.Session.TrySwapNearbyChassis(slot)); for (int t = 0; t < 16; t++) { client.SubmitLocalInput(new PlayerInput(0f, 0f, 0f, 120f, false, false, false), true); nowMs += 16; PumpProxy(nowMs, 60); host.StepOnce(nowMs); PumpProxy(nowMs, 60); client.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } float clientStartTime = client.PredictedWalkerSimTime ?? 0f; float serverStartTime = host.Session.GetWalkerSimTime(true, slot) ?? 0f; int maxUnackedObserved = 0; for (int t = 0; t < 120; t++) { client.SubmitLocalInput(new PlayerInput(0.8f, 0f, 0f, 120f, false, false, false), true); maxUnackedObserved = Math.Max(maxUnackedObserved, client.UnackedInputCount); nowMs += 16; PumpProxy(nowMs, 60); host.StepOnce(nowMs); PumpProxy(nowMs, 60); client.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } Assert.True(maxUnackedObserved >= 5, $"Expected >=5 unacked inputs under 120ms RTT, saw {maxUnackedObserved}"); float? serverWalkerTime = host.Session.GetWalkerSimTime(true, slot); float? clientWalkerTime = client.PredictedWalkerSimTime; Assert.NotNull(serverWalkerTime); Assert.NotNull(clientWalkerTime); float clientDelta = clientWalkerTime!.Value - clientStartTime; float serverDelta = serverWalkerTime!.Value - serverStartTime; Assert.True(MathF.Abs(clientDelta - serverDelta) <= 0.20f, $"Walker SimTime must track 1x within +-0.20s (no 4.83x overdrive): client={clientDelta:F3}s server={serverDelta:F3}s"); // b) Mid-match Jackal -> Breaker chassis swap must produce 0.0m vertical underground _predErrorPos host.Session.State.SpawnChassisDrop(host.Session.State.Contenders[slot].X, host.Session.State.Contenders[slot].Z, Catalog.Jackal); Assert.True(host.Session.TrySwapNearbyChassis(slot)); for (int t = 0; t < 16; t++) { nowMs += 16; PumpProxy(nowMs, 60); host.StepOnce(nowMs); PumpProxy(nowMs, 60); client.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } var cServer = host.Session.State.Contenders[slot]; host.Session.State.SpawnChassisDrop(cServer.X, cServer.Z, Catalog.Breaker); Assert.True(host.Session.TrySwapNearbyChassis(slot)); for (int t = 0; t < 16; t++) { client.SubmitLocalInput(new PlayerInput(0f, 0f, cServer.X, cServer.Z + 120f, false, false, false), true); nowMs += 16; PumpProxy(nowMs, 60); host.StepOnce(nowMs); PumpProxy(nowMs, 60); client.BeginRenderFrame(1.0 / 60.0, 1f); var visPos = client.GetInterpolatedContenderPose(slot, 1f).Pos; float gh = host.Session.State.Terrain.SampleHeight(visPos.X, visPos.Z); Assert.True(visPos.Y >= gh + Catalog.Jackal.HalfHeight * 0.5f, $"Jackal->Breaker swap must not sink underground: visY={visPos.Y:F3}m gh={gh:F3}m"); Assert.True(MathF.Abs(client.CurrentPredictionError.Y) < 0.15f, $"Jackal->Breaker swap must not accumulate vertical sink error: predErrorY={client.CurrentPredictionError.Y:F3}m"); Thread.Sleep(1); } // c) Combat spectator walker (Exemplar) has valid GeomScale > 0, IsDigitigrade, non-zero ComRot, and synced Exemplar HP/armor var exemplar = host.Session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar && s.Alive); exemplar.Stance = SpectatorStance.Provoked; exemplar.TargetContenderId = slot; host.Session.SetContenderPose(slot, exemplar.X, exemplar.Z - 24f, 0f); for (int t = 0; t < 20; t++) { nowMs += 16; PumpProxy(nowMs, 60); host.StepOnce(nowMs); PumpProxy(nowMs, 60); client.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } Assert.True(client.TrySampleInterpolatedWalkerPose(false, exemplar.Id, 1f, out var exSnap), "Combat Exemplar walker snapshot should be available"); Assert.True(exSnap.GeomScale > 0.1f, $"Exemplar GeomScale must be > 0, got {exSnap.GeomScale}"); Assert.True(exSnap.IsDigitigrade, "Exemplar walker must have IsDigitigrade=true"); Assert.True(exSnap.ComRot.LengthSquared() > 0.5f, "Exemplar walker ComRot must be valid normalized quaternion"); var clientExemplar = client.ViewState.Spectators.Spectators.First(s => s.Id == exemplar.Id); Assert.Equal(SpectatorRing.ExemplarSpec.Id, clientExemplar.Grid.Spec.Id); Assert.InRange(clientExemplar.Grid.CoreHp, exemplar.Grid.CoreHp - 1f, exemplar.Grid.CoreHp + 1f); } [Fact] public void Cut5cFix4_Packet2OverflowDeliversAll10CombatSpectators_AndMalformedPacketDoesNotThrow() { var state = new MatchState(seed: 42, ArenaMapKind.Desert); var local = state.Contenders[0]; local.Grid.SwapChassis(Catalog.Bastion); // large 8x8 local grid var contenders = new List(12); var walkers = new List(12); var combatSpecs = new List(10); for (int i = 0; i < 12; i++) { contenders.Add(new NetContenderState { SlotId = (byte)i, Alive = true, IsHuman = true, Pos = new Vector3(i * 8f, 3f, 0f), Rot = Quaternion.Identity, CoreHpRatio = 1f }); var ws = new WalkerVisualSnapshot { LegCount = 4 }; for (int l = 0; l < 4; l++) ws.FootNormal[l] = Vector3.UnitY; walkers.Add(new NetWalkerEntry { IsContender = true, EntityId = (byte)i, Snapshot = ws }); } for (int i = 0; i < 10; i++) { combatSpecs.Add(new NetSpectatorState { Id = (byte)i, Alive = true, Stance = SpectatorStance.Provoked, TargetContenderId = 0, Pos = new Vector3(40f + i * 4f, 3f, -20f), Rot = Quaternion.Identity }); } byte[] p1 = SnapshotCodec.EncodeCorePvs( 1, 7, 14, 0.25f, 5, 100, 450f, MatchPhase.Active, null, 1, 0xFFF, local, Vector3.Zero, contenders, walkers, combatSpecs, out int writtenInP1); byte[] w1 = SnapshotCodec.WrapLatest(p1, 1, 1); var packet2List = new List(); for (int i = writtenInP1; i < combatSpecs.Count; i++) packet2List.Add(combatSpecs[i]); for (int i = 0; i < 20; i++) { packet2List.Add(new NetSpectatorState { Id = (byte)(20 + i), Alive = true, Stance = SpectatorStance.Neutral, TargetContenderId = -1, Pos = new Vector3(200f, 3f, 200f), Rot = Quaternion.Identity }); } byte[] p2 = SnapshotCodec.EncodeSpectatorOrbitHalf(1, 7, 0, packet2List); byte[] w2 = SnapshotCodec.WrapLatest(p2, 1, 2); Assert.True(w1.Length <= SnapshotCodec.MaxLatestFrameBytes); Assert.True(w2.Length <= SnapshotCodec.MaxLatestFrameBytes); Assert.True(EncodeRudpLatestDatagram(w1, 1).Length <= SnapshotCodec.MaxLatestDatagramBytes); Assert.True(EncodeRudpLatestDatagram(w2, 2).Length <= SnapshotCodec.MaxLatestDatagramBytes); var dec1 = SnapshotCodec.DecodeCorePvs(SnapshotCodec.Unwrap(w1).Payload.Span); var dec2 = SnapshotCodec.DecodeSpectatorOrbitHalf(SnapshotCodec.Unwrap(w2).Payload.Span); var deliveredCombatIds = dec1.CombatSpectators.Select(s => s.Id) .Concat(dec2.Spectators.Where(s => s.Stance != SpectatorStance.Neutral).Select(s => s.Id)) .OrderBy(id => id) .ToList(); Assert.Equal(Enumerable.Range(0, 10).Select(i => (byte)i).ToList(), deliveredCombatIds); // b) Malformed 120B packet with cellCount=200 must return false cleanly without throwing! byte[] bad = new byte[120]; bad[0] = (byte)LatestPacketKind.CorePvs; bad[91] = 200; // cellCount = 200 > 64 and > remaining bytes Assert.False(SnapshotCodec.TryDecodeCorePvs(bad, out _)); bad[0] = (byte)LatestPacketKind.SpectatorOrbitHalf; bad[10] = 250; Assert.False(SnapshotCodec.TryDecodeSpectatorOrbitHalf(bad, out _)); bad[0] = (byte)LatestPacketKind.RadarContacts; bad[9] = 250; Assert.False(SnapshotCodec.TryDecodeRadarContacts(bad, out _)); } [Fact] public void Cut5cFix5_TimedOutClientDisconnectsCleanly_AndDeadSlotReconnectIsRejected() { 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, "Ghost"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); int slot = client.LocalContenderId; Guid token = client.ReconnectToken; Assert.True(client.ConnectionStatus.Connected); // a) Simulate > 6000ms server silence -> client MUST transition to Disconnected (not stuck Connected)! client.PumpNetwork(nowMs + 7000); Assert.False(client.ConnectionStatus.Connected); Assert.False(client.IsJoined); Assert.Contains("DISCONNECTED", client.ConnectionStatus.StateLabel, StringComparison.OrdinalIgnoreCase); // Server also times out client & destroys that slot's chassis nowMs += ServerMatchHost.IdleTimeoutMs + 500; host.StepOnce(nowMs); var deadContender = host.Session.State.Contenders[slot]; deadContender.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0f, deadContender.Grid.HitSequence + 1); Assert.False(deadContender.Alive); // b) Reconnecting with dead-slot ReconnectToken MUST be rejected cleanly instead of hijacking another AI slot! using var deadReconnect = new RemoteArenaSession(ep, "Ghost", token); Assert.False(PumpUntil(host, new[] { deadReconnect }, () => deadReconnect.IsJoined, ref nowMs, 800)); Assert.NotNull(deadReconnect.ConnectionStatus.LastError); Assert.Contains("destroyed", deadReconnect.ConnectionStatus.LastError!, StringComparison.OrdinalIgnoreCase); Assert.Equal(0, host.ConnectedHumanCount); } [Fact] public void Cut5cFix6_Dense12QuadWalkersAndExemplar_OmitsSelfWalkerAndDeliversExemplar() { 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, "QuadLead"); long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); int slot = client.LocalContenderId; // Place all 12 contenders as Bastion quad walkers in a tight open cluster around the Exemplar var exemplar = host.Session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar && s.Alive); exemplar.Stance = SpectatorStance.Provoked; exemplar.TargetContenderId = slot; for (int i = 0; i < MatchState.ContenderCount; i++) { host.Session.State.Contenders[i].Grid.SwapChassis(Catalog.Bastion); float angle = i * (MathF.PI * 2f / MatchState.ContenderCount); float dist = i == slot ? 12f : 28f + i * 2f; host.Session.SetContenderPose(i, exemplar.X + MathF.Cos(angle) * dist, exemplar.Z + MathF.Sin(angle) * dist, angle + MathF.PI); } DecodedCorePvsSnapshot? lastCore = null; int maxUdpBytes = 0; client.DebugInboundLatestDropFilter = payload => { if (SnapshotCodec.TryDecodeCorePvs(payload, out var core)) { lastCore = core; byte[] frame = SnapshotCodec.WrapLatest(payload, 1, core.SnapshotSeq); maxUdpBytes = Math.Max(maxUdpBytes, EncodeRudpLatestDatagram(frame, core.SnapshotSeq).Length); } return false; }; for (int t = 0; t < 20; t++) { nowMs += 16; host.StepOnce(nowMs); client.BeginRenderFrame(1.0 / 60.0, 1f); Thread.Sleep(1); } byte exemplarIdx = (byte)host.Session.State.Spectators.Spectators.Select((s, idx) => (s, idx)).First(x => ReferenceEquals(x.s, exemplar)).idx; Assert.NotNull(lastCore); _output.WriteLine($"Cut5cFix6: maxUdpBytes={maxUdpBytes}B, walkers=[{string.Join(",", lastCore!.Walkers.Select(w => $"{(w.IsContender ? 'C' : 'S')}{w.EntityId}"))}]"); Assert.True(maxUdpBytes > 0 && maxUdpBytes <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet 1 UDP datagram must be <= {SnapshotCodec.MaxLatestDatagramBytes}B, got {maxUdpBytes}B"); Assert.DoesNotContain(lastCore.Walkers, w => w.IsContender && w.EntityId == slot); Assert.Contains(lastCore.Walkers, w => !w.IsContender && w.EntityId == exemplarIdx); Assert.True(client.TrySampleInterpolatedWalkerPose(false, exemplar.Id, 1f, out _), "Client must receive Exemplar walker snapshot even under dense 12 quad-walker contention"); } [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 { PacketType = CultNetRudpPacketType.Data, ConnectionId = 0x52544431, Sequence = sequence, ChannelId = SnapshotCodec.ChannelLatest, Sequenced = true, Payload = frameBytes }); private static bool PumpUntil( ServerMatchHost host, RemoteArenaSession[] clients, Func condition, ref long nowMs, int timeoutMs) { var deadline = DateTimeOffset.UtcNow.AddMilliseconds(timeoutMs); while (DateTimeOffset.UtcNow < deadline) { nowMs += 16; host.StepOnce(nowMs); for (int i = 0; i < clients.Length; i++) { clients[i].PumpNetwork(); } if (condition()) return true; Thread.Sleep(2); } return condition(); } } }