Cut 10a: cross-zone orbital drop altitudes, squad formation spawns, and wide drop FOV

This commit is contained in:
Meta Vens 2026-12-05 19:32:20 +01:00
commit 26f5438ed5
24 changed files with 1754 additions and 211 deletions

View file

@ -17,11 +17,15 @@ namespace RustToDust.Client;
public sealed class CameraJuiceState
{
public const float BaseFovDeg = 58.0f;
public const float DropFreefallFovDeg = 82.0f;
public const float DropRetroFovDeg = 76.0f;
private const float ZeroEpsilon = 1e-4f;
private const float TraumaDecayPerSec = 1.95f;
private const float RecoilDecayRate = 14.0f;
private const float FootstepDecayRate = 16.0f;
private const float FovBlendRate = 6.0f;
private const float DropFovBlendInRate = 5.0f;
private const float DropFovBlendOutRate = 3.8f;
private float _time;
@ -236,7 +240,7 @@ public sealed class CameraJuiceState
}
}
public void Update(float dt, float localSpeedMps, bool isVtol)
public void Update(float dt, float localSpeedMps, bool isVtol, bool isInDropPod = false, OrbitalPodPhase podPhase = OrbitalPodPhase.Freefall)
{
float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.1f) : 0f;
if (stepDt > 0f)
@ -258,15 +262,28 @@ public sealed class CameraJuiceState
}
float speed = float.IsFinite(localSpeedMps) ? MathF.Max(0f, localSpeedMps) : 0f;
float speedStart = isVtol ? 14f : 12f;
float speedFull = isVtol ? 46f : 36f;
float targetFovOffset = speed > speedStart
? Math.Clamp((speed - speedStart) / (speedFull - speedStart), 0f, 1f) * (isVtol ? 4.8f : 3.4f)
: 0f;
float targetFovOffset;
float blendRate;
if (isInDropPod)
{
targetFovOffset = podPhase == OrbitalPodPhase.RetroBurn
? (DropRetroFovDeg - BaseFovDeg)
: (DropFreefallFovDeg - BaseFovDeg) + Math.Clamp(speed / 62f, 0f, 2.0f);
blendRate = DropFovBlendInRate;
}
else
{
float speedStart = isVtol ? 14f : 12f;
float speedFull = isVtol ? 46f : 36f;
targetFovOffset = speed > speedStart
? Math.Clamp((speed - speedStart) / (speedFull - speedStart), 0f, 1f) * (isVtol ? 4.8f : 3.4f)
: 0f;
blendRate = FovOffsetDeg > targetFovOffset + 0.5f ? DropFovBlendOutRate : FovBlendRate;
}
if (stepDt > 0f)
{
float blend = 1f - MathF.Exp(-FovBlendRate * stepDt);
float blend = 1f - MathF.Exp(-blendRate * stepDt);
FovOffsetDeg += (targetFovOffset - FovOffsetDeg) * blend;
if (MathF.Abs(FovOffsetDeg) < 0.002f && targetFovOffset == 0f)
{

View file

@ -31,12 +31,14 @@ public partial class Hud : CanvasLayer
private static readonly Color TextLight = Color.FromHtml("#e4dfd2");
private static readonly Color TextMuted = Color.FromHtml("#989487");
private static readonly Color CyanCol = Color.FromHtml("#44d9e8");
private static readonly Color AlliedCol = Color.FromHtml("#52e3a8");
private static readonly Color GoldCol = Color.FromHtml("#e6b838");
private static readonly Color RedCol = Color.FromHtml("#d93829");
private readonly Func<IClientArenaSession?> _getSession;
private readonly Action<int, string> _onEquipCargo;
private readonly Func<float> _getCameraYaw;
private readonly Func<System.Numerics.Vector3, (bool Visible, bool Behind, Vector2 ScreenPos)>? _projectWorld;
private Label _chassisHeader = null!;
private Label _planeBadge = null!;
@ -55,6 +57,7 @@ public partial class Hud : CanvasLayer
private Label _mapAttribLabel = null!;
private ColorRect _vignetteRect = null!;
private ShaderMaterial _vignetteMat = null!;
private SquadChevronOverlay _squadOverlay = null!;
private CrosshairOverlay _crosshair = null!;
private float _damagePulse;
private float _lowCoreRatio;
@ -94,11 +97,16 @@ public partial class Hud : CanvasLayer
public event Action? SoloRequested;
public event Action<bool>? NetworkPanelToggled;
public Hud(Func<IClientArenaSession?> getSession, Action<int, string> onEquipCargo, Func<float>? getCameraYaw = null)
public Hud(
Func<IClientArenaSession?> getSession,
Action<int, string> onEquipCargo,
Func<float>? getCameraYaw = null,
Func<System.Numerics.Vector3, (bool Visible, bool Behind, Vector2 ScreenPos)>? projectWorld = null)
{
_getSession = getSession;
_onEquipCargo = onEquipCargo;
_getCameraYaw = getCameraYaw ?? (() => 0f);
_projectWorld = projectWorld;
Layer = 10;
}
@ -362,11 +370,14 @@ public partial class Hud : CanvasLayer
? MathF.Max(0f, localPod.LastAgl)
: MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z));
float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY);
float horizSpeed = localPod is not null
? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ)
: player.Speed;
bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn;
_chassisHeader.Text = "ORBITAL DROP POD";
_planeBadge.Text = burning ? "RETRO BURN" : "FREEFALL";
_planeBadge.Modulate = burning ? OrangeCol : CyanCol;
_statsLabel.Text = $"ALT {agl:F0}m | VEL {velDown:F0} m/s | ALIVE {aliveCount} / {state.Contenders.Count}";
_statsLabel.Text = $"ALT {agl:F0}m | HORIZ {horizSpeed:F0} m/s | VERT {velDown:F0} m/s | ALIVE {aliveCount} / {state.Contenders.Count}";
_controlsHint.Text = "WASD Steer Pod | Mouse Look | Retro-Burn Auto | Wheel Zoom";
}
else
@ -481,7 +492,10 @@ public partial class Hud : CanvasLayer
? MathF.Max(0f, localPod.LastAgl)
: MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z));
float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY);
_promptLabel.Text = $"ORBITAL INSERTION — ALT {agl:F0}m | VEL {velDown:F0}m/s | [WASD] STEER"
float horizSpeed = localPod is not null
? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ)
: player.Speed;
_promptLabel.Text = $"ORBITAL INSERTION — ALT {agl:F0}m | HORIZ {horizSpeed:F0} m/s | VERT {velDown:F0} m/s | [WASD] STEER"
+ (localPod?.Phase == OrbitalPodPhase.RetroBurn ? " [RETRO BURN]" : "");
_promptLabel.Visible = true;
}
@ -491,6 +505,10 @@ public partial class Hud : CanvasLayer
_promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text);
}
// Squad 3D projected chevrons
_squadOverlay.SetState(session, _projectWorld);
_squadOverlay.QueueRedraw();
// Crosshair + Heat Arc / Orbital Altimeter + Directional Incoming Hit Arcs
_crosshair.SetState(state, player, _getCameraYaw(), localPod);
_crosshair.QueueRedraw();
@ -567,6 +585,11 @@ public partial class Hud : CanvasLayer
_vignetteRect.SetAnchorsPreset(Control.LayoutPreset.FullRect);
AddChild(_vignetteRect);
_squadOverlay = new SquadChevronOverlay { Name = "SquadChevrons" };
_squadOverlay.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_squadOverlay.MouseFilter = Control.MouseFilterEnum.Ignore;
AddChild(_squadOverlay);
_crosshair = new CrosshairOverlay { Name = "Crosshair" };
_crosshair.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_crosshair.MouseFilter = Control.MouseFilterEnum.Ignore;
@ -1527,10 +1550,14 @@ public partial class Hud : CanvasLayer
{
float agl = _localPod is not null ? MathF.Max(0f, _localPod.LastAgl) : 0f;
float vel = _localPod is not null ? MathF.Max(0f, -_localPod.VelY) : 0f;
float horizSpeed = _localPod is not null
? MathF.Sqrt(_localPod.VelX * _localPod.VelX + _localPod.VelZ * _localPod.VelZ)
: _player.Speed;
bool burning = _localPod?.Phase == OrbitalPodPhase.RetroBurn;
Color bracketCol = burning ? OrangeCol : CyanCol;
float altFrac = Math.Clamp(agl / 410f, 0f, 1f);
float startAlt = OrbitalPodPreset.GetStartAltAgl(OrbitalPodKind.Contender, _lastState?.MapKind ?? ArenaMapKind.Desert);
float altFrac = Math.Clamp(agl / MathF.Max(1f, startAlt), 0f, 1f);
const float barX = 72f;
const float barH = 76f;
Vector2 topL = center + new Vector2(-barX, -barH * 0.5f);
@ -1544,8 +1571,8 @@ public partial class Hud : CanvasLayer
DrawString(
ThemeDB.FallbackFont,
center + new Vector2(-46f, 54f),
$"ALT {agl:F0}m | {vel:F0}m/s",
center + new Vector2(-88f, 54f),
$"ALT {agl:F0}m | HORIZ {horizSpeed:F0} m/s | VERT {vel:F0} m/s",
HorizontalAlignment.Left,
-1,
11,
@ -1750,15 +1777,31 @@ public partial class Hud : CanvasLayer
if (pod.PodKind == OrbitalPodKind.Contender)
{
bool isLocalPod = pod.ContenderId == localId;
Color pCol = isLocalPod ? OliveCol : OrangeCol;
float sz = isLocalPod ? 5.5f : 3.6f;
var pts = new[]
bool isAllyPod = !isLocalPod && state.AreAllies(localId, pod.ContenderId);
if (isAllyPod)
{
pp + new Vector2(0f, -sz),
pp + new Vector2(-sz * 0.8f, sz * 0.7f),
pp + new Vector2(sz * 0.8f, sz * 0.7f)
};
DrawColoredPolygon(pts, pCol);
const float d = 4.6f;
var pts = new[]
{
pp + new Vector2(0f, -d),
pp + new Vector2(d, 0f),
pp + new Vector2(0f, d),
pp + new Vector2(-d, 0f)
};
DrawColoredPolygon(pts, AlliedCol);
}
else
{
Color pCol = isLocalPod ? OliveCol : OrangeCol;
float sz = isLocalPod ? 5.5f : 3.6f;
var pts = new[]
{
pp + new Vector2(0f, -sz),
pp + new Vector2(-sz * 0.8f, sz * 0.7f),
pp + new Vector2(sz * 0.8f, sz * 0.7f)
};
DrawColoredPolygon(pts, pCol);
}
}
else
{
@ -1869,6 +1912,23 @@ public partial class Hud : CanvasLayer
continue;
}
if (state.AreAllies(localId, c.Id))
{
float allyClampR = MathF.Max(4f, radius - 4.6f - 1f);
var (aPos, _, _) = _session.GetInterpolatedContenderPose(c.Id, 1f);
var p = ClampToRadarDisc(center, allyClampR, WorldToRadar(center, scale, aPos.X, aPos.Z, _cameraYaw));
const float d = 4.6f;
var pts = new[]
{
p + new Vector2(0f, -d),
p + new Vector2(d, 0f),
p + new Vector2(0f, d),
p + new Vector2(-d, 0f)
};
DrawColoredPolygon(pts, AlliedCol);
continue;
}
contenderContacts.TryGetValue(c.Id, out var mem);
if (!MatchState.IsContactOnRadar(mem))
{
@ -1895,4 +1955,102 @@ public partial class Hud : CanvasLayer
private static readonly Color PatronColor = Color.FromHtml("#4ba8a5");
}
private sealed partial class SquadChevronOverlay : Control
{
private IClientArenaSession? _session;
private Func<System.Numerics.Vector3, (bool Visible, bool Behind, Vector2 ScreenPos)>? _projectWorld;
public void SetState(
IClientArenaSession session,
Func<System.Numerics.Vector3, (bool Visible, bool Behind, Vector2 ScreenPos)>? projectWorld)
{
_session = session;
_projectWorld = projectWorld;
}
public override void _Draw()
{
if (_session is null || _projectWorld is null) return;
var state = _session.ViewState;
if (state.SquadSize <= 1) return;
int localId = _session.LocalContenderId;
Vector2 viewSize = Size;
if (viewSize.X < 64f || viewSize.Y < 64f) return;
var (localPos, _, _) = _session.GetInterpolatedContenderPose(localId, 1f);
const float borderPad = 36f;
Vector2 center = viewSize * 0.5f;
float halfW = MathF.Max(16f, center.X - borderPad);
float halfH = MathF.Max(16f, center.Y - borderPad);
for (int i = 0; i < state.Contenders.Count; i++)
{
var c = state.Contenders[i];
if (c.Id == localId || !c.Alive || !state.AreAllies(localId, c.Id)) continue;
var (allyPos, _, _) = _session.GetInterpolatedContenderPose(c.Id, 1f);
float dist = (allyPos - localPos).Length();
float headOffset = c.IsInDropPod ? 3.4f : (c.Grid.Spec.HalfHeight + 1.9f);
var worldHead = new System.Numerics.Vector3(allyPos.X, allyPos.Y + headOffset, allyPos.Z);
var (visible, behind, sp) = _projectWorld(worldHead);
if (!visible) continue;
bool inFrame = !behind &&
sp.X >= borderPad && sp.X <= viewSize.X - borderPad &&
sp.Y >= borderPad && sp.Y <= viewSize.Y - borderPad;
string label = $"{c.Name} {dist:F0}m";
if (inFrame)
{
var pts = new[]
{
sp + new Vector2(0f, 5f),
sp + new Vector2(-6f, -5f),
sp + new Vector2(6f, -5f)
};
DrawColoredPolygon(pts, AlliedCol);
DrawString(
ThemeDB.FallbackFont,
sp + new Vector2(-28f, -11f),
label,
HorizontalAlignment.Left,
-1,
10,
AlliedCol);
}
else
{
Vector2 dir = behind ? (center - sp) : (sp - center);
if (dir.LengthSquared() < 1e-4f) dir = Vector2.Up;
else dir = dir.Normalized();
float tx = MathF.Abs(dir.X) > 1e-4f ? halfW / MathF.Abs(dir.X) : float.PositiveInfinity;
float ty = MathF.Abs(dir.Y) > 1e-4f ? halfH / MathF.Abs(dir.Y) : float.PositiveInfinity;
Vector2 edge = center + dir * MathF.Min(tx, ty);
Vector2 perp = new(-dir.Y, dir.X);
var pts = new[]
{
edge + dir * 7f,
edge - dir * 5f + perp * 5f,
edge - dir * 5f - perp * 5f
};
DrawColoredPolygon(pts, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.88f));
Vector2 textPos = new(
Math.Clamp(edge.X - 32f, 10f, viewSize.X - 110f),
Math.Clamp(edge.Y + (dir.Y > 0f ? -12f : 18f), 16f, viewSize.Y - 12f));
DrawString(
ThemeDB.FallbackFont,
textPos,
label,
HorizontalAlignment.Left,
-1,
10,
new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.90f));
}
}
}
}
}

View file

@ -16,11 +16,22 @@ public sealed partial class LobbyScreen : CanvasLayer
{
public required PanelContainer Frame;
public required Label IndexLabel;
public required Label SquadBadge;
public required Label NameLabel;
public required Label RoleBadge;
public required Label ReadyBadge;
}
private static readonly Color[] SquadColors =
{
Color.FromHtml("#52e3a8"),
ImperialChrome.CyanCol,
ImperialChrome.GoldCol,
ImperialChrome.OrangeCol,
ImperialChrome.OliveCol,
Color.FromHtml("#d67cff")
};
private readonly SlotRowView[] _slotViews = new SlotRowView[MatchState.ContenderCount];
private Control _root = null!;
@ -32,11 +43,13 @@ public sealed partial class LobbyScreen : CanvasLayer
private OptionButton _mapOption = null!;
private LineEdit _seedEdit = null!;
private OptionButton _squadOption = null!;
private Button _applyConfigBtn = null!;
private Button _randomSeedBtn = null!;
private Label _authorityNoteLabel = null!;
private Label _netStatusLabel = null!;
private Button _switchSquadBtn = null!;
private Button _readyBtn = null!;
private Button _launchBtn = null!;
private Button _leaveBtn = null!;
@ -44,6 +57,7 @@ public sealed partial class LobbyScreen : CanvasLayer
private IClientArenaSession? _activeSession;
private int? _lastSyncedSeed;
private byte? _lastSyncedMap;
private byte? _lastSyncedSquadSize;
public LobbyScreen()
{
@ -72,6 +86,7 @@ public sealed partial class LobbyScreen : CanvasLayer
_activeSession = null;
_lastSyncedSeed = null;
_lastSyncedMap = null;
_lastSyncedSquadSize = null;
_seedEdit?.ReleaseFocus();
}
}
@ -101,9 +116,11 @@ public sealed partial class LobbyScreen : CanvasLayer
_countdownLabel.AddThemeColorOverride("font_color", net.LastError is not null ? ImperialChrome.RedCol : ImperialChrome.OrangeCol);
_rosterSummaryLabel.Text = "Awaiting authoritative lobby roster...";
_readyBtn.Disabled = true;
_switchSquadBtn.Disabled = true;
_launchBtn.Visible = false;
_mapOption.Disabled = true;
_seedEdit.Editable = false;
_squadOption.Disabled = true;
_applyConfigBtn.Disabled = true;
_randomSeedBtn.Disabled = true;
_authorityNoteLabel.Text = "Waiting for server snapshot...";
@ -114,9 +131,11 @@ public sealed partial class LobbyScreen : CanvasLayer
int localId = session.LocalContenderId;
bool isHost = lobby.HostSlotId.HasValue && lobby.HostSlotId.Value == localId;
bool localReady = false;
byte localSquadId = 0;
int humanCount = 0;
int readyCount = 0;
int aiCount = 0;
byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4);
for (int i = 0; i < _slotViews.Length; i++)
{
@ -126,8 +145,19 @@ public sealed partial class LobbyScreen : CanvasLayer
var slot = lobby.Slots[i];
bool isLocalSlot = slot.SlotId == localId;
bool isHostSlot = lobby.HostSlotId.HasValue && slot.SlotId == lobby.HostSlotId.Value;
if (isLocalSlot) localSquadId = slot.SquadId;
view.IndexLabel.Text = $"SLOT {slot.SlotId + 1:00}";
if (squadSize > 1)
{
view.SquadBadge.Text = $"[SQ {slot.SquadId + 1}]";
view.SquadBadge.AddThemeColorOverride("font_color", SquadColors[slot.SquadId % SquadColors.Length]);
}
else
{
view.SquadBadge.Text = "[FFA]";
view.SquadBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
}
if (slot.IsHuman)
{
humanCount++;
@ -183,7 +213,7 @@ public sealed partial class LobbyScreen : CanvasLayer
_panel.SetAccentColor(ImperialChrome.CyanCol);
}
// Sync Map & Seed without clobbering active typing by host
// Sync Map, Seed & SquadSize without clobbering active typing by host
if (_lastSyncedMap != lobby.SelectedMap)
{
_lastSyncedMap = lobby.SelectedMap;
@ -194,17 +224,28 @@ public sealed partial class LobbyScreen : CanvasLayer
_lastSyncedSeed = lobby.SelectedSeed;
_seedEdit.Text = lobby.SelectedSeed.ToString(CultureInfo.InvariantCulture);
}
if (_lastSyncedSquadSize != squadSize)
{
_lastSyncedSquadSize = squadSize;
_squadOption.Select(squadSize - 1);
}
// Strict host authority gating
_mapOption.Disabled = !isHost;
_seedEdit.Editable = isHost;
_squadOption.Disabled = !isHost;
_applyConfigBtn.Disabled = !isHost;
_randomSeedBtn.Disabled = !isHost;
_authorityNoteLabel.Text = isHost
? "HOST AUTHORITY: You control drop zone, seed, and forced launch."
: "READ-ONLY: Only the match host can edit map, seed, or force launch.";
? "HOST AUTHORITY: You control drop zone, seed, squad mode, and forced launch."
: "READ-ONLY: Only the match host can edit map, seed, squad mode, or force launch.";
_authorityNoteLabel.AddThemeColorOverride("font_color", isHost ? ImperialChrome.GoldCol : ImperialChrome.TextMuted);
_switchSquadBtn.Disabled = squadSize <= 1;
_switchSquadBtn.Text = squadSize > 1
? $"SWITCH SQUAD [SQ {localSquadId + 1}]"
: "SWITCH SQUAD (FFA)";
_readyBtn.Disabled = false;
_readyBtn.Text = localReady ? "READY [ON] — CLICK TO UNREADY" : "READY UP";
ImperialChrome.StyleButton(_readyBtn, localReady ? ImperialChrome.OliveCol : ImperialChrome.CyanCol, 14);
@ -240,10 +281,10 @@ public sealed partial class LobbyScreen : CanvasLayer
_panel.AnchorRight = 0.5f;
_panel.AnchorTop = 0.5f;
_panel.AnchorBottom = 0.5f;
_panel.OffsetLeft = -500f;
_panel.OffsetRight = 500f;
_panel.OffsetTop = -305f;
_panel.OffsetBottom = 305f;
_panel.OffsetLeft = -515f;
_panel.OffsetRight = 515f;
_panel.OffsetTop = -330f;
_panel.OffsetBottom = 330f;
_root.AddChild(_panel);
var vbox = new VBoxContainer();
@ -309,9 +350,13 @@ public sealed partial class LobbyScreen : CanvasLayer
frame.AddChild(row);
var idxLbl = ImperialChrome.CreateLabel($"SLOT {i + 1:00}", 11, ImperialChrome.TextMuted);
idxLbl.CustomMinimumSize = new Vector2(64f, 0f);
idxLbl.CustomMinimumSize = new Vector2(60f, 0f);
row.AddChild(idxLbl);
var sqLbl = ImperialChrome.CreateLabel("[SQ 1]", 11, SquadColors[0]);
sqLbl.CustomMinimumSize = new Vector2(54f, 0f);
row.AddChild(sqLbl);
var nameLbl = ImperialChrome.CreateLabel("AI BACKFILL", 12, ImperialChrome.TextMuted);
nameLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
nameLbl.ClipText = true;
@ -332,6 +377,7 @@ public sealed partial class LobbyScreen : CanvasLayer
{
Frame = frame,
IndexLabel = idxLbl,
SquadBadge = sqLbl,
NameLabel = nameLbl,
RoleBadge = roleLbl,
ReadyBadge = readyLbl
@ -392,7 +438,23 @@ public sealed partial class LobbyScreen : CanvasLayer
};
seedRow.AddChild(_randomSeedBtn);
_applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP & SEED", ImperialChrome.GoldCol, 12, 32f);
var squadRow = new HBoxContainer();
squadRow.AddThemeConstantOverride("separation", 8);
rightCol.AddChild(squadRow);
var squadLbl = ImperialChrome.CreateLabel("SQUAD", 12, ImperialChrome.TextMuted);
squadLbl.CustomMinimumSize = new Vector2(68f, 0f);
squadRow.AddChild(squadLbl);
_squadOption = new OptionButton { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
_squadOption.AddItem("FFA (1)", 0);
_squadOption.AddItem("DUO (2)", 1);
_squadOption.AddItem("TRIO (3)", 2);
_squadOption.AddItem("QUAD (4)", 3);
_squadOption.Select(2);
ImperialChrome.StyleOptionButton(_squadOption, ImperialChrome.CyanCol, 13);
_squadOption.ItemSelected += _ => ApplyConfigFromUi();
squadRow.AddChild(_squadOption);
_applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP, SEED & SQUAD", ImperialChrome.GoldCol, 12, 32f);
_applyConfigBtn.Pressed += ApplyConfigFromUi;
rightCol.AddChild(_applyConfigBtn);
@ -405,6 +467,10 @@ public sealed partial class LobbyScreen : CanvasLayer
var spacer = new Control { SizeFlagsVertical = Control.SizeFlags.ExpandFill };
rightCol.AddChild(spacer);
_switchSquadBtn = ImperialChrome.CreateButton("SWITCH SQUAD [SQ 1]", SquadColors[0], 13, 36f);
_switchSquadBtn.Pressed += OnSwitchSquadPressed;
rightCol.AddChild(_switchSquadBtn);
_readyBtn = ImperialChrome.CreateButton("READY UP", ImperialChrome.CyanCol, 14, 42f);
_readyBtn.Pressed += OnReadyPressed;
rightCol.AddChild(_readyBtn);
@ -438,6 +504,27 @@ public sealed partial class LobbyScreen : CanvasLayer
_activeSession.SetLobbyReady(!currentReady);
}
private void OnSwitchSquadPressed()
{
if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return;
byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4);
if (squadSize <= 1) return;
int maxSquads = Math.Max(1, (MatchState.ContenderCount + squadSize - 1) / squadSize);
int localId = _activeSession.LocalContenderId;
byte curSq = 0;
for (int i = 0; i < lobby.Slots.Count; i++)
{
if (lobby.Slots[i].SlotId == localId)
{
curSq = lobby.Slots[i].SquadId;
break;
}
}
byte nextSq = (byte)((curSq + 1) % maxSquads);
_activeSession.RequestLobbySquad(nextSq);
}
private void OnLaunchPressed()
{
_activeSession?.RequestLobbyStart();
@ -452,9 +539,10 @@ public sealed partial class LobbyScreen : CanvasLayer
int seed = int.TryParse(_seedEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed)
? parsed
: lobby.SelectedSeed;
byte squadSize = (byte)Math.Clamp(_squadOption.Selected + 1, 1, 4);
_seedEdit.ReleaseFocus();
_activeSession.RequestLobbyConfig(seed, mapKind);
_activeSession.RequestLobbyConfig(seed, mapKind, squadSize);
}
private static void ApplyRowFrame(PanelContainer frame, Color borderColor, bool highlighted)

View file

@ -64,6 +64,7 @@ public partial class Main : Node3D
private readonly List<ISimEvent> _frameEvents = new(128);
private readonly List<FootstepPulse> _frameFootsteps = new(32);
private ArenaMapKind _mapKind = ArenaMapKind.Sion;
private byte _squadSize = 3;
private string _callsign = "Pilot";
private string _lastEndpoint = $"127.0.0.1:{DefaultNetPort}";
@ -158,11 +159,11 @@ public partial class Main : Node3D
Name = "ShoulderCamera",
Current = true,
Fov = 58f,
Far = 4200f
Far = 4800f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" };
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw, ProjectWorldToHud) { Name = "Hud" };
_hud.JoinRequested += OnJoinRequested;
_hud.HostRequested += OnHostRequested;
_hud.SoloRequested += OnSoloRequested;
@ -226,6 +227,11 @@ public partial class Main : Node3D
string? cliName = GetCliArg("--name");
string? cliMap = GetCliArg("--map");
string? cliSeed = GetCliArg("--seed");
string? cliSquadSize = GetCliArg("--squad-size");
if (int.TryParse(cliSquadSize ?? System.Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedSquad))
{
_squadSize = (byte)Math.Clamp(parsedSquad, 1, 4);
}
bool cliSolo = GetCliArg("--solo", allowBareFlag: true) is not null
|| System.Environment.GetEnvironmentVariable("RTD_SOLO") == "1";
bool cliLobby = GetCliArg("--lobby", allowBareFlag: true) is not null
@ -291,7 +297,7 @@ public partial class Main : Node3D
: $"127.0.0.1:{hostTarget.Trim()}";
}
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
@ -419,13 +425,17 @@ public partial class Main : Node3D
DisposeSessionAndDirectory();
}
public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false)
public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false, byte? squadSize = null)
{
_seed = seed;
if (mapKind.HasValue)
{
_mapKind = mapKind.Value;
}
if (squadSize.HasValue)
{
_squadSize = (byte)Math.Clamp((int)squadSize.Value, 1, 4);
}
DisposeSessionAndDirectory();
Failure = null;
@ -433,7 +443,7 @@ public partial class Main : Node3D
try
{
_session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop);
_session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop, squadSize: _squadSize);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: true);
}
@ -450,7 +460,7 @@ public partial class Main : Node3D
Failure = null;
_hud.SetNetworkError(null);
EnsureMenuSionBackdrop();
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort);
_mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize);
_mainMenu.SetHostPanelOpen(false);
SetScreenMode(ClientScreenMode.MainMenu);
}
@ -593,10 +603,13 @@ public partial class Main : Node3D
string serverName,
bool startInLobby,
bool listOnPublicDirectory,
bool fallbackToLocalOnFailure)
bool fallbackToLocalOnFailure,
byte? squadSize = null)
{
string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim();
string cleanServerName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim();
byte activeSquadSize = (byte)Math.Clamp((int)(squadSize ?? _squadSize), 1, 4);
_squadSize = activeSquadSize;
Failure = null;
_hud.SetNetworkError(null);
_mainMenu.SetHostError(null);
@ -612,7 +625,8 @@ public partial class Main : Node3D
mapKind,
startInLobby: startInLobby,
serverName: cleanServerName,
minHumansToStart: 1);
minHumansToStart: 1,
squadSize: activeSquadSize);
hostSession.Host.Session.SetHumanSlot(0, true, nextCallsign);
DisposeSessionAndDirectory();
@ -641,7 +655,7 @@ public partial class Main : Node3D
Failure = ex.Message;
if (fallbackToLocalOnFailure && _session is null)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign);
_session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: false);
}
@ -677,7 +691,7 @@ public partial class Main : Node3D
Failure = ex.Message;
if (!fromBrowser && _session is null && _screenMode == ClientScreenMode.InMatch)
{
_session = new LocalArenaSession(_seed, _mapKind, _callsign);
_session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize);
SetScreenMode(ClientScreenMode.InMatch);
BindSessionPresentation(resetCamera: false);
}
@ -737,11 +751,12 @@ public partial class Main : Node3D
}
}
private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign)
private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign, byte squadSize)
{
_callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim();
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
_hud.SetNetworkDefaults(_lastEndpoint, _callsign);
Reset(_seed, mapKind, skipInitialDrop: false);
Reset(_seed, mapKind, skipInitialDrop: false, squadSize: _squadSize);
}
private void OnMainMenuServerBrowser(string callsign)
@ -751,10 +766,11 @@ public partial class Main : Node3D
SetScreenMode(ClientScreenMode.ServerBrowser);
}
private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign)
private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign, byte squadSize)
{
string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND");
string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture);
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
StartListenHostSession(
hostArg,
callsign,
@ -762,7 +778,8 @@ public partial class Main : Node3D
serverName,
startInLobby: true,
listOnPublicDirectory: listOnPublicDirectory,
fallbackToLocalOnFailure: false);
fallbackToLocalOnFailure: false,
squadSize: _squadSize);
}
private void OnBrowserJoinRequested(string endpointText, string callsign)
@ -810,7 +827,7 @@ public partial class Main : Node3D
_prevLocalLifecycle = p.Lifecycle;
if (p.IsInDropPod)
{
_cameraPitch = Mathf.DegToRad(36f);
_cameraPitch = Mathf.DegToRad(34f);
_orbitalPodCamBlend = 1.0f;
}
else
@ -833,7 +850,7 @@ public partial class Main : Node3D
_audio.ResetForSession(_session);
}
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f;
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4800f : 2600f;
_atmosphere.ApplyMap(_mapKind);
bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby;
@ -1381,7 +1398,7 @@ public partial class Main : Node3D
var local = _session.LocalContender;
if (local.Lifecycle == ContenderLifecycle.Deploying && _prevLocalLifecycle != ContenderLifecycle.Deploying)
{
_cameraPitch = Mathf.DegToRad(36f);
_cameraPitch = Mathf.DegToRad(34f);
_orbitalPodCamBlend = 1.0f;
}
_prevLocalLifecycle = local.Lifecycle;
@ -1389,21 +1406,27 @@ public partial class Main : Node3D
var localPos = new System.Numerics.Vector3(local.X, local.Y, local.Z);
_camJuice.ConsumeEvents(_frameEvents, _session.LocalContenderId, localPos, _session);
_camJuice.ConsumeFootsteps(_frameFootsteps, _session.LocalContenderId);
OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall;
float camHorizSpeed = local.Speed;
if (local.IsInDropPod)
{
var pods = _session.ActivePods;
for (int i = 0; i < pods.Count; i++)
{
if (pods[i].PodKind == OrbitalPodKind.Contender &&
pods[i].ContenderId == _session.LocalContenderId &&
pods[i].Phase == OrbitalPodPhase.RetroBurn)
pods[i].ContenderId == _session.LocalContenderId)
{
_camJuice.ApplyOrbitalBurnRumble(1.0f);
localPodPhase = pods[i].Phase;
camHorizSpeed = MathF.Sqrt(pods[i].VelX * pods[i].VelX + pods[i].VelZ * pods[i].VelZ);
if (pods[i].Phase == OrbitalPodPhase.RetroBurn)
{
_camJuice.ApplyOrbitalBurnRumble(1.0f);
}
break;
}
}
}
_camJuice.Update(dt, local.Speed, local.Grid.Spec.IsVtol);
_camJuice.Update(dt, camHorizSpeed, local.Grid.Spec.IsVtol, local.IsInDropPod, localPodPhase);
}
private static readonly Color DesertDustTint = new(0.76f, 0.59f, 0.40f, 1.0f);
@ -1768,11 +1791,11 @@ public partial class Main : Node3D
new Vector3(posInterp.X, surfY + 0.35f, posInterp.Z));
_orbitalPodCamBlend = 1.0f;
float backDist = 23.0f * _cameraZoom;
Vector3 pivot = new(posInterp.X, posInterp.Y + 3.2f, posInterp.Z);
float backDist = 28.0f * _cameraZoom;
Vector3 pivot = new(posInterp.X, posInterp.Y + 4.0f, posInterp.Z);
lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized();
float effectiveRight = 2.6f;
float effectiveRight = 1.6f;
if (CastStaticCameraRay(pivot, camRight, effectiveRight, out float rightHitDist))
{
effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist));
@ -1993,4 +2016,16 @@ public partial class Main : Node3D
{
_session?.RequestEquipCargo(cargoIndex, hardpointId);
}
private (bool Visible, bool Behind, Vector2 ScreenPos) ProjectWorldToHud(System.Numerics.Vector3 worldPos)
{
if (_camera is null || !GodotObject.IsInstanceValid(_camera) || !_camera.IsInsideTree())
{
return (false, false, Vector2.Zero);
}
var wp = new Vector3(worldPos.X, worldPos.Y, worldPos.Z);
bool behind = _camera.IsPositionBehind(wp);
Vector2 sp = _camera.UnprojectPosition(wp);
return (true, behind, sp);
}
}

View file

@ -22,11 +22,13 @@ public sealed partial class MainMenu : CanvasLayer
private ImperialChromePanel _menuPanel = null!;
private ImperialChromePanel _hostPanel = null!;
private LineEdit _callsignEdit = null!;
private OptionButton _soloSquadOption = null!;
private Label _statusLabel = null!;
private LineEdit _serverNameEdit = null!;
private LineEdit _portEdit = null!;
private OptionButton _hostMapOption = null!;
private OptionButton _hostSquadOption = null!;
private CheckBox _listPublicCheck = null!;
private Label _directoryHintLabel = null!;
private Label _hostErrorLabel = null!;
@ -42,9 +44,9 @@ public sealed partial class MainMenu : CanvasLayer
Layer = 20;
}
public event Action<ArenaMapKind, string>? PlaySoloRequested;
public event Action<ArenaMapKind, string, byte>? PlaySoloRequested;
public event Action<string>? ServerBrowserRequested;
public event Action<int, string, ArenaMapKind, bool, string>? HostLobbyRequested;
public event Action<int, string, ArenaMapKind, bool, string, byte>? HostLobbyRequested;
public event Action<string>? CallsignChanged;
public event Action? QuitRequested;
public event Action? ResumeRequested;
@ -97,13 +99,16 @@ public sealed partial class MainMenu : CanvasLayer
}
}
public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076)
public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076, byte defaultSquadSize = 3)
{
_directoryUrl = directoryUrl ?? string.Empty;
if (_callsignEdit is not null)
{
_callsignEdit.Text = SanitizeCallsign(callsign);
}
int sqIdx = Math.Clamp((int)defaultSquadSize, 1, 4) - 1;
_soloSquadOption?.Select(sqIdx);
_hostSquadOption?.Select(sqIdx);
if (_portEdit is not null)
{
_portEdit.Text = defaultPort.ToString(CultureInfo.InvariantCulture);
@ -120,6 +125,14 @@ public sealed partial class MainMenu : CanvasLayer
}
}
public byte SelectedSoloSquadSize => _soloSquadOption is not null
? (byte)Math.Clamp(_soloSquadOption.Selected + 1, 1, 4)
: (byte)3;
public byte SelectedHostSquadSize => _hostSquadOption is not null
? (byte)Math.Clamp(_hostSquadOption.Selected + 1, 1, 4)
: (byte)3;
public void SetStatus(string? message, bool isError = false)
{
if (_statusLabel is null) return;
@ -213,14 +226,26 @@ public sealed partial class MainMenu : CanvasLayer
_callsignEdit.TextChanged += txt => CallsignChanged?.Invoke(SanitizeCallsign(txt));
callRow.AddChild(_callsignEdit);
var squadRow = new HBoxContainer();
squadRow.AddThemeConstantOverride("separation", 10);
vbox.AddChild(squadRow);
var squadLbl = ImperialChrome.CreateLabel("SQUAD MODE", 12, ImperialChrome.TextMuted);
squadLbl.CustomMinimumSize = new Vector2(82f, 0f);
squadRow.AddChild(squadLbl);
_soloSquadOption = CreateSquadOptionButton();
_soloSquadOption.ItemSelected += idx => _hostSquadOption?.Select((int)idx);
squadRow.AddChild(_soloSquadOption);
vbox.AddChild(ImperialChrome.MakeRule());
var playSionBtn = ImperialChrome.CreateButton("PLAY SOLO — SION", ImperialChrome.OliveCol, 14, 38f);
playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign);
playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign, SelectedSoloSquadSize);
vbox.AddChild(playSionBtn);
var playDesertBtn = ImperialChrome.CreateButton("PLAY SOLO — DESERT", ImperialChrome.OrangeCol, 14, 38f);
playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign);
playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign, SelectedSoloSquadSize);
vbox.AddChild(playDesertBtn);
var browserBtn = ImperialChrome.CreateButton("SERVER BROWSER", ImperialChrome.CyanCol, 14, 38f);
@ -314,6 +339,15 @@ public sealed partial class MainMenu : CanvasLayer
ImperialChrome.StyleOptionButton(_hostMapOption, ImperialChrome.OliveCol, 13);
mapRow.AddChild(_hostMapOption);
var hostSqRow = new HBoxContainer();
hostSqRow.AddThemeConstantOverride("separation", 8);
vbox.AddChild(hostSqRow);
var hostSqLbl = ImperialChrome.CreateLabel("SQUAD MODE", 11, ImperialChrome.TextMuted);
hostSqLbl.CustomMinimumSize = new Vector2(106f, 0f);
hostSqRow.AddChild(hostSqLbl);
_hostSquadOption = CreateSquadOptionButton();
hostSqRow.AddChild(_hostSquadOption);
_listPublicCheck = new CheckBox
{
Text = "List on Public Directory",
@ -361,7 +395,22 @@ public sealed partial class MainMenu : CanvasLayer
bool listPublic = _listPublicCheck.ButtonPressed;
SetHostError(null);
HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign);
HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign, SelectedHostSquadSize);
}
private static OptionButton CreateSquadOptionButton()
{
var opt = new OptionButton
{
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
opt.AddItem("FFA (1)", 0);
opt.AddItem("DUO (2)", 1);
opt.AddItem("TRIO (3)", 2);
opt.AddItem("QUAD (4)", 3);
opt.Select(2);
ImperialChrome.StyleOptionButton(opt, ImperialChrome.CyanCol, 13);
return opt;
}
private void BuildPauseRoot()

View file

@ -1930,9 +1930,12 @@ public partial class Smoke : Node
bool sawRetroBurn = false;
bool sawGearEarlyTouchdown = false;
bool sawWideDropFov = false;
int touchdownTick = -1;
int debrisAtTouchdown = 0;
Check(session.ViewState.SquadSize == 3, $"Expected Solo Sion default SquadSize == 3, got {session.ViewState.SquadSize}");
_main.SetScriptedInput(new PlayerInput(
Throttle: 1f,
Steer: 0f,
@ -1942,7 +1945,7 @@ public partial class Smoke : Node
InteractPickup: false,
Brake: false));
for (int tick = 0; tick < 620; tick++)
for (int tick = 0; tick < 2000; tick++)
{
var tickInp = _main.Session.LocalContender.IsInDropPod
? new PlayerInput(1f, 0f, player.X, player.Z + 120f, false, false, false)
@ -1955,26 +1958,40 @@ public partial class Smoke : Node
session.DrainSimEvents(evs);
_main.Arena.ConsumeEvents(session, evs, Array.Empty<FootstepPulse>(), 1f / 60f, _main.SampleCurrentMapGroundTint);
_main.CameraJuice.ConsumeEvents(evs, session.LocalContenderId, new System.Numerics.Vector3(player.X, player.Y, player.Z), session);
_main.Audio.UpdateFrame(session, evs, Array.Empty<FootstepPulse>(), _main.Camera.GlobalPosition, 1f / 60f, 1f);
_main.Hud.Sync(session);
if (tick == 270) // t = 4.5s: gear pods should have landed while player is still falling
{
sawGearEarlyTouchdown = session.ViewState.GroundDrops.Count >= 35 && player.IsInDropPod;
}
OrbitalPodPhase podPhase = OrbitalPodPhase.Freefall;
float dropHorizSpeed = player.Speed;
if (player.IsInDropPod)
{
foreach (var pod in session.ActivePods)
{
if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == player.Id && pod.Phase == OrbitalPodPhase.RetroBurn)
if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == player.Id)
{
sawRetroBurn = true;
podPhase = pod.Phase;
dropHorizSpeed = MathF.Sqrt(pod.VelX * pod.VelX + pod.VelZ * pod.VelZ);
if (pod.Phase == OrbitalPodPhase.RetroBurn)
{
sawRetroBurn = true;
}
break;
}
}
}
else if (touchdownTick < 0 && player.IsGroundedActive)
_main.CameraJuice.Update(1f / 60f, dropHorizSpeed, player.Grid.Spec.IsVtol, player.IsInDropPod, podPhase);
if (player.IsInDropPod && (CameraJuiceState.BaseFovDeg + _main.CameraJuice.FovOffsetDeg) >= 80f)
{
sawWideDropFov = true;
}
_main.Audio.UpdateFrame(session, evs, Array.Empty<FootstepPulse>(), _main.Camera.GlobalPosition, 1f / 60f, 1f);
_main.Hud.Sync(session);
if (!sawGearEarlyTouchdown && session.ViewState.GroundDrops.Count >= 35 && player.IsInDropPod)
{
sawGearEarlyTouchdown = true;
}
if (!player.IsInDropPod && touchdownTick < 0 && player.IsGroundedActive)
{
touchdownTick = tick;
debrisAtTouchdown = _main.Arena.Debris.ActiveCount;
@ -1982,9 +1999,10 @@ public partial class Smoke : Node
}
}
Check(sawGearEarlyTouchdown, $"Expected >= 35 Wave 0 gear drops on ground at t=4.5s while player still in pod (drops={session.ViewState.GroundDrops.Count}, inPod={player.IsInDropPod})");
Check(sawGearEarlyTouchdown, $"Expected >= 35 Wave 0 gear drops on ground while player still in pod (drops={session.ViewState.GroundDrops.Count}, inPod={player.IsInDropPod})");
Check(sawRetroBurn, "Expected local player pod to enter RetroBurn phase");
Check(touchdownTick > 240 && touchdownTick < 620, $"Expected player pod touchdown in (240, 620) ticks, got {touchdownTick}");
Check(sawWideDropFov, $"Expected wide drop-camera FOV >= 80 deg during Freefall, peak offset={_main.CameraJuice.FovOffsetDeg:F2}");
Check(touchdownTick > 1000 && touchdownTick < 2000, $"Expected Sion 1620m player pod touchdown in (1000, 2000) ticks, got {touchdownTick}");
Check(debrisAtTouchdown >= 4, $"Expected >= 4 blown-off petals in DebrisSystem on touchdown, got {debrisAtTouchdown}");
Check(VehicleVisualInstance.PerfMaterialDupCount == 0, $"Expected 0 material duplicates during orbital drop, got {VehicleVisualInstance.PerfMaterialDupCount}");
@ -2197,8 +2215,9 @@ public partial class Smoke : Node
{
sim.SetContenderPose(cIdx, 480f + cIdx * 12f, 480f);
}
int enemyIdx = sim.State.SquadSize > 1 ? sim.State.SquadSize : 1;
sim.SetContenderPose(0, 0f, 0f, 0f);
sim.SetContenderPose(1, 0f, 125f, MathF.PI); // target Anvil/rival 125m ahead
sim.SetContenderPose(enemyIdx, 0f, 125f, MathF.PI); // target Anvil/rival 125m ahead (non-ally)
int audioShotsBefore = _main.Audio.Total3DPlaysRequested;
bool sawMirrorRocket = false;

View file

@ -58,7 +58,9 @@ namespace RustToDust.Core
bool RequestEquipCargo(int cargoIndex, string hardpointId);
void RequestNewMatch(int seed, ArenaMapKind mapKind);
bool SetLobbyReady(bool ready) => false;
bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => false;
bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => RequestLobbyConfig(seed, mapKind, LobbyState?.SquadSize ?? 3);
bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize) => false;
bool RequestLobbySquad(byte targetSquadId) => false;
bool RequestLobbyStart() => false;
(Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha);

View file

