Cut 5c-1: Multi-human authoritative sim, SimSnapshot/SimEvent boundary, RustToDust.Net & RustToDust.Server
This commit is contained in:
parent
8eba2ea39f
commit
d8f5c49b8d
34 changed files with 5785 additions and 700 deletions
357
tests/RustToDust.Tests/CultNetMultiplayerTests.cs
Normal file
357
tests/RustToDust.Tests/CultNetMultiplayerTests.cs
Normal file
|
|
@ -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<NetContenderState>(12);
|
||||
var walkers = new List<NetWalkerEntry>(12);
|
||||
var specs = new List<NetSpectatorState>(10);
|
||||
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
contenders.Add(new NetContenderState
|
||||
{
|
||||
SlotId = (byte)i,
|
||||
Alive = true,
|
||||
IsHuman = 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<bool> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue