diff --git a/RustToDust.slnx b/RustToDust.slnx
index 5955da4..28d4f8b 100644
--- a/RustToDust.slnx
+++ b/RustToDust.slnx
@@ -2,6 +2,8 @@
+
+
diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs
index e9516dc..f814157 100644
--- a/client/ArenaRenderer.cs
+++ b/client/ArenaRenderer.cs
@@ -520,7 +520,7 @@ public partial class ArenaRenderer : Node3D
vis.Visual.Root.QueueFree();
}
- var role = c.IsPlayer ? VehicleVisualRole.Player : VehicleVisualRole.Rival;
+ var role = c.Id == 0 ? VehicleVisualRole.Player : VehicleVisualRole.Rival;
var instance = VehicleVisualInstance.Create(_assetCache, c.Grid.Spec.Id, role);
instance.SyncMountedGear(c.Grid);
_actorsGroup.AddChild(instance.Root);
@@ -537,15 +537,15 @@ public partial class ArenaRenderer : Node3D
vis.Visual.Root.Transform = new Transform3D(new Basis(q), pos);
float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f;
- bool castShadows = !hasCam || c.IsPlayer || distSq <= 75f * 75f;
- bool useStaticLod = hasCam && !c.IsPlayer && !vis.Visual.HasAnyStrippedCell &&
+ bool castShadows = !hasCam || c.Id == 0 || distSq <= 75f * 75f;
+ bool useStaticLod = hasCam && c.Id != 0 && !vis.Visual.HasAnyStrippedCell &&
(vis.Visual.IsStaticLod ? distSq > 64f * 64f : distSq > 68f * 68f);
vis.Visual.SetLodState(useStaticLod, castShadows);
vis.Visual.SyncMountedGear(c.Grid);
if (!useStaticLod)
{
- if (!hasCam || c.IsPlayer || distSq <= 55f * 55f)
+ if (!hasCam || c.Id == 0 || distSq <= 55f * 55f)
{
vis.RigDtAccum = 0f;
vis.RigSkipFrames = 0;
diff --git a/client/Hud.cs b/client/Hud.cs
index ea57868..ecfdc0f 100644
--- a/client/Hud.cs
+++ b/client/Hud.cs
@@ -150,7 +150,7 @@ public partial class Hud : CanvasLayer
public void Sync(ArenaSession session)
{
var state = session.State;
- var player = state.Player;
+ var player = state.Contenders[0];
// Top-Left Status
_chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant();
@@ -202,9 +202,10 @@ public partial class Hud : CanvasLayer
_safeLabel.Modulate = RedCol;
}
- if (state.PlayerDetectedByCount > 0)
+ int detectedBy = state.ObserverStates.TryGetValue(0, out var obs0) ? obs0.DetectedByCount : 0;
+ if (detectedBy > 0)
{
- _detectionLabel.Text = $"DETECTED BY {state.PlayerDetectedByCount}";
+ _detectionLabel.Text = $"DETECTED BY {detectedBy}";
_detectionLabel.Modulate = RedCol;
}
else
@@ -237,14 +238,14 @@ public partial class Hud : CanvasLayer
SyncBroadcastChyron(state.Broadcast);
// Outcome
- if (state.Phase == MatchPhase.Victory)
+ if (state.Phase == MatchPhase.Completed && state.WinnerContenderId == 0)
{
_outcomeBanner.Visible = true;
_outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", OliveCol);
_outcomeLabel.Text = "VICTORY — LAST RIG STANDING\n[R] New Drop";
_outcomeLabel.Modulate = OliveCol;
}
- else if (state.Phase == MatchPhase.Defeat)
+ else if (!player.Alive || state.Phase == MatchPhase.Completed)
{
_outcomeBanner.Visible = true;
_outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", RedCol);
@@ -513,7 +514,7 @@ public partial class Hud : CanvasLayer
{
var session = _getSession();
if (session is null) return;
- var cargo = session.State.Player.Grid.Cargo;
+ var cargo = session.State.Contenders[0].Grid.Cargo;
if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count)
{
_onEquipCargo(_selectedCargoIndex, hardpointId);
@@ -1068,13 +1069,14 @@ public partial class Hud : CanvasLayer
}
// Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory; hidden Exemplars vanish!)
+ var obs0 = _state.GetOrCreateObserverState(0);
var specs = _state.Spectators.Spectators;
for (int i = 0; i < specs.Count; i++)
{
var s = specs[i];
if (!s.Alive) continue;
- _state.SpectatorContacts.TryGetValue(s.Id, out var mem);
+ obs0.SpectatorContacts.TryGetValue(s.Id, out var mem);
if (!MatchState.IsContactOnRadar(mem))
{
continue;
@@ -1100,11 +1102,11 @@ public partial class Hud : CanvasLayer
if (tid >= 0 && tid < _state.Contenders.Count && _state.Contenders[tid].Alive)
{
var tgt = _state.Contenders[tid];
- bool targetVisible = tgt.IsPlayer ||
- (_state.ContenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer);
+ bool targetVisible = tgt.Id == 0 ||
+ (obs0.ContenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer);
if (targetVisible)
{
- float tgtClampR = MathF.Max(4f, radius - (tgt.IsPlayer ? 7.5f : 4.3f));
+ float tgtClampR = MathF.Max(4f, radius - (tgt.Id == 0 ? 7.5f : 4.3f));
var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw));
DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f);
}
@@ -1134,7 +1136,7 @@ public partial class Hud : CanvasLayer
var c = _state.Contenders[i];
if (!c.Alive) continue;
- if (c.IsPlayer)
+ if (c.Id == 0)
{
float playerClampR = MathF.Max(4f, radius - 6.5f - 1f);
var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, c.X, c.Z, _cameraYaw));
@@ -1152,7 +1154,7 @@ public partial class Hud : CanvasLayer
continue;
}
- _state.ContenderContacts.TryGetValue(c.Id, out var mem);
+ obs0.ContenderContacts.TryGetValue(c.Id, out var mem);
if (!MatchState.IsContactOnRadar(mem))
{
continue;
diff --git a/client/Main.cs b/client/Main.cs
index 4f2dccc..43b5e61 100644
--- a/client/Main.cs
+++ b/client/Main.cs
@@ -126,7 +126,7 @@ public partial class Main : Node3D
private void SetupPerfCombatScenario(ArenaSession session)
{
- var p = session.State.Player;
+ var p = session.State.Contenders[0];
float fwdX = MathF.Sin(p.Yaw);
float fwdZ = MathF.Cos(p.Yaw);
float rightX = -fwdZ;
@@ -187,8 +187,8 @@ public partial class Main : Node3D
try
{
- _session = new ArenaSession(seed, _mapKind);
- var p = _session.State.Player;
+ _session = new ArenaSession(seed, _mapKind, slot0Human: true);
+ var p = _session.State.Contenders[0];
_cameraYaw = p.Yaw;
_cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f);
_cameraZoom = 1.0f;
@@ -319,7 +319,8 @@ public partial class Main : Node3D
if (_perfTargetFrames > 0)
{
long t0 = Stopwatch.GetTimestamp();
- _session.Step(input);
+ _session.SetHumanInput(0, input);
+ _session.Step();
long t1 = Stopwatch.GetTimestamp();
double toMs = 1000.0 / Stopwatch.Frequency;
_perfPendingStepMs += (t1 - t0) * toMs;
@@ -327,7 +328,8 @@ public partial class Main : Node3D
}
else
{
- _session.Step(input);
+ _session.SetHumanInput(0, input);
+ _session.Step();
}
}
@@ -536,7 +538,7 @@ public partial class Main : Node3D
if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f;
if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f;
- bool isVtol = Session.State.Player.Grid.Spec.IsVtol;
+ bool isVtol = Session.State.Contenders[0].Grid.Spec.IsVtol;
float verticalThrottle = 0f;
if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f;
if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f;
@@ -561,7 +563,7 @@ public partial class Main : Node3D
private (float AimX, float AimY, float AimZ) ComputeCenterScreenAim()
{
- var player = Session.State.Player;
+ var player = Session.State.Contenders[0];
var spec = player.Grid.Spec;
Vector2 screenSize = GetViewport().GetVisibleRect().Size;
if (screenSize.X < 2f || screenSize.Y < 2f)
@@ -667,7 +669,7 @@ public partial class Main : Node3D
private void UpdateCamera(float dt, float alpha)
{
- var p = Session.State.Player;
+ var p = Session.State.Contenders[0];
var spec = p.Grid.Spec;
var (posInterp, _, _) = Session.GetInterpolatedContenderPose(p.Id, alpha);
@@ -794,7 +796,7 @@ public partial class Main : Node3D
private void OnEquipCargo(int cargoIndex, string hardpointId)
{
- _session?.TryEquipCargo(cargoIndex, hardpointId);
+ _session?.TryEquipCargo(0, cargoIndex, hardpointId);
}
private void SetupLightingAndSky()
diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs
index 2224d1a..4d7d85e 100644
--- a/client/tests/Smoke.cs
+++ b/client/tests/Smoke.cs
@@ -62,7 +62,7 @@ public partial class Smoke : Node
Check(!_main.GetWorld3D().Space.IsValid, "Godot should have no active 3D physics space");
Check(_main.Terrain.BakedTileCount == 64, $"Expected 64 baked terrain tiles, got {_main.Terrain.BakedTileCount}");
- var player = _main.Session.State.Player;
+ var player = _main.Session.State.Contenders[0];
float startX = player.X;
float startZ = player.Z;
@@ -580,7 +580,7 @@ public partial class Smoke : Node
}
// Seed realistic combat telemetry so the preview clearly showcases armor stripping, hit-flash, cargo rack, and thermal heat
- var player = _main.Session.State.Player;
+ var player = _main.Session.State.Contenders[0];
var grid = player.Grid;
grid.TryAddCargo(Catalog.TouringPlasma);
grid.TryAddCargo(Catalog.GoldRadiator);
@@ -925,7 +925,7 @@ public partial class Smoke : Node
// 6. All 7 walkers (including Kestrel) walk through real ArenaSession + Hybrid B FK snapshot cleanly
{
- using var walkSession = new RustToDust.Ymir.ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert);
+ using var walkSession = new RustToDust.Ymir.ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int cIdx = 1; cIdx < walkSession.State.Contenders.Count; cIdx++)
{
walkSession.SetContenderPose(cIdx, 450f + cIdx * 18f, 450f);
@@ -946,10 +946,10 @@ public partial class Smoke : Node
{
var wSpec = Catalog.ChassisById[wId];
walkSession.SetContenderPose(0, 0f, 0f, 0f);
- if (walkSession.State.Player.Grid.Spec.Id != wId)
+ if (walkSession.State.Contenders[0].Grid.Spec.Id != wId)
{
walkSession.State.SpawnChassisDrop(0f, 0f, wSpec);
- Check(walkSession.TrySwapNearbyChassis(), $"Failed to swap walkSession player to '{wId}'");
+ Check(walkSession.TrySwapNearbyChassis(0), $"Failed to swap walkSession player to '{wId}'");
}
var vis = VehicleVisualInstance.Create(cache, wId, VehicleVisualRole.Player);
@@ -961,10 +961,10 @@ public partial class Smoke : Node
Check(footNode is not null && pelvisNode is not null,
$"Missing FK nodes '{footNodeName}'/'{pelvisNodeName}' on walker '{wId}'");
- var player = walkSession.State.Player;
+ var player = walkSession.State.Contenders[0];
for (int step = 0; step < 60; step++)
{
- walkSession.Step(new PlayerInput(
+ walkSession.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: 0f,
AimWorldX: player.X,
@@ -972,6 +972,7 @@ public partial class Smoke : Node
Fire: false,
InteractPickup: false,
Brake: false));
+ walkSession.Step();
bool hasSnap = walkSession.TrySampleInterpolatedWalkerPose(true, player.Id, 1f, out var walkerSnap);
Check(hasSnap, $"Missing WalkerVisualSnapshot for '{wId}' at step {step}");
@@ -1133,7 +1134,7 @@ public partial class Smoke : Node
// 10. MultiMeshPartPool & PomDecalPool sanity: live arena submits into MultiMeshPartPool and PomDecalPool stamps impacts cleanly
{
_main.Arena.PomDecals.StampTestDecal(
- new Vector3(_main.Session.State.Player.X + 2f, _main.Session.State.Terrain.SampleHeight(_main.Session.State.Player.X + 2f, _main.Session.State.Player.Z) + 0.03f, _main.Session.State.Player.Z),
+ new Vector3(_main.Session.State.Contenders[0].X + 2f, _main.Session.State.Terrain.SampleHeight(_main.Session.State.Contenders[0].X + 2f, _main.Session.State.Contenders[0].Z) + 0.03f, _main.Session.State.Contenders[0].Z),
Vector3.Up, 1.2f, tileIndex: 14);
_main.Arena.Sync(_main.Session, 1.6f, 1f / 60f);
Check(_main.Arena.PartPool.TotalSubmittedInstances > 0,
@@ -1141,7 +1142,7 @@ public partial class Smoke : Node
Check(_main.Arena.PomDecals.ActiveCount >= 1,
$"Expected PomDecalPool to hold >= 1 active decal, got {_main.Arena.PomDecals.ActiveCount}");
- _main.Hud.PushTestHitArc(_main.Session.State.Player.X + 20f, _main.Session.State.Player.Z + 10f, WeaponVisualClass.Explosive);
+ _main.Hud.PushTestHitArc(_main.Session.State.Contenders[0].X + 20f, _main.Session.State.Contenders[0].Z + 10f, WeaponVisualClass.Explosive);
Check(_main.Hud.ActiveHitArcCount >= 1, "Expected CrosshairOverlay to accept incoming hit arc");
}
@@ -1223,7 +1224,7 @@ public partial class Smoke : Node
int vfxBefore = _main.Arena.TransientVfxCount;
int tracerId = _main.Session.State.AllocateTracerId();
- Vector3 pPos = new(_main.Session.State.Player.X, _main.Session.State.Player.Y, _main.Session.State.Player.Z);
+ Vector3 pPos = new(_main.Session.State.Contenders[0].X, _main.Session.State.Contenders[0].Y, _main.Session.State.Contenders[0].Z);
tracers.Add(new TracerEvent(
pPos.X, pPos.Y + 1f, pPos.Z,
pPos.X + 20f, pPos.Y + 1f, pPos.Z,
@@ -1400,7 +1401,7 @@ public partial class Smoke : Node
private async Task VerifyMaxLoadPaladinGarageAsync()
{
- var grid = _main.Session.State.Player.Grid;
+ var grid = _main.Session.State.Contenders[0].Grid;
grid.SwapChassis(Catalog.Paladin);
Check(grid.TryMount(Catalog.TouringPlasma, "hp.weapon.sh_l"), "Expected TouringPlasma on Paladin hp.weapon.sh_l");
Check(grid.TryMount(Catalog.WeldedPlate, "hp.armor.torso"), "Expected WeldedPlate on Paladin hp.armor.torso");
@@ -1483,7 +1484,7 @@ public partial class Smoke : Node
Vector2 vpSize = GetViewport().GetVisibleRect().Size;
Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Sion HUD panels overlapped or clipped at {vpSize}");
- var player = sionState.Player;
+ var player = sionState.Contenders[0];
float startX = player.X;
float startZ = player.Z;
_main.SetScriptedInput(new PlayerInput(
diff --git a/src/RustToDust.Core/Broadcast.cs b/src/RustToDust.Core/Broadcast.cs
index a1b12e3..193f0a1 100644
--- a/src/RustToDust.Core/Broadcast.cs
+++ b/src/RustToDust.Core/Broadcast.cs
@@ -1,3 +1,4 @@
+using System;
using System.Collections.Generic;
namespace RustToDust.Core
@@ -25,6 +26,7 @@ namespace RustToDust.Core
public IReadOnlyList Lines => _lines;
public BroadcastLine? Latest => _lines.Count > 0 ? _lines[_lines.Count - 1] : null;
public long Version { get; private set; }
+ public event Action? LineEmitted;
public void Emit(float timestamp, BroadcastKind kind, string text)
{
@@ -32,8 +34,10 @@ namespace RustToDust.Core
{
_lines.RemoveAt(0);
}
- _lines.Add(new BroadcastLine(timestamp, kind, text));
+ var line = new BroadcastLine(timestamp, kind, text);
+ _lines.Add(line);
Version++;
+ LineEmitted?.Invoke(line);
}
public void EmitMatchStart(float timestamp, ArenaMapKind mapKind = ArenaMapKind.Desert) =>
diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs
index 1eabe95..83573d7 100644
--- a/src/RustToDust.Core/GridChassis.cs
+++ b/src/RustToDust.Core/GridChassis.cs
@@ -808,6 +808,167 @@ namespace RustToDust.Core
return max > 0f ? cur / max : 0f;
}
+ public float ComputeMaxThermalRatio()
+ {
+ float worst = 0f;
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ var m = Mounted[i];
+ float span = MathF.Max(1f, m.Spec.MaxTemp - AmbientTemp);
+ float ratio = Math.Clamp((m.CurrentTemp - AmbientTemp) / span, 0f, 1.5f);
+ if (ratio > worst) worst = ratio;
+ }
+ for (int y = 0; y < Spec.Height; y++)
+ {
+ for (int x = 0; x < Spec.Width; x++)
+ {
+ if (!Spec.IsActive(x, y)) continue;
+ float ratio = Math.Clamp((Temperature[x, y] - AmbientTemp) / 380f, 0f, 1.5f);
+ if (ratio > worst) worst = ratio;
+ }
+ }
+ return worst;
+ }
+
+ public byte[] QuantizeArmorBytes()
+ {
+ int count = 0;
+ for (int y = 0; y < Spec.Height; y++)
+ for (int x = 0; x < Spec.Width; x++)
+ if (Spec.IsActive(x, y)) count++;
+
+ var bytes = new byte[count];
+ int idx = 0;
+ for (int y = 0; y < Spec.Height; y++)
+ {
+ for (int x = 0; x < Spec.Width; x++)
+ {
+ if (!Spec.IsActive(x, y)) continue;
+ float max = MathF.Max(0.01f, MaxArmor[x, y]);
+ float ratio = Math.Clamp(Armor[x, y] / max, 0f, 1f);
+ bytes[idx++] = (byte)Math.Clamp((int)MathF.Round(ratio * 255f), 0, 255);
+ }
+ }
+ return bytes;
+ }
+
+ public void ApplyReplicatedArmorBytes(ReadOnlySpan armorBytes)
+ {
+ int idx = 0;
+ for (int y = 0; y < Spec.Height; y++)
+ {
+ for (int x = 0; x < Spec.Width; x++)
+ {
+ if (!Spec.IsActive(x, y)) continue;
+ if (idx >= armorBytes.Length) return;
+ Armor[x, y] = MaxArmor[x, y] * (armorBytes[idx++] / 255f);
+ }
+ }
+ }
+
+ public void ApplyReplicatedDamage(int cellX, int cellY, float cellArmor, float cellTemp, float coreHp, int hitSequence)
+ {
+ if (Spec.IsActive(cellX, cellY))
+ {
+ Armor[cellX, cellY] = MathF.Max(0f, cellArmor);
+ Temperature[cellX, cellY] = MathF.Max(AmbientTemp, cellTemp);
+ LastHitX = cellX;
+ LastHitY = cellY;
+ }
+ CoreHp = MathF.Max(0f, coreHp);
+ if (hitSequence > HitSequence)
+ {
+ HitSequence = hitSequence;
+ }
+ else
+ {
+ HitSequence++;
+ }
+ UpdateMountedTelemetry();
+ }
+
+ public void ApplyReplicatedThermal(ReadOnlySpan quantizedCellTemps, ReadOnlySpan mountedTemps, ReadOnlySpan mountedCooldowns)
+ {
+ int idx = 0;
+ for (int y = 0; y < Spec.Height; y++)
+ {
+ for (int x = 0; x < Spec.Width; x++)
+ {
+ if (!Spec.IsActive(x, y)) continue;
+ if (idx < quantizedCellTemps.Length)
+ {
+ Temperature[x, y] = AmbientTemp + quantizedCellTemps[idx++] * 2.0f;
+ }
+ }
+ }
+
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ if (i < mountedTemps.Length)
+ {
+ Mounted[i].CurrentTemp = mountedTemps[i];
+ Mounted[i].CurrentPerformance = Mounted[i].Spec.Performance(mountedTemps[i]);
+ }
+ if (i < mountedCooldowns.Length)
+ {
+ Mounted[i].Cooldown = mountedCooldowns[i];
+ }
+ }
+ }
+
+ public void ApplyReplicatedLoadout(
+ ChassisSpec spec,
+ float coreHp,
+ float maxCoreHp,
+ ReadOnlySpan armorBytes,
+ IReadOnlyList<(string ModuleId, string HardpointId)> mounted,
+ IReadOnlyList? cargoIds,
+ Func moduleResolver)
+ {
+ if (!string.Equals(Spec.Id, spec.Id, StringComparison.Ordinal))
+ {
+ Spec = spec;
+ Temperature = new float[spec.Width, spec.Height];
+ Armor = new float[spec.Width, spec.Height];
+ MaxArmor = new float[spec.Width, spec.Height];
+ BorderCells = new bool[spec.Width, spec.Height];
+ _netHeat = new float[spec.Width, spec.Height];
+ _cellThermalMass = new float[spec.Width, spec.Height];
+ _cellConductivity = new float[spec.Width, spec.Height];
+ InitializeGridState(spec, preserveCoreRatio: false, previousRatio: 1f);
+ }
+
+ Mounted.Clear();
+ for (int i = 0; i < mounted.Count; i++)
+ {
+ var (modId, hpId) = mounted[i];
+ var modSpec = moduleResolver(modId);
+ if (modSpec is not null)
+ {
+ Mounted.Add(new MountedModule(modSpec, hpId, AmbientTemp));
+ }
+ }
+
+ if (cargoIds is not null)
+ {
+ Cargo.Clear();
+ for (int i = 0; i < cargoIds.Count; i++)
+ {
+ var modSpec = moduleResolver(cargoIds[i]);
+ if (modSpec is not null)
+ {
+ Cargo.Add(modSpec);
+ }
+ }
+ }
+
+ RecalculateArmorAndThermal(grantNewArmorDelta: false);
+ MaxCoreHp = maxCoreHp > 0f ? maxCoreHp : MaxCoreHp;
+ CoreHp = Math.Clamp(coreHp, 0f, MaxCoreHp);
+ ApplyReplicatedArmorBytes(armorBytes);
+ UpdateMountedTelemetry();
+ }
+
private (int X, int Y) ResolveHitCell(float localRight, float localForward, float localHeightNorm)
{
int w = Spec.Width;
diff --git a/src/RustToDust.Core/IClientArenaSession.cs b/src/RustToDust.Core/IClientArenaSession.cs
new file mode 100644
index 0000000..06f14e3
--- /dev/null
+++ b/src/RustToDust.Core/IClientArenaSession.cs
@@ -0,0 +1,61 @@
+using System;
+using System.Collections.Generic;
+using System.Numerics;
+
+namespace RustToDust.Core
+{
+ public enum ClientMatchOutcome
+ {
+ Active,
+ Victory,
+ Defeat
+ }
+
+ public enum NetworkMode
+ {
+ Solo,
+ ListenHost,
+ RemoteClient
+ }
+
+ public readonly record struct NetworkStatusSnapshot(
+ NetworkMode Mode,
+ bool Connected,
+ int PingMs,
+ int ConnectedHumans,
+ int MaxHumans,
+ string StateLabel,
+ string? LastError = null);
+
+ public readonly record struct ClientRayHit(
+ bool Hit,
+ ulong StableId,
+ Vector3 Point,
+ Vector3 Normal,
+ float Fraction);
+
+ public interface IClientArenaSession : IDisposable
+ {
+ MatchState ViewState { get; }
+ int LocalContenderId { get; }
+ ContenderState LocalContender { get; }
+ ClientMatchOutcome LocalOutcome { get; }
+ int LocalDetectedByCount { get; }
+ IReadOnlyDictionary LocalContenderContacts { get; }
+ IReadOnlyDictionary LocalSpectatorContacts { get; }
+ NetworkStatusSnapshot ConnectionStatus { get; }
+
+ bool IsContenderVisible(int contenderId);
+ bool IsSpectatorVisible(int spectatorId);
+
+ void BeginRenderFrame(double dt, float physicsAlpha);
+ void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick);
+ bool RequestEquipCargo(int cargoIndex, string hardpointId);
+ void RequestNewMatch(int seed, ArenaMapKind mapKind);
+
+ (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha);
+ (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha);
+ bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap);
+ ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation);
+ }
+}
diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs
index e5be58b..f9f2ec2 100644
--- a/src/RustToDust.Core/MatchRules.cs
+++ b/src/RustToDust.Core/MatchRules.cs
@@ -252,31 +252,36 @@ namespace RustToDust.Core
return rad;
}
- public static void ApplyPlayerInput(MatchState state, PlayerInput input)
+ public static void ApplyHumanInput(MatchState state, int contenderId, in PlayerInput input)
{
- var player = state.Player;
- if (!player.Alive)
+ if (contenderId < 0 || contenderId >= state.Contenders.Count)
{
- player.ThrottleCmd = 0f;
- player.SteerCmd = 0f;
- player.VerticalThrottleCmd = 0f;
- player.FireCmd = false;
- player.BrakeCmd = true;
return;
}
- player.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f);
- player.SteerCmd = Math.Clamp(input.Steer, -1f, 1f);
- player.VerticalThrottleCmd = Math.Clamp(input.VerticalThrottle, -1f, 1f);
- player.AimX = input.AimWorldX;
- player.AimY = input.AimWorldY;
- player.AimZ = input.AimWorldZ;
- player.FireCmd = input.Fire;
- player.BrakeCmd = input.Brake;
+ var human = state.Contenders[contenderId];
+ if (!human.Alive)
+ {
+ human.ThrottleCmd = 0f;
+ human.SteerCmd = 0f;
+ human.VerticalThrottleCmd = 0f;
+ human.FireCmd = false;
+ human.BrakeCmd = true;
+ return;
+ }
+
+ human.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f);
+ human.SteerCmd = Math.Clamp(input.Steer, -1f, 1f);
+ human.VerticalThrottleCmd = Math.Clamp(input.VerticalThrottle, -1f, 1f);
+ human.AimX = float.IsFinite(input.AimWorldX) ? input.AimWorldX : human.AimX;
+ human.AimY = float.IsFinite(input.AimWorldY) ? input.AimWorldY : float.NaN;
+ human.AimZ = float.IsFinite(input.AimWorldZ) ? input.AimWorldZ : human.AimZ;
+ human.FireCmd = input.Fire;
+ human.BrakeCmd = input.Brake;
if (input.InteractPickup)
{
- state.TryInteractNearestDrop(0);
+ state.TryInteractNearestDrop(contenderId);
}
}
@@ -287,7 +292,7 @@ namespace RustToDust.Core
for (int i = 0; i < state.Contenders.Count; i++)
{
var ai = state.Contenders[i];
- if (ai.IsPlayer || !ai.Alive)
+ if (ai.IsHuman || !ai.Alive)
{
continue;
}
@@ -811,25 +816,25 @@ namespace RustToDust.Core
return;
}
- if (!state.Player.Alive)
- {
- state.Phase = MatchPhase.Defeat;
- return;
- }
-
int aliveCount = 0;
+ ContenderState? survivor = null;
for (int i = 0; i < state.Contenders.Count; i++)
{
if (state.Contenders[i].Alive)
{
aliveCount++;
+ survivor = state.Contenders[i];
}
}
- if (aliveCount <= 1 && state.Player.Alive)
+ if (aliveCount <= 1)
{
- state.Phase = MatchPhase.Victory;
- state.Broadcast.EmitVictory(state.Time, state.Player.Id, state.MapKind);
+ state.Phase = MatchPhase.Completed;
+ state.WinnerContenderId = survivor?.Id;
+ if (survivor is not null)
+ {
+ state.Broadcast.EmitVictory(state.Time, survivor.Id, state.MapKind);
+ }
}
}
diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs
index 655de3c..283dec4 100644
--- a/src/RustToDust.Core/MatchState.cs
+++ b/src/RustToDust.Core/MatchState.cs
@@ -7,8 +7,7 @@ namespace RustToDust.Core
public enum MatchPhase
{
Active,
- Victory,
- Defeat
+ Completed
}
public readonly record struct PlayerInput(
@@ -90,6 +89,33 @@ namespace RustToDust.Core
public bool FaintHorizonPing { get; set; }
}
+ public sealed class ObserverDetectionState
+ {
+ public Dictionary ContenderContacts { get; } = new();
+ public Dictionary SpectatorContacts { get; } = new();
+ public int DetectedByCount { get; set; }
+
+ public PlayerContactMemory GetOrCreateContenderContact(int contenderId)
+ {
+ if (!ContenderContacts.TryGetValue(contenderId, out var mem))
+ {
+ mem = new PlayerContactMemory();
+ ContenderContacts[contenderId] = mem;
+ }
+ return mem;
+ }
+
+ public PlayerContactMemory GetOrCreateSpectatorContact(int spectatorId)
+ {
+ if (!SpectatorContacts.TryGetValue(spectatorId, out var mem))
+ {
+ mem = new PlayerContactMemory();
+ SpectatorContacts[spectatorId] = mem;
+ }
+ return mem;
+ }
+ }
+
public sealed class GroundDrop
{
public GroundDrop(int id, float x, float z, ChassisSpec? chassis, ModuleSpec? module)
@@ -111,11 +137,11 @@ namespace RustToDust.Core
public sealed class ContenderState
{
- public ContenderState(int id, string name, bool isPlayer, ChassisGrid grid, float x, float z, float yaw)
+ public ContenderState(int id, string name, bool isHuman, ChassisGrid grid, float x, float z, float yaw)
{
Id = id;
Name = name;
- IsPlayer = isPlayer;
+ IsHuman = isHuman;
Grid = grid;
X = x;
Y = grid.Spec.HalfHeight + 0.1f;
@@ -134,9 +160,12 @@ namespace RustToDust.Core
}
public int Id { get; }
- public string Name { get; }
- public bool IsPlayer { get; }
+ public string Name { get; set; }
+ public bool IsHuman { get; set; }
public ChassisGrid Grid { get; }
+ public int LoadoutVersion { get; set; } = 1;
+ public int DamageVersion { get; set; } = 1;
+ public float MaxThermalRatio { get; set; }
public float X { get; set; }
public float Y { get; set; }
public float Z { get; set; }
@@ -268,6 +297,7 @@ namespace RustToDust.Core
public Random Rng { get; }
public float Time { get; set; }
public MatchPhase Phase { get; set; } = MatchPhase.Active;
+ public int? WinnerContenderId { get; set; }
public TerrainField Terrain { get; }
public List Contenders { get; } = new();
@@ -279,17 +309,17 @@ namespace RustToDust.Core
public IReadOnlyList ArenaCoverBoxes { get; }
public IReadOnlyList ArenaBoundaryBoxes { get; }
- public Dictionary ContenderContacts { get; } = new();
- public Dictionary SpectatorContacts { get; } = new();
- public int PlayerDetectedByCount { get; set; }
+ public Dictionary ObserverStates { get; } = new();
+ public IReadOnlyDictionary EmptyContacts { get; } = new Dictionary();
public float? LastGunfireX { get; set; }
public float? LastGunfireZ { get; set; }
public float LastGunfireTime { get; set; } = -100f;
- public ContenderState Player => Contenders[0];
-
public event Action? ChassisSwapped;
+ public event Action? LoadoutChanged;
+ public event Action? DropSpawned;
+ public event Action? DropPickedUp;
public long AllocateHitEventId() => _nextHitEventId++;
public int AllocateTracerId() => _nextTracerId++;
@@ -311,30 +341,21 @@ namespace RustToDust.Core
return mem.VisibleToPlayer || mem.FaintHorizonPing || (mem.HasEverBeenSeen && mem.LastSeenAge <= ContactGhostDuration);
}
- public PlayerContactMemory GetOrCreateContenderContact(int contenderId)
+ public ObserverDetectionState GetOrCreateObserverState(int observerId)
{
- if (!ContenderContacts.TryGetValue(contenderId, out var mem))
+ if (!ObserverStates.TryGetValue(observerId, out var obs))
{
- mem = new PlayerContactMemory();
- ContenderContacts[contenderId] = mem;
+ obs = new ObserverDetectionState();
+ ObserverStates[observerId] = obs;
}
- return mem;
- }
-
- public PlayerContactMemory GetOrCreateSpectatorContact(int spectatorId)
- {
- if (!SpectatorContacts.TryGetValue(spectatorId, out var mem))
- {
- mem = new PlayerContactMemory();
- SpectatorContacts[spectatorId] = mem;
- }
- return mem;
+ return obs;
}
public GroundDrop SpawnModuleDrop(float x, float z, ModuleSpec module)
{
var drop = new GroundDrop(_nextDropId++, x, z, null, module);
GroundDrops.Add(drop);
+ DropSpawned?.Invoke(drop);
return drop;
}
@@ -342,11 +363,36 @@ namespace RustToDust.Core
{
var drop = new GroundDrop(_nextDropId++, x, z, chassis, null);
GroundDrops.Add(drop);
+ DropSpawned?.Invoke(drop);
return drop;
}
- public bool TryEquipCargo(int cargoIndex, string hardpointId) =>
- TryEquipCargo(0, cargoIndex, hardpointId);
+ public GroundDrop ApplyReplicatedDropSpawned(int dropId, float x, float z, ChassisSpec? chassis, ModuleSpec? module)
+ {
+ for (int i = 0; i < GroundDrops.Count; i++)
+ {
+ if (GroundDrops[i].Id == dropId)
+ {
+ return GroundDrops[i];
+ }
+ }
+ if (dropId >= _nextDropId) _nextDropId = dropId + 1;
+ var drop = new GroundDrop(dropId, x, z, chassis, module);
+ GroundDrops.Add(drop);
+ return drop;
+ }
+
+ public void ApplyReplicatedDropPickedUp(int dropId)
+ {
+ for (int i = 0; i < GroundDrops.Count; i++)
+ {
+ if (GroundDrops[i].Id == dropId)
+ {
+ GroundDrops[i].PickedUp = true;
+ return;
+ }
+ }
+ }
public bool TryEquipCargo(int contenderId, int cargoIndex, string hardpointId)
{
@@ -372,10 +418,12 @@ namespace RustToDust.Core
{
SpawnModuleDrop(contender.X + 1.5f, contender.Z + 1.5f, displaced[i]);
}
+ contender.LoadoutVersion++;
+ LoadoutChanged?.Invoke(contender);
return true;
}
- public GroundDrop? FindNearestInteractableDrop(int contenderId = 0)
+ public GroundDrop? FindNearestInteractableDrop(int contenderId)
{
if (contenderId < 0 || contenderId >= Contenders.Count)
{
@@ -412,7 +460,7 @@ namespace RustToDust.Core
return nearest;
}
- public bool TryInteractNearestDrop(int contenderId = 0)
+ public bool TryInteractNearestDrop(int contenderId)
{
var nearest = FindNearestInteractableDrop(contenderId);
if (nearest is null)
@@ -432,7 +480,7 @@ namespace RustToDust.Core
return false;
}
- public bool TryPickupNearbyModule(int contenderId = 0)
+ public bool TryPickupNearbyModule(int contenderId)
{
if (contenderId < 0 || contenderId >= Contenders.Count)
{
@@ -469,7 +517,7 @@ namespace RustToDust.Core
return nearest is not null && ExecuteModuleDropPickup(contenderId, contender, nearest);
}
- public bool TrySwapNearbyChassis(int contenderId = 0, int? preferredDropId = null)
+ public bool TrySwapNearbyChassis(int contenderId, int? preferredDropId = null)
{
if (contenderId < 0 || contenderId >= Contenders.Count)
{
@@ -527,10 +575,13 @@ namespace RustToDust.Core
}
drop.PickedUp = true;
+ DropPickedUp?.Invoke(drop.Id, contenderId);
if (boltedHardpointId is not null)
{
Broadcast.EmitQuickBolt(Time, contenderId, drop.Module.Name, boltedHardpointId);
}
+ contender.LoadoutVersion++;
+ LoadoutChanged?.Invoke(contender);
return true;
}
@@ -544,6 +595,7 @@ namespace RustToDust.Core
var oldChassis = contender.Grid.Spec;
var overflow = contender.Grid.SwapChassis(drop.Chassis);
drop.PickedUp = true;
+ DropPickedUp?.Invoke(drop.Id, contender.Id);
SpawnChassisDrop(contender.X - 2.2f, contender.Z - 2.2f, oldChassis);
for (int i = 0; i < overflow.Count; i++)
@@ -558,8 +610,10 @@ namespace RustToDust.Core
contender.SnapPreviousPose();
contender.ResetAimTracker(contender.Yaw);
contender.AiScavengeCooldown = 4.0f;
+ contender.LoadoutVersion++;
Broadcast.EmitChassisSwap(Time, contender.Id, contender.Grid.Spec.Name);
ChassisSwapped?.Invoke(contender);
+ LoadoutChanged?.Invoke(contender);
return true;
}
@@ -788,23 +842,14 @@ namespace RustToDust.Core
float z = coords[i].Z;
float yaw = MathF.Atan2(-x, -z);
- string name = i == 0 ? "Contender 01 (You)" : $"Contender {i + 1:00}";
+ string name = $"Contender {i + 1:00}";
var grid = Catalog.CreateStarterBuggy();
- var contender = new ContenderState(i, name, i == 0, grid, x, z, yaw);
+ var contender = new ContenderState(i, name, isHuman: false, grid, x, z, yaw);
contender.Y = Terrain.SampleHeight(x, z) + contender.Grid.Spec.HalfHeight + 0.15f;
contender.AimY = contender.Y;
contender.SnapPreviousPose();
contender.ResetAimTracker(yaw);
Contenders.Add(contender);
- if (i > 0)
- {
- ContenderContacts[i] = new PlayerContactMemory();
- }
- }
-
- for (int i = 0; i < Spectators.Spectators.Count; i++)
- {
- SpectatorContacts[Spectators.Spectators[i].Id] = new PlayerContactMemory();
}
}
@@ -941,17 +986,17 @@ namespace RustToDust.Core
const float minSepSq = 220f * 220f;
const float preferOccludedDistSq = 380f * 380f;
- // Player starts in the open Sion Old Town / Rhone plaza facing Basilique de Valere & Chateau de Tourbillon.
- var playerGrid = Catalog.CreateStarterBuggy();
- float playerPad = MathF.Max(playerGrid.Spec.HalfWidth, playerGrid.Spec.HalfLength) + 2.0f;
- (float px, float pz) = FindClearSionPoint(-60f, 360f, playerPad, minNy: 0.84f, maxSearchRadius: 120f);
+ // Slot 0 starts in the open Sion Old Town / Rhone plaza facing Basilique de Valere & Chateau de Tourbillon.
+ var anchorGrid = Catalog.CreateStarterBuggy();
+ float anchorPad = MathF.Max(anchorGrid.Spec.HalfWidth, anchorGrid.Spec.HalfLength) + 2.0f;
+ (float px, float pz) = FindClearSionPoint(-60f, 360f, anchorPad, minNy: 0.84f, maxSearchRadius: 120f);
float pYaw = MathF.Atan2(150f - px, -260f - pz);
- var player = new ContenderState(0, "Contender 01 (You)", true, playerGrid, px, pz, pYaw);
- player.Y = Terrain.SampleHeight(px, pz) + playerGrid.Spec.HalfHeight + 0.15f;
- player.AimY = player.Y;
- player.SnapPreviousPose();
- player.ResetAimTracker(pYaw);
- Contenders.Add(player);
+ var anchor = new ContenderState(0, "Contender 01", isHuman: false, anchorGrid, px, pz, pYaw);
+ anchor.Y = Terrain.SampleHeight(px, pz) + anchorGrid.Spec.HalfHeight + 0.15f;
+ anchor.AimY = anchor.Y;
+ anchor.SnapPreviousPose();
+ anchor.ResetAimTracker(pYaw);
+ Contenders.Add(anchor);
for (int i = 1; i < ContenderCount; i++)
{
@@ -993,7 +1038,7 @@ namespace RustToDust.Core
}
float playerDistSq = (cx - px) * (cx - px) + (cz - pz) * (cz - pz);
- if (playerDistSq >= preferOccludedDistSq || IsSionSpawnOccludedFromPlayer(player, cx, cz, grid.Spec))
+ if (playerDistSq >= preferOccludedDistSq || IsSionSpawnOccludedFromPlayer(anchor, cx, cz, grid.Spec))
{
x = cx;
z = cz;
@@ -1052,18 +1097,12 @@ namespace RustToDust.Core
}
float yaw = MathF.Atan2(-x, -z);
- var contender = new ContenderState(i, $"Contender {i + 1:00}", false, grid, x, z, yaw);
+ var contender = new ContenderState(i, $"Contender {i + 1:00}", isHuman: false, grid, x, z, yaw);
contender.Y = Terrain.SampleHeight(x, z) + grid.Spec.HalfHeight + 0.15f;
contender.AimY = contender.Y;
contender.SnapPreviousPose();
contender.ResetAimTracker(yaw);
Contenders.Add(contender);
- ContenderContacts[i] = new PlayerContactMemory();
- }
-
- for (int i = 0; i < Spectators.Spectators.Count; i++)
- {
- SpectatorContacts[Spectators.Spectators[i].Id] = new PlayerContactMemory();
}
}
@@ -1079,7 +1118,7 @@ namespace RustToDust.Core
}
}
- var p = Player;
+ var p = Contenders[0];
float pYaw = p.Yaw;
for (int i = 0; i < chassisPool.Count; i++)
{
diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs
new file mode 100644
index 0000000..ea53deb
--- /dev/null
+++ b/src/RustToDust.Core/SimEvents.cs
@@ -0,0 +1,332 @@
+using System;
+using System.Collections.Generic;
+using MessagePack;
+
+namespace RustToDust.Core
+{
+ public enum TerrainStampKind : byte
+ {
+ Crater = 0,
+ Scorch = 1,
+ Track = 2
+ }
+
+ public enum SlotControlReason : byte
+ {
+ Joined = 0,
+ HandedToAi = 1,
+ Reclaimed = 2,
+ Eliminated = 3
+ }
+
+ [Union(0, typeof(ShotFiredEvent))]
+ [Union(1, typeof(HitImpactEvent))]
+ [Union(2, typeof(TerrainStampEvent))]
+ [Union(3, typeof(DropSpawnedEvent))]
+ [Union(4, typeof(DropPickedUpEvent))]
+ [Union(5, typeof(ContenderLoadoutEvent))]
+ [Union(6, typeof(EntitySlotControlEvent))]
+ [Union(7, typeof(BroadcastLineEvent))]
+ [Union(8, typeof(ContenderEliminatedEvent))]
+ [Union(9, typeof(SpectatorDestroyedEvent))]
+ [Union(10, typeof(OverheatAlertEvent))]
+ [Union(11, typeof(MatchResetEvent))]
+ // Reserved [Union(12)] DropPodEvent (Cut 6)
+ // Reserved [Union(13)] OrdnanceNodeEvent (Cut 7)
+ public interface ISimEvent
+ {
+ }
+
+ [MessagePackObject]
+ public sealed class ShotFiredEvent : ISimEvent
+ {
+ [Key(0)] public int TracerId { get; set; }
+ [Key(1)] public bool IsSpectatorShooter { get; set; }
+ [Key(2)] public int ShooterId { get; set; }
+ [Key(3)] public float StartX { get; set; }
+ [Key(4)] public float StartY { get; set; }
+ [Key(5)] public float StartZ { get; set; }
+ [Key(6)] public float EndX { get; set; }
+ [Key(7)] public float EndY { get; set; }
+ [Key(8)] public float EndZ { get; set; }
+ [Key(9)] public uint ColorRgba { get; set; }
+ [Key(10)] public float Ttl { get; set; }
+ [Key(11)] public byte WeaponClass { get; set; }
+ [Key(12)] public string WeaponId { get; set; } = string.Empty;
+ }
+
+ [MessagePackObject]
+ public sealed class HitImpactEvent : ISimEvent
+ {
+ [Key(0)] public long EventId { get; set; }
+ [Key(1)] public float HitX { get; set; }
+ [Key(2)] public float HitY { get; set; }
+ [Key(3)] public float HitZ { get; set; }
+ [Key(4)] public float NormalX { get; set; }
+ [Key(5)] public float NormalY { get; set; }
+ [Key(6)] public float NormalZ { get; set; }
+ [Key(7)] public float SourceX { get; set; }
+ [Key(8)] public float SourceY { get; set; }
+ [Key(9)] public float SourceZ { get; set; }
+ [Key(10)] public byte TargetKind { get; set; }
+ [Key(11)] public int TargetId { get; set; }
+ [Key(12)] public int CellX { get; set; }
+ [Key(13)] public int CellY { get; set; }
+ [Key(14)] public byte WeaponClass { get; set; }
+ [Key(15)] public string WeaponId { get; set; } = string.Empty;
+ [Key(16)] public bool IsAirburst { get; set; }
+ [Key(17)] public float Ttl { get; set; }
+ [Key(18)] public float NewCellArmor { get; set; }
+ [Key(19)] public float NewCellTemp { get; set; }
+ [Key(20)] public float NewCoreHp { get; set; }
+ [Key(21)] public int HitSequence { get; set; }
+ // Cut 5d/6/7 forward contract fields (Ruling 4)
+ [Key(22)] public int ShooterId { get; set; }
+ [Key(23)] public bool IsContenderShooter { get; set; }
+ [Key(24)] public float ArmorDamage { get; set; }
+ [Key(25)] public float CoreDamage { get; set; }
+ [Key(26)] public bool Killed { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class TerrainStampEvent : ISimEvent
+ {
+ [Key(0)] public byte Kind { get; set; }
+ [Key(1)] public float X { get; set; }
+ [Key(2)] public float Z { get; set; }
+ [Key(3)] public float Radius { get; set; }
+ [Key(4)] public float Depth { get; set; }
+ [Key(5)] public float Yaw { get; set; }
+ [Key(6)] public float Length { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class DropSpawnedEvent : ISimEvent
+ {
+ [Key(0)] public int DropId { get; set; }
+ [Key(1)] public float X { get; set; }
+ [Key(2)] public float Z { get; set; }
+ [Key(3)] public string? ChassisId { get; set; }
+ [Key(4)] public string? ModuleId { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class DropPickedUpEvent : ISimEvent
+ {
+ [Key(0)] public int DropId { get; set; }
+ [Key(1)] public int ContenderId { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class MountedSlotDto
+ {
+ [Key(0)] public string ModuleId { get; set; } = string.Empty;
+ [Key(1)] public string HardpointId { get; set; } = string.Empty;
+ }
+
+ [MessagePackObject]
+ public sealed class ContenderLoadoutEvent : ISimEvent
+ {
+ [Key(0)] public int ContenderId { get; set; }
+ [Key(1)] public int LoadoutVersion { get; set; }
+ [Key(2)] public string ChassisId { get; set; } = string.Empty;
+ [Key(3)] public float CoreHp { get; set; }
+ [Key(4)] public float MaxCoreHp { get; set; }
+ [Key(5)] public byte[] ArmorBytes { get; set; } = Array.Empty();
+ [Key(6)] public List Mounted { get; set; } = new();
+ [Key(7)] public List? CargoIds { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class EntitySlotControlEvent : ISimEvent
+ {
+ [Key(0)] public int ContenderId { get; set; }
+ [Key(1)] public bool IsHuman { get; set; }
+ [Key(2)] public string Name { get; set; } = string.Empty;
+ [Key(3)] public byte Reason { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class BroadcastLineEvent : ISimEvent
+ {
+ [Key(0)] public float Timestamp { get; set; }
+ [Key(1)] public byte Kind { get; set; }
+ [Key(2)] public string Text { get; set; } = string.Empty;
+ }
+
+ [MessagePackObject]
+ public sealed class ContenderEliminatedEvent : ISimEvent
+ {
+ [Key(0)] public int VictimId { get; set; }
+ [Key(1)] public int KillerId { get; set; }
+ [Key(2)] public bool IsSpectatorKiller { get; set; }
+ [Key(3)] public int KillerKills { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class SpectatorDestroyedEvent : ISimEvent
+ {
+ [Key(0)] public int SpectatorId { get; set; }
+ [Key(1)] public int KillerContenderId { get; set; }
+ [Key(2)] public int KillerKills { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class OverheatAlertEvent : ISimEvent
+ {
+ [Key(0)] public int ContenderId { get; set; }
+ [Key(1)] public bool IsOverheating { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class ContenderInitialDto
+ {
+ [Key(0)] public int Id { get; set; }
+ [Key(1)] public string Name { get; set; } = string.Empty;
+ [Key(2)] public bool IsHuman { get; set; }
+ [Key(3)] public float X { get; set; }
+ [Key(4)] public float Y { get; set; }
+ [Key(5)] public float Z { get; set; }
+ [Key(6)] public float Yaw { get; set; }
+ [Key(7)] public int Kills { get; set; }
+ [Key(8)] public ContenderLoadoutEvent Loadout { get; set; } = new();
+ }
+
+ [MessagePackObject]
+ public sealed class SpectatorInitialDto
+ {
+ [Key(0)] public int Id { get; set; }
+ [Key(1)] public byte Tier { get; set; }
+ [Key(2)] public byte Stance { get; set; }
+ [Key(3)] public float X { get; set; }
+ [Key(4)] public float Y { get; set; }
+ [Key(5)] public float Z { get; set; }
+ [Key(6)] public float Yaw { get; set; }
+ [Key(7)] public string ChassisId { get; set; } = string.Empty;
+ [Key(8)] public float CoreHp { get; set; }
+ [Key(9)] public float MaxCoreHp { get; set; }
+ [Key(10)] public byte[] ArmorBytes { get; set; } = Array.Empty();
+ [Key(11)] public List Mounted { get; set; } = new();
+ }
+
+ [MessagePackObject]
+ public sealed class GroundDropDto
+ {
+ [Key(0)] public int Id { get; set; }
+ [Key(1)] public float X { get; set; }
+ [Key(2)] public float Z { get; set; }
+ [Key(3)] public string? ChassisId { get; set; }
+ [Key(4)] public string? ModuleId { get; set; }
+ [Key(5)] public bool PickedUp { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class InitialMatchStateDto
+ {
+ [Key(0)] public uint MatchGeneration { get; set; }
+ [Key(1)] public int Seed { get; set; }
+ [Key(2)] public byte MapKind { get; set; }
+ [Key(3)] public float SimTime { get; set; }
+ [Key(4)] public float SafeRadius { get; set; }
+ [Key(5)] public byte Phase { get; set; }
+ [Key(6)] public int? WinnerContenderId { get; set; }
+ [Key(7)] public List Contenders { get; set; } = new();
+ [Key(8)] public List Spectators { get; set; } = new();
+ [Key(9)] public List GroundDrops { get; set; } = new();
+ [Key(10)] public List TerrainStamps { get; set; } = new();
+ }
+
+ [MessagePackObject]
+ public sealed class MatchResetEvent : ISimEvent
+ {
+ [Key(0)] public uint MatchGeneration { get; set; }
+ [Key(1)] public int Seed { get; set; }
+ [Key(2)] public byte MapKind { get; set; }
+ [Key(3)] public int AssignedContenderId { get; set; }
+ [Key(4)] public InitialMatchStateDto FullInitialState { get; set; } = new();
+ }
+
+ [Union(0, typeof(JoinReqMsg))]
+ [Union(1, typeof(JoinAcceptedMsg))]
+ [Union(2, typeof(JoinRejectedMsg))]
+ [Union(3, typeof(LeaveMsg))]
+ [Union(4, typeof(EquipCargoCmdMsg))]
+ [Union(5, typeof(NewMatchCmdMsg))]
+ [Union(6, typeof(SimEventBatchMsg))]
+ [Union(7, typeof(EntitySyncSnapshotMsg))]
+ public interface ISchemaWireMessage
+ {
+ }
+
+ [MessagePackObject]
+ public sealed class JoinReqMsg : ISchemaWireMessage
+ {
+ [Key(0)] public string Callsign { get; set; } = string.Empty;
+ [Key(1)] public Guid ReconnectToken { get; set; }
+ [Key(2)] public string ClientVersion { get; set; } = "rtd-5c";
+ }
+
+ [MessagePackObject]
+ public sealed class JoinAcceptedMsg : ISchemaWireMessage
+ {
+ [Key(0)] public uint PeerId { get; set; }
+ [Key(1)] public Guid ReconnectToken { get; set; }
+ [Key(2)] public int AssignedContenderId { get; set; }
+ [Key(3)] public uint MatchGeneration { get; set; }
+ [Key(4)] public InitialMatchStateDto InitialState { get; set; } = new();
+ }
+
+ [MessagePackObject]
+ public sealed class JoinRejectedMsg : ISchemaWireMessage
+ {
+ [Key(0)] public string Reason { get; set; } = string.Empty;
+ }
+
+ [MessagePackObject]
+ public sealed class LeaveMsg : ISchemaWireMessage
+ {
+ [Key(0)] public string Reason { get; set; } = string.Empty;
+ }
+
+ [MessagePackObject]
+ public sealed class EquipCargoCmdMsg : ISchemaWireMessage
+ {
+ [Key(0)] public uint ReqSeq { get; set; }
+ [Key(1)] public int CargoIndex { get; set; }
+ [Key(2)] public string HardpointId { get; set; } = string.Empty;
+ }
+
+ [MessagePackObject]
+ public sealed class NewMatchCmdMsg : ISchemaWireMessage
+ {
+ [Key(0)] public uint ReqSeq { get; set; }
+ [Key(1)] public int Seed { get; set; }
+ [Key(2)] public byte MapKind { get; set; }
+ }
+
+ [MessagePackObject]
+ public sealed class SimEventBatchMsg : ISchemaWireMessage
+ {
+ [Key(0)] public ulong BatchSeq { get; set; }
+ [Key(1)] public uint SimTick { get; set; }
+ [Key(2)] public float SimTime { get; set; }
+ [Key(3)] public uint MatchGeneration { get; set; }
+ [Key(4)] public List Events { get; set; } = new();
+ }
+
+ [MessagePackObject]
+ public sealed class EntitySyncSnapshotMsg : ISchemaWireMessage
+ {
+ [Key(0)] public bool IsContender { get; set; }
+ [Key(1)] public int EntityId { get; set; }
+ [Key(2)] public bool Alive { get; set; }
+ [Key(3)] public float PosX { get; set; }
+ [Key(4)] public float PosY { get; set; }
+ [Key(5)] public float PosZ { get; set; }
+ [Key(6)] public float Yaw { get; set; }
+ [Key(7)] public float CoreHp { get; set; }
+ [Key(8)] public float MaxCoreHp { get; set; }
+ [Key(9)] public byte[] ArmorBytes { get; set; } = Array.Empty();
+ [Key(10)] public ContenderLoadoutEvent? ContenderLoadout { get; set; }
+ }
+}
diff --git a/src/RustToDust.Core/SpectatorRing.cs b/src/RustToDust.Core/SpectatorRing.cs
index a4414ea..dc4373e 100644
--- a/src/RustToDust.Core/SpectatorRing.cs
+++ b/src/RustToDust.Core/SpectatorRing.cs
@@ -163,6 +163,8 @@ namespace RustToDust.Core
public float SafeRadius { get; private set; }
public IReadOnlyList Spectators => _spectators;
+ public void SetReplicatedSafeRadius(float radius) => SafeRadius = radius;
+
public void UpdateSafeRadius(float matchTime)
{
if (matchTime <= GraceDuration)
diff --git a/src/RustToDust.Core/WalkerVisualSnapshot.cs b/src/RustToDust.Core/WalkerVisualSnapshot.cs
new file mode 100644
index 0000000..f1de4e8
--- /dev/null
+++ b/src/RustToDust.Core/WalkerVisualSnapshot.cs
@@ -0,0 +1,73 @@
+using System;
+using System.Numerics;
+using System.Runtime.CompilerServices;
+
+namespace RustToDust.Core
+{
+ [InlineArray(4)]
+ public struct LegArray4
+ {
+ private T _element0;
+ }
+
+ public struct WalkerLegAngles
+ {
+ public float HipPitch;
+ public float HipRoll;
+ public float KneeFlex;
+ public float HockFlex;
+ public float AnklePitch;
+
+ public static WalkerLegAngles Lerp(in WalkerLegAngles a, in WalkerLegAngles b, float t) => new()
+ {
+ HipPitch = a.HipPitch + (b.HipPitch - a.HipPitch) * t,
+ HipRoll = a.HipRoll + (b.HipRoll - a.HipRoll) * t,
+ KneeFlex = a.KneeFlex + (b.KneeFlex - a.KneeFlex) * t,
+ HockFlex = a.HockFlex + (b.HockFlex - a.HockFlex) * t,
+ AnklePitch = a.AnklePitch + (b.AnklePitch - a.AnklePitch) * t
+ };
+ }
+
+ public struct WalkerVisualSnapshot
+ {
+ public int LegCount;
+ public float GeomScale;
+ public bool IsDigitigrade;
+ public bool IsArachnidUp;
+ public Vector3 ComPos;
+ public Quaternion ComRot;
+ public LegArray4 LegAngles;
+ public LegArray4 FootNormal;
+ public LegArray4 LoadG;
+
+ public static WalkerVisualSnapshot Interpolate(in WalkerVisualSnapshot prev, in WalkerVisualSnapshot curr, float alpha)
+ {
+ float t = Math.Clamp(alpha, 0f, 1f);
+ Quaternion q0 = prev.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(prev.ComRot);
+ Quaternion q1 = curr.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(curr.ComRot);
+ if (Quaternion.Dot(q0, q1) < 0f)
+ {
+ q1 = -q1;
+ }
+
+ WalkerVisualSnapshot res = new()
+ {
+ LegCount = curr.LegCount,
+ GeomScale = curr.GeomScale,
+ IsDigitigrade = curr.IsDigitigrade,
+ IsArachnidUp = curr.IsArachnidUp,
+ ComPos = Vector3.Lerp(prev.ComPos, curr.ComPos, t),
+ ComRot = Quaternion.Slerp(q0, q1, t)
+ };
+
+ for (int i = 0; i < curr.LegCount; i++)
+ {
+ res.LegAngles[i] = WalkerLegAngles.Lerp(prev.LegAngles[i], curr.LegAngles[i], t);
+ Vector3 n = Vector3.Lerp(prev.FootNormal[i], curr.FootNormal[i], t);
+ res.FootNormal[i] = n.LengthSquared() > 1e-6f ? Vector3.Normalize(n) : Vector3.UnitY;
+ res.LoadG[i] = prev.LoadG[i] + (curr.LoadG[i] - prev.LoadG[i]) * t;
+ }
+ return res;
+ }
+ }
+}
diff --git a/src/RustToDust.Net/ListenHostArenaSession.cs b/src/RustToDust.Net/ListenHostArenaSession.cs
new file mode 100644
index 0000000..a95663c
--- /dev/null
+++ b/src/RustToDust.Net/ListenHostArenaSession.cs
@@ -0,0 +1,104 @@
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Numerics;
+using RustToDust.Core;
+
+namespace RustToDust.Net
+{
+ public sealed class ListenHostArenaSession : IClientArenaSession
+ {
+ private readonly ServerMatchHost _host;
+
+ public ListenHostArenaSession(
+ IPAddress bindAddress,
+ int port,
+ int seed = 42,
+ ArenaMapKind mapKind = ArenaMapKind.Desert,
+ int maxHumans = MatchState.ContenderCount)
+ {
+ _host = new ServerMatchHost(
+ bindAddress,
+ port,
+ seed,
+ mapKind,
+ maxHumans: maxHumans,
+ autoRestartSec: 0,
+ allowClientReset: false,
+ hostContenderId: 0);
+ }
+
+ public ServerMatchHost Host => _host;
+ public MatchState ViewState => _host.Session.State;
+ public int LocalContenderId => 0;
+ public ContenderState LocalContender => _host.Session.State.Contenders[0];
+
+ public ClientMatchOutcome LocalOutcome =>
+ _host.Session.State.Phase == MatchPhase.Active
+ ? (LocalContender.Alive ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
+ : (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
+
+ public int LocalDetectedByCount =>
+ _host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.DetectedByCount : 0;
+
+ public IReadOnlyDictionary LocalContenderContacts =>
+ _host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.ContenderContacts : _host.Session.State.EmptyContacts;
+
+ public IReadOnlyDictionary LocalSpectatorContacts =>
+ _host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.SpectatorContacts : _host.Session.State.EmptyContacts;
+
+ public NetworkStatusSnapshot ConnectionStatus =>
+ new(
+ NetworkMode.ListenHost,
+ Connected: true,
+ PingMs: 0,
+ ConnectedHumans: _host.ConnectedHumanCount,
+ MaxHumans: MatchState.ContenderCount,
+ StateLabel: $"HOST :{_host.BoundPort} ({_host.ConnectedHumanCount}/12)");
+
+ public bool IsContenderVisible(int contenderId) => true;
+ public bool IsSpectatorVisible(int spectatorId) => true;
+
+ public void BeginRenderFrame(double dt, float physicsAlpha)
+ {
+ }
+
+ public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick)
+ {
+ if (!isPhysicsTick) return;
+ _host.SetHostInput(input);
+ _host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
+ }
+
+ public bool RequestEquipCargo(int cargoIndex, string hardpointId) =>
+ _host.Session.TryEquipCargo(0, cargoIndex, hardpointId);
+
+ public void RequestNewMatch(int seed, ArenaMapKind mapKind) =>
+ _host.ResetMatch(seed, mapKind);
+
+ public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) =>
+ _host.Session.GetInterpolatedContenderPose(contenderId, alpha);
+
+ public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) =>
+ _host.Session.GetInterpolatedSpectatorPose(spectatorId, alpha);
+
+ public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) =>
+ _host.Session.TrySampleInterpolatedWalkerPose(isContender, id, alpha, out snap);
+
+ public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
+ {
+ var hit = _host.Session.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
+ return new ClientRayHit(
+ hit.Hit,
+ hit.StableId,
+ new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z),
+ new Vector3(hit.Normal.X, hit.Normal.Y, hit.Normal.Z),
+ hit.Fraction);
+ }
+
+ public void Dispose()
+ {
+ _host.Dispose();
+ }
+ }
+}
diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs
new file mode 100644
index 0000000..c8e74bb
--- /dev/null
+++ b/src/RustToDust.Net/RemoteArenaSession.cs
@@ -0,0 +1,1341 @@
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Net.Sockets;
+using System.Numerics;
+using System.Threading;
+using GameCult.Mesh;
+using GameCult.Networking;
+using RustToDust.Core;
+using RustToDust.Ymir;
+using Ymir.Box3D;
+
+namespace RustToDust.Net
+{
+ public sealed class RemoteArenaSession : IClientArenaSession
+ {
+ private const int MaxUnackedInputs = 32;
+ private const float InterpDelaySec = 0.050f;
+ private const float HardSnapThresholdM = 4.0f;
+ private const float ErrorDecayTauSec = 0.10f;
+
+ private readonly record struct BufferedInput(uint Seq, PlayerInput Input);
+
+ private struct PoseSample
+ {
+ public float SimTime;
+ public Vector3 Pos;
+ public Quaternion Rot;
+ public Vector3 Vel;
+ }
+
+ private struct WalkerSample
+ {
+ public float SimTime;
+ public WalkerVisualSnapshot Snap;
+ }
+
+ private readonly Socket _socket;
+ private readonly CultNetRudpSocketTransportConnection _conn;
+ private readonly string _callsign;
+ private readonly List _unackedInputs = new(MaxUnackedInputs);
+ private readonly bool[] _contenderVisible = new bool[MatchState.ContenderCount];
+ private readonly bool[] _spectatorVisible = new bool[SpectatorRing.DefaultSpectatorCount];
+ private readonly List[] _contenderTimeline = new List[MatchState.ContenderCount];
+ private readonly List[] _spectatorTimeline = new List[SpectatorRing.DefaultSpectatorCount];
+ private readonly Dictionary> _contenderWalkerTimelines = new();
+ private readonly Dictionary> _spectatorWalkerTimelines = new();
+ private readonly Dictionary _pingSamples = new();
+
+ private MatchState _viewState;
+ private Box3DSoaWorld? _predWorld;
+ private Box3DSoaBodyHandle? _predBody;
+ private WalkerState? _predWalker;
+ private string _predChassisId = string.Empty;
+
+ private Vector3 _predErrorPos;
+ private Quaternion _predErrorRot = Quaternion.Identity;
+
+ private Guid _reconnectToken;
+ private uint _matchGeneration;
+ private uint _nextInputSeq = 1;
+ private uint _nextCmdSeq = 1;
+ private long _outLatestSeq = 1;
+ private long _outSchemaSeq = 1;
+ private uint _lastSnapshotSeq;
+ private uint _lastOrbitSeq;
+ private uint _lastRadarSeq;
+ private int _localContenderId;
+ private int _localDetectedByCount;
+ private float _latestServerSimTime;
+ private float _renderTime;
+ private int _pingMs;
+ private int _connectedHumans = 1;
+ private bool _joinSent;
+ private bool _joined;
+ private string? _lastError;
+ private bool _disposed;
+
+ public RemoteArenaSession(
+ IPEndPoint serverEndPoint,
+ string callsign = "Pilot",
+ Guid reconnectToken = default)
+ {
+ _callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
+ _reconnectToken = reconnectToken;
+
+ for (int i = 0; i < _contenderTimeline.Length; i++) _contenderTimeline[i] = new List(16);
+ for (int i = 0; i < _spectatorTimeline.Length; i++) _spectatorTimeline[i] = new List(16);
+
+ _viewState = new MatchState(42, ArenaMapKind.Desert);
+ for (int i = 0; i < _contenderVisible.Length; i++) _contenderVisible[i] = i == 0;
+
+ _socket = new Socket(serverEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
+ {
+ Blocking = false
+ };
+ _socket.Bind(new IPEndPoint(
+ serverEndPoint.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any,
+ 0));
+
+ _conn = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions
+ {
+ Mode = CultNetRudpSocketMode.Client,
+ RuntimeId = "rtd-client",
+ Socket = _socket,
+ RemoteEndPoint = serverEndPoint,
+ ConnectionId = 0x52544431,
+ ResendDelayMs = 100,
+ MaxFragmentBytes = SnapshotCodec.MaxLatestDatagramBytes,
+ MaxPayloadBytes = 256 * 1024,
+ MaxPendingReliablePackets = 2048
+ });
+ _conn.Connect();
+ }
+
+ public Func? DebugInboundLatestDropFilter { get; set; }
+ public Guid ReconnectToken => _reconnectToken;
+ public bool IsJoined => _joined;
+ public uint LastSnapshotSeq => _lastSnapshotSeq;
+ public int UnackedInputCount => _unackedInputs.Count;
+ public Vector3 CurrentPredictionError => _predErrorPos;
+
+ public MatchState ViewState => _viewState;
+ public int LocalContenderId => _localContenderId;
+ public ContenderState LocalContender => _viewState.Contenders[_localContenderId];
+
+ public ClientMatchOutcome LocalOutcome =>
+ _viewState.Phase == MatchPhase.Active
+ ? (LocalContender.Alive ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
+ : (_viewState.WinnerContenderId == _localContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
+
+ public int LocalDetectedByCount => _localDetectedByCount;
+
+ public IReadOnlyDictionary LocalContenderContacts =>
+ _viewState.ObserverStates.TryGetValue(_localContenderId, out var obs) ? obs.ContenderContacts : _viewState.EmptyContacts;
+
+ public IReadOnlyDictionary LocalSpectatorContacts =>
+ _viewState.ObserverStates.TryGetValue(_localContenderId, out var obs) ? obs.SpectatorContacts : _viewState.EmptyContacts;
+
+ public NetworkStatusSnapshot ConnectionStatus =>
+ new(
+ NetworkMode.RemoteClient,
+ Connected: _joined && _conn.Connected,
+ PingMs: _pingMs,
+ ConnectedHumans: _connectedHumans,
+ MaxHumans: MatchState.ContenderCount,
+ StateLabel: _joined ? $"ONLINE ({_pingMs} ms)" : (_lastError ?? "CONNECTING"),
+ LastError: _lastError);
+
+ public bool IsContenderVisible(int contenderId) =>
+ contenderId >= 0 && contenderId < _contenderVisible.Length && _contenderVisible[contenderId];
+
+ public bool IsSpectatorVisible(int spectatorId)
+ {
+ int idx = spectatorId >= 1000 ? spectatorId - 1000 : spectatorId;
+ return idx >= 0 && idx < _spectatorVisible.Length && _spectatorVisible[idx];
+ }
+
+ public bool WaitUntilJoined(TimeSpan timeout)
+ {
+ var deadline = DateTimeOffset.UtcNow + timeout;
+ while (DateTimeOffset.UtcNow < deadline)
+ {
+ PumpNetwork();
+ if (_joined) return true;
+ if (_lastError is not null) return false;
+ Thread.Sleep(2);
+ }
+ return _joined;
+ }
+
+ public void DisconnectGracefully(string reason = "Leave")
+ {
+ if (_disposed) return;
+ try
+ {
+ if (_conn.Connected)
+ {
+ SendSchemaMessage(new LeaveMsg { Reason = reason });
+ _conn.PollResends();
+ _conn.Disconnect();
+ }
+ }
+ catch
+ {
+ }
+ }
+
+ public void BeginRenderFrame(double dt, float physicsAlpha)
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+
+ PumpNetwork();
+
+ float fdt = (float)Math.Max(0.0, dt);
+ MatchRules.AdvanceTracers(_viewState, fdt);
+ MatchRules.AdvanceHitEvents(_viewState, fdt);
+
+ if (_joined)
+ {
+ _renderTime += fdt;
+ float minRender = _latestServerSimTime - 0.16f;
+ float maxRender = _latestServerSimTime - 0.015f;
+ if (_renderTime < minRender || _renderTime > _latestServerSimTime + 0.05f)
+ {
+ _renderTime = Math.Max(0f, _latestServerSimTime - InterpDelaySec);
+ }
+ else if (_renderTime > maxRender && maxRender > 0f)
+ {
+ _renderTime = maxRender;
+ }
+ }
+
+ if (fdt > 0f)
+ {
+ float decay = MathF.Exp(-fdt / ErrorDecayTauSec);
+ _predErrorPos *= decay;
+ if (_predErrorPos.LengthSquared() < 1e-8f)
+ {
+ _predErrorPos = Vector3.Zero;
+ }
+ _predErrorRot = Quaternion.Slerp(_predErrorRot, Quaternion.Identity, 1f - decay);
+ if (MathF.Abs(_predErrorRot.W) > 0.999999f)
+ {
+ _predErrorRot = Quaternion.Identity;
+ }
+ }
+ }
+
+ public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick)
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ if (!isPhysicsTick || !_joined)
+ {
+ return;
+ }
+
+ uint seq = _nextInputSeq++;
+ uint nowMs = unchecked((uint)Environment.TickCount64);
+ var pkt = new ClientInputPacket(_matchGeneration, seq, nowMs, input);
+ byte[] payload = SnapshotCodec.EncodeClientInput(pkt);
+ byte[] wire = SnapshotCodec.WrapLatest(payload, _matchGeneration, _outLatestSeq++, SnapshotCodec.SchemaInputId);
+ _conn.SendLatest(wire);
+
+ if (_unackedInputs.Count >= MaxUnackedInputs)
+ {
+ _unackedInputs.RemoveAt(0);
+ }
+ _unackedInputs.Add(new BufferedInput(seq, input));
+
+ StepLocalPredictionTick(input, updatePreviousPose: true);
+ }
+
+ public bool RequestEquipCargo(int cargoIndex, string hardpointId)
+ {
+ if (!_joined) return false;
+ SendSchemaMessage(new EquipCargoCmdMsg
+ {
+ ReqSeq = _nextCmdSeq++,
+ CargoIndex = cargoIndex,
+ HardpointId = hardpointId
+ });
+ return true;
+ }
+
+ public void RequestNewMatch(int seed, ArenaMapKind mapKind)
+ {
+ if (!_joined) return;
+ SendSchemaMessage(new NewMatchCmdMsg
+ {
+ ReqSeq = _nextCmdSeq++,
+ Seed = seed,
+ MapKind = (byte)mapKind
+ });
+ }
+
+ public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha)
+ {
+ if (contenderId < 0 || contenderId >= _viewState.Contenders.Count)
+ {
+ return (Vector3.Zero, Quaternion.Identity, Vector3.Zero);
+ }
+
+ if (contenderId == _localContenderId)
+ {
+ var c = _viewState.Contenders[contenderId];
+ float t = Math.Clamp(alpha, 0f, 1f);
+ var prevPos = new Vector3(c.PrevX, c.PrevY, c.PrevZ);
+ var currPos = new Vector3(c.X, c.Y, c.Z);
+ var prevQ = NormalizeQuat(new Quaternion(c.PrevRotX, c.PrevRotY, c.PrevRotZ, c.PrevRotW));
+ var currQ = NormalizeQuat(new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW));
+ if (Quaternion.Dot(prevQ, currQ) < 0f) currQ = -currQ;
+
+ Vector3 basePos = Vector3.Lerp(prevPos, currPos, t);
+ Quaternion baseRot = Quaternion.Slerp(prevQ, currQ, t);
+ return (
+ basePos + _predErrorPos,
+ NormalizeQuat(_predErrorRot * baseRot),
+ new Vector3(c.VelX, c.VelY, c.VelZ));
+ }
+
+ return SamplePoseTimeline(_contenderTimeline[contenderId], _viewState.Contenders[contenderId]);
+ }
+
+ public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha)
+ {
+ var list = _viewState.Spectators.Spectators;
+ SpectatorState? spec = null;
+ for (int i = 0; i < list.Count; i++)
+ {
+ if (list[i].Id == spectatorId)
+ {
+ spec = list[i];
+ break;
+ }
+ }
+ int idx = spectatorId >= 1000 ? spectatorId - 1000 : spectatorId;
+ if (spec is null || idx < 0 || idx >= _spectatorTimeline.Length)
+ {
+ return (Vector3.Zero, Quaternion.Identity, Vector3.Zero);
+ }
+
+ var timeline = _spectatorTimeline[idx];
+ if (timeline.Count == 0)
+ {
+ return (
+ new Vector3(spec.X, spec.Y, spec.Z),
+ NormalizeQuat(new Quaternion(spec.CurrRotX, spec.CurrRotY, spec.CurrRotZ, spec.CurrRotW)),
+ new Vector3(spec.VelX, spec.VelY, spec.VelZ));
+ }
+ return SampleTimelineSamples(timeline);
+ }
+
+ public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap)
+ {
+ if (isContender && id == _localContenderId)
+ {
+ if (_predWalker is not null && _predWalker.Initialized)
+ {
+ snap = WalkerVisualSnapshot.Interpolate(in _predWalker.PrevSnap, in _predWalker.CurrSnap, alpha);
+ snap.ComPos += _predErrorPos;
+ snap.ComRot = NormalizeQuat(_predErrorRot * snap.ComRot);
+ return true;
+ }
+ snap = default;
+ return false;
+ }
+
+ int key = !isContender && id >= 1000 ? id - 1000 : id;
+ var map = isContender ? _contenderWalkerTimelines : _spectatorWalkerTimelines;
+ if (!map.TryGetValue(key, out var list) || list.Count == 0)
+ {
+ snap = default;
+ return false;
+ }
+
+ if (list.Count == 1 || _renderTime <= list[0].SimTime)
+ {
+ snap = list[0].Snap;
+ return true;
+ }
+
+ int last = list.Count - 1;
+ if (_renderTime >= list[last].SimTime)
+ {
+ snap = list[last].Snap;
+ return true;
+ }
+
+ for (int i = 0; i < last; i++)
+ {
+ var a = list[i];
+ var b = list[i + 1];
+ if (_renderTime >= a.SimTime && _renderTime <= b.SimTime)
+ {
+ float span = MathF.Max(1e-5f, b.SimTime - a.SimTime);
+ float u = Math.Clamp((_renderTime - a.SimTime) / span, 0f, 1f);
+ snap = WalkerVisualSnapshot.Interpolate(in a.Snap, in b.Snap, u);
+ return true;
+ }
+ }
+
+ snap = list[last].Snap;
+ return true;
+ }
+
+ public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
+ {
+ float bestFrac = 1.00001f;
+ ClientRayHit best = default;
+
+ if (_predWorld is not null)
+ {
+ var staticHit = _predWorld.CastRayClosest(
+ (origin.X, origin.Y, origin.Z),
+ (translation.X, translation.Y, translation.Z));
+ if (staticHit.Hit && staticHit.StableId < ArenaSession.ContenderStableIdBase)
+ {
+ bestFrac = staticHit.Fraction;
+ best = new ClientRayHit(
+ true,
+ staticHit.StableId,
+ new Vector3(staticHit.Point.X, staticHit.Point.Y, staticHit.Point.Z),
+ new Vector3(staticHit.Normal.X, staticHit.Normal.Y, staticHit.Normal.Z),
+ staticHit.Fraction);
+ }
+ }
+
+ float len = translation.Length();
+ if (len > 1e-5f)
+ {
+ Vector3 dir = translation / len;
+ for (int i = 0; i < _viewState.Contenders.Count; i++)
+ {
+ var c = _viewState.Contenders[i];
+ if (!c.Alive || c.Id == _localContenderId || !IsContenderVisible(c.Id))
+ {
+ continue;
+ }
+ var (pos, rot, _) = GetInterpolatedContenderPose(c.Id, 1f);
+ var half = new Vector3(c.Grid.Spec.HalfWidth, ArenaSession.GetPhysicsHalfHeight(c.Grid.Spec), c.Grid.Spec.HalfLength);
+ if (RayIntersectsObb(origin, dir, len, pos, rot, half, out float frac, out Vector3 normal) && frac < bestFrac)
+ {
+ bestFrac = frac;
+ best = new ClientRayHit(true, ArenaSession.ContenderStableIdBase + (ulong)c.Id, origin + translation * frac, normal, frac);
+ }
+ }
+
+ for (int i = 0; i < _viewState.Spectators.Spectators.Count; i++)
+ {
+ var s = _viewState.Spectators.Spectators[i];
+ if (!s.Alive || !IsSpectatorVisible(s.Id))
+ {
+ continue;
+ }
+ var (pos, rot, _) = GetInterpolatedSpectatorPose(s.Id, 1f);
+ var half = new Vector3(s.Grid.Spec.HalfWidth, ArenaSession.GetPhysicsHalfHeight(s.Grid.Spec), s.Grid.Spec.HalfLength);
+ if (RayIntersectsObb(origin, dir, len, pos, rot, half, out float frac, out Vector3 normal) && frac < bestFrac)
+ {
+ bestFrac = frac;
+ best = new ClientRayHit(true, 3000UL + (ulong)s.Id, origin + translation * frac, normal, frac);
+ }
+ }
+ }
+
+ return best;
+ }
+
+ public void PumpNetwork()
+ {
+ if (_disposed) return;
+
+ if (_conn.Connected && !_joinSent)
+ {
+ _joinSent = true;
+ SendSchemaMessage(new JoinReqMsg
+ {
+ Callsign = _callsign,
+ ReconnectToken = _reconnectToken
+ });
+ }
+
+ int loops = 0;
+ while (loops < 256 && _conn.TryReceiveOnce(out var frame))
+ {
+ loops++;
+ if (frame is null) continue;
+
+ CultMeshRealtimeFrame rt;
+ try
+ {
+ rt = SnapshotCodec.Unwrap(frame.Payload);
+ }
+ catch
+ {
+ continue;
+ }
+
+ if (string.Equals(frame.ChannelId, SnapshotCodec.ChannelSchema, StringComparison.Ordinal))
+ {
+ HandleSchemaFrame(rt.Payload);
+ }
+ else if (string.Equals(frame.ChannelId, SnapshotCodec.ChannelLatest, StringComparison.Ordinal))
+ {
+ if (DebugInboundLatestDropFilter is not null && DebugInboundLatestDropFilter(rt.Payload.ToArray()))
+ {
+ continue;
+ }
+ HandleLatestFrame(rt.Payload.Span);
+ }
+ }
+
+ _conn.PollResends();
+ }
+
+ private void HandleSchemaFrame(ReadOnlyMemory payload)
+ {
+ ISchemaWireMessage msg;
+ try
+ {
+ msg = SnapshotCodec.DeserializeSchemaMessage(payload);
+ }
+ catch
+ {
+ return;
+ }
+
+ switch (msg)
+ {
+ case JoinAcceptedMsg accepted:
+ _reconnectToken = accepted.ReconnectToken;
+ _localContenderId = accepted.AssignedContenderId;
+ _matchGeneration = accepted.MatchGeneration;
+ ApplyInitialMatchState(accepted.InitialState, accepted.AssignedContenderId);
+ _joined = true;
+ break;
+ case JoinRejectedMsg rejected:
+ _lastError = rejected.Reason;
+ break;
+ case SimEventBatchMsg batch:
+ if (batch.MatchGeneration == _matchGeneration || ContainsMatchReset(batch.Events))
+ {
+ ApplyEventBatch(batch);
+ }
+ break;
+ case EntitySyncSnapshotMsg sync:
+ ApplyEntitySync(sync);
+ break;
+ }
+ }
+
+ private static bool ContainsMatchReset(List events)
+ {
+ for (int i = 0; i < events.Count; i++)
+ {
+ if (events[i] is MatchResetEvent) return true;
+ }
+ return false;
+ }
+
+ private void HandleLatestFrame(ReadOnlySpan span)
+ {
+ if (!_joined || span.IsEmpty) return;
+
+ var kind = (LatestPacketKind)span[0];
+ switch (kind)
+ {
+ case LatestPacketKind.CorePvs:
+ var core = SnapshotCodec.DecodeCorePvs(span);
+ if (core.MatchGeneration != _matchGeneration || core.SnapshotSeq <= _lastSnapshotSeq) return;
+ _lastSnapshotSeq = core.SnapshotSeq;
+ ApplyCorePvsSnapshot(core);
+ break;
+ case LatestPacketKind.SpectatorOrbitHalf:
+ var orbit = SnapshotCodec.DecodeSpectatorOrbitHalf(span);
+ if (orbit.MatchGeneration != _matchGeneration || orbit.SnapshotSeq < _lastOrbitSeq) return;
+ _lastOrbitSeq = orbit.SnapshotSeq;
+ ApplySpectatorOrbit(orbit);
+ break;
+ case LatestPacketKind.RadarContacts:
+ var radar = SnapshotCodec.DecodeRadarContacts(span);
+ if (radar.MatchGeneration != _matchGeneration || radar.SnapshotSeq < _lastRadarSeq) return;
+ _lastRadarSeq = radar.SnapshotSeq;
+ ApplyRadarContacts(radar);
+ break;
+ }
+ }
+
+ private void ApplyInitialMatchState(InitialMatchStateDto dto, int localContenderId)
+ {
+ _localContenderId = localContenderId;
+ _matchGeneration = dto.MatchGeneration;
+ _lastSnapshotSeq = 0;
+ _lastOrbitSeq = 0;
+ _lastRadarSeq = 0;
+ _unackedInputs.Clear();
+ _predErrorPos = Vector3.Zero;
+ _predErrorRot = Quaternion.Identity;
+
+ _viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind)
+ {
+ Time = dto.SimTime,
+ Phase = dto.Phase == 1 ? MatchPhase.Completed : MatchPhase.Active,
+ WinnerContenderId = dto.WinnerContenderId
+ };
+ _viewState.Spectators.SetReplicatedSafeRadius(dto.SafeRadius);
+ _latestServerSimTime = dto.SimTime;
+ _renderTime = Math.Max(0f, dto.SimTime - InterpDelaySec);
+
+ for (int i = 0; i < dto.TerrainStamps.Count; i++)
+ {
+ ApplyTerrainStamp(dto.TerrainStamps[i]);
+ }
+
+ _viewState.GroundDrops.Clear();
+ for (int i = 0; i < dto.GroundDrops.Count; i++)
+ {
+ var gd = dto.GroundDrops[i];
+ var d = _viewState.ApplyReplicatedDropSpawned(
+ gd.Id,
+ gd.X,
+ gd.Z,
+ gd.ChassisId is not null && Catalog.ChassisById.TryGetValue(gd.ChassisId, out var cs) ? cs : null,
+ gd.ModuleId is not null && Catalog.ModulesById.TryGetValue(gd.ModuleId, out var ms) ? ms : null);
+ d.PickedUp = gd.PickedUp;
+ }
+
+ int humans = 0;
+ for (int i = 0; i < dto.Contenders.Count && i < _viewState.Contenders.Count; i++)
+ {
+ var cd = dto.Contenders[i];
+ var c = _viewState.Contenders[cd.Id];
+ c.Name = cd.Name;
+ c.IsHuman = cd.IsHuman;
+ if (cd.IsHuman) humans++;
+ c.X = cd.X; c.Y = cd.Y; c.Z = cd.Z; c.Yaw = cd.Yaw;
+ c.Kills = cd.Kills;
+ var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, cd.Yaw);
+ c.CurrRotX = q.X; c.CurrRotY = q.Y; c.CurrRotZ = q.Z; c.CurrRotW = q.W;
+ c.SnapPreviousPose();
+ ApplyLoadoutToContender(c, cd.Loadout);
+ _contenderTimeline[cd.Id].Clear();
+ _contenderVisible[cd.Id] = cd.Id == _localContenderId;
+ }
+ _connectedHumans = Math.Max(1, humans);
+
+ for (int i = 0; i < dto.Spectators.Count && i < _viewState.Spectators.Spectators.Count; i++)
+ {
+ var sd = dto.Spectators[i];
+ var s = _viewState.Spectators.Spectators[i];
+ s.Stance = (SpectatorStance)sd.Stance;
+ s.X = sd.X; s.Y = sd.Y; s.Z = sd.Z; s.Yaw = sd.Yaw;
+ var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, sd.Yaw);
+ s.CurrRotX = q.X; s.CurrRotY = q.Y; s.CurrRotZ = q.Z; s.CurrRotW = q.W;
+ s.SnapPreviousPose();
+ var mounted = new List<(string, string)>(sd.Mounted.Count);
+ for (int m = 0; m < sd.Mounted.Count; m++) mounted.Add((sd.Mounted[m].ModuleId, sd.Mounted[m].HardpointId));
+ if (Catalog.ChassisById.TryGetValue(sd.ChassisId, out var spec))
+ {
+ s.Grid.ApplyReplicatedLoadout(spec, sd.CoreHp, sd.MaxCoreHp, sd.ArmorBytes, mounted, null, id => Catalog.ModulesById.TryGetValue(id, out var ms) ? ms : null);
+ }
+ _spectatorTimeline[i].Clear();
+ _spectatorVisible[i] = false;
+ }
+
+ _contenderWalkerTimelines.Clear();
+ _spectatorWalkerTimelines.Clear();
+
+ RebuildPredictionWorld();
+ }
+
+ private void RebuildPredictionWorld()
+ {
+ _predWorld?.Dispose();
+ _predWorld = new Box3DSoaWorld(capacity: 256, gravityX: 0f, gravityY: -20f, gravityZ: 0f);
+ ArenaSession.BuildStaticArena(_predWorld, _viewState);
+ _predBody = null;
+ _predWalker = null;
+ _predChassisId = string.Empty;
+
+ var local = LocalContender;
+ var q = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW));
+ SpawnLocalPredictionBody(new Vector3(local.X, local.Y, local.Z), q, Vector3.Zero, Vector3.Zero);
+ }
+
+ private void SpawnLocalPredictionBody(Vector3 pos, Quaternion rot, Vector3 vel, Vector3 angVel)
+ {
+ if (_predWorld is null) return;
+ var local = LocalContender;
+ if (!local.Alive)
+ {
+ if (_predBody.HasValue)
+ {
+ _predWorld.RemoveBody(_predBody.Value);
+ _predBody = null;
+ }
+ _predWalker = null;
+ _predChassisId = local.Grid.Spec.Id;
+ return;
+ }
+
+ if (_predBody.HasValue)
+ {
+ _predWorld.RemoveBody(_predBody.Value);
+ _predBody = null;
+ }
+ if (_predWorld.FreeBodySlots < 8)
+ {
+ _predWorld.Step(1e-5f, 1);
+ }
+
+ var spec = local.Grid.Spec;
+ float physHalfH = ArenaSession.GetPhysicsHalfHeight(spec);
+ float volume = 8f * spec.HalfWidth * physHalfH * spec.HalfLength;
+ float density = spec.MassKg / MathF.Max(0.1f, volume);
+
+ var handle = _predWorld.AddBox(
+ ArenaSession.ContenderStableIdBase + (ulong)local.Id,
+ (pos.X, pos.Y, pos.Z),
+ (spec.HalfWidth, physHalfH, spec.HalfLength),
+ density,
+ (rot.X, rot.Y, rot.Z, rot.W),
+ friction: 0.2f,
+ restitution: 0.1f);
+ _predBody = handle;
+
+ var v = _predWorld.View;
+ float mass = v.Mass[handle.Lane];
+ if (mass > 0f)
+ {
+ if (vel.LengthSquared() > 1e-8f)
+ {
+ _predWorld.ApplyImpulse(handle.Lane, (vel.X * mass, vel.Y * mass, vel.Z * mass), (pos.X, pos.Y, pos.Z));
+ }
+ if (angVel.LengthSquared() > 1e-6f)
+ {
+ float ix = mass * (physHalfH * physHalfH + spec.HalfLength * spec.HalfLength) / 3f;
+ float iy = mass * (spec.HalfWidth * spec.HalfWidth + spec.HalfLength * spec.HalfLength) / 3f;
+ float iz = mass * (spec.HalfWidth * spec.HalfWidth + physHalfH * physHalfH) / 3f;
+ Vector3 wLocal = Vector3.Transform(angVel, Quaternion.Conjugate(rot));
+ Vector3 lLocal = new(wLocal.X * ix, wLocal.Y * iy, wLocal.Z * iz);
+ Vector3 L = Vector3.Transform(lLocal, rot);
+ Vector3 ortho = MathF.Abs(L.Y) < 0.9f * L.Length() ? Vector3.UnitY : Vector3.UnitX;
+ Vector3 r = Vector3.Cross(L, ortho);
+ if (r.LengthSquared() > 1e-8f)
+ {
+ r = Vector3.Normalize(r);
+ Vector3 j = Vector3.Cross(L, r) * 0.5f;
+ _predWorld.ApplyImpulse(handle.Lane, (j.X, j.Y, j.Z), (pos.X + r.X, pos.Y + r.Y, pos.Z + r.Z));
+ _predWorld.ApplyImpulse(handle.Lane, (-j.X, -j.Y, -j.Z), (pos.X - r.X, pos.Y - r.Y, pos.Z - r.Z));
+ }
+ }
+ }
+
+ if (spec.IsWalker)
+ {
+ if (_predWalker is null || !string.Equals(_predChassisId, spec.Id, StringComparison.Ordinal))
+ {
+ _predWalker = new WalkerState(spec);
+ _predWalker.InitializePose(pos, rot, spec.MassKg, _viewState.Terrain);
+ }
+ else
+ {
+ _predWalker.SyncBodyPoseOnly(pos, rot, spec.MassKg);
+ }
+ }
+ else
+ {
+ _predWalker = null;
+ }
+ _predChassisId = spec.Id;
+ }
+
+ private void StepLocalPredictionTick(in PlayerInput input, bool updatePreviousPose)
+ {
+ var local = LocalContender;
+ if (updatePreviousPose)
+ {
+ local.SnapPreviousPose();
+ if (_predWalker is { Initialized: true })
+ {
+ _predWalker.SnapshotPrev();
+ }
+ }
+
+ if (_predWorld is null || !_predBody.HasValue || !local.Alive)
+ {
+ return;
+ }
+
+ MatchRules.ApplyHumanInput(_viewState, _localContenderId, input with { InteractPickup = false });
+ int subSteps = _viewState.MapKind == ArenaMapKind.Sion ? 1 : ArenaSession.SubStepCount;
+ ArenaSession.StepContenderPhysicsDrive(
+ local,
+ _predWorld.View,
+ _predBody.Value.Lane,
+ _viewState.Terrain,
+ _viewState.MapKind,
+ _predWalker,
+ ArenaSession.FixedDt,
+ injectEngineHeat: false);
+ _predWorld.Step(ArenaSession.FixedDt, subSteps);
+ ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker);
+ }
+
+ private void ApplyCorePvsSnapshot(DecodedCorePvsSnapshot pkt)
+ {
+ _viewState.Time = pkt.SimTime;
+ _viewState.Phase = pkt.Phase;
+ _viewState.WinnerContenderId = pkt.WinnerContenderId;
+ _viewState.Spectators.SetReplicatedSafeRadius(pkt.SafeRadius);
+ _localDetectedByCount = pkt.DetectedByCount;
+ _latestServerSimTime = MathF.Max(_latestServerSimTime, pkt.SimTime);
+
+ if (pkt.EchoSendMs != 0)
+ {
+ uint nowMs = unchecked((uint)Environment.TickCount64);
+ int rtt = (int)unchecked(nowMs - pkt.EchoSendMs);
+ if (rtt >= 0 && rtt < 5000)
+ {
+ _pingMs = _pingMs == 0 ? rtt : (int)(_pingMs * 0.7f + rtt * 0.3f);
+ }
+ }
+
+ var local = LocalContender;
+ local.InArcWeaponCount = pkt.InArcWeapons;
+ local.OutOfArcWeaponCount = pkt.OutOfArcWeapons;
+ local.DisabledWeaponCount = pkt.DisabledWeapons;
+ local.AllWeaponsOutOfArc = pkt.AllWeaponsOutOfArc;
+ local.MaxThermalRatio = pkt.LocalMaxThermalRatio;
+ if (!pkt.LocalAlive && local.Alive)
+ {
+ local.Grid.ApplyReplicatedDamage(0, 0, 0f, local.Grid.Temperature[0, 0], 0f, local.Grid.HitSequence + 1);
+ }
+ else if (pkt.LocalAlive && local.Grid.CoreHp <= 0f)
+ {
+ local.Grid.ApplyReplicatedDamage(0, 0, local.Grid.Armor[0, 0], local.Grid.Temperature[0, 0], pkt.LocalCoreHp, local.Grid.HitSequence);
+ }
+ local.Grid.ApplyReplicatedThermal(pkt.LocalCellTempsQuantized, pkt.LocalMountedTemps, pkt.LocalMountedCooldowns);
+
+ // Option M Reconciliation for local contender
+ Vector3 prevVisPos = new Vector3(local.X, local.Y, local.Z) + _predErrorPos;
+ Quaternion currQ = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW));
+ Quaternion prevVisRot = NormalizeQuat(_predErrorRot * currQ);
+
+ bool chassisChanged = !string.Equals(_predChassisId, local.Grid.Spec.Id, StringComparison.Ordinal);
+
+ // Discard acked inputs
+ int removeCount = 0;
+ while (removeCount < _unackedInputs.Count && _unackedInputs[removeCount].Seq <= pkt.AckedInputSeq)
+ {
+ removeCount++;
+ }
+ if (removeCount > 0)
+ {
+ _unackedInputs.RemoveRange(0, removeCount);
+ }
+
+ // Snap single-body physics state to authoritative snapshot
+ local.X = pkt.LocalPos.X;
+ local.Y = pkt.LocalPos.Y;
+ local.Z = pkt.LocalPos.Z;
+ local.CurrRotX = pkt.LocalRot.X;
+ local.CurrRotY = pkt.LocalRot.Y;
+ local.CurrRotZ = pkt.LocalRot.Z;
+ local.CurrRotW = pkt.LocalRot.W;
+ local.VelX = pkt.LocalVel.X;
+ local.VelY = pkt.LocalVel.Y;
+ local.VelZ = pkt.LocalVel.Z;
+ SpawnLocalPredictionBody(pkt.LocalPos, pkt.LocalRot, pkt.LocalVel, pkt.LocalAngVel);
+
+ // Replay unacked inputs
+ for (int i = 0; i < _unackedInputs.Count; i++)
+ {
+ StepLocalPredictionTick(_unackedInputs[i].Input, updatePreviousPose: false);
+ }
+ local.SnapPreviousPose();
+ if (_predWalker is { Initialized: true })
+ {
+ _predWalker.SnapshotPrev();
+ }
+
+ Vector3 newPredPos = new(local.X, local.Y, local.Z);
+ Quaternion newPredRot = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW));
+
+ Vector3 deltaPos = prevVisPos - newPredPos;
+ Quaternion deltaRot = NormalizeQuat(prevVisRot * Quaternion.Inverse(newPredRot));
+ if (deltaRot.W < 0f) deltaRot = -deltaRot;
+
+ if (!pkt.LocalAlive || chassisChanged || deltaPos.Length() > HardSnapThresholdM)
+ {
+ _predErrorPos = Vector3.Zero;
+ _predErrorRot = Quaternion.Identity;
+ }
+ else
+ {
+ _predErrorPos = deltaPos;
+ _predErrorRot = deltaRot;
+ }
+
+ // Remote contenders in PVS
+ int humans = local.IsHuman ? 1 : 0;
+ for (int i = 0; i < MatchState.ContenderCount; i++)
+ {
+ if (i == _localContenderId)
+ {
+ _contenderVisible[i] = true;
+ continue;
+ }
+ bool inPvs = (pkt.ContenderPvsMask & (1 << i)) != 0;
+ _contenderVisible[i] = inPvs;
+ if (!inPvs)
+ {
+ _contenderTimeline[i].Clear();
+ }
+ }
+
+ for (int i = 0; i < pkt.Contenders.Count; i++)
+ {
+ var nc = pkt.Contenders[i];
+ if (nc.SlotId == _localContenderId || nc.SlotId >= _viewState.Contenders.Count) continue;
+ var c = _viewState.Contenders[nc.SlotId];
+ c.IsHuman = nc.IsHuman;
+ if (nc.IsHuman) humans++;
+ c.FireCmd = nc.Fire;
+ c.BrakeCmd = nc.Brake;
+ c.ThrottleCmd = nc.Throttle;
+ c.SteerCmd = nc.Steer;
+ c.MaxThermalRatio = nc.MaxThermalRatio;
+ c.X = nc.Pos.X; c.Y = nc.Pos.Y; c.Z = nc.Pos.Z;
+ c.CurrRotX = nc.Rot.X; c.CurrRotY = nc.Rot.Y; c.CurrRotZ = nc.Rot.Z; c.CurrRotW = nc.Rot.W;
+ c.VelX = nc.Vel.X; c.VelY = nc.Vel.Y; c.VelZ = nc.Vel.Z;
+ c.AimX = nc.Pos.X + MathF.Sin(nc.AimYaw) * 25f;
+ c.AimZ = nc.Pos.Z + MathF.Cos(nc.AimYaw) * 25f;
+ c.AimY = nc.Pos.Y + MathF.Tan(nc.AimPitchDeg * (MathF.PI / 180f)) * 25f;
+ if (nc.Snap)
+ {
+ _contenderTimeline[nc.SlotId].Clear();
+ }
+ PushPoseSample(_contenderTimeline[nc.SlotId], pkt.SimTime, nc.Pos, nc.Rot, nc.Vel);
+ }
+ _connectedHumans = Math.Max(1, humans);
+
+ // Walkers in PVS
+ for (int i = 0; i < pkt.Walkers.Count; i++)
+ {
+ var nw = pkt.Walkers[i];
+ if (nw.IsContender && nw.EntityId == _localContenderId)
+ {
+ continue;
+ }
+ var map = nw.IsContender ? _contenderWalkerTimelines : _spectatorWalkerTimelines;
+ if (!map.TryGetValue(nw.EntityId, out var list))
+ {
+ list = new List(16);
+ map[nw.EntityId] = list;
+ }
+ if (list.Count >= 16) list.RemoveAt(0);
+ var snap = nw.Snapshot;
+ if (nw.IsContender && nw.EntityId < _viewState.Contenders.Count)
+ {
+ var c = _viewState.Contenders[nw.EntityId];
+ var g = WalkerGeometrySpec.GetForChassis(c.Grid.Spec.Id);
+ snap.GeomScale = g.ModelHalfHeight > 1e-4f ? c.Grid.Spec.HalfHeight / g.ModelHalfHeight : 1f;
+ snap.IsDigitigrade = g.IsDigitigrade;
+ snap.IsArachnidUp = g.IsArachnidUp;
+ snap.ComPos = new Vector3(c.X, c.Y, c.Z);
+ snap.ComRot = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW);
+ }
+ list.Add(new WalkerSample { SimTime = pkt.SimTime, Snap = snap });
+ }
+
+ // Combat spectators in PVS
+ for (int i = 0; i < pkt.CombatSpectators.Count; i++)
+ {
+ ApplySpectatorSnapshot(pkt.CombatSpectators[i], pkt.SimTime);
+ }
+ }
+
+ private void ApplySpectatorOrbit(DecodedSpectatorOrbitSnapshot orbit)
+ {
+ // Clear visibility for spectators in this half before re-marking PVS ones
+ var specs = _viewState.Spectators.Spectators;
+ for (int i = orbit.HalfIndex; i < specs.Count; i += 2)
+ {
+ if (specs[i].Stance == SpectatorStance.Neutral)
+ {
+ _spectatorVisible[i] = false;
+ }
+ }
+ for (int i = 0; i < orbit.Spectators.Count; i++)
+ {
+ ApplySpectatorSnapshot(orbit.Spectators[i], _latestServerSimTime);
+ }
+ }
+
+ private void ApplySpectatorSnapshot(in NetSpectatorState ns, float simTime)
+ {
+ if (ns.Id >= _spectatorVisible.Length || ns.Id >= _viewState.Spectators.Spectators.Count) return;
+ _spectatorVisible[ns.Id] = true;
+ var s = _viewState.Spectators.Spectators[ns.Id];
+ s.Stance = ns.Stance;
+ s.TargetContenderId = ns.TargetContenderId >= 0 ? ns.TargetContenderId : null;
+ s.X = ns.Pos.X; s.Y = ns.Pos.Y; s.Z = ns.Pos.Z;
+ s.CurrRotX = ns.Rot.X; s.CurrRotY = ns.Rot.Y; s.CurrRotZ = ns.Rot.Z; s.CurrRotW = ns.Rot.W;
+ s.VelX = ns.Vel.X; s.VelY = ns.Vel.Y; s.VelZ = ns.Vel.Z;
+ if (ns.Snap) _spectatorTimeline[ns.Id].Clear();
+ PushPoseSample(_spectatorTimeline[ns.Id], simTime, ns.Pos, ns.Rot, ns.Vel);
+ }
+
+ private void ApplyRadarContacts(DecodedRadarContactsSnapshot radar)
+ {
+ var obs = _viewState.GetOrCreateObserverState(_localContenderId);
+ obs.ContenderContacts.Clear();
+ for (int i = 0; i < radar.Contenders.Count; i++)
+ {
+ var rc = radar.Contenders[i];
+ obs.ContenderContacts[rc.EntityId] = new PlayerContactMemory
+ {
+ VisibleToPlayer = rc.Visible,
+ FaintHorizonPing = rc.FaintHorizon,
+ HasEverBeenSeen = rc.HasEverBeenSeen,
+ LastSeenAge = rc.LastSeenAge,
+ LastSeenX = rc.LastSeenX,
+ LastSeenZ = rc.LastSeenZ
+ };
+ }
+
+ obs.SpectatorContacts.Clear();
+ for (int i = 0; i < radar.Spectators.Count; i++)
+ {
+ var rs = radar.Spectators[i];
+ if (rs.EntityId >= _viewState.Spectators.Spectators.Count) continue;
+ int sId = _viewState.Spectators.Spectators[rs.EntityId].Id;
+ obs.SpectatorContacts[sId] = new PlayerContactMemory
+ {
+ VisibleToPlayer = rs.Visible,
+ FaintHorizonPing = rs.FaintHorizon,
+ HasEverBeenSeen = rs.HasEverBeenSeen,
+ LastSeenAge = rs.LastSeenAge,
+ LastSeenX = rs.LastSeenX,
+ LastSeenZ = rs.LastSeenZ
+ };
+ }
+ }
+
+ private void ApplyEventBatch(SimEventBatchMsg batch)
+ {
+ for (int i = 0; i < batch.Events.Count; i++)
+ {
+ switch (batch.Events[i])
+ {
+ case ShotFiredEvent shot:
+ _viewState.Tracers.Add(new TracerEvent(
+ shot.StartX, shot.StartY, shot.StartZ,
+ shot.EndX, shot.EndY, shot.EndZ,
+ shot.ColorRgba,
+ shot.Ttl,
+ (WeaponVisualClass)shot.WeaponClass,
+ shot.WeaponId,
+ shot.TracerId));
+ break;
+ case HitImpactEvent hit:
+ _viewState.HitEvents.Add(new HitFeedbackEvent(
+ hit.EventId,
+ hit.HitX, hit.HitY, hit.HitZ,
+ hit.NormalX, hit.NormalY, hit.NormalZ,
+ hit.SourceX, hit.SourceY, hit.SourceZ,
+ (HitTargetKind)hit.TargetKind,
+ hit.TargetId,
+ hit.CellX, hit.CellY,
+ (WeaponVisualClass)hit.WeaponClass,
+ hit.WeaponId,
+ hit.IsAirburst,
+ hit.Ttl));
+ if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId >= 0 && hit.TargetId < _viewState.Contenders.Count)
+ {
+ _viewState.Contenders[hit.TargetId].Grid.ApplyReplicatedDamage(
+ hit.CellX, hit.CellY, hit.NewCellArmor, hit.NewCellTemp, hit.NewCoreHp, hit.HitSequence);
+ }
+ else if (hit.TargetKind == (byte)HitTargetKind.Spectator)
+ {
+ int sIdx = hit.TargetId >= 1000 ? hit.TargetId - 1000 : hit.TargetId;
+ if (sIdx >= 0 && sIdx < _viewState.Spectators.Spectators.Count)
+ {
+ _viewState.Spectators.Spectators[sIdx].Grid.ApplyReplicatedDamage(
+ hit.CellX, hit.CellY, hit.NewCellArmor, hit.NewCellTemp, hit.NewCoreHp, hit.HitSequence);
+ }
+ }
+ break;
+ case TerrainStampEvent stamp:
+ ApplyTerrainStamp(stamp);
+ break;
+ case DropSpawnedEvent ds:
+ _viewState.ApplyReplicatedDropSpawned(
+ ds.DropId, ds.X, ds.Z,
+ ds.ChassisId is not null && Catalog.ChassisById.TryGetValue(ds.ChassisId, out var cs) ? cs : null,
+ ds.ModuleId is not null && Catalog.ModulesById.TryGetValue(ds.ModuleId, out var ms) ? ms : null);
+ break;
+ case DropPickedUpEvent dp:
+ _viewState.ApplyReplicatedDropPickedUp(dp.DropId);
+ break;
+ case ContenderLoadoutEvent cl:
+ if (cl.ContenderId >= 0 && cl.ContenderId < _viewState.Contenders.Count)
+ {
+ ApplyLoadoutToContender(_viewState.Contenders[cl.ContenderId], cl);
+ if (cl.ContenderId == _localContenderId)
+ {
+ var l = LocalContender;
+ SpawnLocalPredictionBody(
+ new Vector3(l.X, l.Y, l.Z),
+ NormalizeQuat(new Quaternion(l.CurrRotX, l.CurrRotY, l.CurrRotZ, l.CurrRotW)),
+ new Vector3(l.VelX, l.VelY, l.VelZ),
+ Vector3.Zero);
+ }
+ }
+ break;
+ case EntitySlotControlEvent slotCtrl:
+ if (slotCtrl.ContenderId >= 0 && slotCtrl.ContenderId < _viewState.Contenders.Count)
+ {
+ var c = _viewState.Contenders[slotCtrl.ContenderId];
+ c.IsHuman = slotCtrl.IsHuman;
+ c.Name = slotCtrl.Name;
+ }
+ break;
+ case BroadcastLineEvent bl:
+ _viewState.Broadcast.Emit(bl.Timestamp, (BroadcastKind)bl.Kind, bl.Text);
+ break;
+ case ContenderEliminatedEvent elim:
+ if (elim.VictimId >= 0 && elim.VictimId < _viewState.Contenders.Count)
+ {
+ var v = _viewState.Contenders[elim.VictimId];
+ v.Grid.ApplyReplicatedDamage(0, 0, 0f, v.Grid.Temperature[0, 0], 0f, v.Grid.HitSequence + 1);
+ }
+ if (!elim.IsSpectatorKiller && elim.KillerId >= 0 && elim.KillerId < _viewState.Contenders.Count)
+ {
+ _viewState.Contenders[elim.KillerId].Kills = elim.KillerKills;
+ }
+ break;
+ case SpectatorDestroyedEvent sdet:
+ {
+ int sIdx = sdet.SpectatorId >= 1000 ? sdet.SpectatorId - 1000 : sdet.SpectatorId;
+ if (sIdx >= 0 && sIdx < _viewState.Spectators.Spectators.Count)
+ {
+ var s = _viewState.Spectators.Spectators[sIdx];
+ s.Grid.ApplyReplicatedDamage(0, 0, 0f, s.Grid.Temperature[0, 0], 0f, s.Grid.HitSequence + 1);
+ }
+ if (sdet.KillerContenderId >= 0 && sdet.KillerContenderId < _viewState.Contenders.Count)
+ {
+ _viewState.Contenders[sdet.KillerContenderId].Kills = sdet.KillerKills;
+ }
+ break;
+ }
+ case MatchResetEvent reset:
+ ApplyInitialMatchState(reset.FullInitialState, reset.AssignedContenderId);
+ break;
+ }
+ }
+ }
+
+ private void ApplyEntitySync(EntitySyncSnapshotMsg sync)
+ {
+ if (sync.IsContender && sync.EntityId >= 0 && sync.EntityId < _viewState.Contenders.Count)
+ {
+ var c = _viewState.Contenders[sync.EntityId];
+ c.X = sync.PosX; c.Y = sync.PosY; c.Z = sync.PosZ; c.Yaw = sync.Yaw;
+ var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, sync.Yaw);
+ c.CurrRotX = q.X; c.CurrRotY = q.Y; c.CurrRotZ = q.Z; c.CurrRotW = q.W;
+ c.SnapPreviousPose();
+ if (sync.ContenderLoadout is not null)
+ {
+ ApplyLoadoutToContender(c, sync.ContenderLoadout);
+ }
+ c.Grid.ApplyReplicatedArmorBytes(sync.ArmorBytes);
+ c.Grid.ApplyReplicatedDamage(0, 0, c.Grid.Armor[0, 0], c.Grid.Temperature[0, 0], sync.Alive ? sync.CoreHp : 0f, c.Grid.HitSequence);
+ _contenderTimeline[c.Id].Clear();
+ PushPoseSample(_contenderTimeline[c.Id], _latestServerSimTime, new Vector3(c.X, c.Y, c.Z), q, Vector3.Zero);
+ }
+ else if (!sync.IsContender)
+ {
+ int sIdx = sync.EntityId >= 1000 ? sync.EntityId - 1000 : sync.EntityId;
+ if (sIdx >= 0 && sIdx < _viewState.Spectators.Spectators.Count)
+ {
+ var s = _viewState.Spectators.Spectators[sIdx];
+ s.X = sync.PosX; s.Y = sync.PosY; s.Z = sync.PosZ; s.Yaw = sync.Yaw;
+ var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, sync.Yaw);
+ s.CurrRotX = q.X; s.CurrRotY = q.Y; s.CurrRotZ = q.Z; s.CurrRotW = q.W;
+ s.SnapPreviousPose();
+ s.Grid.ApplyReplicatedArmorBytes(sync.ArmorBytes);
+ s.Grid.ApplyReplicatedDamage(0, 0, s.Grid.Armor[0, 0], s.Grid.Temperature[0, 0], sync.Alive ? sync.CoreHp : 0f, s.Grid.HitSequence);
+ _spectatorTimeline[sIdx].Clear();
+ PushPoseSample(_spectatorTimeline[sIdx], _latestServerSimTime, new Vector3(s.X, s.Y, s.Z), q, Vector3.Zero);
+ }
+ }
+ }
+
+ private void ApplyTerrainStamp(TerrainStampEvent stamp)
+ {
+ switch ((TerrainStampKind)stamp.Kind)
+ {
+ case TerrainStampKind.Crater:
+ _viewState.Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth);
+ break;
+ case TerrainStampKind.Scorch:
+ _viewState.Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius);
+ break;
+ case TerrainStampKind.Track:
+ _viewState.Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length);
+ break;
+ }
+ }
+
+ private static void ApplyLoadoutToContender(ContenderState c, ContenderLoadoutEvent cl)
+ {
+ if (!Catalog.ChassisById.TryGetValue(cl.ChassisId, out var spec)) return;
+ var mounted = new List<(string, string)>(cl.Mounted.Count);
+ for (int i = 0; i < cl.Mounted.Count; i++)
+ {
+ mounted.Add((cl.Mounted[i].ModuleId, cl.Mounted[i].HardpointId));
+ }
+ c.LoadoutVersion = cl.LoadoutVersion;
+ c.Grid.ApplyReplicatedLoadout(
+ spec,
+ cl.CoreHp,
+ cl.MaxCoreHp,
+ cl.ArmorBytes,
+ mounted,
+ cl.CargoIds,
+ id => Catalog.ModulesById.TryGetValue(id, out var ms) ? ms : null);
+ }
+
+ private static void PushPoseSample(List timeline, float simTime, Vector3 pos, Quaternion rot, Vector3 vel)
+ {
+ if (timeline.Count >= 16) timeline.RemoveAt(0);
+ timeline.Add(new PoseSample { SimTime = simTime, Pos = pos, Rot = NormalizeQuat(rot), Vel = vel });
+ }
+
+ private (Vector3 Pos, Quaternion Rot, Vector3 Vel) SamplePoseTimeline(List timeline, ContenderState fallback)
+ {
+ if (timeline.Count == 0)
+ {
+ return (
+ new Vector3(fallback.X, fallback.Y, fallback.Z),
+ NormalizeQuat(new Quaternion(fallback.CurrRotX, fallback.CurrRotY, fallback.CurrRotZ, fallback.CurrRotW)),
+ new Vector3(fallback.VelX, fallback.VelY, fallback.VelZ));
+ }
+ return SampleTimelineSamples(timeline);
+ }
+
+ private (Vector3 Pos, Quaternion Rot, Vector3 Vel) SampleTimelineSamples(List timeline)
+ {
+ if (timeline.Count == 1 || _renderTime <= timeline[0].SimTime)
+ {
+ var p = timeline[0];
+ return (p.Pos, p.Rot, p.Vel);
+ }
+ int last = timeline.Count - 1;
+ if (_renderTime >= timeline[last].SimTime)
+ {
+ var p = timeline[last];
+ return (p.Pos, p.Rot, p.Vel);
+ }
+ for (int i = 0; i < last; i++)
+ {
+ var a = timeline[i];
+ var b = timeline[i + 1];
+ if (_renderTime >= a.SimTime && _renderTime <= b.SimTime)
+ {
+ float span = MathF.Max(1e-5f, b.SimTime - a.SimTime);
+ float u = Math.Clamp((_renderTime - a.SimTime) / span, 0f, 1f);
+ Quaternion qa = a.Rot;
+ Quaternion qb = b.Rot;
+ if (Quaternion.Dot(qa, qb) < 0f) qb = -qb;
+ return (
+ Vector3.Lerp(a.Pos, b.Pos, u),
+ Quaternion.Slerp(qa, qb, u),
+ Vector3.Lerp(a.Vel, b.Vel, u));
+ }
+ }
+ var tail = timeline[last];
+ return (tail.Pos, tail.Rot, tail.Vel);
+ }
+
+ private static bool RayIntersectsObb(
+ Vector3 origin,
+ Vector3 dir,
+ float maxDist,
+ Vector3 boxPos,
+ Quaternion boxRot,
+ Vector3 halfExtents,
+ out float frac,
+ out Vector3 worldNormal)
+ {
+ Quaternion inv = Quaternion.Conjugate(NormalizeQuat(boxRot));
+ Vector3 lo = Vector3.Transform(origin - boxPos, inv);
+ Vector3 ld = Vector3.Transform(dir, inv);
+
+ float tMin = 0f;
+ float tMax = maxDist;
+ Vector3 localNormal = Vector3.UnitY;
+
+ if (!Slab(lo.X, ld.X, -halfExtents.X, halfExtents.X, new Vector3(1, 0, 0), ref tMin, ref tMax, ref localNormal)) { frac = 1f; worldNormal = Vector3.UnitY; return false; }
+ if (!Slab(lo.Y, ld.Y, -halfExtents.Y, halfExtents.Y, new Vector3(0, 1, 0), ref tMin, ref tMax, ref localNormal)) { frac = 1f; worldNormal = Vector3.UnitY; return false; }
+ if (!Slab(lo.Z, ld.Z, -halfExtents.Z, halfExtents.Z, new Vector3(0, 0, 1), ref tMin, ref tMax, ref localNormal)) { frac = 1f; worldNormal = Vector3.UnitY; return false; }
+
+ if (tMax < tMin || tMin < 0f || tMin > maxDist)
+ {
+ frac = 1f;
+ worldNormal = Vector3.UnitY;
+ return false;
+ }
+
+ frac = tMin / maxDist;
+ worldNormal = Vector3.Normalize(Vector3.Transform(localNormal, boxRot));
+ return true;
+ }
+
+ private static bool Slab(float o, float d, float minB, float maxB, Vector3 axis, ref float tMin, ref float tMax, ref Vector3 hitNormal)
+ {
+ if (MathF.Abs(d) < 1e-6f)
+ {
+ return o >= minB && o <= maxB;
+ }
+ float invD = 1f / d;
+ float t1 = (minB - o) * invD;
+ float t2 = (maxB - o) * invD;
+ Vector3 n = -MathF.Sign(d) * axis;
+ if (t1 > t2)
+ {
+ (t1, t2) = (t2, t1);
+ }
+ if (t1 > tMin)
+ {
+ tMin = t1;
+ hitNormal = n;
+ }
+ tMax = MathF.Min(tMax, t2);
+ return tMax >= tMin;
+ }
+
+ private void SendSchemaMessage(ISchemaWireMessage msg)
+ {
+ byte[] payload = SnapshotCodec.SerializeSchemaMessage(msg);
+ byte[] wire = SnapshotCodec.WrapSchema(payload, _matchGeneration, _outSchemaSeq++);
+ _conn.SendSchema(wire);
+ }
+
+ private static Quaternion NormalizeQuat(Quaternion q) =>
+ q.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(q);
+
+ public void Dispose()
+ {
+ if (_disposed) return;
+ _disposed = true;
+ DisconnectGracefully("Disposed");
+ _predWorld?.Dispose();
+ _conn.Dispose();
+ _socket.Dispose();
+ }
+ }
+}
diff --git a/src/RustToDust.Net/RustToDust.Net.csproj b/src/RustToDust.Net/RustToDust.Net.csproj
new file mode 100644
index 0000000..7b92aaf
--- /dev/null
+++ b/src/RustToDust.Net/RustToDust.Net.csproj
@@ -0,0 +1,16 @@
+
+
+
+ net8.0
+ enable
+ disable
+
+
+
+
+
+
+
+
+
+
diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs
new file mode 100644
index 0000000..59bd3f0
--- /dev/null
+++ b/src/RustToDust.Net/ServerMatchHost.cs
@@ -0,0 +1,948 @@
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Net.Sockets;
+using System.Numerics;
+using GameCult.Mesh;
+using GameCult.Networking;
+using RustToDust.Core;
+using RustToDust.Ymir;
+
+namespace RustToDust.Net
+{
+ public sealed class ServerMatchHost : IDisposable
+ {
+ public const long IdleTimeoutMs = 5000;
+
+ private sealed class ConnectedPeer
+ {
+ public uint PeerId;
+ public CultNetRudpSocketServerPeer TransportPeer = null!;
+ public string EndpointKey = string.Empty;
+ public Guid ReconnectToken;
+ public int AssignedContenderId;
+ public string Callsign = string.Empty;
+ public long LastHeardUtcMs;
+ public uint LastAcceptedInputSeq;
+ public uint LastEchoSendMs;
+ public bool Active = true;
+ public readonly EntityPvsTracker[] ContenderTrackers = new EntityPvsTracker[MatchState.ContenderCount];
+ public readonly EntityPvsTracker[] SpectatorTrackers = new EntityPvsTracker[SpectatorRing.DefaultSpectatorCount];
+ }
+
+ private struct EntityPvsTracker
+ {
+ public bool InPvs;
+ public bool SnapNext;
+ public int AckedLoadoutVersion;
+ public int AckedDamageVersion;
+ }
+
+ private readonly Socket _socket;
+ private readonly CultNetRudpSocketTransportServer _server;
+ private readonly Dictionary _peersByEndpoint = new(StringComparer.Ordinal);
+ private readonly HashSet _retiredTransportPeers = new();
+ private readonly Dictionary _reconnectTokens = new();
+ private readonly List _stepEvents = new();
+ private readonly List _terrainStampHistory = new();
+ private readonly int _maxHumans;
+ private readonly double _autoRestartSec;
+ private readonly bool _allowClientReset;
+ private readonly int? _hostContenderId;
+
+ private ArenaSession _session;
+ private uint _matchGeneration = 1;
+ private uint _simTick;
+ private uint _snapshotSeq;
+ private ulong _eventBatchSeq = 1;
+ private long _schemaOutSeq = 1;
+ private long _latestOutSeq = 1;
+ private uint _nextPeerId = 1;
+ private float _roundCompletedElapsed;
+ private bool _disposed;
+
+ public ServerMatchHost(
+ IPAddress bindAddress,
+ int port,
+ int seed = 42,
+ ArenaMapKind mapKind = ArenaMapKind.Desert,
+ int maxHumans = MatchState.ContenderCount,
+ double autoRestartSec = 8.0,
+ bool allowClientReset = false,
+ int? hostContenderId = null)
+ {
+ _maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount);
+ _autoRestartSec = autoRestartSec;
+ _allowClientReset = allowClientReset;
+ _hostContenderId = hostContenderId;
+
+ _socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
+ {
+ Blocking = false
+ };
+ _socket.Bind(new IPEndPoint(bindAddress, port));
+ BoundPort = ((IPEndPoint)_socket.LocalEndPoint!).Port;
+
+ _server = new CultNetRudpSocketTransportServer(new CultNetRudpSocketTransportServerOptions
+ {
+ RuntimeId = "rtd-server",
+ Socket = _socket,
+ ConnectionId = 0x52544431,
+ ResendDelayMs = 100,
+ MaxFragmentBytes = SnapshotCodec.MaxLatestDatagramBytes,
+ MaxPayloadBytes = 256 * 1024,
+ MaxPendingReliablePackets = 2048
+ });
+ _server.PeerDisconnected += OnTransportPeerDisconnected;
+
+ _session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0);
+ if (hostContenderId.HasValue)
+ {
+ _session.SetHumanSlot(hostContenderId.Value, true, "Host");
+ }
+ }
+
+ public int BoundPort { get; }
+ public ArenaSession Session => _session;
+ public uint MatchGeneration => _matchGeneration;
+ public uint SimTick => _simTick;
+ public int ConnectedHumanCount => _peersByEndpoint.Count + (_hostContenderId.HasValue ? 1 : 0);
+
+ public void SetHostInput(in PlayerInput input)
+ {
+ if (_hostContenderId.HasValue)
+ {
+ _session.SetHumanInput(_hostContenderId.Value, input);
+ }
+ }
+
+ public void ResetMatch(int seed, ArenaMapKind mapKind)
+ {
+ _session.Dispose();
+ _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0);
+ _matchGeneration++;
+ _simTick = 0;
+ _roundCompletedElapsed = 0f;
+ _terrainStampHistory.Clear();
+ _stepEvents.Clear();
+ _reconnectTokens.Clear();
+
+ if (_hostContenderId.HasValue)
+ {
+ _session.SetHumanSlot(_hostContenderId.Value, true, "Host");
+ }
+
+ foreach (var peer in _peersByEndpoint.Values)
+ {
+ if (!peer.Active) continue;
+ int slot = peer.AssignedContenderId;
+ _session.SetHumanSlot(slot, true, peer.Callsign);
+ _reconnectTokens[peer.ReconnectToken] = (slot, peer.Callsign);
+ InitPeerTrackers(peer);
+ var reset = new MatchResetEvent
+ {
+ MatchGeneration = _matchGeneration,
+ Seed = seed,
+ MapKind = (byte)mapKind,
+ AssignedContenderId = slot,
+ FullInitialState = BuildInitialMatchStateDto(slot)
+ };
+ SendSchemaToPeer(peer, new SimEventBatchMsg
+ {
+ BatchSeq = _eventBatchSeq++,
+ SimTick = _simTick,
+ SimTime = _session.State.Time,
+ MatchGeneration = _matchGeneration,
+ Events = new List { reset }
+ });
+ }
+ }
+
+ public void StepOnce(long nowUtcMs)
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+
+ PollIncoming(nowUtcMs);
+ SweepTimeouts(nowUtcMs);
+
+ _session.Step();
+ _simTick++;
+
+ _stepEvents.Clear();
+ _session.DrainStepEvents(_stepEvents);
+ for (int i = 0; i < _stepEvents.Count; i++)
+ {
+ if (_stepEvents[i] is TerrainStampEvent ts)
+ {
+ _terrainStampHistory.Add(ts);
+ }
+ }
+
+ FlushEventsAndPvsEnter();
+ BroadcastSnapshots();
+ _server.PollResends();
+
+ if (_autoRestartSec > 0 && _session.State.Phase == MatchPhase.Completed)
+ {
+ _roundCompletedElapsed += ArenaSession.FixedDt;
+ if (_roundCompletedElapsed >= _autoRestartSec)
+ {
+ ResetMatch(_session.State.Seed + 1, _session.State.MapKind);
+ }
+ }
+ }
+
+ private void PollIncoming(long nowUtcMs)
+ {
+ int processed = 0;
+ while (processed < 256 && _server.TryReceiveOnce(out var serverFrame))
+ {
+ processed++;
+ if (serverFrame is null || _retiredTransportPeers.Contains(serverFrame.Peer))
+ {
+ continue;
+ }
+
+ CultMeshRealtimeFrame rtFrame;
+ try
+ {
+ rtFrame = SnapshotCodec.Unwrap(serverFrame.Frame.Payload);
+ }
+ catch
+ {
+ continue;
+ }
+
+ string epKey = serverFrame.Peer.RemoteEndPoint.ToString() ?? string.Empty;
+
+ if (string.Equals(serverFrame.Frame.ChannelId, SnapshotCodec.ChannelSchema, StringComparison.Ordinal))
+ {
+ HandleSchemaFrame(serverFrame.Peer, epKey, rtFrame, nowUtcMs);
+ }
+ else if (string.Equals(serverFrame.Frame.ChannelId, SnapshotCodec.ChannelLatest, StringComparison.Ordinal))
+ {
+ HandleLatestFrame(serverFrame.Peer, epKey, rtFrame, nowUtcMs);
+ }
+ }
+ }
+
+ private void HandleSchemaFrame(CultNetRudpSocketServerPeer transportPeer, string epKey, CultMeshRealtimeFrame rtFrame, long nowUtcMs)
+ {
+ ISchemaWireMessage msg;
+ try
+ {
+ msg = SnapshotCodec.DeserializeSchemaMessage(rtFrame.Payload);
+ }
+ catch
+ {
+ return;
+ }
+
+ switch (msg)
+ {
+ case JoinReqMsg join:
+ HandleJoin(transportPeer, epKey, join, nowUtcMs);
+ break;
+ case LeaveMsg:
+ if (_peersByEndpoint.TryGetValue(epKey, out var leaving) && ReferenceEquals(leaving.TransportPeer, transportPeer))
+ {
+ RetirePeer(leaving, SlotControlReason.HandedToAi);
+ }
+ break;
+ case EquipCargoCmdMsg equip:
+ if (_peersByEndpoint.TryGetValue(epKey, out var eqPeer) && eqPeer.Active && ReferenceEquals(eqPeer.TransportPeer, transportPeer))
+ {
+ eqPeer.LastHeardUtcMs = nowUtcMs;
+ _session.TryEquipCargo(eqPeer.AssignedContenderId, equip.CargoIndex, equip.HardpointId);
+ }
+ break;
+ case NewMatchCmdMsg newMatch:
+ if (_peersByEndpoint.TryGetValue(epKey, out var nmPeer) && nmPeer.Active && ReferenceEquals(nmPeer.TransportPeer, transportPeer))
+ {
+ nmPeer.LastHeardUtcMs = nowUtcMs;
+ if (_allowClientReset)
+ {
+ ResetMatch(newMatch.Seed, (ArenaMapKind)newMatch.MapKind);
+ }
+ }
+ break;
+ }
+ }
+
+ private void HandleJoin(CultNetRudpSocketServerPeer transportPeer, string epKey, JoinReqMsg join, long nowUtcMs)
+ {
+ if (_peersByEndpoint.TryGetValue(epKey, out var existing))
+ {
+ if (ReferenceEquals(existing.TransportPeer, transportPeer) && existing.Active)
+ {
+ existing.LastHeardUtcMs = nowUtcMs;
+ SendJoinAccepted(existing);
+ return;
+ }
+ RetirePeer(existing, SlotControlReason.HandedToAi);
+ }
+
+ string callsign = string.IsNullOrWhiteSpace(join.Callsign) ? $"Pilot-{_nextPeerId}" : join.Callsign.Trim();
+ if (callsign.Length > 24) callsign = callsign.Substring(0, 24);
+
+ int slotId = -1;
+ SlotControlReason reason = SlotControlReason.Joined;
+
+ if (join.ReconnectToken != Guid.Empty && _reconnectTokens.TryGetValue(join.ReconnectToken, out var saved))
+ {
+ if (saved.SlotId >= 0 && saved.SlotId < _session.State.Contenders.Count)
+ {
+ var cand = _session.State.Contenders[saved.SlotId];
+ if (cand.Alive && !cand.IsHuman && saved.SlotId != _hostContenderId)
+ {
+ slotId = saved.SlotId;
+ reason = SlotControlReason.Reclaimed;
+ }
+ }
+ }
+
+ if (slotId < 0)
+ {
+ if (ConnectedHumanCount >= _maxHumans)
+ {
+ SendSchemaRaw(transportPeer, new JoinRejectedMsg { Reason = "Server human capacity reached." });
+ return;
+ }
+
+ for (int i = 0; i < _session.State.Contenders.Count; i++)
+ {
+ if (i == _hostContenderId) continue;
+ var c = _session.State.Contenders[i];
+ if (c.Alive && !c.IsHuman)
+ {
+ slotId = i;
+ break;
+ }
+ }
+ }
+
+ if (slotId < 0)
+ {
+ SendSchemaRaw(transportPeer, new JoinRejectedMsg { Reason = "No alive contender slots available." });
+ return;
+ }
+
+ Guid token = join.ReconnectToken != Guid.Empty ? join.ReconnectToken : Guid.NewGuid();
+ _reconnectTokens[token] = (slotId, callsign);
+ _session.SetHumanSlot(slotId, true, callsign);
+
+ var peer = new ConnectedPeer
+ {
+ PeerId = _nextPeerId++,
+ TransportPeer = transportPeer,
+ EndpointKey = epKey,
+ ReconnectToken = token,
+ AssignedContenderId = slotId,
+ Callsign = callsign,
+ LastHeardUtcMs = nowUtcMs
+ };
+ InitPeerTrackers(peer);
+ _peersByEndpoint[epKey] = peer;
+
+ SendJoinAccepted(peer);
+
+ _stepEvents.Add(new EntitySlotControlEvent
+ {
+ ContenderId = slotId,
+ IsHuman = true,
+ Name = callsign,
+ Reason = (byte)reason
+ });
+ }
+
+ private void HandleLatestFrame(CultNetRudpSocketServerPeer transportPeer, string epKey, CultMeshRealtimeFrame rtFrame, long nowUtcMs)
+ {
+ if (!_peersByEndpoint.TryGetValue(epKey, out var peer) || !peer.Active || !ReferenceEquals(peer.TransportPeer, transportPeer))
+ {
+ return;
+ }
+
+ peer.LastHeardUtcMs = nowUtcMs;
+ ClientInputPacket pkt;
+ try
+ {
+ pkt = SnapshotCodec.DecodeClientInput(rtFrame.Payload.Span);
+ }
+ catch
+ {
+ return;
+ }
+
+ if (pkt.MatchGeneration != _matchGeneration || pkt.InputSeq <= peer.LastAcceptedInputSeq)
+ {
+ return;
+ }
+
+ peer.LastAcceptedInputSeq = pkt.InputSeq;
+ peer.LastEchoSendMs = pkt.ClientSendMs;
+ _session.SetHumanInput(peer.AssignedContenderId, pkt.Input);
+ }
+
+ private void SweepTimeouts(long nowUtcMs)
+ {
+ List? timedOut = null;
+ foreach (var peer in _peersByEndpoint.Values)
+ {
+ if (peer.Active && (nowUtcMs - peer.LastHeardUtcMs) > IdleTimeoutMs)
+ {
+ timedOut ??= new List();
+ timedOut.Add(peer);
+ }
+ }
+ if (timedOut is null) return;
+ for (int i = 0; i < timedOut.Count; i++)
+ {
+ RetirePeer(timedOut[i], SlotControlReason.HandedToAi);
+ }
+ }
+
+ private void OnTransportPeerDisconnected(CultNetRudpSocketServerPeer transportPeer)
+ {
+ string epKey = transportPeer.RemoteEndPoint.ToString() ?? string.Empty;
+ if (_peersByEndpoint.TryGetValue(epKey, out var peer) && ReferenceEquals(peer.TransportPeer, transportPeer))
+ {
+ RetirePeer(peer, SlotControlReason.HandedToAi);
+ }
+ }
+
+ private void RetirePeer(ConnectedPeer peer, SlotControlReason reason)
+ {
+ if (!peer.Active) return;
+ peer.Active = false;
+ _peersByEndpoint.Remove(peer.EndpointKey);
+ _retiredTransportPeers.Add(peer.TransportPeer);
+
+ int slot = peer.AssignedContenderId;
+ if (slot >= 0 && slot < _session.State.Contenders.Count)
+ {
+ _session.SetHumanSlot(slot, false);
+ var c = _session.State.Contenders[slot];
+ _stepEvents.Add(new EntitySlotControlEvent
+ {
+ ContenderId = slot,
+ IsHuman = false,
+ Name = c.Name,
+ Reason = (byte)reason
+ });
+ }
+ }
+
+ private void InitPeerTrackers(ConnectedPeer peer)
+ {
+ for (int i = 0; i < _session.State.Contenders.Count; i++)
+ {
+ var c = _session.State.Contenders[i];
+ bool inPvs = _session.IsEntityInPeerPvs(peer.AssignedContenderId, true, c.Id);
+ peer.ContenderTrackers[i] = new EntityPvsTracker
+ {
+ InPvs = inPvs,
+ SnapNext = false,
+ AckedLoadoutVersion = c.LoadoutVersion,
+ AckedDamageVersion = c.DamageVersion
+ };
+ }
+ for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++)
+ {
+ var s = _session.State.Spectators.Spectators[i];
+ bool inPvs = _session.IsEntityInPeerPvs(peer.AssignedContenderId, false, s.Id);
+ peer.SpectatorTrackers[i] = new EntityPvsTracker
+ {
+ InPvs = inPvs,
+ SnapNext = false,
+ AckedLoadoutVersion = 1,
+ AckedDamageVersion = s.Grid.HitSequence
+ };
+ }
+ }
+
+ private void FlushEventsAndPvsEnter()
+ {
+ if (_peersByEndpoint.Count == 0) return;
+
+ foreach (var peer in _peersByEndpoint.Values)
+ {
+ if (!peer.Active) continue;
+ int obsId = peer.AssignedContenderId;
+
+ // Check PVS-enter resyncs
+ for (int i = 0; i < _session.State.Contenders.Count; i++)
+ {
+ var c = _session.State.Contenders[i];
+ bool inPvs = _session.IsEntityInPeerPvs(obsId, true, c.Id);
+ ref var tracker = ref peer.ContenderTrackers[i];
+ if (inPvs && !tracker.InPvs)
+ {
+ tracker.SnapNext = true;
+ if (tracker.AckedLoadoutVersion != c.LoadoutVersion || tracker.AckedDamageVersion != c.DamageVersion)
+ {
+ tracker.AckedLoadoutVersion = c.LoadoutVersion;
+ tracker.AckedDamageVersion = c.DamageVersion;
+ SendSchemaToPeer(peer, new EntitySyncSnapshotMsg
+ {
+ IsContender = true,
+ EntityId = c.Id,
+ Alive = c.Alive,
+ PosX = c.X, PosY = c.Y, PosZ = c.Z, Yaw = c.Yaw,
+ CoreHp = c.Grid.CoreHp,
+ MaxCoreHp = c.Grid.MaxCoreHp,
+ ArmorBytes = c.Grid.QuantizeArmorBytes(),
+ ContenderLoadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == obsId)
+ });
+ }
+ }
+ tracker.InPvs = inPvs;
+ }
+
+ for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++)
+ {
+ var s = _session.State.Spectators.Spectators[i];
+ bool inPvs = _session.IsEntityInPeerPvs(obsId, false, s.Id);
+ ref var tracker = ref peer.SpectatorTrackers[i];
+ if (inPvs && !tracker.InPvs)
+ {
+ tracker.SnapNext = true;
+ if (tracker.AckedDamageVersion != s.Grid.HitSequence)
+ {
+ tracker.AckedDamageVersion = s.Grid.HitSequence;
+ SendSchemaToPeer(peer, new EntitySyncSnapshotMsg
+ {
+ IsContender = false,
+ EntityId = s.Id,
+ Alive = s.Alive,
+ PosX = s.X, PosY = s.Y, PosZ = s.Z, Yaw = s.Yaw,
+ CoreHp = s.Grid.CoreHp,
+ MaxCoreHp = s.Grid.MaxCoreHp,
+ ArmorBytes = s.Grid.QuantizeArmorBytes()
+ });
+ }
+ }
+ tracker.InPvs = inPvs;
+ }
+
+ if (_stepEvents.Count == 0) continue;
+
+ var obs = _session.State.Contenders[obsId];
+ var filtered = new List(_stepEvents.Count);
+ for (int e = 0; e < _stepEvents.Count; e++)
+ {
+ var ev = _stepEvents[e];
+ switch (ev)
+ {
+ case ContenderLoadoutEvent loadout:
+ if (loadout.ContenderId == obsId || _session.IsEntityInPeerPvs(obsId, true, loadout.ContenderId))
+ {
+ var c = _session.State.Contenders[loadout.ContenderId];
+ peer.ContenderTrackers[loadout.ContenderId].AckedLoadoutVersion = c.LoadoutVersion;
+ filtered.Add(loadout.ContenderId == obsId
+ ? loadout
+ : ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: false));
+ }
+ break;
+ case ShotFiredEvent shot:
+ bool shooterVisible = _session.IsEntityInPeerPvs(obsId, !shot.IsSpectatorShooter, shot.ShooterId);
+ float dxEnd = shot.EndX - obs.X;
+ float dzEnd = shot.EndZ - obs.Z;
+ if (shooterVisible || (dxEnd * dxEnd + dzEnd * dzEnd) <= 85f * 85f)
+ {
+ filtered.Add(shot);
+ }
+ break;
+ case HitImpactEvent hit:
+ if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId >= 0 && hit.TargetId < peer.ContenderTrackers.Length)
+ {
+ if (hit.TargetId == obsId || _session.IsEntityInPeerPvs(obsId, true, hit.TargetId))
+ {
+ peer.ContenderTrackers[hit.TargetId].AckedDamageVersion = _session.State.Contenders[hit.TargetId].DamageVersion;
+ filtered.Add(hit);
+ }
+ }
+ else if (hit.TargetKind == (byte)HitTargetKind.Spectator)
+ {
+ int specIdx = hit.TargetId >= 1000 ? hit.TargetId - 1000 : hit.TargetId;
+ if (specIdx >= 0 && specIdx < peer.SpectatorTrackers.Length &&
+ _session.IsEntityInPeerPvs(obsId, false, specIdx))
+ {
+ peer.SpectatorTrackers[specIdx].AckedDamageVersion = _session.State.Spectators.Spectators[specIdx].Grid.HitSequence;
+ filtered.Add(hit);
+ }
+ }
+ else
+ {
+ filtered.Add(hit);
+ }
+ break;
+ default:
+ filtered.Add(ev);
+ break;
+ }
+ }
+
+ if (filtered.Count > 0)
+ {
+ SendSchemaToPeer(peer, new SimEventBatchMsg
+ {
+ BatchSeq = _eventBatchSeq++,
+ SimTick = _simTick,
+ SimTime = _session.State.Time,
+ MatchGeneration = _matchGeneration,
+ Events = filtered
+ });
+ }
+ }
+ }
+
+ private void BroadcastSnapshots()
+ {
+ if (_peersByEndpoint.Count == 0) return;
+
+ bool sendCore = (_simTick % 2) == 0; // 30 Hz
+ bool sendRadar = (_simTick % 6) == 0; // 10 Hz
+ if (!sendCore && !sendRadar) return;
+
+ if (sendCore) _snapshotSeq++;
+
+ foreach (var peer in _peersByEndpoint.Values)
+ {
+ if (!peer.Active) continue;
+ int obsId = peer.AssignedContenderId;
+ var local = _session.State.Contenders[obsId];
+
+ if (sendCore)
+ {
+ SendCoreAndOrbit(peer, local);
+ }
+
+ if (sendRadar)
+ {
+ SendRadar(peer, obsId);
+ }
+ }
+ }
+
+ private void SendCoreAndOrbit(ConnectedPeer peer, ContenderState local)
+ {
+ int obsId = local.Id;
+ ushort pvsMask = 0;
+ var pvsContenders = new List(MatchState.ContenderCount);
+ var walkerCandidates = new List<(float DistSq, NetWalkerEntry Entry)>(12);
+ var combatSpecs = new List(12);
+ var neutralSpecsHalf = new List(28);
+
+ for (int i = 0; i < _session.State.Contenders.Count; i++)
+ {
+ var c = _session.State.Contenders[i];
+ if (c.Id == obsId)
+ {
+ pvsMask |= (ushort)(1 << c.Id);
+ if (c.Grid.Spec.IsWalker && _session.TrySampleInterpolatedWalkerPose(true, c.Id, 1f, out var lw))
+ {
+ walkerCandidates.Add((0f, new NetWalkerEntry { IsContender = true, EntityId = (byte)c.Id, Snapshot = lw }));
+ }
+ continue;
+ }
+
+ if (!_session.IsEntityInPeerPvs(obsId, true, c.Id))
+ {
+ continue;
+ }
+
+ pvsMask |= (ushort)(1 << c.Id);
+ bool snap = peer.ContenderTrackers[c.Id].SnapNext;
+ peer.ContenderTrackers[c.Id].SnapNext = false;
+
+ float pitchDeg = MatchRules.ComputeLocalPitchDeg(
+ new Vector3(c.AimX - c.X, (float.IsNaN(c.AimY) ? c.Y : c.AimY) - c.Y, c.AimZ - c.Z),
+ new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW));
+
+ pvsContenders.Add(new NetContenderState
+ {
+ SlotId = (byte)c.Id,
+ Alive = c.Alive,
+ IsHuman = c.IsHuman,
+ Fire = c.FireCmd,
+ Brake = c.BrakeCmd,
+ Snap = snap,
+ Pos = new Vector3(c.X, c.Y, c.Z),
+ Rot = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW),
+ Vel = new Vector3(c.VelX, c.VelY, c.VelZ),
+ AimYaw = MathF.Atan2(c.AimX - c.X, c.AimZ - c.Z),
+ AimPitchDeg = pitchDeg,
+ Throttle = c.ThrottleCmd,
+ Steer = c.SteerCmd,
+ CoreHpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 0f,
+ MaxThermalRatio = c.MaxThermalRatio
+ });
+
+ float d2 = (c.X - local.X) * (c.X - local.X) + (c.Z - local.Z) * (c.Z - local.Z);
+ if (c.Alive && c.Grid.Spec.IsWalker && d2 <= 220f * 220f &&
+ _session.TrySampleInterpolatedWalkerPose(true, c.Id, 1f, out var ws))
+ {
+ walkerCandidates.Add((d2, new NetWalkerEntry { IsContender = true, EntityId = (byte)c.Id, Snapshot = ws }));
+ }
+ }
+
+ byte halfIndex = (byte)(_snapshotSeq & 1);
+ var specs = _session.State.Spectators.Spectators;
+ for (int i = 0; i < specs.Count; i++)
+ {
+ var s = specs[i];
+ if (!_session.IsEntityInPeerPvs(obsId, false, i))
+ {
+ continue;
+ }
+
+ bool snap = peer.SpectatorTrackers[i].SnapNext;
+ peer.SpectatorTrackers[i].SnapNext = false;
+
+ var ns = new NetSpectatorState
+ {
+ Id = (byte)i,
+ Alive = s.Alive,
+ Stance = s.Stance,
+ Snap = snap,
+ TargetContenderId = (sbyte)(s.TargetContenderId ?? -1),
+ Pos = new Vector3(s.X, s.Y, s.Z),
+ Rot = new Quaternion(s.CurrRotX, s.CurrRotY, s.CurrRotZ, s.CurrRotW),
+ Vel = new Vector3(s.VelX, s.VelY, s.VelZ)
+ };
+
+ if (s.Stance != SpectatorStance.Neutral)
+ {
+ combatSpecs.Add(ns);
+ float d2 = (s.X - local.X) * (s.X - local.X) + (s.Z - local.Z) * (s.Z - local.Z);
+ if (s.Alive && s.Grid.Spec.IsWalker && d2 <= 220f * 220f &&
+ _session.TrySampleInterpolatedWalkerPose(false, s.Id, 1f, out var sws))
+ {
+ walkerCandidates.Add((d2, new NetWalkerEntry { IsContender = false, EntityId = (byte)i, Snapshot = sws }));
+ }
+ }
+ else if ((i & 1) == halfIndex)
+ {
+ neutralSpecsHalf.Add(ns);
+ }
+ }
+
+ walkerCandidates.Sort((a, b) => a.DistSq.CompareTo(b.DistSq));
+ var walkers = new List(walkerCandidates.Count);
+ for (int i = 0; i < walkerCandidates.Count; i++)
+ {
+ walkers.Add(walkerCandidates[i].Entry);
+ }
+
+ Vector3 localAngVel = Vector3.Zero;
+ var body = _session.GetContenderBody(local.Id);
+ if (body is { } bHandle)
+ {
+ var v = _session.World.View;
+ localAngVel = new Vector3(v.AngularVelocityX[bHandle.Lane], v.AngularVelocityY[bHandle.Lane], v.AngularVelocityZ[bHandle.Lane]);
+ }
+
+ byte detectedBy = _session.State.ObserverStates.TryGetValue(obsId, out var obsState)
+ ? (byte)Math.Clamp(obsState.DetectedByCount, 0, 255)
+ : (byte)0;
+
+ byte[] corePayload = SnapshotCodec.EncodeCorePvs(
+ _matchGeneration,
+ _snapshotSeq,
+ _simTick,
+ _session.State.Time,
+ peer.LastAcceptedInputSeq,
+ peer.LastEchoSendMs,
+ _session.State.Spectators.SafeRadius,
+ _session.State.Phase,
+ _session.State.WinnerContenderId,
+ detectedBy,
+ pvsMask,
+ local,
+ localAngVel,
+ pvsContenders,
+ walkers,
+ combatSpecs);
+
+ SendLatestToPeer(peer, corePayload);
+
+ if (neutralSpecsHalf.Count > 0)
+ {
+ byte[] orbitPayload = SnapshotCodec.EncodeSpectatorOrbitHalf(
+ _matchGeneration,
+ _snapshotSeq,
+ halfIndex,
+ neutralSpecsHalf);
+ SendLatestToPeer(peer, orbitPayload);
+ }
+ }
+
+ private void SendRadar(ConnectedPeer peer, int obsId)
+ {
+ if (!_session.State.ObserverStates.TryGetValue(obsId, out var obsState))
+ {
+ return;
+ }
+
+ var cList = new List(12);
+ foreach (var kv in obsState.ContenderContacts)
+ {
+ if (!MatchState.IsContactOnRadar(kv.Value)) continue;
+ cList.Add(new NetRadarContact
+ {
+ EntityId = (byte)kv.Key,
+ Visible = kv.Value.VisibleToPlayer,
+ FaintHorizon = kv.Value.FaintHorizonPing,
+ HasEverBeenSeen = kv.Value.HasEverBeenSeen,
+ LastSeenAge = kv.Value.LastSeenAge,
+ LastSeenX = kv.Value.LastSeenX,
+ LastSeenZ = kv.Value.LastSeenZ
+ });
+ }
+
+ var sList = new List(32);
+ foreach (var kv in obsState.SpectatorContacts)
+ {
+ if (!MatchState.IsContactOnRadar(kv.Value)) continue;
+ int specIdx = kv.Key >= 1000 ? kv.Key - 1000 : kv.Key;
+ if (specIdx < 0 || specIdx >= _session.State.Spectators.Spectators.Count) continue;
+ sList.Add(new NetRadarContact
+ {
+ EntityId = (byte)specIdx,
+ Visible = kv.Value.VisibleToPlayer,
+ FaintHorizon = kv.Value.FaintHorizonPing,
+ HasEverBeenSeen = kv.Value.HasEverBeenSeen,
+ LastSeenAge = kv.Value.LastSeenAge,
+ LastSeenX = kv.Value.LastSeenX,
+ LastSeenZ = kv.Value.LastSeenZ
+ });
+ }
+
+ byte[] payload = SnapshotCodec.EncodeRadarContacts(_matchGeneration, _snapshotSeq, cList, sList);
+ SendLatestToPeer(peer, payload);
+ }
+
+ private void SendJoinAccepted(ConnectedPeer peer)
+ {
+ var msg = new JoinAcceptedMsg
+ {
+ PeerId = peer.PeerId,
+ ReconnectToken = peer.ReconnectToken,
+ AssignedContenderId = peer.AssignedContenderId,
+ MatchGeneration = _matchGeneration,
+ InitialState = BuildInitialMatchStateDto(peer.AssignedContenderId)
+ };
+ SendSchemaToPeer(peer, msg);
+ }
+
+ private InitialMatchStateDto BuildInitialMatchStateDto(int forContenderId)
+ {
+ var dto = new InitialMatchStateDto
+ {
+ MatchGeneration = _matchGeneration,
+ Seed = _session.State.Seed,
+ MapKind = (byte)_session.State.MapKind,
+ SimTime = _session.State.Time,
+ SafeRadius = _session.State.Spectators.SafeRadius,
+ Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : 0),
+ WinnerContenderId = _session.State.WinnerContenderId,
+ TerrainStamps = new List(_terrainStampHistory)
+ };
+
+ for (int i = 0; i < _session.State.Contenders.Count; i++)
+ {
+ var c = _session.State.Contenders[i];
+ dto.Contenders.Add(new ContenderInitialDto
+ {
+ Id = c.Id,
+ Name = c.Name,
+ IsHuman = c.IsHuman,
+ X = c.X, Y = c.Y, Z = c.Z, Yaw = c.Yaw,
+ Kills = c.Kills,
+ Loadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == forContenderId)
+ });
+ }
+
+ for (int i = 0; i < _session.State.Spectators.Spectators.Count; i++)
+ {
+ var s = _session.State.Spectators.Spectators[i];
+ var mounted = new List(s.Grid.Mounted.Count);
+ for (int m = 0; m < s.Grid.Mounted.Count; m++)
+ {
+ mounted.Add(new MountedSlotDto { ModuleId = s.Grid.Mounted[m].Spec.Id, HardpointId = s.Grid.Mounted[m].HardpointId });
+ }
+ dto.Spectators.Add(new SpectatorInitialDto
+ {
+ Id = s.Id,
+ Tier = (byte)s.Tier,
+ Stance = (byte)s.Stance,
+ X = s.X, Y = s.Y, Z = s.Z, Yaw = s.Yaw,
+ ChassisId = s.Grid.Spec.Id,
+ CoreHp = s.Grid.CoreHp,
+ MaxCoreHp = s.Grid.MaxCoreHp,
+ ArmorBytes = s.Grid.QuantizeArmorBytes(),
+ Mounted = mounted
+ });
+ }
+
+ for (int i = 0; i < _session.State.GroundDrops.Count; i++)
+ {
+ var d = _session.State.GroundDrops[i];
+ dto.GroundDrops.Add(new GroundDropDto
+ {
+ Id = d.Id,
+ X = d.X,
+ Z = d.Z,
+ ChassisId = d.Chassis?.Id,
+ ModuleId = d.Module?.Id,
+ PickedUp = d.PickedUp
+ });
+ }
+
+ return dto;
+ }
+
+ private void SendSchemaToPeer(ConnectedPeer peer, ISchemaWireMessage msg)
+ {
+ if (!peer.Active || _retiredTransportPeers.Contains(peer.TransportPeer)) return;
+ SendSchemaRaw(peer.TransportPeer, msg);
+ }
+
+ private void SendSchemaRaw(CultNetRudpSocketServerPeer transportPeer, ISchemaWireMessage msg)
+ {
+ byte[] payload = SnapshotCodec.SerializeSchemaMessage(msg);
+ byte[] wire = SnapshotCodec.WrapSchema(payload, _matchGeneration, _schemaOutSeq++);
+ try
+ {
+ _server.SendSchema(transportPeer, wire);
+ }
+ catch
+ {
+ // Transport peer will be swept by timeout/disconnect
+ }
+ }
+
+ private void SendLatestToPeer(ConnectedPeer peer, byte[] payload)
+ {
+ if (!peer.Active || _retiredTransportPeers.Contains(peer.TransportPeer)) return;
+ byte[] wire = SnapshotCodec.WrapLatest(payload, _matchGeneration, _latestOutSeq++);
+ try
+ {
+ _server.Send(peer.TransportPeer, SnapshotCodec.ChannelLatest, wire);
+ }
+ catch
+ {
+ }
+ }
+
+ public void Dispose()
+ {
+ if (_disposed) return;
+ _disposed = true;
+ _server.PeerDisconnected -= OnTransportPeerDisconnected;
+ _server.Dispose();
+ _socket.Dispose();
+ _session.Dispose();
+ }
+ }
+}
diff --git a/src/RustToDust.Net/SnapshotCodec.cs b/src/RustToDust.Net/SnapshotCodec.cs
new file mode 100644
index 0000000..2fd6dd3
--- /dev/null
+++ b/src/RustToDust.Net/SnapshotCodec.cs
@@ -0,0 +1,833 @@
+using System;
+using System.Buffers.Binary;
+using System.Collections.Generic;
+using System.Numerics;
+using GameCult.Mesh;
+using MessagePack;
+using RustToDust.Core;
+
+namespace RustToDust.Net
+{
+ public enum LatestPacketKind : byte
+ {
+ CorePvs = 1,
+ SpectatorOrbitHalf = 2,
+ RadarContacts = 3,
+ ClientInput = 16
+ }
+
+ public readonly record struct ClientInputPacket(
+ uint MatchGeneration,
+ uint InputSeq,
+ uint ClientSendMs,
+ PlayerInput Input);
+
+ public struct NetContenderState
+ {
+ public byte SlotId;
+ public bool Alive;
+ public bool IsHuman;
+ public bool Fire;
+ public bool Brake;
+ public bool Snap;
+ public Vector3 Pos;
+ public Quaternion Rot;
+ public Vector3 Vel;
+ public float AimYaw;
+ public float AimPitchDeg;
+ public float Throttle;
+ public float Steer;
+ public float CoreHpRatio;
+ public float MaxThermalRatio;
+ }
+
+ public struct NetSpectatorState
+ {
+ public byte Id;
+ public bool Alive;
+ public SpectatorStance Stance;
+ public bool Snap;
+ public sbyte TargetContenderId;
+ public Vector3 Pos;
+ public Quaternion Rot;
+ public Vector3 Vel;
+ }
+
+ public struct NetWalkerEntry
+ {
+ public bool IsContender;
+ public byte EntityId;
+ public WalkerVisualSnapshot Snapshot;
+ }
+
+ public struct NetRadarContact
+ {
+ public byte EntityId;
+ public bool Visible;
+ public bool FaintHorizon;
+ public bool HasEverBeenSeen;
+ public float LastSeenAge;
+ public float LastSeenX;
+ public float LastSeenZ;
+ }
+
+ public sealed class DecodedCorePvsSnapshot
+ {
+ public uint MatchGeneration;
+ public uint SnapshotSeq;
+ public uint SimTick;
+ public float SimTime;
+ public uint AckedInputSeq;
+ public uint EchoSendMs;
+ public float SafeRadius;
+ public MatchPhase Phase;
+ public int? WinnerContenderId;
+ public byte DetectedByCount;
+ public int InArcWeapons;
+ public int OutOfArcWeapons;
+ public int DisabledWeapons;
+ public bool AllWeaponsOutOfArc;
+ public ushort ContenderPvsMask;
+
+ public bool LocalAlive;
+ public Vector3 LocalPos;
+ public Quaternion LocalRot;
+ public Vector3 LocalVel;
+ public Vector3 LocalAngVel;
+ public float LocalCoreHp;
+ public float LocalMaxThermalRatio;
+ public byte[] LocalCellTempsQuantized = Array.Empty();
+ public float[] LocalMountedTemps = Array.Empty();
+ public float[] LocalMountedCooldowns = Array.Empty();
+
+ public List Contenders = new();
+ public List Walkers = new();
+ public List CombatSpectators = new();
+ }
+
+ public sealed class DecodedSpectatorOrbitSnapshot
+ {
+ public uint MatchGeneration;
+ public uint SnapshotSeq;
+ public byte HalfIndex;
+ public List Spectators = new();
+ }
+
+ public sealed class DecodedRadarContactsSnapshot
+ {
+ public uint MatchGeneration;
+ public uint SnapshotSeq;
+ public List Contenders = new();
+ public List Spectators = new();
+ }
+
+ public static class SnapshotCodec
+ {
+ public const int MaxLatestDatagramBytes = 1152;
+ public const string ChannelLatest = "latest";
+ public const string ChannelSchema = "schema";
+ public const string SchemaLatestId = "rtd.snap";
+ public const string SchemaInputId = "rtd.in";
+ public const string SchemaEventsId = "rtd.evt";
+ public const string BodyMatchId = "m";
+
+ // CultMeshRealtimeWireProtocol fixed header (37) + "latest" (6) + "rtd.snap" (8) + "m" (1) = 52 bytes
+ public const int CultMeshLatestOverheadBytes = 52;
+ public const int MaxLatestPayloadBytes = MaxLatestDatagramBytes - CultMeshLatestOverheadBytes; // 1100 bytes
+
+ public static byte[] WrapLatest(ReadOnlySpan payload, long producerEpoch, long sequence, string schemaId = SchemaLatestId)
+ {
+ var frame = new CultMeshRealtimeFrame
+ {
+ ChannelId = ChannelLatest,
+ SchemaId = schemaId,
+ BodyId = BodyMatchId,
+ ProducerEpoch = producerEpoch,
+ Sequence = sequence,
+ Delivery = CultMeshRealtimeDelivery.LatestOnly,
+ Payload = payload.ToArray()
+ };
+ byte[] encoded = CultMeshRealtimeWireProtocol.EncodeFrame(frame);
+ if (encoded.Length > MaxLatestDatagramBytes)
+ {
+ throw new InvalidOperationException(
+ $"Latest packet exceeded {MaxLatestDatagramBytes}B MTU cap ({encoded.Length}B).");
+ }
+ return encoded;
+ }
+
+ public static byte[] WrapSchema(ReadOnlySpan payload, long producerEpoch, long sequence, string schemaId = SchemaEventsId)
+ {
+ var frame = new CultMeshRealtimeFrame
+ {
+ ChannelId = ChannelSchema,
+ SchemaId = schemaId,
+ BodyId = BodyMatchId,
+ ProducerEpoch = producerEpoch,
+ Sequence = sequence,
+ Delivery = CultMeshRealtimeDelivery.ReliableOrdered,
+ Payload = payload.ToArray()
+ };
+ return CultMeshRealtimeWireProtocol.EncodeFrame(frame);
+ }
+
+ public static CultMeshRealtimeFrame Unwrap(byte[] wireBytes) =>
+ CultMeshRealtimeWireProtocol.DecodeFrame(wireBytes);
+
+ public static byte[] SerializeSchemaMessage(ISchemaWireMessage msg) =>
+ MessagePackSerializer.Serialize(msg);
+
+ public static ISchemaWireMessage DeserializeSchemaMessage(ReadOnlyMemory payload) =>
+ MessagePackSerializer.Deserialize(payload);
+
+ public static byte[] EncodeClientInput(in ClientInputPacket pkt)
+ {
+ byte[] buf = new byte[36];
+ var span = buf.AsSpan();
+ span[0] = (byte)LatestPacketKind.ClientInput;
+ BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(1), pkt.MatchGeneration);
+ BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(5), pkt.InputSeq);
+ BinaryPrimitives.WriteUInt32LittleEndian(span.Slice(9), pkt.ClientSendMs);
+ BinaryPrimitives.WriteSingleLittleEndian(span.Slice(13), pkt.Input.AimWorldX);
+ BinaryPrimitives.WriteSingleLittleEndian(span.Slice(17), pkt.Input.AimWorldY);
+ BinaryPrimitives.WriteSingleLittleEndian(span.Slice(21), pkt.Input.AimWorldZ);
+ BinaryPrimitives.WriteInt16LittleEndian(span.Slice(25), EncodeSnorm16(pkt.Input.Throttle));
+ BinaryPrimitives.WriteInt16LittleEndian(span.Slice(27), EncodeSnorm16(pkt.Input.Steer));
+ BinaryPrimitives.WriteInt16LittleEndian(span.Slice(29), EncodeSnorm16(pkt.Input.VerticalThrottle));
+ byte flags = 0;
+ if (pkt.Input.Fire) flags |= 1;
+ if (pkt.Input.Brake) flags |= 2;
+ if (pkt.Input.InteractPickup) flags |= 4;
+ span[31] = flags;
+ return buf; // 32-36 B
+ }
+
+ public static ClientInputPacket DecodeClientInput(ReadOnlySpan span)
+ {
+ if (span.Length < 32 || span[0] != (byte)LatestPacketKind.ClientInput)
+ {
+ throw new InvalidOperationException("Invalid ClientInput packet.");
+ }
+ uint gen = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(1));
+ uint seq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(5));
+ uint sendMs = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(9));
+ float ax = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(13));
+ float ay = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(17));
+ float az = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(21));
+ float throttle = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(25)));
+ float steer = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(27)));
+ float vert = DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(29)));
+ byte flags = span[31];
+ return new ClientInputPacket(
+ gen,
+ seq,
+ sendMs,
+ new PlayerInput(
+ throttle,
+ steer,
+ ax,
+ az,
+ (flags & 1) != 0,
+ (flags & 4) != 0,
+ (flags & 2) != 0,
+ ay,
+ vert));
+ }
+
+ public static byte[] EncodeCorePvs(
+ uint matchGeneration,
+ uint snapshotSeq,
+ uint simTick,
+ float simTime,
+ uint ackedInputSeq,
+ uint echoSendMs,
+ float safeRadius,
+ MatchPhase phase,
+ int? winnerContenderId,
+ byte detectedByCount,
+ ushort contenderPvsMask,
+ ContenderState localContender,
+ Vector3 localAngVel,
+ IReadOnlyList pvsContenders,
+ IReadOnlyList pvsWalkers,
+ IReadOnlyList combatSpectators)
+ {
+ Span buf = stackalloc byte[MaxLatestPayloadBytes];
+ int offset = 0;
+
+ buf[offset++] = (byte)LatestPacketKind.CorePvs;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), simTick); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), simTime); offset += 4;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), ackedInputSeq); offset += 4;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), echoSendMs); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), safeRadius); offset += 4;
+
+ byte phaseByte = (byte)(phase == MatchPhase.Completed ? 1 : 0);
+ if (winnerContenderId.HasValue) phaseByte |= 2;
+ buf[offset++] = phaseByte;
+ buf[offset++] = (byte)(sbyte)(winnerContenderId ?? -1);
+ buf[offset++] = detectedByCount;
+
+ ushort arc = (ushort)(
+ (Math.Clamp(localContender.InArcWeaponCount, 0, 15)) |
+ (Math.Clamp(localContender.OutOfArcWeaponCount, 0, 15) << 4) |
+ (Math.Clamp(localContender.DisabledWeaponCount, 0, 15) << 8) |
+ (localContender.AllWeaponsOutOfArc ? (1 << 12) : 0));
+ BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), arc); offset += 2;
+ BinaryPrimitives.WriteUInt16LittleEndian(buf.Slice(offset), contenderPvsMask); offset += 2;
+
+ // Local prediction + telemetry block
+ buf[offset++] = (byte)(localContender.Alive ? 1 : 0);
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.X); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Y); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Z); offset += 4;
+ WriteQuatSnorm16(buf.Slice(offset), new Quaternion(localContender.CurrRotX, localContender.CurrRotY, localContender.CurrRotZ, localContender.CurrRotW));
+ offset += 8;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelX); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelY); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.VelZ); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.X); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.Y); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localAngVel.Z); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), localContender.Grid.CoreHp); offset += 4;
+ buf[offset++] = EncodeRatioByte(localContender.MaxThermalRatio, maxVal: 1.5f);
+
+ int cellCountPos = offset++;
+ int cellCount = 0;
+ var grid = localContender.Grid;
+ for (int y = 0; y < grid.Spec.Height && cellCount < 64; y++)
+ {
+ for (int x = 0; x < grid.Spec.Width && cellCount < 64; x++)
+ {
+ if (!grid.Spec.IsActive(x, y)) continue;
+ int qTemp = (int)MathF.Round((grid.Temperature[x, y] - ChassisGrid.AmbientTemp) * 0.5f);
+ buf[offset++] = (byte)Math.Clamp(qTemp, 0, 255);
+ cellCount++;
+ }
+ }
+ buf[cellCountPos] = (byte)cellCount;
+
+ int mountedCount = Math.Min(8, grid.Mounted.Count);
+ buf[offset++] = (byte)mountedCount;
+ for (int i = 0; i < mountedCount; i++)
+ {
+ var m = grid.Mounted[i];
+ int qTemp = (int)MathF.Round((m.CurrentTemp - ChassisGrid.AmbientTemp) * 0.5f);
+ buf[offset++] = (byte)Math.Clamp(qTemp, 0, 255);
+ int qCd = (int)MathF.Round(m.Cooldown * 25f);
+ buf[offset++] = (byte)Math.Clamp(qCd, 0, 255);
+ }
+
+ // PVS Contenders (each 35 B)
+ int contenderCountPos = offset++;
+ int contendersWritten = 0;
+ for (int i = 0; i < pvsContenders.Count; i++)
+ {
+ if (offset + 35 > MaxLatestPayloadBytes - 2)
+ {
+ break;
+ }
+ var c = pvsContenders[i];
+ buf[offset++] = c.SlotId;
+ byte flags = 0;
+ if (c.Alive) flags |= 1;
+ if (c.IsHuman) flags |= 2;
+ if (c.Fire) flags |= 4;
+ if (c.Brake) flags |= 8;
+ if (c.Snap) flags |= 16;
+ buf[offset++] = flags;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.X); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.Y); offset += 4;
+ BinaryPrimitives.WriteSingleLittleEndian(buf.Slice(offset), c.Pos.Z); offset += 4;
+ WriteQuatSnorm16(buf.Slice(offset), c.Rot); offset += 8;
+ WriteVelShort(buf.Slice(offset), c.Vel); offset += 6;
+ BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeAngleShort(c.AimYaw)); offset += 2;
+ buf[offset++] = (byte)(sbyte)Math.Clamp(MathF.Round(c.AimPitchDeg), -90, 90);
+ buf[offset++] = EncodeSnorm8(c.Throttle);
+ buf[offset++] = EncodeSnorm8(c.Steer);
+ buf[offset++] = EncodeRatioByte(c.CoreHpRatio, 1.0f);
+ buf[offset++] = EncodeRatioByte(c.MaxThermalRatio, 1.5f);
+ contendersWritten++;
+ }
+ buf[contenderCountPos] = (byte)contendersWritten;
+
+ // Walkers (capped strictly by remaining MTU budget!)
+ int walkerCountPos = offset++;
+ int walkersWritten = 0;
+ for (int i = 0; i < pvsWalkers.Count; i++)
+ {
+ var w = pvsWalkers[i];
+ int legCount = Math.Clamp(w.Snapshot.LegCount, 0, 4);
+ int bytesNeeded = 2 + legCount * 13;
+ if (offset + bytesNeeded > MaxLatestPayloadBytes - 1)
+ {
+ break;
+ }
+ buf[offset++] = (byte)((w.IsContender ? 0x80 : 0x00) | (w.EntityId & 0x7F));
+ buf[offset++] = (byte)legCount;
+ for (int l = 0; l < legCount; l++)
+ {
+ var ang = w.Snapshot.LegAngles[l];
+ BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HipPitch)); offset += 2;
+ BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HipRoll)); offset += 2;
+ BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.KneeFlex)); offset += 2;
+ BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.HockFlex)); offset += 2;
+ BinaryPrimitives.WriteInt16LittleEndian(buf.Slice(offset), EncodeWalkerAngle(ang.AnklePitch)); offset += 2;
+ WriteOctNormal(buf.Slice(offset), w.Snapshot.FootNormal[l]); offset += 2;
+ buf[offset++] = (byte)Math.Clamp((int)MathF.Round(w.Snapshot.LoadG[l] * 50f), 0, 255);
+ }
+ walkersWritten++;
+ }
+ buf[walkerCountPos] = (byte)walkersWritten;
+
+ // Active Combat Spectators (26 B each, capped strictly by remaining MTU budget!)
+ int combatSpecCountPos = offset++;
+ int specsWritten = 0;
+ for (int i = 0; i < combatSpectators.Count; i++)
+ {
+ if (offset + 26 > MaxLatestPayloadBytes)
+ {
+ break;
+ }
+ WriteCompactSpectator(buf.Slice(offset), combatSpectators[i]);
+ offset += 26;
+ specsWritten++;
+ }
+ buf[combatSpecCountPos] = (byte)specsWritten;
+
+ return buf.Slice(0, offset).ToArray();
+ }
+
+ public static DecodedCorePvsSnapshot DecodeCorePvs(ReadOnlySpan span)
+ {
+ if (span.Length < 40 || span[0] != (byte)LatestPacketKind.CorePvs)
+ {
+ throw new InvalidOperationException("Invalid CorePvs snapshot packet.");
+ }
+ int offset = 1;
+ var res = new DecodedCorePvsSnapshot
+ {
+ MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)),
+ };
+ offset += 4;
+ res.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
+ res.SimTick = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
+ res.SimTime = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4;
+ res.AckedInputSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
+ res.EchoSendMs = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
+ res.SafeRadius = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4;
+
+ byte phaseByte = span[offset++];
+ res.Phase = (phaseByte & 1) != 0 ? MatchPhase.Completed : MatchPhase.Active;
+ sbyte winnerRaw = (sbyte)span[offset++];
+ res.WinnerContenderId = (phaseByte & 2) != 0 ? winnerRaw : null;
+ res.DetectedByCount = span[offset++];
+
+ ushort arc = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2;
+ res.InArcWeapons = arc & 0xF;
+ res.OutOfArcWeapons = (arc >> 4) & 0xF;
+ res.DisabledWeapons = (arc >> 8) & 0xF;
+ res.AllWeaponsOutOfArc = (arc & (1 << 12)) != 0;
+ res.ContenderPvsMask = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(offset)); offset += 2;
+
+ res.LocalAlive = (span[offset++] & 1) != 0;
+ res.LocalPos = new Vector3(
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)),
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)),
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8)));
+ offset += 12;
+ res.LocalRot = ReadQuatSnorm16(span.Slice(offset)); offset += 8;
+ res.LocalVel = new Vector3(
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)),
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)),
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8)));
+ offset += 12;
+ res.LocalAngVel = new Vector3(
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)),
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)),
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8)));
+ offset += 12;
+ res.LocalCoreHp = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)); offset += 4;
+ res.LocalMaxThermalRatio = span[offset++] / 255f * 1.5f;
+
+ int cellCount = span[offset++];
+ res.LocalCellTempsQuantized = span.Slice(offset, cellCount).ToArray();
+ offset += cellCount;
+
+ int mountedCount = span[offset++];
+ res.LocalMountedTemps = new float[mountedCount];
+ res.LocalMountedCooldowns = new float[mountedCount];
+ for (int i = 0; i < mountedCount; i++)
+ {
+ res.LocalMountedTemps[i] = ChassisGrid.AmbientTemp + span[offset++] * 2.0f;
+ res.LocalMountedCooldowns[i] = span[offset++] / 25f;
+ }
+
+ int contenderCount = span[offset++];
+ for (int i = 0; i < contenderCount; i++)
+ {
+ byte slotId = span[offset++];
+ byte flags = span[offset++];
+ Vector3 pos = new(
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset)),
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 4)),
+ BinaryPrimitives.ReadSingleLittleEndian(span.Slice(offset + 8)));
+ offset += 12;
+ Quaternion rot = ReadQuatSnorm16(span.Slice(offset)); offset += 8;
+ Vector3 vel = ReadVelShort(span.Slice(offset)); offset += 6;
+ float aimYaw = DecodeAngleShort(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset))); offset += 2;
+ float aimPitch = (sbyte)span[offset++];
+ float throttle = DecodeSnorm8(span[offset++]);
+ float steer = DecodeSnorm8(span[offset++]);
+ float coreRatio = span[offset++] / 255f;
+ float thermalRatio = span[offset++] / 255f * 1.5f;
+
+ res.Contenders.Add(new NetContenderState
+ {
+ SlotId = slotId,
+ Alive = (flags & 1) != 0,
+ IsHuman = (flags & 2) != 0,
+ Fire = (flags & 4) != 0,
+ Brake = (flags & 8) != 0,
+ Snap = (flags & 16) != 0,
+ Pos = pos,
+ Rot = rot,
+ Vel = vel,
+ AimYaw = aimYaw,
+ AimPitchDeg = aimPitch,
+ Throttle = throttle,
+ Steer = steer,
+ CoreHpRatio = coreRatio,
+ MaxThermalRatio = thermalRatio
+ });
+ }
+
+ int walkerCount = span[offset++];
+ for (int i = 0; i < walkerCount; i++)
+ {
+ byte tag = span[offset++];
+ bool isContender = (tag & 0x80) != 0;
+ byte entityId = (byte)(tag & 0x7F);
+ int legCount = span[offset++];
+ var snap = new WalkerVisualSnapshot { LegCount = legCount };
+ for (int l = 0; l < legCount; l++)
+ {
+ snap.LegAngles[l] = new WalkerLegAngles
+ {
+ HipPitch = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset))),
+ HipRoll = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 2))),
+ KneeFlex = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 4))),
+ HockFlex = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 6))),
+ AnklePitch = DecodeWalkerAngle(BinaryPrimitives.ReadInt16LittleEndian(span.Slice(offset + 8)))
+ };
+ offset += 10;
+ snap.FootNormal[l] = ReadOctNormal(span.Slice(offset)); offset += 2;
+ snap.LoadG[l] = span[offset++] / 50f;
+ }
+ res.Walkers.Add(new NetWalkerEntry
+ {
+ IsContender = isContender,
+ EntityId = entityId,
+ Snapshot = snap
+ });
+ }
+
+ int specCount = span[offset++];
+ for (int i = 0; i < specCount; i++)
+ {
+ res.CombatSpectators.Add(ReadCompactSpectator(span.Slice(offset)));
+ offset += 26;
+ }
+
+ return res;
+ }
+
+ public static byte[] EncodeSpectatorOrbitHalf(
+ uint matchGeneration,
+ uint snapshotSeq,
+ byte halfIndex,
+ IReadOnlyList spectators)
+ {
+ Span buf = stackalloc byte[MaxLatestPayloadBytes];
+ int offset = 0;
+ buf[offset++] = (byte)LatestPacketKind.SpectatorOrbitHalf;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4;
+ buf[offset++] = halfIndex;
+ int countPos = offset++;
+ int count = 0;
+ for (int i = 0; i < spectators.Count; i++)
+ {
+ if (offset + 26 > MaxLatestPayloadBytes)
+ {
+ break;
+ }
+ WriteCompactSpectator(buf.Slice(offset), spectators[i]);
+ offset += 26;
+ count++;
+ }
+ buf[countPos] = (byte)count;
+ return buf.Slice(0, offset).ToArray();
+ }
+
+ public static DecodedSpectatorOrbitSnapshot DecodeSpectatorOrbitHalf(ReadOnlySpan span)
+ {
+ if (span.Length < 11 || span[0] != (byte)LatestPacketKind.SpectatorOrbitHalf)
+ {
+ throw new InvalidOperationException("Invalid SpectatorOrbitHalf packet.");
+ }
+ int offset = 1;
+ var res = new DecodedSpectatorOrbitSnapshot
+ {
+ MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)),
+ };
+ offset += 4;
+ res.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
+ res.HalfIndex = span[offset++];
+ int count = span[offset++];
+ for (int i = 0; i < count; i++)
+ {
+ res.Spectators.Add(ReadCompactSpectator(span.Slice(offset)));
+ offset += 26;
+ }
+ return res;
+ }
+
+ public static byte[] EncodeRadarContacts(
+ uint matchGeneration,
+ uint snapshotSeq,
+ IReadOnlyList contenders,
+ IReadOnlyList spectators)
+ {
+ Span buf = stackalloc byte[MaxLatestPayloadBytes];
+ int offset = 0;
+ buf[offset++] = (byte)LatestPacketKind.RadarContacts;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), matchGeneration); offset += 4;
+ BinaryPrimitives.WriteUInt32LittleEndian(buf.Slice(offset), snapshotSeq); offset += 4;
+
+ int cPos = offset++;
+ int cWritten = 0;
+ for (int i = 0; i < contenders.Count; i++)
+ {
+ if (offset + 11 > MaxLatestPayloadBytes - 1) break;
+ WriteRadarContact(buf.Slice(offset), contenders[i]);
+ offset += 11;
+ cWritten++;
+ }
+ buf[cPos] = (byte)cWritten;
+
+ int sPos = offset++;
+ int sWritten = 0;
+ for (int i = 0; i < spectators.Count; i++)
+ {
+ if (offset + 11 > MaxLatestPayloadBytes) break;
+ WriteRadarContact(buf.Slice(offset), spectators[i]);
+ offset += 11;
+ sWritten++;
+ }
+ buf[sPos] = (byte)sWritten;
+ return buf.Slice(0, offset).ToArray();
+ }
+
+ public static DecodedRadarContactsSnapshot DecodeRadarContacts(ReadOnlySpan span)
+ {
+ if (span.Length < 11 || span[0] != (byte)LatestPacketKind.RadarContacts)
+ {
+ throw new InvalidOperationException("Invalid RadarContacts packet.");
+ }
+ int offset = 1;
+ var res = new DecodedRadarContactsSnapshot
+ {
+ MatchGeneration = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)),
+ };
+ offset += 4;
+ res.SnapshotSeq = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(offset)); offset += 4;
+ int cCount = span[offset++];
+ for (int i = 0; i < cCount; i++)
+ {
+ res.Contenders.Add(ReadRadarContact(span.Slice(offset)));
+ offset += 11;
+ }
+ int sCount = span[offset++];
+ for (int i = 0; i < sCount; i++)
+ {
+ res.Spectators.Add(ReadRadarContact(span.Slice(offset)));
+ offset += 11;
+ }
+ return res;
+ }
+
+ private static void WriteRadarContact(Span dst, in NetRadarContact c)
+ {
+ dst[0] = c.EntityId;
+ byte flags = 0;
+ if (c.Visible) flags |= 1;
+ if (c.FaintHorizon) flags |= 2;
+ if (c.HasEverBeenSeen) flags |= 4;
+ dst[1] = flags;
+ int ageSteps = float.IsFinite(c.LastSeenAge) ? (int)MathF.Round(c.LastSeenAge / 0.025f) : 255;
+ dst[2] = (byte)Math.Clamp(ageSteps, 0, 255);
+ BinaryPrimitives.WriteSingleLittleEndian(dst.Slice(3), c.LastSeenX);
+ BinaryPrimitives.WriteSingleLittleEndian(dst.Slice(7), c.LastSeenZ);
+ }
+
+ private static NetRadarContact ReadRadarContact(ReadOnlySpan src)
+ {
+ byte id = src[0];
+ byte flags = src[1];
+ byte ageSteps = src[2];
+ return new NetRadarContact
+ {
+ EntityId = id,
+ Visible = (flags & 1) != 0,
+ FaintHorizon = (flags & 2) != 0,
+ HasEverBeenSeen = (flags & 4) != 0,
+ LastSeenAge = ageSteps >= 255 ? float.PositiveInfinity : ageSteps * 0.025f,
+ LastSeenX = BinaryPrimitives.ReadSingleLittleEndian(src.Slice(3)),
+ LastSeenZ = BinaryPrimitives.ReadSingleLittleEndian(src.Slice(7))
+ };
+ }
+
+ private static void WriteCompactSpectator(Span dst, in NetSpectatorState s)
+ {
+ dst[0] = s.Id;
+ byte flags = (byte)((s.Alive ? 1 : 0) | (((byte)s.Stance & 3) << 1) | (s.Snap ? 8 : 0));
+ dst[1] = flags;
+ dst[2] = (byte)s.TargetContenderId;
+ WriteInt24(dst.Slice(3), s.Pos.X);
+ WriteInt24(dst.Slice(6), s.Pos.Y);
+ WriteInt24(dst.Slice(9), s.Pos.Z);
+ WriteQuatSnorm16(dst.Slice(12), s.Rot);
+ WriteVelShort(dst.Slice(20), s.Vel);
+ }
+
+ private static NetSpectatorState ReadCompactSpectator(ReadOnlySpan src)
+ {
+ byte id = src[0];
+ byte flags = src[1];
+ sbyte target = (sbyte)src[2];
+ Vector3 pos = new(ReadInt24(src.Slice(3)), ReadInt24(src.Slice(6)), ReadInt24(src.Slice(9)));
+ Quaternion rot = ReadQuatSnorm16(src.Slice(12));
+ Vector3 vel = ReadVelShort(src.Slice(20));
+ return new NetSpectatorState
+ {
+ Id = id,
+ Alive = (flags & 1) != 0,
+ Stance = (SpectatorStance)((flags >> 1) & 3),
+ Snap = (flags & 8) != 0,
+ TargetContenderId = target,
+ Pos = pos,
+ Rot = rot,
+ Vel = vel
+ };
+ }
+
+ private static short EncodeSnorm16(float v) =>
+ (short)Math.Clamp(MathF.Round(Math.Clamp(v, -1f, 1f) * 32767f), -32767, 32767);
+
+ private static float DecodeSnorm16(short v) => v / 32767f;
+
+ private static byte EncodeSnorm8(float v) =>
+ (byte)(sbyte)Math.Clamp(MathF.Round(Math.Clamp(v, -1f, 1f) * 127f), -127, 127);
+
+ private static float DecodeSnorm8(byte b) => (sbyte)b / 127f;
+
+ private static byte EncodeRatioByte(float v, float maxVal) =>
+ (byte)Math.Clamp((int)MathF.Round((Math.Clamp(v, 0f, maxVal) / maxVal) * 255f), 0, 255);
+
+ private static short EncodeAngleShort(float rad) =>
+ (short)Math.Clamp((int)MathF.Round(MatchRules.NormalizeAngle(rad) / MathF.PI * 32767f), -32767, 32767);
+
+ private static float DecodeAngleShort(short v) => (v / 32767f) * MathF.PI;
+
+ private static short EncodeWalkerAngle(float rad) =>
+ (short)Math.Clamp((int)MathF.Round(rad * 4096f), short.MinValue, short.MaxValue);
+
+ private static float DecodeWalkerAngle(short v) => v / 4096f;
+
+ private static void WriteQuatSnorm16(Span dst, Quaternion q)
+ {
+ if (q.LengthSquared() < 1e-6f) q = Quaternion.Identity;
+ else q = Quaternion.Normalize(q);
+ BinaryPrimitives.WriteInt16LittleEndian(dst, EncodeSnorm16(q.X));
+ BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(2), EncodeSnorm16(q.Y));
+ BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(4), EncodeSnorm16(q.Z));
+ BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(6), EncodeSnorm16(q.W));
+ }
+
+ private static Quaternion ReadQuatSnorm16(ReadOnlySpan src)
+ {
+ var q = new Quaternion(
+ DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src)),
+ DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(2))),
+ DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(4))),
+ DecodeSnorm16(BinaryPrimitives.ReadInt16LittleEndian(src.Slice(6))));
+ return q.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(q);
+ }
+
+ private static void WriteVelShort(Span dst, Vector3 v)
+ {
+ BinaryPrimitives.WriteInt16LittleEndian(dst, (short)Math.Clamp((int)MathF.Round(v.X * 100f), -32767, 32767));
+ BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(2), (short)Math.Clamp((int)MathF.Round(v.Y * 100f), -32767, 32767));
+ BinaryPrimitives.WriteInt16LittleEndian(dst.Slice(4), (short)Math.Clamp((int)MathF.Round(v.Z * 100f), -32767, 32767));
+ }
+
+ private static Vector3 ReadVelShort(ReadOnlySpan src) => new(
+ BinaryPrimitives.ReadInt16LittleEndian(src) / 100f,
+ BinaryPrimitives.ReadInt16LittleEndian(src.Slice(2)) / 100f,
+ BinaryPrimitives.ReadInt16LittleEndian(src.Slice(4)) / 100f);
+
+ private static void WriteInt24(Span dst, float meters)
+ {
+ int scaled = Math.Clamp((int)MathF.Round(meters * 256f), -8388607, 8388607);
+ dst[0] = (byte)(scaled & 0xFF);
+ dst[1] = (byte)((scaled >> 8) & 0xFF);
+ dst[2] = (byte)((scaled >> 16) & 0xFF);
+ }
+
+ private static float ReadInt24(ReadOnlySpan src)
+ {
+ int v = src[0] | (src[1] << 8) | (src[2] << 16);
+ if ((v & 0x800000) != 0)
+ {
+ v |= unchecked((int)0xFF000000);
+ }
+ return v / 256f;
+ }
+
+ private static void WriteOctNormal(Span dst, Vector3 n)
+ {
+ if (n.LengthSquared() < 1e-6f) n = Vector3.UnitY;
+ else n = Vector3.Normalize(n);
+ float sum = MathF.Abs(n.X) + MathF.Abs(n.Y) + MathF.Abs(n.Z);
+ float ox = n.X / sum;
+ float oy = n.Z / sum;
+ if (n.Y < 0f)
+ {
+ float sx = (1f - MathF.Abs(oy)) * (ox >= 0f ? 1f : -1f);
+ float sy = (1f - MathF.Abs(ox)) * (oy >= 0f ? 1f : -1f);
+ ox = sx;
+ oy = sy;
+ }
+ dst[0] = EncodeSnorm8(ox);
+ dst[1] = EncodeSnorm8(oy);
+ }
+
+ private static Vector3 ReadOctNormal(ReadOnlySpan src)
+ {
+ float ox = DecodeSnorm8(src[0]);
+ float oy = DecodeSnorm8(src[1]);
+ float ny = 1f - MathF.Abs(ox) - MathF.Abs(oy);
+ if (ny < 0f)
+ {
+ float oldOx = ox;
+ ox = (1f - MathF.Abs(oy)) * (oldOx >= 0f ? 1f : -1f);
+ oy = (1f - MathF.Abs(oldOx)) * (oy >= 0f ? 1f : -1f);
+ }
+ var v = new Vector3(ox, ny, oy);
+ return v.LengthSquared() < 1e-6f ? Vector3.UnitY : Vector3.Normalize(v);
+ }
+ }
+}
diff --git a/src/RustToDust.Server/Program.cs b/src/RustToDust.Server/Program.cs
new file mode 100644
index 0000000..71d24ed
--- /dev/null
+++ b/src/RustToDust.Server/Program.cs
@@ -0,0 +1,132 @@
+using System;
+using System.Diagnostics;
+using System.Globalization;
+using System.Net;
+using System.Threading;
+using RustToDust.Core;
+using RustToDust.Net;
+using RustToDust.Ymir;
+
+namespace RustToDust.Server
+{
+ public static class Program
+ {
+ public static int Main(string[] args)
+ {
+ string bindStr = Environment.GetEnvironmentVariable("RTD_BIND") ?? "127.0.0.1";
+ int port = TryParseInt(Environment.GetEnvironmentVariable("RTD_PORT"), 3076);
+ string mapStr = Environment.GetEnvironmentVariable("RTD_MAP") ?? "desert";
+ int seed = TryParseInt(Environment.GetEnvironmentVariable("RTD_SEED"), 42);
+ int maxHumans = MatchState.ContenderCount;
+ double autoRestartSec = 8.0;
+ double durationSec = 0.0;
+ bool allowClientReset = false;
+
+ for (int i = 0; i < args.Length; i++)
+ {
+ string a = args[i];
+ if (a == "--bind" && i + 1 < args.Length) bindStr = args[++i];
+ else if (a.StartsWith("--bind=", StringComparison.Ordinal)) bindStr = a.Substring("--bind=".Length);
+ else if (a == "--port" && i + 1 < args.Length) port = TryParseInt(args[++i], port);
+ else if (a.StartsWith("--port=", StringComparison.Ordinal)) port = TryParseInt(a.Substring("--port=".Length), port);
+ else if (a == "--map" && i + 1 < args.Length) mapStr = args[++i];
+ else if (a.StartsWith("--map=", StringComparison.Ordinal)) mapStr = a.Substring("--map=".Length);
+ else if (a == "--seed" && i + 1 < args.Length) seed = TryParseInt(args[++i], seed);
+ else if (a.StartsWith("--seed=", StringComparison.Ordinal)) seed = TryParseInt(a.Substring("--seed=".Length), seed);
+ else if (a == "--max-humans" && i + 1 < args.Length) maxHumans = TryParseInt(args[++i], maxHumans);
+ else if (a.StartsWith("--max-humans=", StringComparison.Ordinal)) maxHumans = TryParseInt(a.Substring("--max-humans=".Length), maxHumans);
+ else if (a == "--auto-restart-sec" && i + 1 < args.Length) autoRestartSec = TryParseDouble(args[++i], autoRestartSec);
+ else if (a.StartsWith("--auto-restart-sec=", StringComparison.Ordinal)) autoRestartSec = TryParseDouble(a.Substring("--auto-restart-sec=".Length), autoRestartSec);
+ else if (a == "--duration-sec" && i + 1 < args.Length) durationSec = TryParseDouble(args[++i], durationSec);
+ else if (a.StartsWith("--duration-sec=", StringComparison.Ordinal)) durationSec = TryParseDouble(a.Substring("--duration-sec=".Length), durationSec);
+ else if (a == "--allow-client-reset") allowClientReset = true;
+ else if (a == "--assets-dir" && i + 1 < args.Length) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", args[++i]);
+ else if (a.StartsWith("--assets-dir=", StringComparison.Ordinal)) Environment.SetEnvironmentVariable("RTD_ASSETS_DIR", a.Substring("--assets-dir=".Length));
+ }
+
+ if (!IPAddress.TryParse(bindStr, out var bindIp))
+ {
+ Console.Error.WriteLine($"Invalid --bind IP address: '{bindStr}'");
+ return 2;
+ }
+
+ ArenaMapKind mapKind = string.Equals(mapStr, "sion", StringComparison.OrdinalIgnoreCase)
+ ? ArenaMapKind.Sion
+ : ArenaMapKind.Desert;
+
+ using var cts = new CancellationTokenSource();
+ ConsoleCancelEventHandler cancelHandler = (_, e) =>
+ {
+ e.Cancel = true;
+ cts.Cancel();
+ };
+ EventHandler exitHandler = (_, _) => cts.Cancel();
+ Console.CancelKeyPress += cancelHandler;
+ AppDomain.CurrentDomain.ProcessExit += exitHandler;
+
+ try
+ {
+ using var host = new ServerMatchHost(
+ bindIp,
+ port,
+ seed,
+ mapKind,
+ maxHumans,
+ autoRestartSec,
+ allowClientReset);
+
+ Console.WriteLine($"RustToDust.Server listening on {bindIp}:{host.BoundPort} (map={mapKind}, seed={seed}, maxHumans={maxHumans})");
+
+ double tickSec = ArenaSession.FixedDt;
+ var sw = Stopwatch.StartNew();
+ double nextTickSec = sw.Elapsed.TotalSeconds;
+ double endSec = durationSec > 0.0 ? durationSec : double.PositiveInfinity;
+
+ while (!cts.IsCancellationRequested && sw.Elapsed.TotalSeconds < endSec)
+ {
+ double nowSec = sw.Elapsed.TotalSeconds;
+ if (nowSec >= nextTickSec)
+ {
+ host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
+ nextTickSec += tickSec;
+ if (nowSec - nextTickSec > 0.25)
+ {
+ nextTickSec = nowSec + tickSec;
+ }
+ }
+ else
+ {
+ double remainingMs = (nextTickSec - nowSec) * 1000.0;
+ if (remainingMs > 2.0)
+ {
+ Thread.Sleep(1);
+ }
+ else
+ {
+ Thread.Yield();
+ }
+ }
+ }
+
+ Console.WriteLine($"RustToDust.Server shutting down cleanly after {host.SimTick} ticks.");
+ return 0;
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine($"RustToDust.Server fatal error: {ex}");
+ return 1;
+ }
+ finally
+ {
+ Console.CancelKeyPress -= cancelHandler;
+ AppDomain.CurrentDomain.ProcessExit -= exitHandler;
+ }
+ }
+
+ private static int TryParseInt(string? s, int fallback) =>
+ int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) ? v : fallback;
+
+ private static double TryParseDouble(string? s, double fallback) =>
+ double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out double v) ? v : fallback;
+ }
+}
diff --git a/src/RustToDust.Server/RustToDust.Server.csproj b/src/RustToDust.Server/RustToDust.Server.csproj
new file mode 100644
index 0000000..3198130
--- /dev/null
+++ b/src/RustToDust.Server/RustToDust.Server.csproj
@@ -0,0 +1,18 @@
+
+
+
+ Exe
+ net8.0
+ LatestMajor
+ enable
+ disable
+
+
+
+
+
+
+
+
+
+
diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs
index babdcf9..7b291c2 100644
--- a/src/RustToDust.Ymir/ArenaSession.cs
+++ b/src/RustToDust.Ymir/ArenaSession.cs
@@ -26,12 +26,29 @@ namespace RustToDust.Ymir
private readonly Dictionary _spectatorWalkers = new();
private readonly Dictionary _entityByStableId = new();
private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount];
+ private readonly PlayerInput[] _humanInputs = new PlayerInput[MatchState.ContenderCount];
+ private readonly bool[] _pendingInteract = new bool[MatchState.ContenderCount];
+ private readonly bool[,] _contenderPvs = new bool[MatchState.ContenderCount, MatchState.ContenderCount];
+ private readonly bool[,] _spectatorPvs;
+ private readonly List _stepEvents = new();
private bool _disposed;
- public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert)
+ public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false)
{
State = new MatchState(seed, mapKind);
+ _spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count];
+
State.ChassisSwapped += OnContenderChassisSwapped;
+ State.LoadoutChanged += OnContenderLoadoutChanged;
+ State.DropSpawned += OnDropSpawned;
+ State.DropPickedUp += OnDropPickedUp;
+ State.Broadcast.LineEmitted += OnBroadcastLineEmitted;
+
+ if (slot0Human && State.Contenders.Count > 0)
+ {
+ State.Contenders[0].IsHuman = true;
+ State.Contenders[0].Name = "Contender 01 (You)";
+ }
_world = new Box3DSoaWorld(
capacity: WorldBodyCapacity,
@@ -39,10 +56,10 @@ namespace RustToDust.Ymir
gravityY: -20f,
gravityZ: 0f);
- BuildStaticArena();
+ BuildStaticArena(_world, State);
SpawnContenderBodies();
SpawnSpectatorBodies();
- UpdatePlayerDetectionMemory();
+ UpdateObserverDetectionMemories();
}
public static bool PerfEnabled;
@@ -57,11 +74,154 @@ namespace RustToDust.Ymir
public MatchState State { get; }
public Box3DSoaWorld World => _world;
- public bool TryEquipCargo(int cargoIndex, string hardpointId) =>
- State.TryEquipCargo(cargoIndex, hardpointId);
+ public void SetHumanSlot(int contenderId, bool isHuman, string? callsign = null)
+ {
+ if (contenderId < 0 || contenderId >= State.Contenders.Count)
+ {
+ return;
+ }
+ var c = State.Contenders[contenderId];
+ bool changed = c.IsHuman != isHuman || (callsign is not null && !string.Equals(c.Name, callsign, StringComparison.Ordinal));
+ c.IsHuman = isHuman;
+ if (callsign is not null)
+ {
+ c.Name = callsign;
+ }
+ else if (!isHuman)
+ {
+ c.Name = $"Contender {contenderId + 1:00}";
+ }
- public bool TrySwapNearbyChassis() =>
- State.TrySwapNearbyChassis(0);
+ _humanInputs[contenderId] = default;
+ _pendingInteract[contenderId] = false;
+ c.ThrottleCmd = 0f;
+ c.SteerCmd = 0f;
+ c.VerticalThrottleCmd = 0f;
+ c.FireCmd = false;
+ c.BrakeCmd = false;
+ c.ResetAimTracker(c.Yaw);
+
+ if (isHuman)
+ {
+ State.GetOrCreateObserverState(contenderId);
+ }
+
+ if (changed)
+ {
+ UpdateObserverDetectionMemories();
+ }
+ }
+
+ public void SetHumanInput(int contenderId, in PlayerInput input)
+ {
+ if (contenderId < 0 || contenderId >= _humanInputs.Length)
+ {
+ return;
+ }
+ _humanInputs[contenderId] = input;
+ if (input.InteractPickup)
+ {
+ _pendingInteract[contenderId] = true;
+ }
+ }
+
+ public void DrainStepEvents(List dest)
+ {
+ if (_stepEvents.Count == 0)
+ {
+ return;
+ }
+ dest.AddRange(_stepEvents);
+ _stepEvents.Clear();
+ }
+
+ public bool IsEntityInPeerPvs(int observerContenderId, bool isContender, int entityId)
+ {
+ if (observerContenderId < 0 || observerContenderId >= MatchState.ContenderCount)
+ {
+ return false;
+ }
+ if (isContender)
+ {
+ return entityId >= 0 && entityId < MatchState.ContenderCount && _contenderPvs[observerContenderId, entityId];
+ }
+ int specIdx = entityId >= 1000 ? entityId - 1000 : entityId;
+ return specIdx >= 0 && specIdx < _spectatorPvs.GetLength(1) && _spectatorPvs[observerContenderId, specIdx];
+ }
+
+ public bool TryEquipCargo(int contenderId, int cargoIndex, string hardpointId) =>
+ State.TryEquipCargo(contenderId, cargoIndex, hardpointId);
+
+ public bool TrySwapNearbyChassis(int contenderId) =>
+ State.TrySwapNearbyChassis(contenderId);
+
+ private void OnDropSpawned(GroundDrop drop)
+ {
+ _stepEvents.Add(new DropSpawnedEvent
+ {
+ DropId = drop.Id,
+ X = drop.X,
+ Z = drop.Z,
+ ChassisId = drop.Chassis?.Id,
+ ModuleId = drop.Module?.Id
+ });
+ }
+
+ private void OnDropPickedUp(int dropId, int contenderId)
+ {
+ _stepEvents.Add(new DropPickedUpEvent
+ {
+ DropId = dropId,
+ ContenderId = contenderId
+ });
+ }
+
+ private void OnContenderLoadoutChanged(ContenderState c)
+ {
+ _stepEvents.Add(BuildContenderLoadoutEvent(c, includeCargo: true));
+ }
+
+ private void OnBroadcastLineEmitted(BroadcastLine line)
+ {
+ _stepEvents.Add(new BroadcastLineEvent
+ {
+ Timestamp = line.Timestamp,
+ Kind = (byte)line.Kind,
+ Text = line.Text
+ });
+ }
+
+ public static ContenderLoadoutEvent BuildContenderLoadoutEvent(ContenderState c, bool includeCargo)
+ {
+ var mounted = new List(c.Grid.Mounted.Count);
+ for (int i = 0; i < c.Grid.Mounted.Count; i++)
+ {
+ var m = c.Grid.Mounted[i];
+ mounted.Add(new MountedSlotDto { ModuleId = m.Spec.Id, HardpointId = m.HardpointId });
+ }
+
+ List? cargo = null;
+ if (includeCargo)
+ {
+ cargo = new List(c.Grid.Cargo.Count);
+ for (int i = 0; i < c.Grid.Cargo.Count; i++)
+ {
+ cargo.Add(c.Grid.Cargo[i].Id);
+ }
+ }
+
+ return new ContenderLoadoutEvent
+ {
+ ContenderId = c.Id,
+ LoadoutVersion = c.LoadoutVersion,
+ ChassisId = c.Grid.Spec.Id,
+ CoreHp = c.Grid.CoreHp,
+ MaxCoreHp = c.Grid.MaxCoreHp,
+ ArmorBytes = c.Grid.QuantizeArmorBytes(),
+ Mounted = mounted,
+ CargoIds = cargo
+ };
+ }
public Box3DSoaBodyHandle? GetContenderBody(int contenderId) =>
_contenderBodies.TryGetValue(contenderId, out var h) ? h : null;
@@ -377,7 +537,7 @@ namespace RustToDust.Ymir
}
}
- public void Step(PlayerInput input)
+ public void Step()
{
ObjectDisposedException.ThrowIf(_disposed, this);
@@ -391,17 +551,33 @@ namespace RustToDust.Ymir
int subSteps = State.MapKind == ArenaMapKind.Sion ? 1 : SubStepCount;
+ void ApplyAllHumanInputs()
+ {
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ var c = State.Contenders[i];
+ if (!c.IsHuman)
+ {
+ continue;
+ }
+ var inp = _humanInputs[i];
+ bool interact = _pendingInteract[i];
+ _pendingInteract[i] = false;
+ MatchRules.ApplyHumanInput(State, i, inp with { InteractPickup = interact });
+ }
+ }
+
if (!PerfEnabled)
{
UpdateRingClearance();
- MatchRules.ApplyPlayerInput(State, input);
+ ApplyAllHumanInputs();
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
ApplyPhysicsDrives();
_world.Step(FixedDt, subSteps);
SyncBodiesFromWorld();
- UpdatePlayerDetectionMemory();
+ UpdateObserverDetectionMemories();
StepThermalAndCooldowns();
ProcessWeapons();
MatchRules.UpdateMatchOutcome(State);
@@ -412,7 +588,7 @@ namespace RustToDust.Ymir
long t0 = Stopwatch.GetTimestamp();
UpdateRingClearance();
long t1 = Stopwatch.GetTimestamp();
- MatchRules.ApplyPlayerInput(State, input);
+ ApplyAllHumanInputs();
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
long t2 = Stopwatch.GetTimestamp();
ApplyPhysicsDrives();
@@ -421,7 +597,7 @@ namespace RustToDust.Ymir
long t4 = Stopwatch.GetTimestamp();
SyncBodiesFromWorld();
long t5 = Stopwatch.GetTimestamp();
- UpdatePlayerDetectionMemory();
+ UpdateObserverDetectionMemories();
long t6 = Stopwatch.GetTimestamp();
StepThermalAndCooldowns();
ProcessWeapons();
@@ -437,13 +613,13 @@ namespace RustToDust.Ymir
PerfWeaponsMs += (t7 - t6) * toMs;
}
- private void BuildStaticArena()
+ public static void BuildStaticArena(Box3DSoaWorld world, MatchState state)
{
- if (State.MapKind == ArenaMapKind.Sion && State.SionMap is { } sion)
+ if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion)
{
var meta = sion.Metadata;
- float half = State.Terrain.MapHalfExtent;
- _world.AddStaticHeightField(
+ float half = state.Terrain.MapHalfExtent;
+ world.AddStaticHeightField(
GroundStableId,
(-half, 0f, -half),
sion.Heights,
@@ -456,10 +632,10 @@ namespace RustToDust.Ymir
restitution: 0.0f);
ulong boxId = StaticBoxStableIdBase;
- for (int i = 0; i < State.ArenaBoundaryBoxes.Count; i++)
+ for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++)
{
- var b = State.ArenaBoundaryBoxes[i];
- _world.AddStaticBox(
+ var b = state.ArenaBoundaryBoxes[i];
+ world.AddStaticBox(
boxId++,
(b.X, b.Y, b.Z),
(b.HalfX, b.HalfY, b.HalfZ),
@@ -470,7 +646,7 @@ namespace RustToDust.Ymir
for (int i = 0; i < sion.CollisionMeshes.Count; i++)
{
var col = sion.CollisionMeshes[i];
- _world.AddStaticMesh(
+ world.AddStaticMesh(
StaticMeshStableIdBase + (ulong)i,
(0f, 0f, 0f),
col.Vertices,
@@ -483,7 +659,7 @@ namespace RustToDust.Ymir
// Desert safety floor slab at y = -20m below the lowest possible terrain valley (-18m);
// primary terrain support comes from 4-corner spring-damper sampling of State.Terrain.
- _world.AddStaticBox(
+ world.AddStaticBox(
GroundStableId,
(0f, -20f, 0f),
(800f, 1f, 800f),
@@ -491,10 +667,10 @@ namespace RustToDust.Ymir
restitution: 0.05f);
ulong nextId = StaticBoxStableIdBase;
- for (int i = 0; i < State.ArenaBoundaryBoxes.Count; i++)
+ for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++)
{
- var b = State.ArenaBoundaryBoxes[i];
- _world.AddStaticBox(
+ var b = state.ArenaBoundaryBoxes[i];
+ world.AddStaticBox(
nextId++,
(b.X, b.Y, b.Z),
(b.HalfX, b.HalfY, b.HalfZ),
@@ -502,10 +678,10 @@ namespace RustToDust.Ymir
restitution: 0.1f);
}
- for (int i = 0; i < State.ArenaCoverBoxes.Count; i++)
+ for (int i = 0; i < state.ArenaCoverBoxes.Count; i++)
{
- var b = State.ArenaCoverBoxes[i];
- _world.AddStaticBox(
+ var b = state.ArenaCoverBoxes[i];
+ world.AddStaticBox(
nextId++,
(b.X, b.Y, b.Z),
(b.HalfX, b.HalfY, b.HalfZ),
@@ -523,7 +699,7 @@ namespace RustToDust.Ymir
}
}
- private static float GetPhysicsHalfHeight(ChassisSpec spec) =>
+ public static float GetPhysicsHalfHeight(ChassisSpec spec) =>
spec.IsWalker
? spec.HalfHeight * (spec.Plane == GridPlane.Dorsal ? 0.62f : 0.72f)
: spec.HalfHeight;
@@ -719,6 +895,145 @@ namespace RustToDust.Ymir
target.X, MatchRules.GetTargetAimY(target.Y, target.HalfHeight), target.Z);
}
+ public static void StepContenderPhysicsDrive(
+ ContenderState c,
+ Box3DSoaView view,
+ int lane,
+ TerrainField terrain,
+ ArenaMapKind mapKind,
+ WalkerState? walker,
+ float dt,
+ bool injectEngineHeat)
+ {
+ float mass = view.Mass[lane];
+ if (mass <= 0f)
+ {
+ return;
+ }
+
+ var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]);
+ var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]);
+ var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]);
+ var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]);
+
+ if (c.Grid.Spec.IsVtol)
+ {
+ ApplyVtolFlightDrive(c, lane, mass, pos, q, vel, angVel, view, terrain, dt, injectEngineHeat);
+ return;
+ }
+
+ if (c.Grid.Spec.IsWalker && walker is not null)
+ {
+ var wFwd = Vector3.Transform(Vector3.UnitZ, q);
+ wFwd.Y = 0f;
+ wFwd = wFwd.LengthSquared() < 1e-4f ? Vector3.UnitZ : Vector3.Normalize(wFwd);
+ float wMaxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed) * c.Grid.LegIntegrity;
+ Vector3 desiredHorizVel = wFwd * (c.ThrottleCmd * wMaxSpeed);
+ float wTargetYawVel = -c.SteerCmd * c.Grid.ComputeTurnRate();
+
+ if (injectEngineHeat && MathF.Abs(c.ThrottleCmd) > 0.05f)
+ {
+ for (int m = 0; m < c.Grid.Mounted.Count; m++)
+ {
+ var mod = c.Grid.Mounted[m];
+ if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f)
+ {
+ c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * dt);
+ }
+ }
+ }
+
+ WalkerLocomotion.StepWalker(
+ walker, c.Grid, terrain, view, lane, mass,
+ pos, q, vel, angVel, desiredHorizVel, wTargetYawVel, c.BrakeCmd, dt);
+ return;
+ }
+
+ ComputeTerrainSupport(
+ pos, q, vel, angVel, mass, c.Grid.Spec, terrain, mapKind, dt,
+ out Vector3 supportForce,
+ out Vector3 supportTorque,
+ out Vector3 terrainNormal,
+ out int groundedCorners);
+
+ var forward = Vector3.Transform(Vector3.UnitZ, q);
+ forward.Y = 0f;
+ if (forward.LengthSquared() < 1e-4f) forward = Vector3.UnitZ;
+ else forward = Vector3.Normalize(forward);
+
+ var right = Vector3.Cross(forward, Vector3.UnitY);
+ var up = Vector3.Transform(Vector3.UnitY, q);
+
+ Vector3 driveForward = forward;
+ Vector3 driveRight = right;
+ if (groundedCorners > 0)
+ {
+ Vector3 fSlope = forward - terrainNormal * Vector3.Dot(forward, terrainNormal);
+ if (fSlope.LengthSquared() > 1e-4f) driveForward = Vector3.Normalize(fSlope);
+ Vector3 rSlope = right - terrainNormal * Vector3.Dot(right, terrainNormal);
+ if (rSlope.LengthSquared() > 1e-4f) driveRight = Vector3.Normalize(rSlope);
+ }
+
+ float thrust = c.Grid.ComputeDriveThrust();
+ float maxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed);
+ float forwardSpeed = Vector3.Dot(vel, driveForward);
+ float lateralSpeed = Vector3.Dot(vel, driveRight);
+ float gripScale = groundedCorners > 0 ? (0.4f + 0.6f * (groundedCorners / 4f)) : 0.12f;
+
+ Vector3 force = supportForce;
+ Vector3 effectiveDriveFwd = driveForward;
+ if (groundedCorners > 0 && terrainNormal.Y < 0.78f)
+ {
+ Vector3 cliffHoriz = new Vector3(terrainNormal.X, 0f, terrainNormal.Z);
+ if (cliffHoriz.LengthSquared() > 1e-4f)
+ {
+ cliffHoriz = Vector3.Normalize(cliffHoriz);
+ float intoCliff = Vector3.Dot(effectiveDriveFwd, cliffHoriz);
+ if (intoCliff < 0f)
+ {
+ effectiveDriveFwd -= cliffHoriz * intoCliff;
+ effectiveDriveFwd.Y = MathF.Min(effectiveDriveFwd.Y, 0.25f);
+ }
+ }
+ }
+ force += effectiveDriveFwd * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed) * gripScale;
+ force -= driveRight * (lateralSpeed * mass * 8.5f * gripScale);
+
+ if (c.BrakeCmd && groundedCorners > 0)
+ {
+ var horizVel = new Vector3(vel.X, 0f, vel.Z);
+ force -= horizVel * (mass * 7f);
+ }
+
+ if (injectEngineHeat && MathF.Abs(c.ThrottleCmd) > 0.05f)
+ {
+ for (int m = 0; m < c.Grid.Mounted.Count; m++)
+ {
+ var mod = c.Grid.Mounted[m];
+ if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f)
+ {
+ c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * dt);
+ }
+ }
+ }
+
+ float turnRate = c.Grid.ComputeTurnRate();
+ float targetYawVel = -c.SteerCmd * turnRate;
+ float hx = view.Size0[lane];
+ float hz = view.Size2[lane];
+ float iy = mass * (hx * hx + hz * hz) / 3f;
+
+ Vector3 torque = ComputeRightingTorque(c.Grid.Spec, q, up, angVel, mass, terrainNormal, supportTorque, terrainBlend: 0.85f);
+ torque.Y = iy * (targetYawVel - angVel.Y) * 8f;
+
+ view.ForceX[lane] = force.X;
+ view.ForceY[lane] = force.Y;
+ view.ForceZ[lane] = force.Z;
+ view.TorqueX[lane] = torque.X;
+ view.TorqueY[lane] = torque.Y;
+ view.TorqueZ[lane] = torque.Z;
+ }
+
private void ApplyPhysicsDrives()
{
var view = _world.View;
@@ -732,146 +1047,22 @@ namespace RustToDust.Ymir
continue;
}
- int lane = handle.Lane;
- float mass = view.Mass[lane];
- if (mass <= 0f)
+ WalkerState? ws = null;
+ if (c.Grid.Spec.IsWalker && !_contenderWalkers.TryGetValue(c.Id, out ws))
{
- continue;
+ int lane = handle.Lane;
+ float mass = view.Mass[lane];
+ if (mass <= 0f) continue;
+ ws = new WalkerState(c.Grid.Spec);
+ ws.InitializePose(
+ new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]),
+ new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]),
+ mass,
+ State.Terrain);
+ _contenderWalkers[c.Id] = ws;
}
- var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]);
- var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]);
- var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]);
- var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]);
-
- if (c.Grid.Spec.IsVtol)
- {
- ApplyVtolFlightDrive(c, lane, mass, pos, q, vel, angVel, view);
- continue;
- }
-
- if (c.Grid.Spec.IsWalker)
- {
- if (!_contenderWalkers.TryGetValue(c.Id, out var ws))
- {
- ws = new WalkerState(c.Grid.Spec);
- ws.InitializePose(pos, q, mass, State.Terrain);
- _contenderWalkers[c.Id] = ws;
- }
-
- var wFwd = Vector3.Transform(Vector3.UnitZ, q);
- wFwd.Y = 0f;
- wFwd = wFwd.LengthSquared() < 1e-4f ? Vector3.UnitZ : Vector3.Normalize(wFwd);
- float wMaxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed) * c.Grid.LegIntegrity;
- Vector3 desiredHorizVel = wFwd * (c.ThrottleCmd * wMaxSpeed);
- float wTargetYawVel = -c.SteerCmd * c.Grid.ComputeTurnRate();
-
- if (MathF.Abs(c.ThrottleCmd) > 0.05f)
- {
- for (int m = 0; m < c.Grid.Mounted.Count; m++)
- {
- var mod = c.Grid.Mounted[m];
- if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f)
- {
- c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * FixedDt);
- }
- }
- }
-
- WalkerLocomotion.StepWalker(
- ws, c.Grid, State.Terrain, view, lane, mass,
- pos, q, vel, angVel, desiredHorizVel, wTargetYawVel, c.BrakeCmd, FixedDt);
- continue;
- }
-
- ComputeTerrainSupport(
- pos, q, vel, angVel, mass, c.Grid.Spec,
- out Vector3 supportForce,
- out Vector3 supportTorque,
- out Vector3 terrainNormal,
- out int groundedCorners);
-
- var forward = Vector3.Transform(Vector3.UnitZ, q);
- forward.Y = 0f;
- if (forward.LengthSquared() < 1e-4f) forward = Vector3.UnitZ;
- else forward = Vector3.Normalize(forward);
-
- var right = Vector3.Cross(forward, Vector3.UnitY);
- var up = Vector3.Transform(Vector3.UnitY, q);
-
- Vector3 driveForward = forward;
- Vector3 driveRight = right;
- if (groundedCorners > 0)
- {
- Vector3 fSlope = forward - terrainNormal * Vector3.Dot(forward, terrainNormal);
- if (fSlope.LengthSquared() > 1e-4f) driveForward = Vector3.Normalize(fSlope);
- Vector3 rSlope = right - terrainNormal * Vector3.Dot(right, terrainNormal);
- if (rSlope.LengthSquared() > 1e-4f) driveRight = Vector3.Normalize(rSlope);
- }
-
- float thrust = c.Grid.ComputeDriveThrust();
- float maxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed);
- float forwardSpeed = Vector3.Dot(vel, driveForward);
- float lateralSpeed = Vector3.Dot(vel, driveRight);
- float gripScale = groundedCorners > 0 ? (0.4f + 0.6f * (groundedCorners / 4f)) : 0.12f;
-
- Vector3 force = supportForce;
- // On steep cliffs (ny < 0.78), strip inward horizontal thrust so vehicles slide along the slope instead of burrowing
- Vector3 effectiveDriveFwd = driveForward;
- if (groundedCorners > 0 && terrainNormal.Y < 0.78f)
- {
- Vector3 cliffHoriz = new Vector3(terrainNormal.X, 0f, terrainNormal.Z);
- if (cliffHoriz.LengthSquared() > 1e-4f)
- {
- cliffHoriz = Vector3.Normalize(cliffHoriz);
- float intoCliff = Vector3.Dot(effectiveDriveFwd, cliffHoriz);
- if (intoCliff < 0f)
- {
- effectiveDriveFwd -= cliffHoriz * intoCliff;
- effectiveDriveFwd.Y = MathF.Min(effectiveDriveFwd.Y, 0.25f);
- }
- }
- }
- // Drive thrust along slope-aligned forward with smooth terminal velocity drag at MaxSpeed
- force += effectiveDriveFwd * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed) * gripScale;
- // Lateral tire / stride grip
- force -= driveRight * (lateralSpeed * mass * 8.5f * gripScale);
-
- if (c.BrakeCmd && groundedCorners > 0)
- {
- var horizVel = new Vector3(vel.X, 0f, vel.Z);
- force -= horizVel * (mass * 7f);
- }
-
- // Engine heat from throttle
- if (MathF.Abs(c.ThrottleCmd) > 0.05f)
- {
- for (int m = 0; m < c.Grid.Mounted.Count; m++)
- {
- var mod = c.Grid.Mounted[m];
- if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f)
- {
- c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * FixedDt);
- }
- }
- }
-
- float turnRate = c.Grid.ComputeTurnRate();
- // Steer > 0 turns right (clockwise looking from +Y down => negative Y torque when +Z is forward)
- float targetYawVel = -c.SteerCmd * turnRate;
- float hx = view.Size0[lane];
- float hz = view.Size2[lane];
- float iy = mass * (hx * hx + hz * hz) / 3f;
-
- Vector3 torque = ComputeRightingTorque(c.Grid.Spec, q, up, angVel, mass, terrainNormal, supportTorque, terrainBlend: 0.85f);
- torque.Y = iy * (targetYawVel - angVel.Y) * 8f;
-
- view.ForceX[lane] = force.X;
- view.ForceY[lane] = force.Y;
- view.ForceZ[lane] = force.Z;
- view.TorqueX[lane] = torque.X;
- view.TorqueY[lane] = torque.Y;
- view.TorqueZ[lane] = torque.Z;
+ StepContenderPhysicsDrive(c, view, handle.Lane, State.Terrain, State.MapKind, ws, FixedDt, injectEngineHeat: true);
}
// Spectators
@@ -944,7 +1135,7 @@ namespace RustToDust.Ymir
}
ComputeTerrainSupport(
- pos, q, vel, angVel, mass, s.Grid.Spec,
+ pos, q, vel, angVel, mass, s.Grid.Spec, State.Terrain, State.MapKind, FixedDt,
out Vector3 supportForce,
out Vector3 supportTorque,
out Vector3 terrainNormal,
@@ -969,7 +1160,7 @@ namespace RustToDust.Ymir
}
}
- private void ApplyVtolFlightDrive(
+ private static void ApplyVtolFlightDrive(
ContenderState c,
int lane,
float mass,
@@ -977,14 +1168,17 @@ namespace RustToDust.Ymir
Quaternion q,
Vector3 vel,
Vector3 angVel,
- Box3DSoaView view)
+ Box3DSoaView view,
+ TerrainField terrain,
+ float dt,
+ bool injectEngineHeat)
{
var spec = c.Grid.Spec;
float minAlt = MatchRules.VtolMinClearanceAgl;
float maxAlt = MathF.Max(minAlt, spec.HoverMaxAltitudeM);
const float verticalSpeed = 14f;
float enginePerf = c.Grid.ComputeEngineThermalPerformance();
- c.TargetHoverAltAgl = Math.Clamp(c.TargetHoverAltAgl + c.VerticalThrottleCmd * verticalSpeed * FixedDt, minAlt, maxAlt);
+ c.TargetHoverAltAgl = Math.Clamp(c.TargetHoverAltAgl + c.VerticalThrottleCmd * verticalSpeed * dt, minAlt, maxAlt);
var forward = Vector3.Transform(Vector3.UnitZ, q);
forward.Y = 0f;
@@ -997,13 +1191,13 @@ namespace RustToDust.Ymir
float perimDist = MathF.Max(spec.HalfWidth, spec.HalfLength) + 2.5f;
// Sample terrain at center, 4-point perimeter (HalfLength + 2.5m), and horizontal velocity lookahead (0.20s, 0.35s)
- float ghCenter = State.Terrain.SampleHeight(pos.X, pos.Z);
- float ghFront = State.Terrain.SampleHeight(pos.X + forward.X * perimDist, pos.Z + forward.Z * perimDist);
- float ghBack = State.Terrain.SampleHeight(pos.X - forward.X * perimDist, pos.Z - forward.Z * perimDist);
- float ghRight = State.Terrain.SampleHeight(pos.X + right.X * perimDist, pos.Z + right.Z * perimDist);
- float ghLeft = State.Terrain.SampleHeight(pos.X - right.X * perimDist, pos.Z - right.Z * perimDist);
- float ghLook1 = State.Terrain.SampleHeight(pos.X + horizVel.X * 0.20f, pos.Z + horizVel.Z * 0.20f);
- float ghLook2 = State.Terrain.SampleHeight(pos.X + horizVel.X * 0.35f, pos.Z + horizVel.Z * 0.35f);
+ float ghCenter = terrain.SampleHeight(pos.X, pos.Z);
+ float ghFront = terrain.SampleHeight(pos.X + forward.X * perimDist, pos.Z + forward.Z * perimDist);
+ float ghBack = terrain.SampleHeight(pos.X - forward.X * perimDist, pos.Z - forward.Z * perimDist);
+ float ghRight = terrain.SampleHeight(pos.X + right.X * perimDist, pos.Z + right.Z * perimDist);
+ float ghLeft = terrain.SampleHeight(pos.X - right.X * perimDist, pos.Z - right.Z * perimDist);
+ float ghLook1 = terrain.SampleHeight(pos.X + horizVel.X * 0.20f, pos.Z + horizVel.Z * 0.20f);
+ float ghLook2 = terrain.SampleHeight(pos.X + horizVel.X * 0.35f, pos.Z + horizVel.Z * 0.35f);
float ghSafe = MathF.Max(
ghCenter,
MathF.Max(
@@ -1014,13 +1208,13 @@ namespace RustToDust.Ymir
ghCenter,
MathF.Max(
MathF.Max(
- State.Terrain.SampleHeight(pos.X + forward.X * spec.HalfLength, pos.Z + forward.Z * spec.HalfLength),
- State.Terrain.SampleHeight(pos.X - forward.X * spec.HalfLength, pos.Z - forward.Z * spec.HalfLength)),
+ terrain.SampleHeight(pos.X + forward.X * spec.HalfLength, pos.Z + forward.Z * spec.HalfLength),
+ terrain.SampleHeight(pos.X - forward.X * spec.HalfLength, pos.Z - forward.Z * spec.HalfLength)),
MathF.Max(
- State.Terrain.SampleHeight(pos.X + right.X * spec.HalfWidth, pos.Z + right.Z * spec.HalfWidth),
- State.Terrain.SampleHeight(pos.X - right.X * spec.HalfWidth, pos.Z - right.Z * spec.HalfWidth))));
+ terrain.SampleHeight(pos.X + right.X * spec.HalfWidth, pos.Z + right.Z * spec.HalfWidth),
+ terrain.SampleHeight(pos.X - right.X * spec.HalfWidth, pos.Z - right.Z * spec.HalfWidth))));
- var (tnx, tny, tnz) = State.Terrain.SampleNormal(pos.X, pos.Z);
+ var (tnx, tny, tnz) = terrain.SampleNormal(pos.X, pos.Z);
var terrainNormal = new Vector3(tnx, tny, tnz);
float bottomY = pos.Y - spec.HalfHeight;
@@ -1064,7 +1258,7 @@ namespace RustToDust.Ymir
{
float availDist = MathF.Max(0.15f, bottomAgl - 0.65f);
float reqDecel = (vel.Y * vel.Y) / (2f * availDist) + 20f;
- float arrestAccel = MathF.Min(reqDecel, (-vel.Y / FixedDt) + 20f);
+ float arrestAccel = MathF.Min(reqDecel, (-vel.Y / dt) + 20f);
hoverForceY += mass * arrestAccel;
}
}
@@ -1080,7 +1274,7 @@ namespace RustToDust.Ymir
float vDotN = Vector3.Dot(vel, terrainNormal);
if (bottomAgl < minAlt && vDotN < 0f)
{
- float deflectMag = MathF.Min(-vDotN * mass * 28f, -vDotN * mass / FixedDt);
+ float deflectMag = MathF.Min(-vDotN * mass * 28f, -vDotN * mass / dt);
force += terrainNormal * deflectMag;
}
@@ -1101,7 +1295,7 @@ namespace RustToDust.Ymir
{
driveForce -= horizDir * (intoLook * brakeFrac * 0.95f);
}
- float maxBrake = (horizSpeed * mass) / FixedDt;
+ float maxBrake = (horizSpeed * mass) / dt;
float desiredBrake = horizSpeed * mass * 16f * brakeFrac;
force -= horizDir * MathF.Min(desiredBrake, maxBrake);
}
@@ -1124,7 +1318,7 @@ namespace RustToDust.Ymir
float velIntoCliff = Vector3.Dot(horizVel, cliffDir);
if (velIntoCliff < 0f)
{
- float stopMag = MathF.Min(-velIntoCliff * mass * 24f, -velIntoCliff * mass / FixedDt);
+ float stopMag = MathF.Min(-velIntoCliff * mass * 24f, -velIntoCliff * mass / dt);
force += cliffDir * stopMag;
}
force += cliffDir * (mass * 12f * Math.Clamp(cliffPush.Length(), 0f, 1f));
@@ -1138,14 +1332,17 @@ namespace RustToDust.Ymir
}
// Engine heat from hover lift + horizontal thrust
- float liftWork = 0.25f + 0.55f * MathF.Abs(c.VerticalThrottleCmd);
- float heatFraction = MathF.Max(MathF.Abs(c.ThrottleCmd), liftWork);
- for (int m = 0; m < c.Grid.Mounted.Count; m++)
+ if (injectEngineHeat)
{
- var mod = c.Grid.Mounted[m];
- if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f)
+ float liftWork = 0.25f + 0.55f * MathF.Abs(c.VerticalThrottleCmd);
+ float heatFraction = MathF.Max(MathF.Abs(c.ThrottleCmd), liftWork);
+ for (int m = 0; m < c.Grid.Mounted.Count; m++)
{
- c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * heatFraction * FixedDt);
+ var mod = c.Grid.Mounted[m];
+ if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f)
+ {
+ c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * heatFraction * dt);
+ }
}
}
@@ -1248,13 +1445,16 @@ namespace RustToDust.Ymir
return supportTorque + arrestTorque + tiltAxis * (mass * rightingGain) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * dampingGain);
}
- private void ComputeTerrainSupport(
+ private static void ComputeTerrainSupport(
Vector3 pos,
Quaternion q,
Vector3 vel,
Vector3 angVel,
float mass,
ChassisSpec spec,
+ TerrainField terrain,
+ ArenaMapKind mapKind,
+ float dt,
out Vector3 supportForce,
out Vector3 supportTorque,
out Vector3 terrainNormal,
@@ -1264,7 +1464,7 @@ namespace RustToDust.Ymir
supportTorque = Vector3.Zero;
groundedCorners = 0;
- var (nx, ny, nz) = State.Terrain.SampleNormal(pos.X, pos.Z);
+ var (nx, ny, nz) = terrain.SampleNormal(pos.X, pos.Z);
terrainNormal = new Vector3(nx, ny, nz);
// Blend smoothly from pure vertical on flat ground to surface normal on steep mesa/dune slopes
@@ -1272,7 +1472,7 @@ namespace RustToDust.Ymir
Vector3 supportDir = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, slopeBlend));
float orthoScale = MathF.Max(0.35f, terrainNormal.Y);
- bool isSion = State.MapKind == ArenaMapKind.Sion;
+ bool isSion = mapKind == ArenaMapKind.Sion;
float hx = MathF.Min(spec.HalfWidth * 0.9f, 2.4f);
float hz = MathF.Min(spec.HalfLength * 0.9f, 2.8f);
float bottomY = -spec.HalfHeight;
@@ -1293,7 +1493,7 @@ namespace RustToDust.Ymir
{
Vector3 r = Vector3.Transform(corners[k], q);
Vector3 wp = pos + r;
- float gh = State.Terrain.SampleHeight(wp.X, wp.Z);
+ float gh = terrain.SampleHeight(wp.X, wp.Z);
float pen = (gh + restTravel) - wp.Y;
if (pen > 0f)
{
@@ -1310,7 +1510,7 @@ namespace RustToDust.Ymir
}
// Center skid-plate bump-stop prevents belly clipping when straddling sharp ridge crests at speed
- float ghCenter = State.Terrain.SampleHeight(pos.X, pos.Z);
+ float ghCenter = terrain.SampleHeight(pos.X, pos.Z);
float centerGap = (pos.Y - spec.HalfHeight) - ghCenter;
float centerPen = (ghCenter + 0.08f) - (pos.Y - spec.HalfHeight);
if (!isSion && centerPen > 0f)
@@ -1349,11 +1549,36 @@ namespace RustToDust.Ymir
// On Sion, Ymir's StaticHeightField handles rigid normal contact directly without double-bouncing.
if (!isSion && maxPen > 0f && vDotN < 0f)
{
- float deflectMag = MathF.Min(-vDotN * mass * 42f, -vDotN * mass / FixedDt);
+ float deflectMag = MathF.Min(-vDotN * mass * 42f, -vDotN * mass / dt);
supportForce += terrainNormal * deflectMag;
}
}
+ public static void SyncContenderPoseFromLane(ContenderState c, Box3DSoaView view, int lane, WalkerState? walker)
+ {
+ c.X = view.PositionX[lane];
+ c.Y = view.PositionY[lane];
+ c.Z = view.PositionZ[lane];
+ c.CurrRotX = view.RotationX[lane];
+ c.CurrRotY = view.RotationY[lane];
+ c.CurrRotZ = view.RotationZ[lane];
+ c.CurrRotW = view.RotationW[lane];
+ var q = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW);
+ var forward = Vector3.Transform(Vector3.UnitZ, q);
+ c.Yaw = MathF.Atan2(forward.X, forward.Z);
+ float vx = view.VelocityX[lane];
+ float vy = view.VelocityY[lane];
+ float vz = view.VelocityZ[lane];
+ c.VelX = vx;
+ c.VelY = vy;
+ c.VelZ = vz;
+ c.Speed = MathF.Sqrt(vx * vx + vz * vz);
+ if (walker is not null)
+ {
+ walker.SyncBodyPoseOnly(new Vector3(c.X, c.Y, c.Z), Quaternion.Normalize(q), view.Mass[lane]);
+ }
+ }
+
private void SyncBodiesFromWorld()
{
var view = _world.View;
@@ -1369,27 +1594,8 @@ namespace RustToDust.Ymir
int lane = handle.Lane;
float prevX = c.X;
float prevZ = c.Z;
- c.X = view.PositionX[lane];
- c.Y = view.PositionY[lane];
- c.Z = view.PositionZ[lane];
- c.CurrRotX = view.RotationX[lane];
- c.CurrRotY = view.RotationY[lane];
- c.CurrRotZ = view.RotationZ[lane];
- c.CurrRotW = view.RotationW[lane];
- var q = new Quaternion(c.CurrRotX, c.CurrRotY, c.CurrRotZ, c.CurrRotW);
- var forward = Vector3.Transform(Vector3.UnitZ, q);
- c.Yaw = MathF.Atan2(forward.X, forward.Z);
- float vx = view.VelocityX[lane];
- float vy = view.VelocityY[lane];
- float vz = view.VelocityZ[lane];
- c.VelX = vx;
- c.VelY = vy;
- c.VelZ = vz;
- c.Speed = MathF.Sqrt(vx * vx + vz * vz);
- if (_contenderWalkers.TryGetValue(c.Id, out var ws))
- {
- ws.SyncBodyPoseOnly(new Vector3(c.X, c.Y, c.Z), Quaternion.Normalize(q), view.Mass[lane]);
- }
+ _contenderWalkers.TryGetValue(c.Id, out var ws);
+ SyncContenderPoseFromLane(c, view, lane, ws);
float stepDist = MathF.Sqrt((c.X - prevX) * (c.X - prevX) + (c.Z - prevZ) * (c.Z - prevZ));
float groundY = State.Terrain.SampleHeight(c.X, c.Z);
@@ -1433,128 +1639,187 @@ namespace RustToDust.Ymir
}
}
- private void UpdatePlayerDetectionMemory()
+ private void UpdateObserverDetectionMemories()
{
- var p = State.Player;
- if (!p.Alive)
+ for (int h = 0; h < State.Contenders.Count; h++)
{
- State.PlayerDetectedByCount = 0;
- return;
- }
-
- float pEyeY = MatchRules.GetObserverEyeY(p.Y, p.Grid.Spec.HalfHeight);
- float pTargetY = MatchRules.GetTargetAimY(p.Y, p.Grid.Spec.HalfHeight);
- int detectedBy = 0;
-
- for (int i = 0; i < State.Contenders.Count; i++)
- {
- var c = State.Contenders[i];
- if (c.IsPlayer)
+ var obs = State.Contenders[h];
+ if (!obs.IsHuman && !State.ObserverStates.ContainsKey(obs.Id))
{
continue;
}
- var mem = State.GetOrCreateContenderContact(c.Id);
- if (!c.Alive)
+ var memState = State.GetOrCreateObserverState(obs.Id);
+ if (!obs.Alive)
{
- mem.VisibleToPlayer = false;
- mem.FaintHorizonPing = false;
- mem.LastSeenAge = float.PositiveInfinity;
+ memState.DetectedByCount = 0;
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ _contenderPvs[obs.Id, i] = i == obs.Id;
+ }
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ {
+ _spectatorPvs[obs.Id, i] = false;
+ }
continue;
}
- float dxC = c.X - p.X;
- float dzC = c.Z - p.Z;
- float distSqC = dxC * dxC + dzC * dzC;
+ float pEyeY = MatchRules.GetObserverEyeY(obs.Y, obs.Grid.Spec.HalfHeight);
+ float pTargetY = MatchRules.GetTargetAimY(obs.Y, obs.Grid.Spec.HalfHeight);
+ int detectedBy = 0;
- bool playerSees = HasLineOfSight(
- p.X, pEyeY, p.Z,
- c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z);
-
- if (playerSees)
+ for (int i = 0; i < State.Contenders.Count; i++)
{
- mem.VisibleToPlayer = true;
- mem.FaintHorizonPing = false;
- mem.LastSeenAge = 0f;
- mem.LastSeenX = c.X;
- mem.LastSeenZ = c.Z;
- mem.HasEverBeenSeen = true;
- }
- else
- {
- mem.VisibleToPlayer = false;
- mem.FaintHorizonPing = false;
- if (mem.HasEverBeenSeen)
+ var c = State.Contenders[i];
+ if (c.Id == obs.Id)
{
- mem.LastSeenAge += FixedDt;
+ _contenderPvs[obs.Id, i] = true;
+ continue;
+ }
+
+ var mem = memState.GetOrCreateContenderContact(c.Id);
+ if (!c.Alive)
+ {
+ mem.VisibleToPlayer = false;
+ mem.FaintHorizonPing = false;
+ mem.LastSeenAge = float.PositiveInfinity;
+ _contenderPvs[obs.Id, i] = false;
+ continue;
+ }
+
+ float dxC = c.X - obs.X;
+ float dzC = c.Z - obs.Z;
+ float distSqC = dxC * dxC + dzC * dzC;
+
+ bool obsSees = HasLineOfSight(
+ obs.X, pEyeY, obs.Z,
+ c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z);
+
+ if (obsSees)
+ {
+ mem.VisibleToPlayer = true;
+ mem.FaintHorizonPing = false;
+ mem.LastSeenAge = 0f;
+ mem.LastSeenX = c.X;
+ mem.LastSeenZ = c.Z;
+ mem.HasEverBeenSeen = true;
+ }
+ else
+ {
+ mem.VisibleToPlayer = false;
+ mem.FaintHorizonPing = false;
+ if (mem.HasEverBeenSeen)
+ {
+ mem.LastSeenAge += FixedDt;
+ }
+ }
+
+ _contenderPvs[obs.Id, i] = obsSees || ComputeConservativePvs(obs, pEyeY, c.X, c.Y, c.Z, c.Grid.Spec, distSqC);
+
+ if (distSqC <= 240f * 240f &&
+ HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, obs.X, pTargetY, obs.Z))
+ {
+ detectedBy++;
}
}
- if (distSqC <= 240f * 240f &&
- HasLineOfSight(c.X, MatchRules.GetObserverEyeY(c.Y, c.Grid.Spec.HalfHeight), c.Z, p.X, pTargetY, p.Z))
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
{
- detectedBy++;
- }
- }
+ var s = State.Spectators.Spectators[i];
+ var mem = memState.GetOrCreateSpectatorContact(s.Id);
+ if (!s.Alive)
+ {
+ mem.VisibleToPlayer = false;
+ mem.FaintHorizonPing = false;
+ mem.LastSeenAge = float.PositiveInfinity;
+ _spectatorPvs[obs.Id, i] = false;
+ continue;
+ }
- for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ float sdx = s.X - obs.X;
+ float sdz = s.Z - obs.Z;
+ float sDistSq = sdx * sdx + sdz * sdz;
+
+ bool obsSees = HasLineOfSight(
+ obs.X, pEyeY, obs.Z,
+ s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z);
+
+ if (obsSees)
+ {
+ mem.VisibleToPlayer = true;
+ mem.FaintHorizonPing = false;
+ mem.LastSeenAge = 0f;
+ mem.LastSeenX = s.X;
+ mem.LastSeenZ = s.Z;
+ mem.HasEverBeenSeen = true;
+ }
+ else
+ {
+ mem.VisibleToPlayer = false;
+ if (mem.HasEverBeenSeen)
+ {
+ mem.LastSeenAge += FixedDt;
+ }
+
+ bool horizonPing = false;
+ if (s.RadarSignature >= 0.9f && sDistSq <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange)
+ {
+ horizonPing = HasLineOfSight(
+ obs.X, pEyeY + 14f, obs.Z,
+ s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z);
+ }
+ mem.FaintHorizonPing = horizonPing;
+ }
+
+ _spectatorPvs[obs.Id, i] = obsSees || ComputeConservativePvs(obs, pEyeY, s.X, s.Y, s.Z, s.Grid.Spec, sDistSq);
+
+ if (s.Stance != SpectatorStance.Neutral &&
+ s.TargetContenderId == obs.Id &&
+ s.HasTargetLos)
+ {
+ detectedBy++;
+ }
+ }
+
+ memState.DetectedByCount = detectedBy;
+ }
+ }
+
+ private bool ComputeConservativePvs(
+ ContenderState obs,
+ float obsEyeY,
+ float tx,
+ float ty,
+ float tz,
+ ChassisSpec targetSpec,
+ float distSq)
+ {
+ if (distSq <= 65f * 65f)
{
- var s = State.Spectators.Spectators[i];
- var mem = State.GetOrCreateSpectatorContact(s.Id);
- if (!s.Alive)
+ return true;
+ }
+
+ float aimY = MatchRules.GetTargetAimY(ty, targetSpec.HalfHeight);
+ if (HasLineOfSight(obs.X, obsEyeY + 1.0f, obs.Z, tx, aimY, tz))
+ {
+ return true;
+ }
+
+ float dx = tx - obs.X;
+ float dz = tz - obs.Z;
+ float len = MathF.Sqrt(dx * dx + dz * dz);
+ if (len > 1f)
+ {
+ float sideX = (-dz / len) * MathF.Max(1.0f, targetSpec.HalfWidth * 0.85f);
+ float sideZ = (dx / len) * MathF.Max(1.0f, targetSpec.HalfWidth * 0.85f);
+ if (HasLineOfSight(obs.X, obsEyeY, obs.Z, tx + sideX, aimY, tz + sideZ) ||
+ HasLineOfSight(obs.X, obsEyeY, obs.Z, tx - sideX, aimY, tz - sideZ))
{
- mem.VisibleToPlayer = false;
- mem.FaintHorizonPing = false;
- mem.LastSeenAge = float.PositiveInfinity;
- continue;
- }
-
- float sdx = s.X - p.X;
- float sdz = s.Z - p.Z;
- float sDistSq = sdx * sdx + sdz * sdz;
-
- bool playerSees = HasLineOfSight(
- p.X, pEyeY, p.Z,
- s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z);
-
- if (playerSees)
- {
- mem.VisibleToPlayer = true;
- mem.FaintHorizonPing = false;
- mem.LastSeenAge = 0f;
- mem.LastSeenX = s.X;
- mem.LastSeenZ = s.Z;
- mem.HasEverBeenSeen = true;
- }
- else
- {
- mem.VisibleToPlayer = false;
- if (mem.HasEverBeenSeen)
- {
- mem.LastSeenAge += FixedDt;
- }
-
- // Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range;
- // low-signature Exemplars vanish completely when terrain-occluded.
- bool horizonPing = false;
- if (s.RadarSignature >= 0.9f && sDistSq <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange)
- {
- horizonPing = HasLineOfSight(
- p.X, pEyeY + 14f, p.Z,
- s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z);
- }
- mem.FaintHorizonPing = horizonPing;
- }
-
- if (s.Stance != SpectatorStance.Neutral &&
- s.TargetContenderId == p.Id &&
- s.HasTargetLos)
- {
- detectedBy++;
+ return true;
}
}
- State.PlayerDetectedByCount = detectedBy;
+ return false;
}
private void StepThermalAndCooldowns()
@@ -1582,14 +1847,18 @@ namespace RustToDust.Ymir
}
}
+ c.MaxThermalRatio = c.Grid.ComputeMaxThermalRatio();
+
if (anyOverheat && !c.OverheatWarned)
{
c.OverheatWarned = true;
State.Broadcast.EmitOverheat(State.Time, c.Id);
+ _stepEvents.Add(new OverheatAlertEvent { ContenderId = c.Id, IsOverheating = true });
}
- else if (!anyOverheat)
+ else if (!anyOverheat && c.OverheatWarned)
{
c.OverheatWarned = false;
+ _stepEvents.Add(new OverheatAlertEvent { ContenderId = c.Id, IsOverheating = false });
}
}
@@ -1632,7 +1901,7 @@ namespace RustToDust.Ymir
view.RotationW[lane]);
ulong shooterStableId = ContenderStableIdBase + (ulong)c.Id;
- if (c.IsPlayer)
+ if (c.IsHuman)
{
UpdateWeaponArcTelemetry(c, shooterQuat, shooterStableId);
}
@@ -1651,7 +1920,7 @@ namespace RustToDust.Ymir
aimX: c.AimX,
aimY: c.AimY,
aimZ: c.AimZ,
- extraSpread: c.IsPlayer ? 0f : c.AiAimSpreadRad,
+ extraSpread: c.IsHuman ? 0f : c.AiAimSpreadRad,
view: view);
}
@@ -2025,13 +2294,17 @@ namespace RustToDust.Ymir
out float tx, out float ty, out float tz, out float terrainDist);
Vector3 endPt;
+ int shooterEntityId = isSpectatorShooter
+ ? (int)(shooterStableId - SpectatorStableIdBase)
+ : (shooterContender?.Id ?? -1);
if (hitTerrain && terrainDist < boxDist)
{
endPt = new Vector3(tx, ty, tz);
StampTerrainWeaponImpact(mod.Spec.Id, tx, tz, burstIndex: b);
var (tnx, tny, tnz) = State.Terrain.SampleNormal(tx, tz);
+ long hitId = State.AllocateHitEventId();
State.HitEvents.Add(new HitFeedbackEvent(
- EventId: State.AllocateHitEventId(),
+ EventId: hitId,
HitX: tx,
HitY: ty,
HitZ: tz,
@@ -2049,6 +2322,20 @@ namespace RustToDust.Ymir
WeaponId: mod.Spec.Id,
IsAirburst: false,
Ttl: 0.35f));
+ _stepEvents.Add(new HitImpactEvent
+ {
+ EventId = hitId,
+ HitX = tx, HitY = ty, HitZ = tz,
+ NormalX = tnx, NormalY = tny, NormalZ = tnz,
+ SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z,
+ TargetKind = (byte)HitTargetKind.Terrain,
+ TargetId = -1,
+ WeaponClass = (byte)weaponClass,
+ WeaponId = mod.Spec.Id,
+ Ttl = 0.35f,
+ ShooterId = shooterEntityId,
+ IsContenderShooter = !isSpectatorShooter
+ });
}
else
{
@@ -2071,14 +2358,16 @@ namespace RustToDust.Ymir
shooterContender,
shooterLabel,
isSpectatorShooter,
+ shooterEntityId,
view);
}
else if (hitAny && hitStableId != shooterStableId)
{
// Static cover box hit
Vector3 rev = -dir;
+ long hitId = State.AllocateHitEventId();
State.HitEvents.Add(new HitFeedbackEvent(
- EventId: State.AllocateHitEventId(),
+ EventId: hitId,
HitX: endPt.X,
HitY: endPt.Y,
HitZ: endPt.Z,
@@ -2096,13 +2385,29 @@ namespace RustToDust.Ymir
WeaponId: mod.Spec.Id,
IsAirburst: isPdFlak,
Ttl: 0.35f));
+ _stepEvents.Add(new HitImpactEvent
+ {
+ EventId = hitId,
+ HitX = endPt.X, HitY = endPt.Y, HitZ = endPt.Z,
+ NormalX = rev.X, NormalY = rev.Y, NormalZ = rev.Z,
+ SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z,
+ TargetKind = (byte)HitTargetKind.StaticCover,
+ TargetId = (int)hitStableId,
+ WeaponClass = (byte)weaponClass,
+ WeaponId = mod.Spec.Id,
+ IsAirburst = isPdFlak,
+ Ttl = 0.35f,
+ ShooterId = shooterEntityId,
+ IsContenderShooter = !isSpectatorShooter
+ });
}
else if (isPdFlak && b == 0)
{
Vector3 airPt = muzzle + dir * MathF.Min(range, MathF.Max(20f, aimDelta.Length()));
Vector3 rev = -dir;
+ long hitId = State.AllocateHitEventId();
State.HitEvents.Add(new HitFeedbackEvent(
- EventId: State.AllocateHitEventId(),
+ EventId: hitId,
HitX: airPt.X,
HitY: airPt.Y,
HitZ: airPt.Z,
@@ -2120,9 +2425,25 @@ namespace RustToDust.Ymir
WeaponId: mod.Spec.Id,
IsAirburst: true,
Ttl: 0.35f));
+ _stepEvents.Add(new HitImpactEvent
+ {
+ EventId = hitId,
+ HitX = airPt.X, HitY = airPt.Y, HitZ = airPt.Z,
+ NormalX = rev.X, NormalY = rev.Y, NormalZ = rev.Z,
+ SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z,
+ TargetKind = (byte)HitTargetKind.StaticCover,
+ TargetId = -1,
+ WeaponClass = (byte)weaponClass,
+ WeaponId = mod.Spec.Id,
+ IsAirburst = true,
+ Ttl = 0.35f,
+ ShooterId = shooterEntityId,
+ IsContenderShooter = !isSpectatorShooter
+ });
}
}
+ int tracerId = State.AllocateTracerId();
State.Tracers.Add(new TracerEvent(
muzzle.X, muzzle.Y, muzzle.Z,
endPt.X, endPt.Y, endPt.Z,
@@ -2130,7 +2451,19 @@ namespace RustToDust.Ymir
tracerTtl,
weaponClass,
mod.Spec.Id,
- State.AllocateTracerId()));
+ tracerId));
+ _stepEvents.Add(new ShotFiredEvent
+ {
+ TracerId = tracerId,
+ IsSpectatorShooter = isSpectatorShooter,
+ ShooterId = shooterEntityId,
+ StartX = muzzle.X, StartY = muzzle.Y, StartZ = muzzle.Z,
+ EndX = endPt.X, EndY = endPt.Y, EndZ = endPt.Z,
+ ColorRgba = tracerColor,
+ Ttl = tracerTtl,
+ WeaponClass = (byte)weaponClass,
+ WeaponId = mod.Spec.Id
+ });
}
shooterGrid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput);
@@ -2164,6 +2497,7 @@ namespace RustToDust.Ymir
ContenderState? shooterContender,
string shooterLabel,
bool isSpectatorShooter,
+ int shooterEntityId,
Box3DSoaView view)
{
if (targetRef.IsContender)
@@ -2177,8 +2511,10 @@ namespace RustToDust.Ymir
var (localRight, localForward, localHeightNorm) = ComputeLocalHitCoords(hitPoint, body.Lane, target.Grid.Spec, view);
Vector3 hitNormal = ComputeBoxFaceNormal(hitPoint, body.Lane, target.Grid.Spec, view, -shotDir);
var result = target.Grid.ApplyHit(localRight, localForward, localHeightNorm, damage, heatTransfer);
+ target.DamageVersion++;
+ long hitId = State.AllocateHitEventId();
State.HitEvents.Add(new HitFeedbackEvent(
- EventId: State.AllocateHitEventId(),
+ EventId: hitId,
HitX: hitPoint.X,
HitY: hitPoint.Y,
HitZ: hitPoint.Z,
@@ -2197,9 +2533,34 @@ namespace RustToDust.Ymir
IsAirburst: isPdFlak && target.Grid.Spec.IsVtol,
Ttl: 0.35f));
+ _stepEvents.Add(new HitImpactEvent
+ {
+ EventId = hitId,
+ HitX = hitPoint.X, HitY = hitPoint.Y, HitZ = hitPoint.Z,
+ NormalX = hitNormal.X, NormalY = hitNormal.Y, NormalZ = hitNormal.Z,
+ SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z,
+ TargetKind = (byte)HitTargetKind.Contender,
+ TargetId = target.Id,
+ CellX = result.CellX,
+ CellY = result.CellY,
+ WeaponClass = (byte)weaponClass,
+ WeaponId = weaponId,
+ IsAirburst = isPdFlak && target.Grid.Spec.IsVtol,
+ Ttl = 0.35f,
+ NewCellArmor = target.Grid.Armor[result.CellX, result.CellY],
+ NewCellTemp = target.Grid.Temperature[result.CellX, result.CellY],
+ NewCoreHp = target.Grid.CoreHp,
+ HitSequence = target.Grid.HitSequence,
+ ShooterId = shooterEntityId,
+ IsContenderShooter = !isSpectatorShooter,
+ ArmorDamage = result.ArmorDamage,
+ CoreDamage = result.CoreDamage,
+ Killed = result.CoreDestroyed
+ });
+
if (result.CoreDestroyed)
{
- HandleContenderEliminated(target, shooterContender, shooterLabel, isSpectatorShooter);
+ HandleContenderEliminated(target, shooterContender, shooterEntityId, shooterLabel, isSpectatorShooter);
}
}
else
@@ -2236,8 +2597,9 @@ namespace RustToDust.Ymir
var (localRight, localForward, localHeightNorm) = ComputeLocalHitCoords(hitPoint, body.Lane, spec.Grid.Spec, view);
Vector3 hitNormal = ComputeBoxFaceNormal(hitPoint, body.Lane, spec.Grid.Spec, view, -shotDir);
var result = spec.Grid.ApplyHit(localRight, localForward, localHeightNorm, damage, heatTransfer);
+ long hitId = State.AllocateHitEventId();
State.HitEvents.Add(new HitFeedbackEvent(
- EventId: State.AllocateHitEventId(),
+ EventId: hitId,
HitX: hitPoint.X,
HitY: hitPoint.Y,
HitZ: hitPoint.Z,
@@ -2256,6 +2618,31 @@ namespace RustToDust.Ymir
IsAirburst: isPdFlak && spec.Grid.Spec.IsVtol,
Ttl: 0.35f));
+ _stepEvents.Add(new HitImpactEvent
+ {
+ EventId = hitId,
+ HitX = hitPoint.X, HitY = hitPoint.Y, HitZ = hitPoint.Z,
+ NormalX = hitNormal.X, NormalY = hitNormal.Y, NormalZ = hitNormal.Z,
+ SourceX = shooterPos.X, SourceY = shooterPos.Y, SourceZ = shooterPos.Z,
+ TargetKind = (byte)HitTargetKind.Spectator,
+ TargetId = spec.Id,
+ CellX = result.CellX,
+ CellY = result.CellY,
+ WeaponClass = (byte)weaponClass,
+ WeaponId = weaponId,
+ IsAirburst = isPdFlak && spec.Grid.Spec.IsVtol,
+ Ttl = 0.35f,
+ NewCellArmor = spec.Grid.Armor[result.CellX, result.CellY],
+ NewCellTemp = spec.Grid.Temperature[result.CellX, result.CellY],
+ NewCoreHp = spec.Grid.CoreHp,
+ HitSequence = spec.Grid.HitSequence,
+ ShooterId = shooterEntityId,
+ IsContenderShooter = !isSpectatorShooter,
+ ArmorDamage = result.ArmorDamage,
+ CoreDamage = result.CoreDamage,
+ Killed = result.CoreDestroyed
+ });
+
if (result.CoreDestroyed)
{
HandleSpectatorDestroyed(spec, shooterContender, shooterLabel);
@@ -2266,6 +2653,7 @@ namespace RustToDust.Ymir
private void HandleContenderEliminated(
ContenderState victim,
ContenderState? shooterContender,
+ int shooterEntityId,
string shooterLabel,
bool isSpectatorShooter)
{
@@ -2289,6 +2677,15 @@ namespace RustToDust.Ymir
State.Terrain.StampCrater(victim.X, victim.Z, radius: 5.2f, depth: 1.3f);
State.Terrain.StampScorch(victim.X, victim.Z, radius: 6.2f);
+ _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f });
+ _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f });
+ _stepEvents.Add(new ContenderEliminatedEvent
+ {
+ VictimId = victim.Id,
+ KillerId = shooterEntityId,
+ IsSpectatorKiller = isSpectatorShooter,
+ KillerKills = shooterContender?.Kills ?? 0
+ });
State.Broadcast.EmitElimination(State.Time, shooterLabel, victim.Name, isSpectatorShooter);
}
@@ -2314,6 +2711,14 @@ namespace RustToDust.Ymir
State.Terrain.StampCrater(spec.X, spec.Z, radius: 4.5f, depth: 1.1f);
State.Terrain.StampScorch(spec.X, spec.Z, radius: 5.4f);
+ _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f });
+ _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f });
+ _stepEvents.Add(new SpectatorDestroyedEvent
+ {
+ SpectatorId = spec.Id,
+ KillerContenderId = shooterContender?.Id ?? -1,
+ KillerKills = shooterContender?.Kills ?? 0
+ });
State.Broadcast.EmitElimination(State.Time, shooterLabel, $"{spec.Tier} Spectator", false);
}
@@ -2324,11 +2729,14 @@ namespace RustToDust.Ymir
case "recoilless":
State.Terrain.StampCrater(x, z, radius: 4.2f, depth: 1.05f);
State.Terrain.StampScorch(x, z, radius: 4.5f);
+ _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = x, Z = z, Radius = 4.2f, Depth = 1.05f });
+ _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = x, Z = z, Radius = 4.5f });
break;
case "flak":
if (burstIndex == 0)
{
State.Terrain.StampCrater(x, z, radius: 2.0f, depth: 0.35f);
+ _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = x, Z = z, Radius = 2.0f, Depth = 0.35f });
}
break;
}
@@ -2440,6 +2848,10 @@ namespace RustToDust.Ymir
}
_disposed = true;
State.ChassisSwapped -= OnContenderChassisSwapped;
+ State.LoadoutChanged -= OnContenderLoadoutChanged;
+ State.DropSpawned -= OnDropSpawned;
+ State.DropPickedUp -= OnDropPickedUp;
+ State.Broadcast.LineEmitted -= OnBroadcastLineEmitted;
_world.Dispose();
}
}
diff --git a/src/RustToDust.Ymir/LocalArenaSession.cs b/src/RustToDust.Ymir/LocalArenaSession.cs
new file mode 100644
index 0000000..242be7c
--- /dev/null
+++ b/src/RustToDust.Ymir/LocalArenaSession.cs
@@ -0,0 +1,101 @@
+using System;
+using System.Collections.Generic;
+using System.Numerics;
+using RustToDust.Core;
+
+namespace RustToDust.Ymir
+{
+ public sealed class LocalArenaSession : IClientArenaSession
+ {
+ private readonly List _discardEvents = new();
+
+ public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null)
+ {
+ Inner = new ArenaSession(seed, mapKind, slot0Human: true);
+ if (!string.IsNullOrWhiteSpace(callsign))
+ {
+ Inner.SetHumanSlot(0, true, callsign);
+ }
+ }
+
+ public ArenaSession Inner { get; private set; }
+ public MatchState ViewState => Inner.State;
+ public int LocalContenderId => 0;
+ public ContenderState LocalContender => Inner.State.Contenders[0];
+
+ public ClientMatchOutcome LocalOutcome =>
+ Inner.State.Phase == MatchPhase.Active
+ ? (LocalContender.Alive ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
+ : (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
+
+ public int LocalDetectedByCount =>
+ Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.DetectedByCount : 0;
+
+ public IReadOnlyDictionary LocalContenderContacts =>
+ Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.ContenderContacts : Inner.State.EmptyContacts;
+
+ public IReadOnlyDictionary LocalSpectatorContacts =>
+ Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.SpectatorContacts : Inner.State.EmptyContacts;
+
+ public NetworkStatusSnapshot ConnectionStatus =>
+ new(NetworkMode.Solo, Connected: true, PingMs: 0, ConnectedHumans: 1, MaxHumans: 1, StateLabel: "SOLO");
+
+ public bool IsContenderVisible(int contenderId) => true;
+ public bool IsSpectatorVisible(int spectatorId) => true;
+
+ public void BeginRenderFrame(double dt, float physicsAlpha)
+ {
+ }
+
+ public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick)
+ {
+ if (!isPhysicsTick)
+ {
+ return;
+ }
+ Inner.SetHumanInput(0, input);
+ Inner.Step();
+ _discardEvents.Clear();
+ Inner.DrainStepEvents(_discardEvents);
+ }
+
+ public bool RequestEquipCargo(int cargoIndex, string hardpointId) =>
+ Inner.TryEquipCargo(0, cargoIndex, hardpointId);
+
+ public void RequestNewMatch(int seed, ArenaMapKind mapKind)
+ {
+ string? name = LocalContender.Name;
+ Inner.Dispose();
+ Inner = new ArenaSession(seed, mapKind, slot0Human: true);
+ if (!string.IsNullOrWhiteSpace(name))
+ {
+ Inner.SetHumanSlot(0, true, name);
+ }
+ }
+
+ public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) =>
+ Inner.GetInterpolatedContenderPose(contenderId, alpha);
+
+ public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedSpectatorPose(int spectatorId, float alpha) =>
+ Inner.GetInterpolatedSpectatorPose(spectatorId, alpha);
+
+ public bool TrySampleInterpolatedWalkerPose(bool isContender, int id, float alpha, out WalkerVisualSnapshot snap) =>
+ Inner.TrySampleInterpolatedWalkerPose(isContender, id, alpha, out snap);
+
+ public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
+ {
+ var hit = Inner.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
+ return new ClientRayHit(
+ hit.Hit,
+ hit.StableId,
+ new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z),
+ new Vector3(hit.Normal.X, hit.Normal.Y, hit.Normal.Z),
+ hit.Fraction);
+ }
+
+ public void Dispose()
+ {
+ Inner.Dispose();
+ }
+ }
+}
diff --git a/src/RustToDust.Ymir/WalkerLocomotion.cs b/src/RustToDust.Ymir/WalkerLocomotion.cs
index d23cdc9..6707d0b 100644
--- a/src/RustToDust.Ymir/WalkerLocomotion.cs
+++ b/src/RustToDust.Ymir/WalkerLocomotion.cs
@@ -6,12 +6,6 @@ using Ymir.Box3D;
namespace RustToDust.Ymir
{
- [InlineArray(4)]
- public struct LegArray4
- {
- private T _element0;
- }
-
public readonly struct WalkerLegSpec
{
public WalkerLegSpec(
@@ -193,67 +187,6 @@ namespace RustToDust.Ymir
}
}
- public struct WalkerLegAngles
- {
- public float HipPitch;
- public float HipRoll;
- public float KneeFlex;
- public float HockFlex;
- public float AnklePitch;
-
- public static WalkerLegAngles Lerp(in WalkerLegAngles a, in WalkerLegAngles b, float t) => new()
- {
- HipPitch = a.HipPitch + (b.HipPitch - a.HipPitch) * t,
- HipRoll = a.HipRoll + (b.HipRoll - a.HipRoll) * t,
- KneeFlex = a.KneeFlex + (b.KneeFlex - a.KneeFlex) * t,
- HockFlex = a.HockFlex + (b.HockFlex - a.HockFlex) * t,
- AnklePitch = a.AnklePitch + (b.AnklePitch - a.AnklePitch) * t
- };
- }
-
- public struct WalkerVisualSnapshot
- {
- public int LegCount;
- public float GeomScale;
- public bool IsDigitigrade;
- public bool IsArachnidUp;
- public Vector3 ComPos;
- public Quaternion ComRot;
- public LegArray4 LegAngles;
- public LegArray4 FootNormal;
- public LegArray4 LoadG;
-
- public static WalkerVisualSnapshot Interpolate(in WalkerVisualSnapshot prev, in WalkerVisualSnapshot curr, float alpha)
- {
- float t = Math.Clamp(alpha, 0f, 1f);
- Quaternion q0 = prev.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(prev.ComRot);
- Quaternion q1 = curr.ComRot.LengthSquared() < 1e-6f ? Quaternion.Identity : Quaternion.Normalize(curr.ComRot);
- if (Quaternion.Dot(q0, q1) < 0f)
- {
- q1 = -q1;
- }
-
- WalkerVisualSnapshot res = new()
- {
- LegCount = curr.LegCount,
- GeomScale = curr.GeomScale,
- IsDigitigrade = curr.IsDigitigrade,
- IsArachnidUp = curr.IsArachnidUp,
- ComPos = Vector3.Lerp(prev.ComPos, curr.ComPos, t),
- ComRot = Quaternion.Slerp(q0, q1, t)
- };
-
- for (int i = 0; i < curr.LegCount; i++)
- {
- res.LegAngles[i] = WalkerLegAngles.Lerp(prev.LegAngles[i], curr.LegAngles[i], t);
- Vector3 n = Vector3.Lerp(prev.FootNormal[i], curr.FootNormal[i], t);
- res.FootNormal[i] = n.LengthSquared() > 1e-6f ? Vector3.Normalize(n) : Vector3.UnitY;
- res.LoadG[i] = prev.LoadG[i] + (curr.LoadG[i] - prev.LoadG[i]) * t;
- }
- return res;
- }
- }
-
public struct WalkerJointActuator
{
public WalkerLegAngles Theta;
diff --git a/tests/RustToDust.Tests/ArenaSessionTests.cs b/tests/RustToDust.Tests/ArenaSessionTests.cs
index 0f4dbd1..4fb51df 100644
--- a/tests/RustToDust.Tests/ArenaSessionTests.cs
+++ b/tests/RustToDust.Tests/ArenaSessionTests.cs
@@ -11,8 +11,8 @@ namespace RustToDust.Tests
[Fact]
public void DrivingAndFiring_MovesBuggyInYmirAndBuildsWeaponHeat()
{
- using var session = new ArenaSession(seed: 42);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
+ var player = session.State.Contenders[0];
float startX = player.X;
float startZ = player.Z;
float startYaw = player.Yaw;
@@ -20,7 +20,7 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 120; tick++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: 0.45f,
AimWorldX: player.X + 40f,
@@ -28,6 +28,7 @@ namespace RustToDust.Tests
Fire: true,
InteractPickup: false,
Brake: false));
+ session.Step();
if (session.State.Tracers.Count > 0)
{
@@ -52,30 +53,30 @@ namespace RustToDust.Tests
[Fact]
public void ChassisSwap_ToManticoreAndRaptor_ReplacesBodyWithoutLeakingYmirLanes()
{
- using var session = new ArenaSession(seed: 77);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 77, slot0Human: true);
+ var player = session.State.Contenders[0];
int initialFreeSlots = session.World.FreeBodySlots;
// Step once to settle world
- session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false));
+ session.Step();
// Spawn Manticore (Dorsal) right beside player and swap
session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Manticore);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal("manticore", player.Grid.Spec.Id);
Assert.Equal(GridPlane.Dorsal, player.Grid.Spec.Plane);
// Step so Ymir reclaims old tombstone lane
- session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false));
+ session.Step();
Assert.Equal(initialFreeSlots, session.World.FreeBodySlots);
// Now spawn Raptor (Coronal) beside player and swap
session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Raptor);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal("raptor", player.Grid.Spec.Id);
Assert.Equal(GridPlane.Coronal, player.Grid.Spec.Plane);
- session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false));
+ session.Step();
Assert.Equal(initialFreeSlots, session.World.FreeBodySlots);
}
@@ -101,20 +102,21 @@ namespace RustToDust.Tests
[Fact]
public void BroadsideFire_UsesDirectionalSupportRadiusNotMaxExtent()
{
- using var session = new ArenaSession(seed: 19);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 19, slot0Human: true);
+ var player = session.State.Contenders[0];
// Swap to Tank / Anvil (HalfWidth = 1.93m, HalfLength = 2.83m) where broadside vs forward differs by ~0.9m.
session.State.SpawnChassisDrop(player.X + 0.5f, player.Z + 0.5f, Catalog.Tank);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(Catalog.Tank.Id, player.Grid.Spec.Id);
// Step once to settle body, then aim strictly perpendicular (broadside) to player's Yaw.
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, false));
+ session.Step();
float broadsideX = MathF.Cos(player.Yaw);
float broadsideZ = -MathF.Sin(player.Yaw);
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: player.X + broadsideX * 30f,
@@ -122,6 +124,7 @@ namespace RustToDust.Tests
Fire: true,
InteractPickup: false,
Brake: true));
+ session.Step();
Assert.NotEmpty(session.State.Tracers);
var tracer = session.State.Tracers[^1];
@@ -136,15 +139,16 @@ namespace RustToDust.Tests
[Fact]
public void TracerEvent_AssignsMonotonicId_AndPreservesAcrossAdvance()
{
- using var session = new ArenaSession(seed: 19);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 19, slot0Human: true);
+ var player = session.State.Contenders[0];
float aimX = player.X + MathF.Sin(player.Yaw) * 25f;
float aimZ = player.Z + MathF.Cos(player.Yaw) * 25f;
var ids = new List();
for (int tick = 0; tick < 30 && ids.Count < 2; tick++)
{
- session.Step(new PlayerInput(0f, 0f, aimX, aimZ, Fire: true, InteractPickup: false, Brake: true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, aimX, aimZ, Fire: true, InteractPickup: false, Brake: true));
+ session.Step();
foreach (var t in session.State.Tracers)
{
if (!ids.Contains(t.Id))
diff --git a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs
new file mode 100644
index 0000000..6f1dd60
--- /dev/null
+++ b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs
@@ -0,0 +1,357 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Numerics;
+using System.Threading;
+using GameCult.Mesh;
+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);
+
+ _output.WriteLine($"Max wire bytes: Packet1={w1.Length}B, Packet2={w2.Length}B, Packet3={w3.Length}B, Input={wIn.Length}B");
+
+ Assert.True(w1.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet1 {w1.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
+ Assert.True(w2.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet2 {w2.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
+ Assert.True(w3.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Packet3 {w3.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B");
+ Assert.True(wIn.Length <= SnapshotCodec.MaxLatestDatagramBytes, $"Input {wIn.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);
+ }
+
+ 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();
+ }
+ }
+}
diff --git a/tests/RustToDust.Tests/DetectionLosTests.cs b/tests/RustToDust.Tests/DetectionLosTests.cs
index 485d7b4..9bc5c4b 100644
--- a/tests/RustToDust.Tests/DetectionLosTests.cs
+++ b/tests/RustToDust.Tests/DetectionLosTests.cs
@@ -25,9 +25,9 @@ namespace RustToDust.Tests
[Fact]
public void MesaBetweenSpectatorAndContender_BlocksLosAndPreventsFiringThroughTerrain()
{
- using var session = new ArenaSession(seed: 42);
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
var mesa = FindTallMesa(session.State.Terrain);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron);
// Place player and spectator on opposite sides of the tall mesa
@@ -42,7 +42,8 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 10; tick++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.False(session.HasLineOfSight(
spec.X, MatchRules.GetObserverEyeY(spec.Y, spec.Grid.Spec.HalfHeight), spec.Z,
@@ -59,9 +60,9 @@ namespace RustToDust.Tests
[Fact]
public void CrestingRidge_RestoresLosAndAllowsSpectatorEngagement()
{
- using var session = new ArenaSession(seed: 42);
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
var mesa = FindTallMesa(session.State.Terrain);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var spec = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Patron);
// Start occluded across the mesa
@@ -69,7 +70,8 @@ namespace RustToDust.Tests
session.SetSpectatorPose(spec.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z);
session.State.Spectators.OnSpectatorDamaged(spec, player.Id);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.False(spec.HasTargetLos);
// Now player crests onto the high mesa plateau overlooking the spectator
@@ -79,7 +81,8 @@ namespace RustToDust.Tests
bool sawTracer = false;
for (int tick = 0; tick < 30; tick++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
if (session.State.Tracers.Count > 0)
{
sawTracer = true;
@@ -95,30 +98,32 @@ namespace RustToDust.Tests
[Fact]
public void LowSignatureExemplar_HiddenBehindRidge_IsInvisibleOnRadar_WhileInLosContactIsVisible()
{
- using var session = new ArenaSession(seed: 42);
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
var mesa = FindTallMesa(session.State.Terrain);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar);
var visibleRival = session.State.Contenders[1];
Assert.True(exemplar.RadarSignature <= 0.25f);
// Reset memory so exemplar has never been seen yet, then hide it on the far side of the mesa
- session.State.SpectatorContacts[exemplar.Id] = new PlayerContactMemory();
+ var obs0 = session.State.GetOrCreateObserverState(0);
+ obs0.SpectatorContacts[exemplar.Id] = new PlayerContactMemory();
session.SetContenderPose(player.Id, mesa.X - mesa.RadiusX - 18f, mesa.Z);
session.SetSpectatorPose(exemplar.Id, mesa.X + mesa.RadiusX + 18f, mesa.Z);
// Place rival contender nearby in clear open LOS on the player's side of the mesa
session.SetContenderPose(visibleRival.Id, mesa.X - mesa.RadiusX - 50f, mesa.Z + 12f);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
- var exMem = session.State.SpectatorContacts[exemplar.Id];
+ var exMem = obs0.SpectatorContacts[exemplar.Id];
Assert.False(exMem.VisibleToPlayer);
Assert.False(exMem.FaintHorizonPing);
Assert.False(MatchState.IsContactOnRadar(exMem), "Hidden low-signature Exemplar must vanish off player radar");
- var rivalMem = session.State.ContenderContacts[visibleRival.Id];
+ var rivalMem = obs0.ContenderContacts[visibleRival.Id];
Assert.True(rivalMem.VisibleToPlayer, "In-LOS contact must be live-visible to player");
Assert.True(MatchState.IsContactOnRadar(rivalMem));
}
@@ -126,9 +131,9 @@ namespace RustToDust.Tests
[Fact]
public void StaticCoverWall_BlocksLineOfSight()
{
- using var session = new ArenaSession(seed: 12);
+ using var session = new ArenaSession(seed: 12, slot0Human: true);
var box = session.State.ArenaCoverBoxes[0];
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var rival = session.State.Contenders[1];
// Ensure rival is a low-profile ground vehicle shorter than the 4m ruin cover wall
@@ -208,7 +213,7 @@ namespace RustToDust.Tests
[Fact]
public void OccludedSpectators_DoNotLeakLiveTargetAfterMemoryExpires_FiveSeconds()
{
- using var session = new ArenaSession(seed: 42);
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
// Shrink safe circle so the tall mesa perimeter is outside SafeRadius
session.State.Time = 360f;
session.State.Spectators.UpdateSafeRadius(session.State.Time);
@@ -230,7 +235,7 @@ namespace RustToDust.Tests
}
Assert.True(bestMinRadius > 0f, "Expected at least one tall Mesa in generated terrain.");
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var tourists = session.State.Spectators.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList();
var provokedSpec = tourists[0];
var clearedSpec = tourists[1];
@@ -265,7 +270,8 @@ namespace RustToDust.Tests
session.SetContenderPose(player.Id, specSideX - (negIsFurther ? 12f : -12f), mesa.Z);
session.SetSpectatorPose(provokedSpec.Id, specSideX, mesa.Z);
session.State.Spectators.OnSpectatorDamaged(provokedSpec, player.Id);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.True(provokedSpec.HasTargetLos, "Expected initial LOS before player drops behind cover");
float provokedKnownX = provokedSpec.LastKnownTargetX;
@@ -277,7 +283,8 @@ namespace RustToDust.Tests
session.SetSpectatorPose(clearedSpec.Id, specSideX, mesa.Z + 4f);
// Verify clearedSpec gets Pass-2 Cleared assignment without LOS
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.False(provokedSpec.HasTargetLos);
Assert.Equal(SpectatorStance.Cleared, clearedSpec.Stance);
Assert.False(clearedSpec.HasTargetLos);
@@ -294,7 +301,8 @@ namespace RustToDust.Tests
session.SetContenderPose(player.Id, occludedX, latZ);
}
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.False(provokedSpec.HasTargetLos, $"Provoked spectator regained unexpected LOS at tick {tick}");
Assert.False(clearedSpec.HasTargetLos, $"Cleared spectator regained unexpected LOS at tick {tick}");
@@ -427,9 +435,9 @@ namespace RustToDust.Tests
[Fact]
public void AiContender_ImmediatelyDropsTrackingAndFiring_OnExactTickLosBreaks()
{
- using var session = new ArenaSession(seed: 12);
+ using var session = new ArenaSession(seed: 12, slot0Human: true);
var box = session.State.ArenaCoverBoxes[0];
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var ai = session.State.Contenders[1];
// Move other rivals far away so only ai <-> player interaction is isolated
@@ -467,7 +475,8 @@ namespace RustToDust.Tests
// Advance `phase` ticks in open LOS; open-LOS acquisition must be immediate on tick 0!
for (int t = 0; t <= phase; t++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.True(ai.FireCmd, $"Expected AI to acquire open-LOS target and fire immediately (phase={phase}, t={t})");
}
@@ -484,7 +493,8 @@ namespace RustToDust.Tests
// Move laterally behind cover to verify AI never steers/aims toward hidden coords
session.SetContenderPose(player.Id, box.X + (occTick % 2 == 0 ? 1.5f : -1.5f), box.Z + box.HalfZ + 8f, yaw: 0f);
}
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Null(ai.AiTargetContenderId);
Assert.False(ai.FireCmd, $"AI leaked FireCmd on occluded tick {occTick} (phase={phase})");
@@ -497,9 +507,9 @@ namespace RustToDust.Tests
[Fact]
public void PlayerDetectedByCount_StaysExactZero_UnderAsymmetricCover_NoFlicker()
{
- using var session = new ArenaSession(seed: 12);
+ using var session = new ArenaSession(seed: 12, slot0Human: true);
var box = session.State.ArenaCoverBoxes.First(b => b.HalfY >= 2.8f);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var rival = session.State.Contenders[1];
// Move all other rivals and spectators far away (> 500m) so only rival <-> player is tested
@@ -536,10 +546,12 @@ namespace RustToDust.Tests
// Re-pin poses each tick so drift never alters cover geometry
session.SetContenderPose(player.Id, box.X, box.Z - box.HalfZ - 4f);
session.SetContenderPose(rival.Id, box.X, box.Z + box.HalfZ + 40f);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
- Assert.True(session.State.ContenderContacts[rival.Id].VisibleToPlayer);
- Assert.Equal(0, session.State.PlayerDetectedByCount);
+ var obs0 = session.State.GetOrCreateObserverState(0);
+ Assert.True(obs0.ContenderContacts[rival.Id].VisibleToPlayer);
+ Assert.Equal(0, obs0.DetectedByCount);
}
}
diff --git a/tests/RustToDust.Tests/HybridBWalkerTests.cs b/tests/RustToDust.Tests/HybridBWalkerTests.cs
index 097cd6c..9dd4a9e 100644
--- a/tests/RustToDust.Tests/HybridBWalkerTests.cs
+++ b/tests/RustToDust.Tests/HybridBWalkerTests.cs
@@ -50,7 +50,7 @@ namespace RustToDust.Tests
// 1. Walk, turn, and climb slopes across all 7 mechs + exemplar_frame
foreach (var spec in specs)
{
- using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert);
+ using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(i, 500f + i * 16f, 500f);
@@ -59,8 +59,8 @@ namespace RustToDust.Tests
// Phase A: start on flat/gentle ground near origin (60 ticks) to verify honest walk slip < 8cm
session.SetContenderPose(0, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, spec);
- Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id}");
- var player = session.State.Player;
+ Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}");
+ var player = session.State.Contenders[0];
Assert.Equal(spec.Id, player.Grid.Spec.Id);
var ws = session.GetWalkerState(true, player.Id);
@@ -70,7 +70,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 60; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0.45f,
Steer: 0f,
AimWorldX: player.X,
@@ -78,6 +78,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
}
Assert.True(ws.MaxFootSlipM < 0.08f,
$"{spec.Id}: normal walk foot slip {ws.MaxFootSlipM:F4}m >= 0.08m (maxSpd={spec.MaxSpeed:F1})");
@@ -123,7 +124,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 180; t++)
{
float steer = MathF.Sin(t * 0.06f) * 0.65f;
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0.85f,
Steer: steer,
AimWorldX: player.X + 40f * MathF.Sin(player.Yaw),
@@ -131,6 +132,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
Assert.True(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z),
$"{spec.Id}: non-finite pose at tick {t}");
@@ -199,7 +201,7 @@ namespace RustToDust.Tests
// 2. Benchmark 12 simultaneous mechs CPU < 1.5 ms/tick
{
- using var benchSession = new ArenaSession(seed: 99, mapKind: ArenaMapKind.Desert);
+ using var benchSession = new ArenaSession(seed: 99, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 0; i < benchSession.State.Contenders.Count; i++)
{
var spec = specs[i % 7];
@@ -225,7 +227,8 @@ namespace RustToDust.Tests
// Warmup JIT
for (int w = 0; w < 20; w++)
{
- benchSession.Step(new PlayerInput(0.8f, 0.2f, 0f, 100f, false, false, false));
+ benchSession.SetHumanInput(0, new PlayerInput(0.8f, 0.2f, 0f, 100f, false, false, false));
+ benchSession.Step();
}
var view = benchSession.World.View;
@@ -261,16 +264,16 @@ namespace RustToDust.Tests
Span legIntegrities = stackalloc float[4];
foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion })
{
- using var session = new ArenaSession(seed: 17, mapKind: ArenaMapKind.Desert);
+ using var session = new ArenaSession(seed: 17, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(i, 450f + i * 16f, 450f);
}
session.SetContenderPose(0, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, spec);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var grid = player.Grid;
// Strip all left-leg cells (Breaker Coronal L: y>=H-2, x Wait 5 idle ticks to verify zero rest creep from dead stop
for (int t = 0; t < 5; t++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
+ session.Step();
}
Vector2 cmdFwd = new(MathF.Sin(yawRad), MathF.Cos(yawRad));
@@ -452,7 +458,7 @@ namespace RustToDust.Tests
Vector2 wStart = new(player.X, player.Z);
for (int t = 0; t < 120; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: 0f,
AimWorldX: player.X + cmdFwd.X * 50f,
@@ -460,6 +466,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
}
float endWSpeed = player.Speed;
Vector2 wDelta = new Vector2(player.X, player.Z) - wStart;
@@ -477,7 +484,7 @@ namespace RustToDust.Tests
Vector2 finalWindowStart = Vector2.Zero;
for (int t = 0; t < 180; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: player.X + cmdFwd.X * 50f,
@@ -485,6 +492,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
if (timeToStop < 0f && player.Speed < 0.30f)
{
@@ -515,7 +523,7 @@ namespace RustToDust.Tests
Vector2 revDir = new(MathF.Sin(player.Yaw), MathF.Cos(player.Yaw));
for (int t = 0; t < 90; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: -1f,
Steer: 0f,
AimWorldX: player.X + revDir.X * 50f,
@@ -523,6 +531,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
}
float revDisp = Vector2.Dot(new Vector2(player.X, player.Z) - sStart, -revDir);
Assert.True(revDisp >= 3.0f,
@@ -531,7 +540,8 @@ namespace RustToDust.Tests
// Settle until stopped before turning test
for (int t = 0; t < 180 && (t < 20 || player.Speed > 0.05f); t++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
+ session.Step();
}
// 4. Hold D (Steer = +1, Throttle = 0) for 1.5s (90 ticks)
@@ -540,7 +550,7 @@ namespace RustToDust.Tests
float accumYaw = 0f;
for (int t = 0; t < 90; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0f,
Steer: 1f,
AimWorldX: player.X,
@@ -548,6 +558,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw);
prevYaw = player.Yaw;
}
@@ -573,7 +584,7 @@ namespace RustToDust.Tests
{
foreach (var spec in new[] { Catalog.Breaker, Catalog.Bastion })
{
- using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(i, 900f + i * 16f, 900f);
@@ -581,8 +592,8 @@ namespace RustToDust.Tests
var sion = session.State.SionMap!;
// Find a clear sloped hillside on Sion (slope ~7-18 deg, free of buildings and low wall meshes along a +/-7m corridor)
- float slopeX = session.State.Player.X;
- float slopeZ = session.State.Player.Z;
+ float slopeX = session.State.Contenders[0].X;
+ float slopeZ = session.State.Contenders[0].Z;
float slopeYaw = 0f;
bool foundSlope = false;
for (float r = 40f; r <= 560f && !foundSlope; r += 20f)
@@ -642,9 +653,9 @@ namespace RustToDust.Tests
session.SetContenderPose(0, slopeX, slopeZ, slopeYaw);
session.State.SpawnChassisDrop(slopeX, slopeZ, spec);
- Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id} on Sion");
+ Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id} on Sion");
session.SetContenderPose(0, slopeX, slopeZ, slopeYaw);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
// 1. Drive forward up/along slope (2.0s)
Vector2 startPos = new(player.X, player.Z);
@@ -654,7 +665,7 @@ namespace RustToDust.Tests
float startY = player.Y;
for (int t = 0; t < 120; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: 0f,
AimWorldX: player.X + fwdDir.X * 50f,
@@ -662,6 +673,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
}
float gEnd = session.State.Terrain.SampleHeight(player.X, player.Z);
float fwdDisp = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir);
@@ -685,7 +697,8 @@ namespace RustToDust.Tests
float accumYaw = 0f;
for (int t = 0; t < 90; t++)
{
- session.Step(new PlayerInput(0f, 1f, player.X, player.Z + 50f, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(0f, 1f, player.X, player.Z + 50f, false, false, false));
+ session.Step();
accumYaw += MatchRules.NormalizeAngle(player.Yaw - prevYaw);
prevYaw = player.Yaw;
}
@@ -697,7 +710,8 @@ namespace RustToDust.Tests
Vector2 finalWinStart = Vector2.Zero;
for (int t = 0; t < 180; t++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 50f, false, false, false));
+ session.Step();
if (timeToStop < 0f && player.Speed < 0.35f) timeToStop = (t + 1) * ArenaSession.FixedDt;
if (t == 71) speedAt1_2s = player.Speed;
if (t == 119) finalWinStart = new Vector2(player.X, player.Z);
@@ -714,7 +728,7 @@ namespace RustToDust.Tests
[Fact]
public void HybridB_Bastion_SteepSionHills_15To22Deg_ClimbsWithoutBeaching()
{
- using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(i, 900f + i * 16f, 900f);
@@ -775,8 +789,8 @@ namespace RustToDust.Tests
session.SetContenderPose(0, sites[0].X, sites[0].Z, sites[0].Yaw);
session.State.SpawnChassisDrop(sites[0].X, sites[0].Z, Catalog.Bastion);
- Assert.True(session.TrySwapNearbyChassis(), "Failed swap to Bastion on Sion");
- var player = session.State.Player;
+ Assert.True(session.TrySwapNearbyChassis(0), "Failed swap to Bastion on Sion");
+ var player = session.State.Contenders[0];
foreach (var site in sites)
{
@@ -787,7 +801,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 120; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: 0f,
AimWorldX: player.X + fwdDir.X * 50f,
@@ -795,6 +809,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
}
float disp2s = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir);
@@ -845,7 +860,7 @@ namespace RustToDust.Tests
{
foreach (var spec in new[] { Catalog.Bastion, Catalog.Manticore })
{
- using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert);
+ using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: true);
for (int i = 2; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(i, 900f + i * 16f, 900f);
@@ -860,7 +875,8 @@ namespace RustToDust.Tests
session.SetContenderPose(0, 0f, 0f, 0f);
for (int t = 0; t < 45; t++)
{
- session.Step(new PlayerInput(0f, 0f, 0f, 80f, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 80f, false, false, false));
+ session.Step();
}
var target = session.State.Contenders[1];
@@ -925,7 +941,7 @@ namespace RustToDust.Tests
foreach (var spec in new[] { Catalog.Bastion, Catalog.Manticore })
{
- using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(i, 900f + i * 16f, 900f);
@@ -933,8 +949,8 @@ namespace RustToDust.Tests
session.SetContenderPose(0, failingSites[0].X, failingSites[0].Z, 0f);
session.State.SpawnChassisDrop(failingSites[0].X, failingSites[0].Z, spec);
- Assert.True(session.TrySwapNearbyChassis(), $"Failed swap to {spec.Id}");
- var player = session.State.Player;
+ Assert.True(session.TrySwapNearbyChassis(0), $"Failed swap to {spec.Id}");
+ var player = session.State.Contenders[0];
foreach (var site in failingSites)
{
@@ -948,7 +964,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 120; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: 0f,
AimWorldX: player.X + fwdDir.X * 50f,
@@ -956,6 +972,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
}
float disp2s = Vector2.Dot(new Vector2(player.X, player.Z) - startPos, fwdDir);
@@ -973,7 +990,7 @@ namespace RustToDust.Tests
[Fact]
public void HybridB_Bastion_StationaryFacingHill_DoesNotHyperExtendLegs()
{
- using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true);
for (int i = 1; i < session.State.Contenders.Count; i++)
{
session.SetContenderPose(i, 900f + i * 16f, 900f);
@@ -986,10 +1003,10 @@ namespace RustToDust.Tests
session.SetContenderPose(0, siteX, siteZ, uphillYaw);
session.State.SpawnChassisDrop(siteX, siteZ, Catalog.Bastion);
- Assert.True(session.TrySwapNearbyChassis(), "Failed swap to Bastion at Site#0");
+ Assert.True(session.TrySwapNearbyChassis(0), "Failed swap to Bastion at Site#0");
session.SetContenderPose(0, siteX, siteZ, uphillYaw);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var ws = session.GetWalkerState(true, player.Id)!;
float modelRide = WalkerLocomotion.GetRideHeight(Catalog.Bastion);
float maxRelCom = 0f;
@@ -997,7 +1014,7 @@ namespace RustToDust.Tests
for (int t = 0; t < 120; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: player.X + MathF.Sin(uphillYaw) * 50f,
@@ -1005,6 +1022,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
float groundY = session.State.Terrain.SampleHeight(player.X, player.Z);
float relCom = player.Y - groundY;
diff --git a/tests/RustToDust.Tests/MultiplayerSimulationTests.cs b/tests/RustToDust.Tests/MultiplayerSimulationTests.cs
new file mode 100644
index 0000000..84b0a3a
--- /dev/null
+++ b/tests/RustToDust.Tests/MultiplayerSimulationTests.cs
@@ -0,0 +1,125 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using RustToDust.Core;
+using RustToDust.Ymir;
+using Xunit;
+
+namespace RustToDust.Tests
+{
+ public sealed class MultiplayerSimulationTests
+ {
+ [Fact]
+ public void TwoHumanSlots_DriveFireSwapAndMatchPhaseStaysActiveUntilSoleSurvivor()
+ {
+ using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Desert, slot0Human: false);
+ session.SetHumanSlot(0, true, "Alpha");
+ session.SetHumanSlot(5, true, "Bravo");
+
+ Assert.True(session.State.Contenders[0].IsHuman);
+ Assert.True(session.State.Contenders[5].IsHuman);
+ Assert.False(session.State.Contenders[1].IsHuman);
+
+ var h0 = session.State.Contenders[0];
+ var h5 = session.State.Contenders[5];
+ session.SetContenderPose(0, -30f, 0f, 0f);
+ session.SetContenderPose(5, 30f, 0f, 0f);
+
+ // Place Rival 2 in open LOS for h0, and behind tall mesa or far away from h5
+ session.SetContenderPose(2, -30f, 55f, MathF.PI);
+
+ float h0StartZ = h0.Z;
+ float h5StartZ = h5.Z;
+
+ var events = new List();
+ for (int t = 0; t < 45; t++)
+ {
+ session.SetHumanInput(0, new PlayerInput(1f, 0f, -30f, 55f, Fire: true, InteractPickup: false, Brake: false));
+ session.SetHumanInput(5, new PlayerInput(-1f, 0.3f, 30f, -50f, Fire: false, InteractPickup: false, Brake: false));
+ session.Step();
+ session.DrainStepEvents(events);
+ }
+
+ Assert.True(h0.Z > h0StartZ + 3f, $"Human 0 should drive forward independently, deltaZ={h0.Z - h0StartZ:F2}");
+ Assert.True(h5.Z < h5StartZ - 2f, $"Human 5 should reverse independently, deltaZ={h5.Z - h5StartZ:F2}");
+ Assert.Contains(events, e => e is ShotFiredEvent sf && !sf.IsSpectatorShooter && sf.ShooterId == 0);
+ Assert.Contains(events, e => e is HitImpactEvent hi && hi.IsContenderShooter && hi.ShooterId == 0 && hi.ArmorDamage > 0f);
+
+ // Kill slot 0 -> match MUST stay Active while multiple contenders remain!
+ h0.Grid.ApplyHit(0f, 0f, 0.5f, 50000f, 0f);
+ Assert.False(h0.Alive);
+ MatchRules.UpdateMatchOutcome(session.State);
+ Assert.Equal(MatchPhase.Active, session.State.Phase);
+
+ // Kill all contenders except slot 5 -> MatchPhase becomes Completed and WinnerContenderId == 5!
+ for (int i = 0; i < session.State.Contenders.Count; i++)
+ {
+ if (i != 5 && session.State.Contenders[i].Alive)
+ {
+ session.State.Contenders[i].Grid.ApplyHit(0f, 0f, 0.5f, 50000f, 0f);
+ }
+ }
+ MatchRules.UpdateMatchOutcome(session.State);
+ Assert.Equal(MatchPhase.Completed, session.State.Phase);
+ Assert.Equal(5, session.State.WinnerContenderId);
+ }
+
+ [Fact]
+ public void PerObserverDetectionIsolation_Human0SeesRivalWhileOccludedHuman5DoesNot()
+ {
+ using var session = new ArenaSession(seed: 12, mapKind: ArenaMapKind.Desert, slot0Human: false);
+ session.SetHumanSlot(0, true, "Alpha");
+ session.SetHumanSlot(5, true, "Bravo");
+
+ var box = session.State.ArenaCoverBoxes[0];
+ var h0 = session.State.Contenders[0];
+ var h5 = session.State.Contenders[5];
+ var rival = session.State.Contenders[2];
+
+ // Move others far away
+ for (int i = 0; i < session.State.Contenders.Count; i++)
+ {
+ if (i != 0 && i != 5 && i != 2)
+ {
+ session.SetContenderPose(i, -650f + i * 12f, -650f);
+ }
+ }
+
+ // Place h0 and rival on same open side of cover wall; place h5 behind cover wall
+ session.SetContenderPose(h0.Id, box.X - 10f, box.Z - box.HalfZ - 12f, 0f);
+ session.SetContenderPose(rival.Id, box.X + 4f, box.Z - box.HalfZ - 12f, 0f);
+ session.SetContenderPose(h5.Id, box.X + 4f, box.Z + box.HalfZ + 8f, 0f);
+
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, rival.X, rival.Z, false, false, true));
+ session.SetHumanInput(5, new PlayerInput(0f, 0f, h5.X, h5.Z, false, false, true));
+ session.Step();
+
+ var obs0 = session.State.ObserverStates[0];
+ var obs5 = session.State.ObserverStates[5];
+
+ Assert.True(obs0.ContenderContacts[rival.Id].VisibleToPlayer);
+ Assert.False(obs5.ContenderContacts[rival.Id].VisibleToPlayer);
+ Assert.False(MatchState.IsContactOnRadar(obs5.ContenderContacts[rival.Id]));
+ Assert.Equal(0, obs5.DetectedByCount);
+ }
+
+ [Fact]
+ public void LocalArenaSession_ImplementsUnifiedClientBoundary()
+ {
+ using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "TestSolo");
+ Assert.Equal(0, local.LocalContenderId);
+ Assert.Equal("TestSolo", local.LocalContender.Name);
+ Assert.Equal(ClientMatchOutcome.Active, local.LocalOutcome);
+ Assert.Equal(NetworkMode.Solo, local.ConnectionStatus.Mode);
+
+ float startZ = local.LocalContender.Z;
+ for (int t = 0; t < 30; t++)
+ {
+ local.SubmitLocalInput(new PlayerInput(1f, 0f, local.LocalContender.X, local.LocalContender.Z + 50f, false, false, false), isPhysicsTick: true);
+ }
+
+ var (pos, _, _) = local.GetInterpolatedContenderPose(0, 1f);
+ Assert.NotEqual(startZ, pos.Z);
+ }
+ }
+}
diff --git a/tests/RustToDust.Tests/PlaytestFixesTests.cs b/tests/RustToDust.Tests/PlaytestFixesTests.cs
index 228b4d9..b285163 100644
--- a/tests/RustToDust.Tests/PlaytestFixesTests.cs
+++ b/tests/RustToDust.Tests/PlaytestFixesTests.cs
@@ -92,9 +92,10 @@ namespace RustToDust.Tests
}
// 4. Zero tick-0 spawn ambush
- var player = state.Player;
+ var player = state.Contenders[0];
float initialHp = player.Grid.CoreHp;
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 10f, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 10f, false, false, true));
+ session.Step();
for (int i = 1; i < state.Contenders.Count; i++)
{
@@ -111,9 +112,9 @@ namespace RustToDust.Tests
{
// Part A: AI Jackal (950 kg) must pick up Hornet (820 kg) via GetChassisUpgradeScore (> 0)
{
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0, 1);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var ai = session.State.Contenders[1];
// Clear unrelated drops so Hornet is the clean target
@@ -131,7 +132,8 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 240 && ai.Grid.Spec.Id == Catalog.Jackal.Id; tick++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
}
Assert.Equal(Catalog.Hornet.Id, ai.Grid.Spec.Id);
@@ -139,9 +141,9 @@ namespace RustToDust.Tests
// Part B: AI Jackal picks up heavy mech drop (Breaker)
{
- using var session = new ArenaSession(seed: 77, ArenaMapKind.Desert);
+ using var session = new ArenaSession(seed: 77, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0, 1);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var ai = session.State.Contenders[1];
foreach (var d in session.State.GroundDrops)
@@ -156,7 +158,8 @@ namespace RustToDust.Tests
session.State.SpawnChassisDrop(0f, 48f, Catalog.Breaker);
for (int tick = 0; tick < 240 && ai.Grid.Spec.Id == Catalog.Jackal.Id; tick++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
}
Assert.Equal(Catalog.Breaker.Id, ai.Grid.Spec.Id);
@@ -167,10 +170,10 @@ namespace RustToDust.Tests
public void NaturalizedBotAim_OffAxisSlewAndJinkOvershoot_ZeroOccludedLeak()
{
// 1. 90-degree off-axis slew delay
- using (var session = new ArenaSession(seed: 42, ArenaMapKind.Desert))
+ using (var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true))
{
IsolateContenders(session, 0, 1);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var ai = session.State.Contenders[1];
// Place AI facing +Z (yaw = 0) and player 60m due +X (90 degrees off-axis) in open LOS
@@ -178,7 +181,8 @@ namespace RustToDust.Tests
session.SetContenderPose(player.Id, 60f, 0f, yaw: 0f);
ai.AiScavengeCooldown = 999f;
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.False(ai.FireCmd, "90-degree off-axis AI must not snap-fire on tick 0 before slewing into cone");
@@ -186,7 +190,8 @@ namespace RustToDust.Tests
for (int t = 0; t < 75; t++)
{
session.SetContenderPose(player.Id, 60f, 0f, yaw: 0f);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
if (ai.FireCmd)
{
eventuallyFired = true;
@@ -249,11 +254,11 @@ namespace RustToDust.Tests
}
// 3. Zero occluded fire / target leak when LOS breaks behind cover
- using (var session = new ArenaSession(seed: 12, ArenaMapKind.Desert))
+ using (var session = new ArenaSession(seed: 12, ArenaMapKind.Desert, slot0Human: true))
{
IsolateContenders(session, 0, 1);
var box = session.State.ArenaCoverBoxes[0];
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var ai = session.State.Contenders[1];
float aiX = box.X;
@@ -262,7 +267,8 @@ namespace RustToDust.Tests
float pz = box.Z - box.HalfZ - 14f;
session.SetContenderPose(ai.Id, aiX, aiZ, MathF.Atan2(px - aiX, pz - aiZ));
session.SetContenderPose(player.Id, px, pz, 0f);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.True(ai.AimTracker.HasTarget);
@@ -272,7 +278,8 @@ namespace RustToDust.Tests
for (int t = 0; t < 10; t++)
{
session.SetContenderPose(player.Id, box.X + (t % 2 == 0 ? 2f : -2f), box.Z + box.HalfZ + 8f, 0f);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Null(ai.AiTargetContenderId);
Assert.False(ai.FireCmd);
@@ -286,14 +293,14 @@ namespace RustToDust.Tests
[Fact]
public void RenderInterpolation_CameraAnchorAndContenderPose_ZeroHorizPhaseMismatchAcrossAlpha()
{
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
// Accelerate player forward for 30 ticks so Prev != Curr with genuine horizontal displacement & rotation
for (int t = 0; t < 30; t++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: 0.35f,
AimWorldX: player.X + MathF.Sin(player.Yaw) * 40f,
@@ -301,6 +308,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
}
float stepHoriz = MathF.Sqrt(
@@ -337,15 +345,15 @@ namespace RustToDust.Tests
[Fact]
public void PointBlankConvergence_LargeChassis_NeverFiresBackward()
{
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0, 1);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var target = session.State.Contenders[1];
// Swap player to Bastion (largest heavy chassis) and target to Raptor (tall mech, small 0.8m footprint)
session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f);
session.State.SpawnChassisDrop(0f, 0f, Catalog.Bastion);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(Catalog.Bastion.Id, player.Grid.Spec.Id);
session.SetContenderPose(target.Id, 0f, 4.5f, yaw: MathF.PI);
@@ -356,14 +364,15 @@ namespace RustToDust.Tests
// Step 1 tick to seat bodies, re-pin poses, then fire point-blank 4.5m in front (+Z)
float aimY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
- session.Step(new PlayerInput(0f, 0f, target.X, target.Z, false, false, true, AimWorldY: aimY));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, target.X, target.Z, false, false, true, AimWorldY: aimY));
+ session.Step();
session.SetContenderPose(player.Id, 0f, 0f, yaw: 0f);
session.SetContenderPose(target.Id, 0f, 4.5f, yaw: MathF.PI);
session.State.Tracers.Clear();
aimY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
float targetArmorBefore = target.Grid.TotalArmorRatio();
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: target.X,
@@ -372,6 +381,7 @@ namespace RustToDust.Tests
InteractPickup: false,
Brake: true,
AimWorldY: aimY));
+ session.Step();
float bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
var playerTracers1 = session.State.Tracers
@@ -396,7 +406,7 @@ namespace RustToDust.Tests
{
m.Cooldown = 0f;
}
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: target.X,
@@ -405,6 +415,7 @@ namespace RustToDust.Tests
InteractPickup: false,
Brake: true,
AimWorldY: aimY));
+ session.Step();
bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
var playerTracersFront = session.State.Tracers
@@ -429,7 +440,7 @@ namespace RustToDust.Tests
{
m.Cooldown = 0f;
}
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: target.X,
@@ -438,6 +449,7 @@ namespace RustToDust.Tests
InteractPickup: false,
Brake: true,
AimWorldY: aimY));
+ session.Step();
bastionMuzzleY = player.Y + player.Grid.Spec.HalfHeight * 0.25f;
var playerTracers2 = session.State.Tracers
@@ -490,9 +502,9 @@ namespace RustToDust.Tests
[Fact]
public void AiScavenge_PrefersBetterUpgradeInPickupRange_OverCloserInferiorWreck()
{
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true);
IsolateContenders(session, 0, 1);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var ai = session.State.Contenders[1];
foreach (var d in session.State.GroundDrops)
@@ -508,7 +520,8 @@ namespace RustToDust.Tests
session.State.SpawnChassisDrop(0f, 1.5f, Catalog.Jackal);
session.State.SpawnChassisDrop(0f, 5.5f, Catalog.Hornet);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Equal(Catalog.Hornet.Id, ai.Grid.Spec.Id);
}
diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj
index 8e36dcc..5c62c25 100644
--- a/tests/RustToDust.Tests/RustToDust.Tests.csproj
+++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj
@@ -16,6 +16,7 @@
+
diff --git a/tests/RustToDust.Tests/SionDetectionLosTests.cs b/tests/RustToDust.Tests/SionDetectionLosTests.cs
index dcb7eac..30ee3f6 100644
--- a/tests/RustToDust.Tests/SionDetectionLosTests.cs
+++ b/tests/RustToDust.Tests/SionDetectionLosTests.cs
@@ -121,9 +121,9 @@ namespace RustToDust.Tests
[Fact]
public void Sion_Contenders_ZeroOccludedRadarLeaks_UnderAndOver350m_EveryTick()
{
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!;
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var nearRival = session.State.Contenders[1];
var farRival = session.State.Contenders[2];
@@ -145,7 +145,8 @@ namespace RustToDust.Tests
var (tempFarX, tempFarZ) = FindClearBuildingAdjacentSpot(sion, -1300f, 1300f);
SwapToChassis(session, farRival, Catalog.Jackal, tempFarX, tempFarZ);
- session.State.ContenderContacts[nearRival.Id] = new PlayerContactMemory();
+ var obs0 = session.State.GetOrCreateObserverState(0);
+ obs0.ContenderContacts[nearRival.Id] = new PlayerContactMemory();
for (int tick = 0; tick < 8; tick++)
{
session.SetContenderPose(player.Id, bldg.CenterX, z1);
@@ -154,9 +155,10 @@ namespace RustToDust.Tests
player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z,
nearRival.X, MatchRules.GetTargetAimY(nearRival.Y, nearRival.Grid.Spec.HalfHeight), nearRival.Z));
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
- var mem = session.State.ContenderContacts[nearRival.Id];
+ var mem = obs0.ContenderContacts[nearRival.Id];
Assert.False(mem.VisibleToPlayer, $"Occluded <350m Sion contender leaked VisibleToPlayer on tick {tick}");
Assert.False(mem.HasEverBeenSeen, $"Occluded <350m Sion contender leaked HasEverBeenSeen on tick {tick}");
Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded <350m Sion contender leaked onto radar on tick {tick}");
@@ -170,7 +172,7 @@ namespace RustToDust.Tests
session.SetContenderPose(player.Id, northX, northZ);
session.SetContenderPose(farRival.Id, southX, southZ);
- session.State.ContenderContacts[farRival.Id] = new PlayerContactMemory();
+ obs0.ContenderContacts[farRival.Id] = new PlayerContactMemory();
for (int tick = 0; tick < 8; tick++)
{
@@ -180,9 +182,10 @@ namespace RustToDust.Tests
player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z,
farRival.X, MatchRules.GetTargetAimY(farRival.Y, farRival.Grid.Spec.HalfHeight), farRival.Z));
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
- var mem = session.State.ContenderContacts[farRival.Id];
+ var mem = obs0.ContenderContacts[farRival.Id];
Assert.False(mem.VisibleToPlayer, $"Occluded >350m Sion contender leaked VisibleToPlayer on tick {tick}");
Assert.False(mem.HasEverBeenSeen, $"Occluded >350m Sion contender leaked HasEverBeenSeen on tick {tick}");
Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded >350m Sion contender leaked onto radar on tick {tick}");
@@ -193,9 +196,9 @@ namespace RustToDust.Tests
public void Sion_Contenders_Over350m_OpenLosDetectedImmediatelyOnEveryTickPhase()
{
// Verify >350m contenders with open LOS are never delayed by mod-4 staggering across contenders 1..4 on tick 0.
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!;
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var (px, pz) = FindClearBuildingAdjacentSpot(sion, 113f, -211f);
SwapToChassis(session, player, Catalog.Condor, px, pz);
@@ -226,15 +229,18 @@ namespace RustToDust.Tests
c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z),
$"Expected clear elevated LOS to contender {c.Id}");
- session.State.ContenderContacts[c.Id] = new PlayerContactMemory();
+ var obs0 = session.State.GetOrCreateObserverState(0);
+ obs0.ContenderContacts[c.Id] = new PlayerContactMemory();
tested.Add(c);
}
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
+ var obs0After = session.State.GetOrCreateObserverState(0);
foreach (var c in tested)
{
- var mem = session.State.ContenderContacts[c.Id];
+ var mem = obs0After.ContenderContacts[c.Id];
Assert.True(mem.VisibleToPlayer, $"Contender {c.Id} >350m with open LOS missed tick-0 detection (staggering leak)");
Assert.True(MatchState.IsContactOnRadar(mem));
}
@@ -243,9 +249,9 @@ namespace RustToDust.Tests
[Fact]
public void Sion_Spectators_ZeroOccludedLeaks_ZeroTick0Blindspots_AndNo950mHardCull()
{
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!;
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
// Part 1: Occluded low-signature Exemplar across Valere hill (>450m) never leaks on any tick (0..9)
var exemplar = session.State.Spectators.Spectators.First(s => s.Tier == SpectatorTier.Exemplar);
@@ -256,7 +262,8 @@ namespace RustToDust.Tests
SwapToChassis(session, player, Catalog.Jackal, northX, northZ);
session.SetSpectatorPose(exemplar.Id, southX, southZ);
- session.State.SpectatorContacts[exemplar.Id] = new PlayerContactMemory();
+ var obs0 = session.State.GetOrCreateObserverState(0);
+ obs0.SpectatorContacts[exemplar.Id] = new PlayerContactMemory();
for (int tick = 0; tick < 10; tick++)
{
@@ -266,9 +273,10 @@ namespace RustToDust.Tests
player.X, MatchRules.GetObserverEyeY(player.Y, player.Grid.Spec.HalfHeight), player.Z,
exemplar.X, MatchRules.GetTargetAimY(exemplar.Y, exemplar.Grid.Spec.HalfHeight), exemplar.Z));
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
- var mem = session.State.SpectatorContacts[exemplar.Id];
+ var mem = obs0.SpectatorContacts[exemplar.Id];
Assert.False(mem.VisibleToPlayer, $"Occluded Sion Exemplar leaked VisibleToPlayer on tick {tick}");
Assert.False(mem.FaintHorizonPing, $"Occluded Sion Exemplar leaked FaintHorizonPing on tick {tick}");
Assert.False(MatchState.IsContactOnRadar(mem), $"Occluded Sion Exemplar leaked onto radar on tick {tick}");
@@ -309,16 +317,17 @@ namespace RustToDust.Tests
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z),
$"Expected open elevated LOS to spectator {s.Id} at dist={actualDist:F1}m");
- session.State.SpectatorContacts[s.Id] = new PlayerContactMemory();
+ obs0.SpectatorContacts[s.Id] = new PlayerContactMemory();
openSpecs.Add(s);
}
// Step ONE tick: all 8 spectators (covering all %4 and %8 phases and >950m) must be visible immediately.
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
foreach (var s in openSpecs)
{
- var mem = session.State.SpectatorContacts[s.Id];
+ var mem = obs0.SpectatorContacts[s.Id];
float d = MathF.Sqrt((s.X - player.X) * (s.X - player.X) + (s.Z - player.Z) * (s.Z - player.Z));
Assert.True(mem.VisibleToPlayer,
$"Open-LOS Sion spectator {s.Id} at {d:F1}m missed tick-0 detection (blindspot or >950m hard cull)");
@@ -329,9 +338,9 @@ namespace RustToDust.Tests
[Fact]
public void Sion_AiContender_NoOddTickTargetDropOrTunnelVision()
{
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var sion = session.State.SionMap!;
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var ai = session.State.Contenders[1];
var closerRival = session.State.Contenders[2];
@@ -357,7 +366,8 @@ namespace RustToDust.Tests
player.X, MatchRules.GetTargetAimY(player.Y, player.Grid.Spec.HalfHeight), player.Z));
// Advance 1 tick so ai locks onto player on tick 1
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId);
// On the next tick (even/odd opposite phase), bring closerRival into open LOS closer than player
@@ -368,7 +378,8 @@ namespace RustToDust.Tests
ai.X, MatchRules.GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight), ai.Z,
closerRival.X, MatchRules.GetTargetAimY(closerRival.Y, closerRival.Grid.Spec.HalfHeight), closerRival.Z));
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Equal(closerRival.Id, ai.AiTargetContenderId);
// 2. Immediate target drop and FireCmd=false across consecutive ticks when LOS breaks behind a Sion building
@@ -392,7 +403,8 @@ namespace RustToDust.Tests
for (int t = 0; t <= phase; t++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Equal(player.Id, ai.AiTargetContenderId);
Assert.True(ai.FireCmd, $"Expected AI to acquire and fire immediately on Sion (phase={phase}, t={t})");
}
@@ -404,7 +416,8 @@ namespace RustToDust.Tests
{
session.SetContenderPose(ai.Id, bldg.CenterX, z1, yaw: 0f);
session.SetContenderPose(player.Id, bldg.CenterX, z2, yaw: 0f);
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z, false, false, true));
+ session.Step();
Assert.Null(ai.AiTargetContenderId);
Assert.False(ai.FireCmd, $"AI leaked FireCmd through Sion building on occluded tick {occTick} (phase={phase})");
diff --git a/tests/RustToDust.Tests/SionMapTests.cs b/tests/RustToDust.Tests/SionMapTests.cs
index f21d062..a68d3e2 100644
--- a/tests/RustToDust.Tests/SionMapTests.cs
+++ b/tests/RustToDust.Tests/SionMapTests.cs
@@ -118,7 +118,7 @@ namespace RustToDust.Tests
[Fact]
public void ArenaSession_SionLoadsHeightfieldAndMeshesSpawnsClearBlocksLosAndStepsCleanly()
{
- using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion);
+ using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true);
var state = session.State;
var sion = state.SionMap!;
@@ -186,12 +186,12 @@ namespace RustToDust.Tests
$"Expected HasLineOfSight above Sion building {tb.Id} roof ({tb.RoofY:F1}m) to be clear");
// Step 180 ticks (3 seconds) driving & firing: zero NaNs, zero underground falls, player moves cleanly
- var player = state.Player;
+ var player = state.Contenders[0];
float pStartX = player.X;
float pStartZ = player.Z;
for (int tick = 0; tick < 180; tick++)
{
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: MathF.Sin(tick * 0.04f) * 0.25f,
AimWorldX: player.X + MathF.Sin(player.Yaw) * 60f,
@@ -199,6 +199,7 @@ namespace RustToDust.Tests
Fire: tick % 10 == 0,
InteractPickup: false,
Brake: false));
+ session.Step();
for (int cIdx = 0; cIdx < state.Contenders.Count; cIdx++)
{
diff --git a/tests/RustToDust.Tests/TerrainTests.cs b/tests/RustToDust.Tests/TerrainTests.cs
index 2bb5cba..231fc9e 100644
--- a/tests/RustToDust.Tests/TerrainTests.cs
+++ b/tests/RustToDust.Tests/TerrainTests.cs
@@ -151,8 +151,8 @@ namespace RustToDust.Tests
[Fact]
public void ArenaSession_BuggyDrivesAcrossDunesWithoutNanAndTracksElevation()
{
- using var session = new ArenaSession(seed: 42);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
+ var player = session.State.Contenders[0];
int initialBrushes = session.State.Terrain.Brushes.Count;
float minGround = float.PositiveInfinity;
@@ -161,7 +161,7 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 360; tick++)
{
float steer = MathF.Sin(tick * 0.025f) * 0.45f;
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: steer,
AimWorldX: player.X + 30f,
@@ -169,6 +169,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
Assert.False(float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z),
$"NaN pose at tick {tick}");
@@ -272,8 +273,8 @@ namespace RustToDust.Tests
private static void RunSteepTerrainStress(int seed, ChassisSpec chassis, bool testDune)
{
- using var session = new ArenaSession(seed);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed, slot0Human: true);
+ var player = session.State.Contenders[0];
TerrainBrush targetBrush = default;
float startX = 0f;
@@ -335,7 +336,7 @@ namespace RustToDust.Tests
if (chassis.Id != player.Grid.Spec.Id)
{
session.State.SpawnChassisDrop(player.X, player.Z, chassis);
- Assert.True(session.TrySwapNearbyChassis(), $"Expected swap to {chassis.Id} to succeed");
+ Assert.True(session.TrySwapNearbyChassis(0), $"Expected swap to {chassis.Id} to succeed");
Assert.Equal(chassis.Id, player.Grid.Spec.Id);
}
@@ -348,7 +349,7 @@ namespace RustToDust.Tests
for (int tick = 0; tick < 600; tick++)
{
float steer = MathF.Sin(tick * 0.03f) * 0.15f;
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 1f,
Steer: steer,
AimWorldX: targetBrush.X,
@@ -356,6 +357,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: false));
+ session.Step();
Assert.False(
float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z),
diff --git a/tests/RustToDust.Tests/VtolAndArcTests.cs b/tests/RustToDust.Tests/VtolAndArcTests.cs
index 9960dd6..8a2ef77 100644
--- a/tests/RustToDust.Tests/VtolAndArcTests.cs
+++ b/tests/RustToDust.Tests/VtolAndArcTests.cs
@@ -31,13 +31,13 @@ namespace RustToDust.Tests
{
foreach (var vtolSpec in new[] { Catalog.Hornet, Catalog.Condor })
{
- using var session = new ArenaSession(seed: 42);
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
IsolateContenders(session, 0);
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
session.SetContenderPose(player.Id, 0f, 0f, 0f);
session.State.SpawnChassisDrop(player.X, player.Z, vtolSpec);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(vtolSpec.Id, player.Grid.Spec.Id);
Assert.True(player.Grid.Spec.IsVtol);
@@ -47,7 +47,8 @@ namespace RustToDust.Tests
// Climb with VerticalThrottle = +1 for 2.5s (150 ticks)
for (int t = 0; t < 150; t++)
{
- session.Step(new PlayerInput(0.4f, 0.1f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 1f));
+ session.SetHumanInput(0, new PlayerInput(0.4f, 0.1f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 1f));
+ session.Step();
}
float ghClimbed = session.State.Terrain.SampleHeight(player.X, player.Z);
@@ -60,13 +61,15 @@ namespace RustToDust.Tests
// Hold hover with VerticalThrottle = 0 for 2.0s (120 ticks) -> settles to TargetHoverAltAgl and holds steady
for (int t = 0; t < 60; t++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f));
+ session.Step();
}
float ghSettled = session.State.Terrain.SampleHeight(player.X, player.Z);
float settledAgl = player.Y - vtolSpec.HalfHeight - ghSettled;
for (int t = 0; t < 60; t++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: 0f));
+ session.Step();
}
float ghHeld = session.State.Terrain.SampleHeight(player.X, player.Z);
float heldAgl = player.Y - vtolSpec.HalfHeight - ghHeld;
@@ -76,7 +79,8 @@ namespace RustToDust.Tests
// Descend with VerticalThrottle = -1 for 3s (180 ticks) - should settle smoothly near 2.5m clearance
for (int t = 0; t < 180; t++)
{
- session.Step(new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: -1f));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 30f, false, false, false, VerticalThrottle: -1f));
+ session.Step();
}
float ghDesc = session.State.Terrain.SampleHeight(player.X, player.Z);
float descAgl = player.Y - vtolSpec.HalfHeight - ghDesc;
@@ -88,8 +92,8 @@ namespace RustToDust.Tests
[Fact]
public void MwllTriangle_ZenithBlindSpot_MainCannonBlocked_WideArcPdAndDistantGroundRigHit()
{
- using var session = new ArenaSession(seed: 42);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
+ var player = session.State.Contenders[0];
var overheadVtol = session.State.Contenders[1];
var distantGroundRig = session.State.Contenders[2];
IsolateContenders(session, player.Id, overheadVtol.Id);
@@ -97,7 +101,7 @@ namespace RustToDust.Tests
// Swap player to Anvil (heavy tracked tank, weapons capped at +30 deg pitch)
session.SetContenderPose(player.Id, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, Catalog.Anvil);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal("anvil", player.Grid.Spec.Id);
// Swap contender 1 to Hornet and position it high overhead (~14m horizontal, ~38m above player => ~+69 deg pitch!)
@@ -109,7 +113,8 @@ namespace RustToDust.Tests
overheadVtol.TargetHoverAltAgl = 38f;
session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f);
// Step once to seat bodies cleanly
- session.Step(new PlayerInput(0f, 0f, overheadVtol.X, overheadVtol.Z, false, false, true, AimWorldY: overheadVtol.Y));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, overheadVtol.X, overheadVtol.Z, false, false, true, AimWorldY: overheadVtol.Y));
+ session.Step();
float vtolArmorBefore = overheadVtol.Grid.TotalArmorRatio();
@@ -118,13 +123,14 @@ namespace RustToDust.Tests
{
overheadVtol.TargetHoverAltAgl = 38f;
session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f);
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
0f, 0f,
overheadVtol.X, overheadVtol.Z,
Fire: true,
InteractPickup: false,
Brake: true,
AimWorldY: overheadVtol.Y));
+ session.Step();
}
Assert.True(player.AllWeaponsOutOfArc,
$"Expected Anvil main cannons to report AllWeaponsOutOfArc (in={player.InArcWeaponCount}, out={player.OutOfArcWeaponCount}, pY={player.Y:F1}, vY={overheadVtol.Y:F1}, vSpec={overheadVtol.Grid.Spec.Id}, vAlt={overheadVtol.TargetHoverAltAgl:F1}, vAlive={overheadVtol.Alive}, vPos=({overheadVtol.X:F1},{overheadVtol.Z:F1}))");
@@ -138,13 +144,14 @@ namespace RustToDust.Tests
{
overheadVtol.TargetHoverAltAgl = 38f;
session.SetContenderPose(overheadVtol.Id, 0f, 14f, 0f);
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
0f, 0f,
overheadVtol.X, overheadVtol.Z,
Fire: true,
InteractPickup: false,
Brake: true,
AimWorldY: overheadVtol.Y));
+ session.Step();
pdTracers += session.State.Tracers.Count;
}
Assert.False(player.AllWeaponsOutOfArc, "Expected Wide-Arc PD module to clear overhead out-of-arc block");
@@ -164,7 +171,8 @@ namespace RustToDust.Tests
float vtolArmorBeforeDistant = overheadVtol.Grid.TotalArmorRatio();
for (int t = 0; t < 90; t++)
{
- session.Step(new PlayerInput(0f, 0f, 0f, -20f, false, false, true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, -20f, false, false, true));
+ session.Step();
}
Assert.True(overheadVtol.Grid.TotalArmorRatio() < vtolArmorBeforeDistant,
"Expected distant ground rig 140m away (~15 deg pitch) to hit the hovering Hornet inside its 30 deg cannon arc");
@@ -173,8 +181,8 @@ namespace RustToDust.Tests
[Fact]
public void GroundRigWithWideArcPd_AutoTracksNearbyAirborneVtolWithoutManualFire()
{
- using var session = new ArenaSession(seed: 42);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
+ var player = session.State.Contenders[0];
var overheadVtol = session.State.Contenders[1];
IsolateContenders(session, player.Id, overheadVtol.Id);
@@ -196,7 +204,7 @@ namespace RustToDust.Tests
{
overheadVtol.TargetHoverAltAgl = 28f;
session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f);
- session.Step(new PlayerInput(
+ session.SetHumanInput(0, new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: 0f,
@@ -204,6 +212,7 @@ namespace RustToDust.Tests
Fire: false,
InteractPickup: false,
Brake: true));
+ session.Step();
if (session.State.Tracers.Count > 0)
{
sawAutoTracer = true;
@@ -219,17 +228,18 @@ namespace RustToDust.Tests
public void QuickBolt_MountsScavengedModuleIntoEmptyMatchingHardpointBeforeCargo()
{
var state = new MatchState(seed: 42);
- var player = state.Player;
+ var player = state.Contenders[0];
+ player.IsHuman = true;
// Swap to Anvil (starter Jackal transfers 1 weapon into hp.weapon.sponson_l, leaving hp.weapon.siege_l, hp.weapon.siege_r, hp.weapon.sponson_r empty!)
state.SpawnChassisDrop(player.X, player.Z, Catalog.Anvil);
- Assert.True(state.TrySwapNearbyChassis());
+ Assert.True(state.TrySwapNearbyChassis(0));
Assert.Null(player.Grid.GetMountedOn("hp.weapon.siege_l"));
int cargoBefore = player.Grid.Cargo.Count;
// Drop 1x1 PointDefenseFlak right at player and press [E]
state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.PointDefenseFlak);
- MatchRules.ApplyPlayerInput(state, new PlayerInput(
+ MatchRules.ApplyHumanInput(state, 0, new PlayerInput(
0f, 0f, player.X, player.Z + 10f,
Fire: false,
InteractPickup: true,
@@ -246,7 +256,7 @@ namespace RustToDust.Tests
Assert.True(player.Grid.TryMount(Catalog.Autocannon, "hp.weapon.siege_r"));
Assert.True(player.Grid.TryMount(Catalog.Mg762, "hp.weapon.sponson_r"));
state.SpawnModuleDrop(player.X + 0.5f, player.Z, Catalog.Flak);
- MatchRules.ApplyPlayerInput(state, new PlayerInput(
+ MatchRules.ApplyHumanInput(state, 0, new PlayerInput(
0f, 0f, player.X, player.Z + 10f,
Fire: false,
InteractPickup: true,
@@ -259,8 +269,8 @@ namespace RustToDust.Tests
[Fact]
public void Vtol_ReverseIntoTallMesaAndCliffDrop_ZeroUndergroundTicks()
{
- using var session = new ArenaSession(seed: 42);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
+ var player = session.State.Contenders[0];
IsolateContenders(session, player.Id);
// Pick the tallest Mesa in generated terrain
@@ -278,7 +288,7 @@ namespace RustToDust.Tests
Assert.True(bestHeight >= 22f, "Expected a tall Mesa in seed 42");
session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Hornet);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal("hornet", player.Grid.Spec.Id);
// 1. Reverse (-Z/+X away from yaw) straight into the tall Mesa cliff face
@@ -290,7 +300,8 @@ namespace RustToDust.Tests
int undergroundReverseTicks = 0;
for (int t = 0; t < 240; t++)
{
- session.Step(new PlayerInput(-1f, 0f, player.X - 30f, player.Z, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(-1f, 0f, player.X - 30f, player.Z, false, false, false));
+ session.Step();
float gh = session.State.Terrain.SampleHeight(player.X, player.Z);
float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh;
if (agl < minReverseAgl) minReverseAgl = agl;
@@ -312,7 +323,8 @@ namespace RustToDust.Tests
int undergroundDropTicks = 0;
for (int t = 0; t < 240; t++)
{
- session.Step(new PlayerInput(1f, 0f, player.X + 30f, player.Z, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(1f, 0f, player.X + 30f, player.Z, false, false, false));
+ session.Step();
float gh = session.State.Terrain.SampleHeight(player.X, player.Z);
float agl = (player.Y - player.Grid.Spec.HalfHeight) - gh;
if (agl < minDropAgl) minDropAgl = agl;
@@ -326,20 +338,21 @@ namespace RustToDust.Tests
[Fact]
public void Vtol_OverheatedEngineToZeroPerf_LosesClimbAuthorityAndSinksTowardMinClearance()
{
- using var session = new ArenaSession(seed: 42);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
+ var player = session.State.Contenders[0];
IsolateContenders(session, player.Id);
session.SetContenderPose(player.Id, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
// Establish steady 20m hover
player.TargetHoverAltAgl = 20f;
session.SetContenderPose(player.Id, 0f, 0f, 0f);
for (int t = 0; t < 45; t++)
{
- session.Step(new PlayerInput(0f, 0f, 0f, 30f, false, false, false));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 30f, false, false, false));
+ session.Step();
}
float hoverAglBefore = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z);
Assert.InRange(hoverAglBefore, 17.5f, 22.5f);
@@ -348,7 +361,8 @@ namespace RustToDust.Tests
for (int t = 0; t < 150; t++)
{
player.Grid.InjectHardpointHeat("hp.engine.core", 15000f);
- session.Step(new PlayerInput(0f, 0f, 0f, 30f, false, false, false, VerticalThrottle: 1f));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, 30f, false, false, false, VerticalThrottle: 1f));
+ session.Step();
}
float hoverAglAfter = (player.Y - player.Grid.Spec.HalfHeight) - session.State.Terrain.SampleHeight(player.X, player.Z);
@@ -362,9 +376,9 @@ namespace RustToDust.Tests
public void StrippedZeroArmorHardpoint_DisablesManualFireAndAutoPointDefense()
{
// 1. Manual FireMountedWeapons disabled when hardpoint armor == 0
- using (var session = new ArenaSession(seed: 42))
+ using (var session = new ArenaSession(seed: 42, slot0Human: true))
{
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var target = session.State.Contenders[1];
IsolateContenders(session, player.Id, target.Id);
@@ -390,7 +404,8 @@ namespace RustToDust.Tests
int tracersFired = 0;
for (int t = 0; t < 20; t++)
{
- session.Step(new PlayerInput(0f, 0f, target.X, target.Z, Fire: true, InteractPickup: false, Brake: true, AimWorldY: target.Y));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, target.X, target.Z, Fire: true, InteractPickup: false, Brake: true, AimWorldY: target.Y));
+ session.Step();
tracersFired += session.State.Tracers.Count(tr =>
MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f);
}
@@ -402,9 +417,9 @@ namespace RustToDust.Tests
}
// 2. Auto-PD TryAutoPointDefenseFire disabled when PD hardpoint armor == 0
- using (var session = new ArenaSession(seed: 42))
+ using (var session = new ArenaSession(seed: 42, slot0Human: true))
{
- var player = session.State.Player;
+ var player = session.State.Contenders[0];
var overheadVtol = session.State.Contenders[1];
IsolateContenders(session, player.Id, overheadVtol.Id);
@@ -434,7 +449,8 @@ namespace RustToDust.Tests
{
overheadVtol.TargetHoverAltAgl = 28f;
session.SetContenderPose(overheadVtol.Id, 20f, 25f, 0f);
- session.Step(new PlayerInput(0f, 0f, 0f, -50f, Fire: false, InteractPickup: false, Brake: true));
+ session.SetHumanInput(0, new PlayerInput(0f, 0f, 0f, -50f, Fire: false, InteractPickup: false, Brake: true));
+ session.Step();
pdTracers += session.State.Tracers.Count(tr =>
MathF.Abs(tr.StartX - player.X) < 10f && MathF.Abs(tr.StartZ - player.Z) < 10f);
}
@@ -447,13 +463,13 @@ namespace RustToDust.Tests
[Fact]
public void SwapChassis_VtolToGroundToVtol_ResetsTargetHoverAltAgl()
{
- using var session = new ArenaSession(seed: 42);
- var player = session.State.Player;
+ using var session = new ArenaSession(seed: 42, slot0Human: true);
+ var player = session.State.Contenders[0];
IsolateContenders(session, player.Id);
session.SetContenderPose(player.Id, 0f, 0f, 0f);
session.State.SpawnChassisDrop(0f, 0f, Catalog.Hornet);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(10f, player.TargetHoverAltAgl);
player.TargetHoverAltAgl = 42f;
@@ -461,13 +477,13 @@ namespace RustToDust.Tests
// Swap to ground rig
session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Jackal);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(3.0f, player.TargetHoverAltAgl);
Assert.Equal(0f, player.VerticalThrottleCmd);
// Swap back to VTOL -> must spawn cleanly at 10m hover, NOT stale 42m
session.State.SpawnChassisDrop(player.X, player.Z, Catalog.Condor);
- Assert.True(session.TrySwapNearbyChassis());
+ Assert.True(session.TrySwapNearbyChassis(0));
Assert.Equal(10.0f, player.TargetHoverAltAgl);
Assert.Equal(0f, player.VerticalThrottleCmd);
float gh = session.State.Terrain.SampleHeight(player.X, player.Z);
@@ -479,7 +495,8 @@ namespace RustToDust.Tests
public void InteractPickup_UsesUnifiedNearestDropPriority_ChassisCloserThanModule()
{
var state = new MatchState(seed: 42);
- var player = state.Player;
+ var player = state.Contenders[0];
+ player.IsHuman = true;
// Remove pre-scattered drops near player to keep test deterministic
state.GroundDrops.Clear();
@@ -490,7 +507,7 @@ namespace RustToDust.Tests
var nearest = state.FindNearestInteractableDrop(0);
Assert.Same(chassisDrop, nearest);
- MatchRules.ApplyPlayerInput(state, new PlayerInput(
+ MatchRules.ApplyHumanInput(state, 0, new PlayerInput(
0f, 0f, player.X, player.Z + 10f,
Fire: false,
InteractPickup: true,