@ -344,7 +344,7 @@ namespace RustToDust.Core
for (int j = 0; j < state.Contenders.Count; j++)
{
var other = state.Contenders[j];
if (other.Id == ai.Id || !other.IsGroundedActive)
if (other.Id == ai.Id || state.AreAllies(ai.Id, other.Id) || !other.IsGroundedActive)
{
continue;
}
@ -843,6 +843,52 @@ namespace RustToDust.Core
state.OrbitalDrop.CheckFinalRingCutoff();
bool canRespawn = state.OrbitalDrop.CanAnyWaitingContenderRespawn();
if (state.SquadSize > 1)
{
uint aliveSquadMask = 0;
ContenderState? lowestActive = null;
ContenderState? lowestWaiting = null;
for (int i = 0; i < state.Contenders.Count; i++)
{
var c = state.Contenders[i];
if (c.Alive)
{
if (c.SquadId < 32)
{
aliveSquadMask |= 1u << c.SquadId;
}
if (lowestActive is null || c.Id < lowestActive.Id)
{
lowestActive = c;
}
}
else if (c.WaitingForRespawn && canRespawn)
{
if (c.SquadId < 32)
{
aliveSquadMask |= 1u << c.SquadId;
}
if (lowestWaiting is null || c.Id < lowestWaiting.Id)
{
lowestWaiting = c;
}
}
}
int survivingSquads = BitOperations.PopCount(aliveSquadMask);
if (survivingSquads <= 1)
{
var winner = lowestActive ?? lowestWaiting;
state.Phase = MatchPhase.Completed;
state.WinnerContenderId = winner?.Id;
if (winner is not null)
{
state.Broadcast.EmitVictory(state.Time, winner.Id, state.MapKind);
}
}
return;
}
int aliveCount = 0;
int waitingCount = 0;
ContenderState? survivor = null;

View file

@ -17,25 +17,34 @@ namespace RustToDust.Core
public string Callsign { get; set; } = string.Empty;
public bool IsHuman { get; set; }
public bool IsReady { get; set; }
public byte SquadId { get; set; }
}
public sealed class LobbyState
{
public const float DefaultCountdownSeconds = 5.0f;
public LobbyState(int contenderCount, ArenaMapKind mapKind, int seed, int? hostSlotId = null, int minHumansToAutoStart = 1)
public LobbyState(
int contenderCount,
ArenaMapKind mapKind,
int seed,
int? hostSlotId = null,
int minHumansToAutoStart = 1,
byte squadSize = 3)
{
SelectedMap = mapKind;
SelectedSeed = seed;
HostSlotId = hostSlotId;
MinHumansToAutoStart = Math.Max(1, minHumansToAutoStart);
SquadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
Slots = new LobbySlotState[contenderCount];
for (int i = 0; i < contenderCount; i++)
{
Slots[i] = new LobbySlotState
{
SlotId = i,
Callsign = $"Contender {i + 1:00}"
Callsign = $"Contender {i + 1:00}",
SquadId = SquadSize > 1 ? (byte)(i / SquadSize) : (byte)i
};
}
}
@ -46,6 +55,7 @@ namespace RustToDust.Core
public bool ForceLaunched { get; set; }
public ArenaMapKind SelectedMap { get; set; }
public int SelectedSeed { get; set; }
public byte SquadSize { get; set; } = 3;
public LobbySlotState[] Slots { get; }
}
@ -205,6 +215,7 @@ namespace RustToDust.Core
public int Id { get; }
public string Name { get; set; }
public bool IsHuman { get; set; }
public byte SquadId { get; set; }
public ChassisGrid Grid { get; set; }
public ContenderLifecycle Lifecycle { get; set; } = ContenderLifecycle.Active;
public int RespawnsRemaining { get; set; } = 1;
@ -336,14 +347,21 @@ namespace RustToDust.Core
private readonly List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> _pendingLootTargets;
private readonly List<(int ContenderId, float X, float Z, float Yaw)> _pendingContenderTargets;
public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false, bool startInLobby = false)
public MatchState(
int seed = 42,
ArenaMapKind mapKind = ArenaMapKind.Desert,
bool skipInitialDrop = false,
bool startInLobby = false,
byte squadSize = 1)
{
Seed = seed;
MapKind = mapKind;
SquadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
_pendingSkipInitialDrop = skipInitialDrop;
Rng = new Random(seed);
Broadcast = new BroadcastFeed();
OrbitalDrop = new OrbitalDropSystem(this);
_pendingContenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(ContenderCount);
List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> lootTargets;
if (mapKind == ArenaMapKind.Sion)
@ -369,6 +387,8 @@ namespace RustToDust.Core
SionMap.Metadata.MaxY + 140f);
SeatSpectatorsOnSion();
SpawnContendersSion();
AssignDefaultSquadIds();
ApplySquadFormationTargets();
lootTargets = BuildInitialLootTargetsSion();
}
else
@ -379,21 +399,17 @@ namespace RustToDust.Core
ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain);
ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f);
SpawnContenders();
AssignDefaultSquadIds();
ApplySquadFormationTargets();
lootTargets = BuildInitialLootTargetsDesert();
}
_pendingLootTargets = lootTargets;
_pendingContenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count);
for (int i = 0; i < Contenders.Count; i++)
{
var c = Contenders[i];
_pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw));
}
if (startInLobby)
{
Phase = MatchPhase.Lobby;
Lobby = new LobbyState(ContenderCount, mapKind, seed);
Lobby = new LobbyState(ContenderCount, mapKind, seed, squadSize: SquadSize);
for (int i = 0; i < Contenders.Count; i++)
{
Contenders[i].Lifecycle = ContenderLifecycle.Deploying;
@ -434,7 +450,12 @@ namespace RustToDust.Core
{
Lobby.CountdownSeconds = null;
Lobby.ForceLaunched = false;
for (int i = 0; i < Contenders.Count && i < Lobby.Slots.Length; i++)
{
Contenders[i].SquadId = SquadSize > 1 ? Lobby.Slots[i].SquadId : (byte)i;
}
}
ApplySquadFormationTargets();
if (_pendingSkipInitialDrop)
{
@ -460,7 +481,49 @@ namespace RustToDust.Core
public int Seed { get; }
public ArenaMapKind MapKind { get; }
public byte SquadSize { get; }
public SionMapData? SionMap { get; }
public bool AreAllies(int contenderA, int contenderB) =>
SquadSize > 1 &&
contenderA >= 0 && contenderA < Contenders.Count &&
contenderB >= 0 && contenderB < Contenders.Count &&
Contenders[contenderA].SquadId == Contenders[contenderB].SquadId;
public ContenderState? GetSquadLeader(byte squadId)
{
ContenderState? best = null;
for (int i = 0; i < Contenders.Count; i++)
{
var c = Contenders[i];
if (c.SquadId != squadId) continue;
if (best is null || (c.IsHuman && !best.IsHuman) || (c.IsHuman == best.IsHuman && c.Id < best.Id))
{
best = c;
}
}
return best;
}
public int GetSquadMemberRank(int contenderId)
{
if (contenderId < 0 || contenderId >= Contenders.Count || SquadSize <= 1)
{
return 0;
}
var target = Contenders[contenderId];
int rank = 0;
for (int i = 0; i < Contenders.Count; i++)
{
var c = Contenders[i];
if (c.Id == target.Id || c.SquadId != target.SquadId) continue;
if ((c.IsHuman && !target.IsHuman) || (c.IsHuman == target.IsHuman && c.Id < target.Id))
{
rank++;
}
}
return rank;
}
public Random Rng { get; }
public float Time { get; set; }
public MatchPhase Phase { get; set; } = MatchPhase.Active;
@ -1297,6 +1360,354 @@ namespace RustToDust.Core
}
}
public static (float FwdOffset, float SideOffset, float AltStagger) GetSquadFormationOffset(int rank) => rank switch
{
0 => (8f, 0f, 0f),
1 => (-6f, -16f, 6f),
2 => (-6f, 16f, 6f),
3 => (-20f, 0f, 12f),
_ => (-20f - (rank - 3) * 14f, 0f, 12f + (rank - 3) * 6f)
};
private void AssignDefaultSquadIds()
{
for (int i = 0; i < Contenders.Count; i++)
{
Contenders[i].SquadId = SquadSize > 1 ? (byte)(i / SquadSize) : (byte)i;
}
}
public void ApplySquadFormationTargets()
{
_pendingContenderTargets.Clear();
if (SquadSize <= 1)
{
for (int i = 0; i < Contenders.Count; i++)
{
var c = Contenders[i];
c.SquadId = (byte)i;
_pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw));
}
return;
}
var squadsById = new Dictionary<byte, List<ContenderState>>();
for (int i = 0; i < Contenders.Count; i++)
{
var c = Contenders[i];
if (!squadsById.TryGetValue(c.SquadId, out var list))
{
list = new List<ContenderState>(SquadSize);
squadsById[c.SquadId] = list;
}
list.Add(c);
}
byte slot0Squad = Contenders.Count > 0 ? Contenders[0].SquadId : (byte)0;
var squadGroups = new List<(byte SquadId, List<ContenderState> Members)>(squadsById.Count);
foreach (var kv in squadsById)
{
kv.Value.Sort(static (a, b) =>
{
int humanCmp = (b.IsHuman ? 1 : 0).CompareTo(a.IsHuman ? 1 : 0);
return humanCmp != 0 ? humanCmp : a.Id.CompareTo(b.Id);
});
squadGroups.Add((kv.Key, kv.Value));
}
squadGroups.Sort((a, b) =>
{
if (a.SquadId == slot0Squad && b.SquadId != slot0Squad) return -1;
if (b.SquadId == slot0Squad && a.SquadId != slot0Squad) return 1;
return a.SquadId.CompareTo(b.SquadId);
});
int squadCount = squadGroups.Count;
Span<(float X, float Z, float Yaw)> anchors = stackalloc (float X, float Z, float Yaw)[squadCount];
var squadRng = new Random(Seed ^ (SquadSize * 7919));
const float minAnchorSepSq = 220f * 220f;
static float MinAnchorDistSq(ReadOnlySpan<(float X, float Z, float Yaw)> placed, int count, float x, float z)
{
float minSq = float.PositiveInfinity;
for (int k = 0; k < count; k++)
{
float dx = x - placed[k].X;
float dz = z - placed[k].Z;
float d2 = dx * dx + dz * dz;
if (d2 < minSq) minSq = d2;
}
return minSq;
}
if (MapKind == ArenaMapKind.Sion && SionMap is not null)
{
var leader0 = squadGroups[0].Members[0];
float pad0 = MathF.Max(leader0.Grid.Spec.HalfWidth, leader0.Grid.Spec.HalfLength) + 2.0f;
(float px, float pz) = FindClearSionPoint(-60f, 360f, pad0, minNy: 0.84f, maxSearchRadius: 120f);
float pYaw = MathF.Atan2(150f - px, -260f - pz);
anchors[0] = (px, pz, pYaw);
for (int s = 1; s < squadCount; s++)
{
var leader = squadGroups[s].Members[0];
float pad = MathF.Max(leader.Grid.Spec.HalfWidth, leader.Grid.Spec.HalfLength) + 2.0f;
float ax = 0f, az = 0f;
bool found = false;
float bestX = 0f, bestZ = 0f, bestMinDistSq = -1f;
for (int attempt = 0; attempt < 48; attempt++)
{
float angle = attempt == 0
? ((s - 1) / (float)Math.Max(1, squadCount - 1)) * MathF.Tau + (float)(squadRng.NextDouble() - 0.5) * 0.25f
: (float)(squadRng.NextDouble() * MathF.Tau);
float r = attempt < 24
? (260f + (float)squadRng.NextDouble() * 640f)
: (440f + (float)squadRng.NextDouble() * 480f);
(float cx, float cz) = FindClearSionPoint(
MathF.Cos(angle) * r,
MathF.Sin(angle) * r,
pad,
minNy: 0.84f,
maxSearchRadius: 280f,
avoidContenders: false);
float d2 = MinAnchorDistSq(anchors, s, cx, cz);
if (d2 > bestMinDistSq)
{
bestMinDistSq = d2;
bestX = cx;
bestZ = cz;
}
if (d2 >= minAnchorSepSq)
{
ax = cx;
az = cz;
found = true;
break;
}
}
if (!found)
{
float[] scanRadii = { 900f, 780f, 640f, 500f };
for (int rIdx = 0; rIdx < scanRadii.Length && !found; rIdx++)
{
float r = scanRadii[rIdx];
for (int a = 0; a < 36; a++)
{
float ang = (a / 36f) * MathF.Tau;
(float cx, float cz) = FindClearSionPoint(
MathF.Cos(ang) * r,
MathF.Sin(ang) * r,
pad,
minNy: 0.84f,
maxSearchRadius: 240f,
avoidContenders: false);
if (MinAnchorDistSq(anchors, s, cx, cz) >= minAnchorSepSq)
{
ax = cx;
az = cz;
found = true;
break;
}
}
}
}
if (!found)
{
ax = bestX;
az = bestZ;
}
anchors[s] = (ax, az, MathF.Atan2(-ax, -az));
}
}
else
{
const float minR = 210f;
const float maxR = 540f;
const float ringSpan = maxR - minR;
for (int s = 0; s < squadCount; s++)
{
float ax = 0f, az = 0f;
bool found = false;
float bestX = 0f, bestZ = 0f, bestMinDistSq = -1f;
float sectorAngle = (s / (float)Math.Max(1, squadCount)) * MathF.Tau;
for (int attempt = 0; attempt < 64; attempt++)
{
float angle = attempt < 12
? sectorAngle + (float)(squadRng.NextDouble() - 0.5) * (attempt == 0 ? 0.16f : 0.42f)
: (float)(squadRng.NextDouble() * MathF.Tau);
float baseR = attempt < 32
? (350f + (float)squadRng.NextDouble() * (maxR - 350f))
: (minR + (float)squadRng.NextDouble() * ringSpan);
float cx = MathF.Cos(angle) * baseR;
float cz = MathF.Sin(angle) * baseR;
for (int step = 0; step < 8; step++)
{
var (_, ny, _) = Terrain.SampleNormal(cx, cz);
if (ny >= 0.94f && !IsNearCoverBox(cx, cz, 8f))
{
break;
}
float r = minR + ((baseR - minR + step * 37f) % ringSpan);
cx = MathF.Cos(angle) * r;
cz = MathF.Sin(angle) * r;
}
if (IsNearCoverBox(cx, cz, 4f)) continue;
float d2 = MinAnchorDistSq(anchors, s, cx, cz);
if (d2 > bestMinDistSq)
{
bestMinDistSq = d2;
bestX = cx;
bestZ = cz;
}
if (d2 >= minAnchorSepSq)
{
ax = cx;
az = cz;
found = true;
break;
}
}
if (!found)
{
for (float r = maxR; r >= 200f && !found; r -= 20f)
{
for (int a = 0; a < 48; a++)
{
float ang = sectorAngle + (a / 48f) * MathF.Tau;
float cx = MathF.Cos(ang) * r;
float cz = MathF.Sin(ang) * r;
if (!IsNearCoverBox(cx, cz, 4f) && MinAnchorDistSq(anchors, s, cx, cz) >= minAnchorSepSq)
{
ax = cx;
az = cz;
found = true;
break;
}
}
}
}
if (!found)
{
ax = bestX;
az = bestZ;
}
anchors[s] = (ax, az, MathF.Atan2(-ax, -az));
}
}
Span<(float X, float Z)> placed = stackalloc (float X, float Z)[Contenders.Count];
int placedCount = 0;
for (int s = 0; s < squadCount; s++)
{
var (ax, az, aYaw) = anchors[s];
float sinY = MathF.Sin(aYaw);
float cosY = MathF.Cos(aYaw);
var members = squadGroups[s].Members;
for (int k = 0; k < members.Count; k++)
{
var c = members[k];
var (fwdOff, sideOff, _) = GetSquadFormationOffset(k);
float rawX = ax + sinY * fwdOff - cosY * sideOff;
float rawZ = az + cosY * fwdOff + sinY * sideOff;
float pad = MathF.Max(c.Grid.Spec.HalfWidth, c.Grid.Spec.HalfLength) + 2.0f;
var (tx, tz) = FindClearSquadMemberPoint(rawX, rawZ, pad, placed, placedCount);
placed[placedCount++] = (tx, tz);
c.X = tx;
c.Z = tz;
c.Yaw = aYaw;
c.Y = Terrain.SampleHeight(tx, tz) + c.Grid.Spec.HalfHeight + 0.15f;
c.AimY = c.Y;
c.SnapPreviousPose();
c.ResetAimTracker(aYaw);
}
}
for (int i = 0; i < Contenders.Count; i++)
{
var c = Contenders[i];
_pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw));
}
}
private (float X, float Z) FindClearSquadMemberPoint(
float rawX,
float rawZ,
float pad,
ReadOnlySpan<(float X, float Z)> placed,
int placedCount)
{
float maxB = Terrain.MapHalfExtent - 28f;
float baseX = Math.Clamp(rawX, -maxB, maxB);
float baseZ = Math.Clamp(rawZ, -maxB, maxB);
if (IsClearSquadMemberCandidate(baseX, baseZ, pad, maxB, minNy: 0.76f, placed, placedCount))
{
return (baseX, baseZ);
}
for (int pass = 0; pass < 2; pass++)
{
float minNy = pass == 0 ? 0.76f : 0f;
for (float r = 4f; r <= 120f; r += 4f)
{
for (int a = 0; a < 16; a++)
{
float ang = (a / 16f) * MathF.Tau;
float cx = Math.Clamp(baseX + MathF.Cos(ang) * r, -maxB, maxB);
float cz = Math.Clamp(baseZ + MathF.Sin(ang) * r, -maxB, maxB);
if (IsClearSquadMemberCandidate(cx, cz, pad, maxB, minNy, placed, placedCount))
{
return (cx, cz);
}
}
}
}
return FindClearDropPoint(baseX, baseZ, pad);
}
private bool IsClearSquadMemberCandidate(
float cx,
float cz,
float pad,
float maxB,
float minNy,
ReadOnlySpan<(float X, float Z)> placed,
int placedCount)
{
const float minMemberSepSq = 14.5f * 14.5f;
if (MathF.Abs(cx) > maxB || MathF.Abs(cz) > maxB) return false;
if (MapKind == ArenaMapKind.Sion && SionMap is not null)
{
if (SionMap.IsInsideAnyBuildingXz(cx, cz, pad)) return false;
if (minNy > 0f && Terrain.SampleNormal(cx, cz).Ny < minNy) return false;
}
else if (IsNearCoverBox(cx, cz, pad))
{
return false;
}
for (int k = 0; k < placedCount; k++)
{
float dx = cx - placed[k].X;
float dz = cz - placed[k].Z;
if (dx * dx + dz * dz < minMemberSepSq) return false;
}
return true;
}
private List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> BuildInitialLootTargetsSion()
{
var targets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(40);

View file

@ -69,7 +69,7 @@ namespace RustToDust.Core
public static class DropWaveConfig
{
public static readonly float[] WaveTimes = { 0f, 75f, 155f, 235f };
public static readonly float[] WaveTimes = { 0f, 85f, 165f, 245f };
public const int MaxRespawnWave = 2;
public const float SionCutoffRadius = 580f;
public const float DesertCutoffRadius = 260f;
@ -91,29 +91,35 @@ namespace RustToDust.Core
float PodFootRadius,
float SafetyMarginM)
{
public static readonly OrbitalPodPreset Contender = new(
StartAltAgl: 410f,
InitialVelY: -28.0f,
TerminalSpeed: 78.0f,
NominalRetroAccel: 105.0f,
TargetTouchdownSpeed: 2.2f,
SteerAccel: 28.0f,
FreefallHorizDrag: 0.90f,
public static OrbitalPodPreset GetContender(ArenaMapKind mapKind) => new(
StartAltAgl: mapKind == ArenaMapKind.Sion ? 1620.0f : 840.0f,
InitialVelY: -24.0f,
TerminalSpeed: 62.0f,
NominalRetroAccel: 125.0f,
TargetTouchdownSpeed: 2.1f,
SteerAccel: 118.0f,
FreefallHorizDrag: 0.95f,
BurnHorizDrag: 4.5f,
PodFootRadius: 1.65f,
SafetyMarginM: 4.0f);
public static readonly OrbitalPodPreset Gear = new(
StartAltAgl: 260f,
InitialVelY: -52.0f,
TerminalSpeed: 90.0f,
public static OrbitalPodPreset GetGear(ArenaMapKind mapKind) => new(
StartAltAgl: mapKind == ArenaMapKind.Sion ? 1580.0f : 740.0f,
InitialVelY: -44.0f,
TerminalSpeed: 68.0f,
NominalRetroAccel: 140.0f,
TargetTouchdownSpeed: 2.2f,
SteerAccel: 0f,
FreefallHorizDrag: 0.90f,
TargetTouchdownSpeed: 2.1f,
SteerAccel: 0.0f,
FreefallHorizDrag: 0.95f,
BurnHorizDrag: 4.5f,
PodFootRadius: 1.1f,
SafetyMarginM: 3.5f);
public static float GetStartAltAgl(OrbitalPodKind kind, ArenaMapKind mapKind) =>
kind == OrbitalPodKind.Contender ? GetContender(mapKind).StartAltAgl : GetGear(mapKind).StartAltAgl;
public static readonly OrbitalPodPreset Contender = GetContender(ArenaMapKind.Desert);
public static readonly OrbitalPodPreset Gear = GetGear(ArenaMapKind.Desert);
}
public sealed class OrbitalPod
@ -278,37 +284,65 @@ namespace RustToDust.Core
}
}
float xCand = Math.Clamp(pod.X + vxNext * dt, -maxBound, maxBound);
float zCand = Math.Clamp(pod.Z + vzNext * dt, -maxBound, maxBound);
float targetX = Math.Clamp(pod.X + vxNext * dt, -maxBound, maxBound);
float targetZ = Math.Clamp(pod.Z + vzNext * dt, -maxBound, maxBound);
float candDx = targetX - pod.X;
float candDz = targetZ - pod.Z;
float candDist = MathF.Sqrt(candDx * candDx + candDz * candDz);
int subSteps = Math.Clamp((int)MathF.Ceiling(candDist / 0.75f), 1, 4);
// Lateral Building Wall & Stepped-Roof Guard: reject/slide horizontal moves that violate stopping altitude or disallowed roof entry
DropSurfaceSample sampleNext = surfaceQuery(xCand, zCand, preset.PodFootRadius, pod.Y + 1.0f);
if (IsBlockedHorizontalMove(pod, sampleNow, sampleNext, surfaceNow, hStop))
// Lateral Building Wall & Stepped-Roof Guard: swept <= 0.75m horizontal sub-steps reject/slide before wall entry
float curX = pod.X;
float curZ = pod.Z;
DropSurfaceSample curSample = sampleNow;
float curSurfaceY = surfaceNow;
float subDt = dt / subSteps;
for (int s = 0; s < subSteps; s++)
{
DropSurfaceSample slideX = surfaceQuery(xCand, pod.Z, preset.PodFootRadius, pod.Y + 1.0f);
DropSurfaceSample slideZ = surfaceQuery(pod.X, zCand, preset.PodFootRadius, pod.Y + 1.0f);
if (!IsBlockedHorizontalMove(pod, sampleNow, slideX, surfaceNow, hStop))
float stepX = Math.Clamp(curX + vxNext * subDt, -maxBound, maxBound);
float stepZ = Math.Clamp(curZ + vzNext * subDt, -maxBound, maxBound);
DropSurfaceSample stepSample = surfaceQuery(stepX, stepZ, preset.PodFootRadius, pod.Y + 1.0f);
if (IsBlockedHorizontalMove(pod, curSample, stepSample, curSurfaceY, hStop))
{
zCand = pod.Z;
vzNext = 0f;
sampleNext = slideX;
}
else if (!IsBlockedHorizontalMove(pod, sampleNow, slideZ, surfaceNow, hStop))
{
xCand = pod.X;
vxNext = 0f;
sampleNext = slideZ;
DropSurfaceSample slideX = surfaceQuery(stepX, curZ, preset.PodFootRadius, pod.Y + 1.0f);
DropSurfaceSample slideZ = surfaceQuery(curX, stepZ, preset.PodFootRadius, pod.Y + 1.0f);
if (!IsBlockedHorizontalMove(pod, curSample, slideX, curSurfaceY, hStop))
{
curX = stepX;
vzNext = 0f;
curSample = slideX;
}
else if (!IsBlockedHorizontalMove(pod, curSample, slideZ, curSurfaceY, hStop))
{
curZ = stepZ;
vxNext = 0f;
curSample = slideZ;
}
else
{
vxNext = 0f;
vzNext = 0f;
break;
}
}
else
{
xCand = pod.X;
zCand = pod.Z;
vxNext = 0f;
vzNext = 0f;
sampleNext = sampleNow;
curX = stepX;
curZ = stepZ;
curSample = stepSample;
}
float subTerrain = terrain.SampleHeight(curX, curZ);
curSurfaceY = curSample.IsBuildingRoof
? MathF.Max(subTerrain, curSample.SurfaceY)
: subTerrain;
}
float xCand = curX;
float zCand = curZ;
DropSurfaceSample sampleNext = curSample;
float terrainNext = terrain.SampleHeight(xCand, zCand);
float surfaceNext = sampleNext.IsBuildingRoof
? MathF.Max(terrainNext, sampleNext.SurfaceY)
@ -623,9 +657,17 @@ namespace RustToDust.Core
{
CancelContenderPod(c.Id);
var preset = OrbitalPodPreset.Contender;
var preset = OrbitalPodPreset.GetContender(_state.MapKind);
float groundY = ResolveGroundSurfaceY(targetX, targetZ, preset.PodFootRadius, surfaceQuery);
float stagger = ((c.Id % 3) - 1) * 6f;
float stagger;
if (_state.SquadSize > 1)
{
(_, _, stagger) = MatchState.GetSquadFormationOffset(_state.GetSquadMemberRank(c.Id));
}
else
{
stagger = ((c.Id % 3) - 1) * 6f;
}
float startY = groundY + preset.StartAltAgl + stagger;
var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw);
@ -708,7 +750,7 @@ namespace RustToDust.Core
ModuleSpec? module,
DropSurfaceQuery surfaceQuery)
{
var preset = OrbitalPodPreset.Gear;
var preset = OrbitalPodPreset.GetGear(_state.MapKind);
float groundY = ResolveGroundSurfaceY(targetX, targetZ, preset.PodFootRadius, surfaceQuery);
float startY = groundY + preset.StartAltAgl;
float yaw = (float)((_nextPodId * 1.17f) % MathF.Tau);
@ -849,23 +891,98 @@ namespace RustToDust.Core
return;
}
// AI steers gently toward nearest unpicked GroundDrop within 180m or inward away from ring perimeter
// Squad V-chevron formation-follow above 140m AGL
if (_state.SquadSize > 1 && pod.LastAgl > 140f)
{
var leader = _state.GetSquadLeader(ai.SquadId);
if (leader is not null && leader.Id != ai.Id && leader.IsInDropPod && leader.ActivePodId.HasValue)
{
var leaderPod = FindPodById(leader.ActivePodId.Value);
if (leaderPod is not null && leaderPod.Phase == OrbitalPodPhase.Freefall)
{
Vector2 fwd = new(leaderPod.LookForwardX, leaderPod.LookForwardZ);
if (fwd.LengthSquared() < 1e-4f)
{
fwd = new Vector2(MathF.Sin(leaderPod.Yaw), MathF.Cos(leaderPod.Yaw));
}
else
{
fwd = Vector2.Normalize(fwd);
}
Vector2 right = new(-fwd.Y, fwd.X);
int rank = _state.GetSquadMemberRank(ai.Id);
var (fwdOff, sideOff, _) = MatchState.GetSquadFormationOffset(rank);
float relFwd = fwdOff - 8f;
float formWorldX = fwd.X * relFwd + right.X * sideOff;
float formWorldZ = fwd.Y * relFwd + right.Y * sideOff;
float fdx = (leaderPod.X + formWorldX) - pod.X;
float fdz = (leaderPod.Z + formWorldZ) - pod.Z;
float fDist = MathF.Sqrt(fdx * fdx + fdz * fdz);
if (fDist > 1.5f)
{
pod.LookForwardX = fdx / fDist;
pod.LookForwardZ = fdz / fDist;
pod.Yaw = MathF.Atan2(pod.LookForwardX, pod.LookForwardZ);
pod.SteerForwardCmd = Math.Clamp(fDist * 0.08f, 0f, 1f);
pod.SteerRightCmd = 0f;
}
else
{
pod.SteerForwardCmd = 0f;
pod.SteerRightCmd = 0f;
}
return;
}
}
}
// Below 140m AGL (or FFA): split cleanly onto clear ground >= 12m from squadmates
float goalX = 0f;
float goalZ = 0f;
bool hasGoal = false;
float safeLimit = MathF.Max(40f, _state.Spectators.SafeRadius - 35f);
float distFromCenter = MathF.Sqrt(pod.X * pod.X + pod.Z * pod.Z);
if (distFromCenter > safeLimit)
if (_state.SquadSize > 1)
{
bool tooCloseToAlly = IsTooCloseToSquadmatePod(ai, pod.X, pod.Z, 12.5f, out float repulseX, out float repulseZ);
var surfNow = _state.DefaultDropSurfaceQuery(pod.X, pod.Z, OrbitalPodPreset.GetContender(_state.MapKind).PodFootRadius, pod.Y + 1.0f);
bool overInvalidBuilding = surfNow.IsInsideBuildingFootprint || (surfNow.IsBuildingRoof && !pod.AllowFlatRoofLanding);
if (tooCloseToAlly || overInvalidBuilding)
{
float seekX = tooCloseToAlly ? repulseX : pod.X;
float seekZ = tooCloseToAlly ? repulseZ : pod.Z;
var (cx, cz) = _state.FindClearDropPoint(seekX, seekZ, 4.5f);
if (!IsTooCloseToSquadmatePod(ai, cx, cz, 12.0f, out _, out _))
{
goalX = cx;
goalZ = cz;
}
else
{
goalX = seekX;
goalZ = seekZ;
}
hasGoal = true;
}
}
if (!hasGoal && distFromCenter > safeLimit)
{
hasGoal = true;
}
else
else if (!hasGoal)
{
float bestSq = 180f * 180f;
for (int i = 0; i < _state.GroundDrops.Count; i++)
{
var d = _state.GroundDrops[i];
if (d.PickedUp) continue;
if (_state.SquadSize > 1 && IsTooCloseToSquadmatePod(ai, d.X, d.Z, 12.0f, out _, out _))
{
continue;
}
float dx = d.X - pod.X;
float dz = d.Z - pod.Z;
float d2 = dx * dx + dz * dz;
@ -898,6 +1015,32 @@ namespace RustToDust.Core
pod.SteerRightCmd = 0f;
}
private bool IsTooCloseToSquadmatePod(ContenderState self, float x, float z, float minSepM, out float escapeX, out float escapeZ)
{
escapeX = x;
escapeZ = z;
float minSepSq = minSepM * minSepM;
for (int i = 0; i < _activePods.Count; i++)
{
var otherPod = _activePods[i];
if (otherPod.PodKind != OrbitalPodKind.Contender || otherPod.ContenderId == self.Id) continue;
if (!_state.AreAllies(self.Id, otherPod.ContenderId)) continue;
float dx = x - otherPod.X;
float dz = z - otherPod.Z;
float d2 = dx * dx + dz * dz;
if (d2 < minSepSq)
{
float dist = MathF.Sqrt(d2);
float nx = dist > 0.1f ? dx / dist : MathF.Cos(self.Id * 2.1f);
float nz = dist > 0.1f ? dz / dist : MathF.Sin(self.Id * 2.1f);
escapeX = otherPod.X + nx * (minSepM + 4f);
escapeZ = otherPod.Z + nz * (minSepM + 4f);
return true;
}
}
return false;
}
public void ApplyPlayerSteerInput(ContenderState human, DropSurfaceQuery? surfaceQuery = null)
{
if (!human.IsInDropPod || !human.ActivePodId.HasValue)

View file

@ -252,6 +252,7 @@ namespace RustToDust.Core
[Key(8)] public ContenderLoadoutEvent Loadout { get; set; } = new();
[Key(9)] public byte LifecycleByte { get; set; }
[Key(10)] public byte RespawnsRemaining { get; set; }
[Key(11)] public byte SquadId { get; set; }
}
[MessagePackObject]
@ -320,6 +321,7 @@ namespace RustToDust.Core
[Key(13)] public bool RespawnCutoffReached { get; set; }
[Key(14)] public List<OrbitalPodDto> ActivePods { get; set; } = new();
[Key(15)] public LobbySnapshotDto? Lobby { get; set; }
[Key(16)] public byte SquadSize { get; set; } = 1;
}
[MessagePackObject]
@ -329,6 +331,7 @@ namespace RustToDust.Core
[Key(1)] public string Callsign { get; set; } = string.Empty;
[Key(2)] public bool IsHuman { get; set; }
[Key(3)] public bool IsReady { get; set; }
[Key(4)] public byte SquadId { get; set; }
}
[MessagePackObject]
@ -341,6 +344,7 @@ namespace RustToDust.Core
[Key(4)] public byte SelectedMap { get; set; }
[Key(5)] public int SelectedSeed { get; set; }
[Key(6)] public List<LobbySlotDto> Slots { get; set; } = new();
[Key(7)] public byte SquadSize { get; set; } = 3;
}
[MessagePackObject]
@ -375,6 +379,7 @@ namespace RustToDust.Core
[Union(11, typeof(LobbyStartCmdMsg))]
[Union(12, typeof(LobbySnapshotMsg))]
[Union(13, typeof(ClientKeepaliveMsg))]
[Union(14, typeof(LobbySquadCmdMsg))]
public interface ISchemaWireMessage
{
}
@ -470,6 +475,14 @@ namespace RustToDust.Core
[Key(0)] public uint ReqSeq { get; set; }
[Key(1)] public int Seed { get; set; }
[Key(2)] public byte MapKind { get; set; }
[Key(3)] public byte SquadSize { get; set; } = 3;
}
[MessagePackObject]
public sealed class LobbySquadCmdMsg : ISchemaWireMessage
{
[Key(0)] public uint ReqSeq { get; set; }
[Key(1)] public byte TargetSquadId { get; set; }
}
[MessagePackObject]

View file

@ -124,7 +124,7 @@ namespace RustToDust.Core
{
public const float InitialRadius = 560f;
public const float MinRadius = 85f;
public const float GraceDuration = 30f;
public const float GraceDuration = 45f;
public const float ShrinkDuration = 360f;
public const int DefaultSpectatorCount = 56;
public const float TargetMemoryDuration = 4.0f;

View file

@ -18,7 +18,8 @@ namespace RustToDust.Net
int maxHumans = MatchState.ContenderCount,
bool startInLobby = false,
string serverName = "Rust to Dust",
int minHumansToStart = 1)
int minHumansToStart = 1,
byte squadSize = 1)
{
_host = new ServerMatchHost(
bindAddress,
@ -31,7 +32,8 @@ namespace RustToDust.Net
hostContenderId: 0,
startInLobby: startInLobby,
serverName: serverName,
minHumansToStart: minHumansToStart);
minHumansToStart: minHumansToStart,
squadSize: squadSize);
}
public ServerMatchHost Host => _host;
@ -44,7 +46,10 @@ namespace RustToDust.Net
? ClientMatchOutcome.Active
: _host.Session.State.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
: ((_host.Session.State.WinnerContenderId == 0 ||
(_host.Session.State.WinnerContenderId.HasValue && _host.Session.State.AreAllies(0, _host.Session.State.WinnerContenderId.Value)))
? ClientMatchOutcome.Victory
: ClientMatchOutcome.Defeat);
public int LocalDetectedByCount =>
_host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.DetectedByCount : 0;
@ -94,6 +99,8 @@ namespace RustToDust.Net
public bool SetLobbyReady(bool ready) => _host.SetLobbyReady(0, ready);
public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => _host.ConfigureLobby(0, seed, mapKind);
public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize) => _host.ConfigureLobby(0, seed, mapKind, squadSize);
public bool RequestLobbySquad(byte targetSquadId) => _host.MovePeerToSquad(0, targetSquadId);
public bool RequestLobbyStart() => _host.LaunchFromLobby(0);
public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) =>

View file

@ -144,7 +144,10 @@ namespace RustToDust.Net
? ClientMatchOutcome.Active
: _viewState.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (_viewState.WinnerContenderId == _localContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
: ((_viewState.WinnerContenderId == _localContenderId ||
(_viewState.WinnerContenderId.HasValue && _viewState.AreAllies(_localContenderId, _viewState.WinnerContenderId.Value)))
? ClientMatchOutcome.Victory
: ClientMatchOutcome.Defeat);
public int LocalDetectedByCount => _localDetectedByCount;
@ -358,14 +361,29 @@ namespace RustToDust.Net
return true;
}
public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind)
public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) =>
RequestLobbyConfig(seed, mapKind, _lobbyState?.SquadSize ?? 0);
public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize)
{
if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false;
SendSchemaMessage(new LobbyConfigCmdMsg
{
ReqSeq = _nextCmdSeq++,
Seed = seed,
MapKind = (byte)mapKind
MapKind = (byte)mapKind,
SquadSize = squadSize
});
return true;
}
public bool RequestLobbySquad(byte targetSquadId)
{
if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false;
SendSchemaMessage(new LobbySquadCmdMsg
{
ReqSeq = _nextCmdSeq++,
TargetSquadId = targetSquadId
});
return true;
}
@ -723,6 +741,7 @@ namespace RustToDust.Net
{
var c = _viewState.Contenders[slot.SlotId];
c.IsHuman = slot.IsHuman;
c.SquadId = slot.SquadId;
if (!string.IsNullOrWhiteSpace(slot.Callsign))
{
c.Name = slot.Callsign;
@ -791,7 +810,8 @@ namespace RustToDust.Net
_predErrorRot = Quaternion.Identity;
Array.Clear(_lastCombatSpecSeenSeq);
_viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind, skipInitialDrop: true)
byte initSquadSize = (byte)Math.Clamp((int)dto.SquadSize, 1, 4);
_viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind, skipInitialDrop: true, squadSize: initSquadSize)
{
Time = dto.SimTime,
Phase = dto.Phase switch
@ -803,6 +823,17 @@ namespace RustToDust.Net
WinnerContenderId = dto.WinnerContenderId
};
_lobbyState = _viewState.Phase == MatchPhase.Lobby ? dto.Lobby : null;
if (_lobbyState is not null)
{
for (int i = 0; i < _lobbyState.Slots.Count; i++)
{
var slot = _lobbyState.Slots[i];
if (slot.SlotId >= 0 && slot.SlotId < _viewState.Contenders.Count)
{
_viewState.Contenders[slot.SlotId].SquadId = slot.SquadId;
}
}
}
_lastKeepaliveUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
_viewState.Spectators.SetReplicatedSafeRadius(dto.SafeRadius);
_viewState.OrbitalDrop.ApplyReplicatedWaveState(
@ -856,6 +887,7 @@ namespace RustToDust.Net
var c = _viewState.Contenders[cd.Id];
c.Name = cd.Name;
c.IsHuman = cd.IsHuman;
c.SquadId = cd.SquadId;
if (cd.IsHuman) humans++;
c.Lifecycle = (ContenderLifecycle)cd.LifecycleByte;
c.RespawnsRemaining = cd.RespawnsRemaining;
@ -1050,7 +1082,7 @@ namespace RustToDust.Net
var pod = pods[i];
if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == _localContenderId)
{
if (pod.FlightTime > 25f)
if (pod.FlightTime > 75f)
{
_viewState.OrbitalDrop.RemoveActivePodAt(i);
}
@ -1067,7 +1099,7 @@ namespace RustToDust.Net
_viewState.FindClearDropPoint,
out _,
out _);
if (touched || pod.FlightTime > 25f)
if (touched || pod.FlightTime > 75f)
{
_viewState.OrbitalDrop.RemoveActivePodAt(i);
}

View file

@ -61,6 +61,7 @@ namespace RustToDust.Net
private readonly byte[] _udpPeekBuf = new byte[65535];
private ArenaSession _session;
private byte _squadSize;
private string _hostCallsign = "Host";
private uint _matchGeneration = 1;
private uint _simTick;
@ -85,7 +86,8 @@ namespace RustToDust.Net
bool startInLobby = false,
string serverName = "Rust to Dust",
int minHumansToStart = 1,
bool restartToLobby = false)
bool restartToLobby = false,
byte squadSize = 1)
{
_maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount);
_autoRestartSec = autoRestartSec;
@ -94,6 +96,7 @@ namespace RustToDust.Net
_serverName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim();
_minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans);
_restartToLobby = restartToLobby;
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
_socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
{
@ -114,7 +117,7 @@ namespace RustToDust.Net
});
_server.PeerDisconnected += OnTransportPeerDisconnected;
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby);
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize);
if (hostContenderId.HasValue)
{
_session.SetHumanSlot(hostContenderId.Value, true, "Host");
@ -174,7 +177,7 @@ namespace RustToDust.Net
_hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name;
}
_session.Dispose();
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby);
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize);
_matchGeneration++;
_simTick = 0;
_roundCompletedElapsed = 0f;
@ -241,7 +244,10 @@ namespace RustToDust.Net
return true;
}
public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind)
public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind) =>
ConfigureLobby(requesterContenderId, seed, mapKind, squadSize: null);
public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind, byte? squadSize)
{
if (_session.State.Phase != MatchPhase.Lobby)
{
@ -252,10 +258,75 @@ namespace RustToDust.Net
return false;
}
if (squadSize.HasValue && squadSize.Value >= 1 && squadSize.Value <= 4)
{
_squadSize = squadSize.Value;
}
ResetMatch(seed, mapKind, startInLobby: true);
return true;
}
public bool MovePeerToSquad(int contenderId, byte targetSquadId)
{
if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby)
{
return false;
}
if (contenderId < 0 || contenderId >= lobby.Slots.Length)
{
return false;
}
byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4);
if (squadSize <= 1)
{
return false;
}
int maxSquads = (MatchState.ContenderCount + squadSize - 1) / squadSize;
byte targetSq = (byte)Math.Clamp((int)targetSquadId, 0, Math.Max(0, maxSquads - 1));
var srcSlot = lobby.Slots[contenderId];
byte srcSq = srcSlot.SquadId;
if (srcSq == targetSq)
{
return true;
}
int targetCount = 0;
LobbySlotState? swapAi = null;
for (int i = 0; i < lobby.Slots.Length; i++)
{
var s = lobby.Slots[i];
if (s.SquadId == targetSq)
{
targetCount++;
if (!s.IsHuman && swapAi is null)
{
swapAi = s;
}
}
}
if (targetCount < squadSize)
{
srcSlot.SquadId = targetSq;
_session.State.Contenders[contenderId].SquadId = targetSq;
}
else if (swapAi is not null)
{
swapAi.SquadId = srcSq;
_session.State.Contenders[swapAi.SlotId].SquadId = srcSq;
srcSlot.SquadId = targetSq;
_session.State.Contenders[contenderId].SquadId = targetSq;
}
else
{
return false;
}
BroadcastLobbySnapshot();
return true;
}
public bool LaunchFromLobby(int requesterContenderId)
{
if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby)
@ -293,6 +364,7 @@ namespace RustToDust.Net
lobby.MinHumansToAutoStart = _minHumansToStart;
lobby.SelectedMap = session.State.MapKind;
lobby.SelectedSeed = session.State.Seed;
lobby.SquadSize = session.State.SquadSize;
lobby.CountdownSeconds = null;
lobby.ForceLaunched = false;
for (int i = 0; i < session.State.Contenders.Count && i < lobby.Slots.Length; i++)
@ -301,6 +373,7 @@ namespace RustToDust.Net
lobby.Slots[i].IsHuman = c.IsHuman;
lobby.Slots[i].Callsign = c.Name;
lobby.Slots[i].IsReady = false;
lobby.Slots[i].SquadId = c.SquadId;
}
}
@ -354,6 +427,7 @@ namespace RustToDust.Net
ForceLaunched = lobby.ForceLaunched,
SelectedMap = (byte)lobby.SelectedMap,
SelectedSeed = lobby.SelectedSeed,
SquadSize = lobby.SquadSize,
Slots = new List<LobbySlotDto>(lobby.Slots.Length)
};
for (int i = 0; i < lobby.Slots.Length; i++)
@ -364,7 +438,8 @@ namespace RustToDust.Net
SlotId = s.SlotId,
Callsign = s.Callsign,
IsHuman = s.IsHuman,
IsReady = s.IsReady
IsReady = s.IsReady,
SquadId = s.SquadId
});
}
return dto;
@ -643,7 +718,15 @@ namespace RustToDust.Net
if (_peersByEndpoint.TryGetValue(epKey, out var cfgPeer) && cfgPeer.Active && ReferenceEquals(cfgPeer.TransportPeer, transportPeer))
{
cfgPeer.LastHeardUtcMs = nowUtcMs;
ConfigureLobby(cfgPeer.AssignedContenderId, cfgCmd.Seed, (ArenaMapKind)cfgCmd.MapKind);
byte? reqSquadSize = cfgCmd.SquadSize >= 1 && cfgCmd.SquadSize <= 4 ? cfgCmd.SquadSize : null;
ConfigureLobby(cfgPeer.AssignedContenderId, cfgCmd.Seed, (ArenaMapKind)cfgCmd.MapKind, reqSquadSize);
}
break;
case LobbySquadCmdMsg sqCmd:
if (_peersByEndpoint.TryGetValue(epKey, out var sqPeer) && sqPeer.Active && ReferenceEquals(sqPeer.TransportPeer, transportPeer))
{
sqPeer.LastHeardUtcMs = nowUtcMs;
MovePeerToSquad(sqPeer.AssignedContenderId, sqCmd.TargetSquadId);
}
break;
case LobbyStartCmdMsg:
@ -924,7 +1007,9 @@ namespace RustToDust.Net
{
if (pod.PodKind == OrbitalPodKind.Contender)
{
return pod.ContenderId == obsId || _session.IsEntityInPeerPvs(obsId, true, pod.ContenderId);
return pod.ContenderId == obsId ||
_session.State.AreAllies(obsId, pod.ContenderId) ||
_session.IsEntityInPeerPvs(obsId, true, pod.ContenderId);
}
return _session.IsPointInPeerPvs(obsId, pod.X, pod.Y + 2.0f, pod.Z);
}
@ -1619,6 +1704,7 @@ namespace RustToDust.Net
MatchGeneration = _matchGeneration,
Seed = _session.State.Seed,
MapKind = (byte)_session.State.MapKind,
SquadSize = _session.State.SquadSize,
SimTime = _session.State.Time,
SafeRadius = _session.State.Spectators.SafeRadius,
Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : _session.State.Phase == MatchPhase.Lobby ? 2 : 0),
@ -1668,7 +1754,9 @@ namespace RustToDust.Net
for (int i = 0; i < _session.State.Contenders.Count; i++)
{
var c = _session.State.Contenders[i];
if (c.Id != forContenderId && !_session.IsEntityInPeerPvs(forContenderId, true, c.Id))
if (c.Id != forContenderId &&
!_session.State.AreAllies(forContenderId, c.Id) &&
!_session.IsEntityInPeerPvs(forContenderId, true, c.Id))
{
continue;
}
@ -1681,7 +1769,8 @@ namespace RustToDust.Net
Kills = c.Kills,
Loadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == forContenderId),
LifecycleByte = (byte)c.Lifecycle,
RespawnsRemaining = (byte)Math.Clamp(c.RespawnsRemaining, 0, 255)
RespawnsRemaining = (byte)Math.Clamp(c.RespawnsRemaining, 0, 255),
SquadId = c.SquadId
});
}

View file

@ -27,6 +27,7 @@ namespace RustToDust.Server
bool startInLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_LOBBY"), false);
int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1);
bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false);
int squadSize = Math.Clamp(TryParseInt(Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), 3), 1, 4);
for (int i = 0; i < args.Length; i++)
{
@ -58,6 +59,8 @@ namespace RustToDust.Server
else if (a == "--min-humans" && i + 1 < args.Length) minHumansToStart = TryParseInt(args[++i], minHumansToStart);
else if (a.StartsWith("--min-humans=", StringComparison.Ordinal)) minHumansToStart = TryParseInt(a.Substring("--min-humans=".Length), minHumansToStart);
else if (a == "--restart-to-lobby") restartToLobby = true;
else if (a == "--squad-size" && i + 1 < args.Length) squadSize = Math.Clamp(TryParseInt(args[++i], squadSize), 1, 4);
else if (a.StartsWith("--squad-size=", StringComparison.Ordinal)) squadSize = Math.Clamp(TryParseInt(a.Substring("--squad-size=".Length), squadSize), 1, 4);
}
if (!IPAddress.TryParse(bindStr, out var bindIp))
@ -95,7 +98,8 @@ namespace RustToDust.Server
startInLobby: startInLobby,
serverName: serverName,
minHumansToStart: minHumansToStart,
restartToLobby: restartToLobby);
restartToLobby: restartToLobby,
squadSize: (byte)squadSize);
host.LogMessage += msg => Console.WriteLine(msg);
static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) =>

View file

@ -35,9 +35,9 @@ namespace RustToDust.Ymir
private long _forwardedPodEventId;
private bool _disposed;
public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false)
public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1)
{
State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby);
State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize);
Ordnance = new OrdnanceRuntime(this);
_spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count];
_forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0;
@ -2047,6 +2047,28 @@ namespace RustToDust.Ymir
}
var mem = memState.GetOrCreateContenderContact(c.Id);
if (State.AreAllies(obs.Id, c.Id))
{
bool allyAlive = c.Alive || c.IsInDropPod;
_contenderPvs[obs.Id, i] = allyAlive;
if (allyAlive)
{
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;
mem.LastSeenAge = float.PositiveInfinity;
}
continue;
}
if (!c.Alive)
{
mem.VisibleToPlayer = false;
@ -2447,7 +2469,7 @@ namespace RustToDust.Ymir
for (int j = 0; j < State.Contenders.Count; j++)
{
var other = State.Contenders[j];
if (other.Id == shooter.Id || !other.IsGroundedActive || !other.Grid.Spec.IsVtol)
if (other.Id == shooter.Id || State.AreAllies(shooter.Id, other.Id) || !other.IsGroundedActive || !other.Grid.Spec.IsVtol)
{
continue;
}
@ -2709,6 +2731,14 @@ namespace RustToDust.Ymir
{
continue;
}
if (shooterStableId >= ContenderStableIdBase && shooterStableId < SpectatorStableIdBase)
{
int shooterCid = (int)(shooterStableId - ContenderStableIdBase);
if (State.AreAllies(shooterCid, c.Id))
{
continue;
}
}
float dx = c.X - aimX;
float dy = c.Y - aimY;
float dz = c.Z - aimZ;
@ -2765,6 +2795,10 @@ namespace RustToDust.Ymir
if (targetRef.IsContender)
{
var target = State.Contenders[targetRef.Index];
if (shooterContender is not null && shooterContender.Id != target.Id && State.AreAllies(shooterContender.Id, target.Id))
{
return;
}
if (!target.IsGroundedActive || !_contenderBodies.TryGetValue(target.Id, out var body))
{
return;
@ -3092,6 +3126,10 @@ namespace RustToDust.Ymir
{
continue;
}
if (shooterContender is not null && shooterContender.Id != c.Id && State.AreAllies(shooterContender.Id, c.Id))
{
continue;
}
ulong cStable = ContenderStableIdBase + (ulong)c.Id;
if (cStable == ignoreStableId)
{

View file

@ -9,9 +9,9 @@ namespace RustToDust.Ymir
{
private readonly List<ISimEvent> _pendingEvents = new();
public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false)
public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false, byte squadSize = 1)
{
Inner = new ArenaSession(seed, mapKind, slot0Human: true, skipInitialDrop: skipInitialDrop)
Inner = new ArenaSession(seed, mapKind, slot0Human: true, skipInitialDrop: skipInitialDrop, squadSize: squadSize)
{
EnableNetworkPvs = false
};
@ -31,7 +31,10 @@ namespace RustToDust.Ymir
? ClientMatchOutcome.Active
: Inner.State.Phase == MatchPhase.Active
? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat)
: (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat);
: ((Inner.State.WinnerContenderId == LocalContenderId ||
(Inner.State.WinnerContenderId.HasValue && Inner.State.AreAllies(LocalContenderId, Inner.State.WinnerContenderId.Value)))
? ClientMatchOutcome.Victory
: ClientMatchOutcome.Defeat);
public int LocalDetectedByCount =>
Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.DetectedByCount : 0;
@ -95,9 +98,10 @@ namespace RustToDust.Ymir
public void RequestNewMatch(int seed, ArenaMapKind mapKind)
{
string? name = LocalContender.Name;
byte squadSize = Inner.State.SquadSize;
_pendingEvents.Clear();
Inner.Dispose();
Inner = new ArenaSession(seed, mapKind, slot0Human: true)
Inner = new ArenaSession(seed, mapKind, slot0Human: true, squadSize: squadSize)
{
EnableNetworkPvs = false
};

View file

@ -434,6 +434,10 @@ namespace RustToDust.Ymir
{
continue;
}
if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && state.AreAllies(inst.ShooterContenderId, c.Id))
{
continue;
}
Vector3 targetPt = _sink.GetActorAimPosition(true, i);
Vector3 delta = targetPt - inst.Pos;
@ -599,7 +603,8 @@ namespace RustToDust.Ymir
if (isContender)
{
var c = _sink.State.Contenders[idx];
if (c.IsGroundedActive)
bool isAlly = !inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && _sink.State.AreAllies(inst.ShooterContenderId, c.Id);
if (c.IsGroundedActive && !isAlly)
{
targetPos = _sink.GetActorAimPosition(true, idx);
return true;
@ -634,6 +639,10 @@ namespace RustToDust.Ymir
{
continue;
}
if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && state.AreAllies(inst.ShooterContenderId, c.Id))
{
continue;
}
Vector3 pt = _sink.GetActorAimPosition(true, i);
Vector3 d = pt - inst.Pos;
float d2 = d.LengthSquared();
@ -686,6 +695,10 @@ namespace RustToDust.Ymir
{
continue;
}
if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && inst.ShooterContenderId != c.Id && state.AreAllies(inst.ShooterContenderId, c.Id))
{
continue;
}
Vector3 pt = _sink.GetActorAimPosition(true, i);
float d2 = Vector3.DistanceSquared(inst.Pos, pt);

View file

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

View file

@ -633,5 +633,80 @@ namespace RustToDust.Tests
Assert.NotNull(res.Summary);
Assert.Equal(new string('\u2022', 16), res.Summary!.Value.ServerName);
}
[Fact]
public void LobbySquadSwap_ReliableRoundTrip()
{
using var listenHost = new ListenHostArenaSession(
IPAddress.Loopback,
0,
seed: 42,
mapKind: ArenaMapKind.Desert,
startInLobby: true,
minHumansToStart: 2,
squadSize: 3);
using var remote = new RemoteArenaSession(
new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort),
"WingBuddy");
var deadline = DateTime.UtcNow.AddSeconds(3);
while (!remote.IsJoined && DateTime.UtcNow < deadline)
{
PumpListenHostAndClient(listenHost, remote);
}
Assert.True(remote.IsJoined);
int remoteId = remote.LocalContenderId;
Assert.Equal((byte)3, listenHost.LobbyState?.SquadSize);
Assert.Equal((byte)3, remote.LobbyState?.SquadSize);
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
// 1. Remote client swaps to Squad 2 -> swaps cleanly with an AI in Squad 2
Assert.True(remote.RequestLobbySquad(2));
PumpListenHostAndClient(listenHost, remote, ticks: 15);
Assert.Equal((byte)2, listenHost.LobbyState!.Slots[remoteId].SquadId);
Assert.Equal((byte)2, remote.LobbyState!.Slots[remoteId].SquadId);
// 2. Host switches SquadMode to Duos (2) -> slots regroup cleanly to 2-player squads
Assert.True(listenHost.RequestLobbyConfig(77, ArenaMapKind.Desert, 2));
PumpListenHostAndClient(listenHost, remote, ticks: 15);
Assert.Equal((byte)2, listenHost.LobbyState!.SquadSize);
Assert.Equal((byte)2, remote.LobbyState!.SquadSize);
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
// 3. Remote swaps to Squad 3, then back to Squad 0 (Host's Duo), both ready up & launch!
Assert.True(remote.RequestLobbySquad(3));
PumpListenHostAndClient(listenHost, remote, ticks: 15);
Assert.Equal((byte)3, remote.LobbyState!.Slots[remoteId].SquadId);
Assert.True(remote.RequestLobbySquad(0));
PumpListenHostAndClient(listenHost, remote, ticks: 15);
Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId);
Assert.True(listenHost.SetLobbyReady(true));
Assert.True(remote.SetLobbyReady(true));
for (int tick = 0; tick < 340; tick++)
{
listenHost.SubmitLocalInput(default, isPhysicsTick: true);
remote.PumpNetwork();
if (listenHost.ViewState.Phase == MatchPhase.Active &&
remote.ViewState.Phase == MatchPhase.Active &&
remote.ActivePods.Count > 0)
{
break;
}
Thread.Sleep(1);
}
PumpListenHostAndClient(listenHost, remote, ticks: 10);
Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase);
Assert.Equal(MatchPhase.Active, remote.ViewState.Phase);
Assert.Equal((byte)2, listenHost.ViewState.SquadSize);
Assert.Equal((byte)2, remote.ViewState.SquadSize);
Assert.Equal(0, listenHost.ViewState.Contenders[remoteId].SquadId);
Assert.Equal(0, remote.ViewState.Contenders[remoteId].SquadId);
Assert.True(listenHost.ViewState.AreAllies(0, remoteId));
Assert.True(remote.ViewState.AreAllies(0, remoteId));
}
}
}

View file

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

View file

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

View file

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