diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 0000000..76736aa
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,6 @@
+
+
+ $(YMIR_ROOT)
+ $(MSBuildThisFileDirectory)..\Ymir
+
+
diff --git a/RustToDust.slnx b/RustToDust.slnx
new file mode 100644
index 0000000..5955da4
--- /dev/null
+++ b/RustToDust.slnx
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
diff --git a/src/RustToDust.Core/Broadcast.cs b/src/RustToDust.Core/Broadcast.cs
new file mode 100644
index 0000000..4fc6231
--- /dev/null
+++ b/src/RustToDust.Core/Broadcast.cs
@@ -0,0 +1,72 @@
+using System.Collections.Generic;
+
+namespace RustToDust.Core
+{
+ public enum BroadcastKind
+ {
+ MatchStart,
+ TouristPull,
+ ExemplarWakeup,
+ PatronClearance,
+ ChassisSwap,
+ Overheat,
+ Elimination,
+ Victory
+ }
+
+ public readonly record struct BroadcastLine(float Timestamp, BroadcastKind Kind, string Text);
+
+ public sealed class BroadcastFeed
+ {
+ private const int MaxLines = 32;
+ private readonly List _lines = new();
+
+ public IReadOnlyList Lines => _lines;
+ public BroadcastLine? Latest => _lines.Count > 0 ? _lines[_lines.Count - 1] : null;
+
+ public void Emit(float timestamp, BroadcastKind kind, string text)
+ {
+ if (_lines.Count >= MaxLines)
+ {
+ _lines.RemoveAt(0);
+ }
+ _lines.Add(new BroadcastLine(timestamp, kind, text));
+ }
+
+ public void EmitMatchStart(float timestamp) =>
+ Emit(timestamp, BroadcastKind.MatchStart,
+ "Imperial Broadcast opens the desert ring. Eight unvarnished rigs enter for the gallery's amusement.");
+
+ public void EmitTouristPull(float timestamp, int contenderId) =>
+ Emit(timestamp, BroadcastKind.TouristPull,
+ $"Contender {contenderId + 1:00} fires on a gilded tourist — crude, lucrative, and deeply impolite.");
+
+ public void EmitExemplarWakeup(float timestamp, int contenderId) =>
+ Emit(timestamp, BroadcastKind.ExemplarWakeup,
+ $"An ornate exemplar accepts the provocation of Contender {contenderId + 1:00}. The gallery hushes.");
+
+ public void EmitPatronClearance(float timestamp, int contenderId) =>
+ Emit(timestamp, BroadcastKind.PatronClearance,
+ $"Contender {contenderId + 1:00} breaches the perimeter line; ring patrons take clearance to correct their posture.");
+
+ public void EmitChassisSwap(float timestamp, int contenderId, string chassisName) =>
+ Emit(timestamp, BroadcastKind.ChassisSwap,
+ $"Contender {contenderId + 1:00} sheds a ruin and mounts a {chassisName}. Vulgar improvisation, yet watchable.");
+
+ public void EmitOverheat(float timestamp, int contenderId) =>
+ Emit(timestamp, BroadcastKind.Overheat,
+ $"Contender {contenderId + 1:00} glows past the thermal plateau — the crowd admires the smoke.");
+
+ public void EmitElimination(float timestamp, string killerLabel, string victimLabel, bool bySpectator)
+ {
+ string line = bySpectator
+ ? $"{killerLabel} restores boundary decorum over {victimLabel}. Order keeps its shine."
+ : $"{killerLabel} performs a decisive eviction on {victimLabel}. The gallery notes the sincerity.";
+ Emit(timestamp, BroadcastKind.Elimination, line);
+ }
+
+ public void EmitVictory(float timestamp, int winnerId) =>
+ Emit(timestamp, BroadcastKind.Victory,
+ $"Contender {winnerId + 1:00} outlasts the dust and the gallery's patience. Broadcast closes with reluctant applause.");
+ }
+}
diff --git a/src/RustToDust.Core/Catalog.cs b/src/RustToDust.Core/Catalog.cs
new file mode 100644
index 0000000..0a48101
--- /dev/null
+++ b/src/RustToDust.Core/Catalog.cs
@@ -0,0 +1,583 @@
+using System;
+using System.Collections.Generic;
+
+namespace RustToDust.Core
+{
+ public static class Catalog
+ {
+ private static bool[] ParseMask(params string[] rows)
+ {
+ int h = rows.Length;
+ int w = rows[0].Length;
+ var mask = new bool[w * h];
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ mask[y * w + x] = rows[y][x] == '#';
+ }
+ }
+ return mask;
+ }
+
+ // ---------------- CHASSIS (6 PLAYABLE) ----------------
+
+ public static readonly ChassisSpec Buggy = new(
+ Id: "buggy",
+ Name: "Dune Buggy",
+ Plane: GridPlane.Dorsal,
+ Width: 3,
+ Height: 4,
+ Mask: ParseMask(
+ "###",
+ "###",
+ "###",
+ "###"),
+ Hardpoints: new[]
+ {
+ new HardpointSpec("wpn_roof", HardpointKind.Weapon, 1, 0, 1, 1, 5f),
+ new HardpointSpec("eng_mid", HardpointKind.Engine, 1, 2, 1, 1, 5f),
+ new HardpointSpec("rad_rear", HardpointKind.Radiator, 1, 3, 1, 1, 0f)
+ },
+ HullConductivity: 8f,
+ BaseCellThermalMass: 10f,
+ BaseCellArmor: 24f,
+ MassKg: 950f,
+ BaseThrust: 13500f,
+ BaseTurnRate: 4.2f,
+ MaxSpeed: 32f,
+ HalfWidth: 1.05f,
+ HalfHeight: 0.75f,
+ HalfLength: 1.65f,
+ CargoCapacity: 4);
+
+ public static readonly ChassisSpec Technical = new(
+ Id: "technical",
+ Name: "Gun Truck",
+ Plane: GridPlane.Dorsal,
+ Width: 3,
+ Height: 5,
+ Mask: ParseMask(
+ "###",
+ "###",
+ "###",
+ "###",
+ "###"),
+ Hardpoints: new[]
+ {
+ new HardpointSpec("wpn_cab", HardpointKind.Weapon, 1, 0, 1, 1, 6f),
+ new HardpointSpec("eng_hood", HardpointKind.Engine, 1, 1, 1, 1, 6f),
+ new HardpointSpec("wpn_bed", HardpointKind.Weapon, 1, 2, 1, 2, 8f),
+ new HardpointSpec("rad_tail", HardpointKind.Radiator, 2, 4, 1, 1, 0f),
+ new HardpointSpec("arm_bumper", HardpointKind.Armor, 0, 0, 1, 1, 10f)
+ },
+ HullConductivity: 8.5f,
+ BaseCellThermalMass: 13f,
+ BaseCellArmor: 34f,
+ MassKg: 1850f,
+ BaseThrust: 22000f,
+ BaseTurnRate: 3.3f,
+ MaxSpeed: 27f,
+ HalfWidth: 1.25f,
+ HalfHeight: 0.95f,
+ HalfLength: 2.3f,
+ CargoCapacity: 6);
+
+ public static readonly ChassisSpec Tank = new(
+ Id: "tank",
+ Name: "Ironclad Tank",
+ Plane: GridPlane.Dorsal,
+ Width: 4,
+ Height: 5,
+ Mask: ParseMask(
+ "####",
+ "####",
+ "####",
+ "####",
+ "####"),
+ Hardpoints: new[]
+ {
+ new HardpointSpec("arm_glacis", HardpointKind.Armor, 1, 0, 2, 1, 24f),
+ new HardpointSpec("wpn_coax", HardpointKind.Weapon, 0, 1, 1, 1, 10f),
+ new HardpointSpec("wpn_turret", HardpointKind.Weapon, 1, 1, 2, 2, 18f),
+ new HardpointSpec("arm_skirt", HardpointKind.Armor, 0, 2, 1, 1, 16f),
+ new HardpointSpec("eng_rear", HardpointKind.Engine, 1, 3, 2, 2, 10f),
+ new HardpointSpec("rad_deck", HardpointKind.Radiator, 3, 3, 1, 1, 0f)
+ },
+ HullConductivity: 9.5f,
+ BaseCellThermalMass: 18f,
+ BaseCellArmor: 62f,
+ MassKg: 4200f,
+ BaseThrust: 38000f,
+ BaseTurnRate: 2.1f,
+ MaxSpeed: 20f,
+ HalfWidth: 1.65f,
+ HalfHeight: 1.1f,
+ HalfLength: 2.65f,
+ CargoCapacity: 8);
+
+ public static readonly ChassisSpec Manticore = new(
+ Id: "manticore",
+ Name: "Manticore Quadruped",
+ Plane: GridPlane.Dorsal,
+ Width: 5,
+ Height: 5,
+ Mask: ParseMask(
+ "#####",
+ ".###.",
+ "#####",
+ ".###.",
+ "#.#.#"),
+ Hardpoints: new[]
+ {
+ new HardpointSpec("wpn_chin", HardpointKind.Weapon, 2, 0, 1, 1, 10f),
+ new HardpointSpec("wpn_left", HardpointKind.Weapon, 0, 2, 1, 1, 8f),
+ new HardpointSpec("wpn_right", HardpointKind.Weapon, 4, 2, 1, 1, 8f),
+ new HardpointSpec("eng_core", HardpointKind.Engine, 2, 1, 1, 2, 12f),
+ new HardpointSpec("rad_left", HardpointKind.Radiator, 1, 1, 1, 1, 4f),
+ new HardpointSpec("rad_right", HardpointKind.Radiator, 3, 1, 1, 1, 4f),
+ new HardpointSpec("arm_back", HardpointKind.Armor, 2, 3, 1, 1, 18f)
+ },
+ HullConductivity: 11f,
+ BaseCellThermalMass: 15f,
+ BaseCellArmor: 46f,
+ MassKg: 2800f,
+ BaseThrust: 33000f,
+ BaseTurnRate: 3.6f,
+ MaxSpeed: 25f,
+ HalfWidth: 1.6f,
+ HalfHeight: 1.35f,
+ HalfLength: 2.1f,
+ CargoCapacity: 7);
+
+ public static readonly ChassisSpec Raptor = new(
+ Id: "raptor",
+ Name: "Raptor Biped",
+ Plane: GridPlane.Coronal,
+ Width: 5,
+ Height: 6,
+ Mask: ParseMask(
+ "..#..",
+ ".###.",
+ "#####",
+ "#.#.#",
+ ".#.#.",
+ ".#.#."),
+ Hardpoints: new[]
+ {
+ new HardpointSpec("rad_lsh", HardpointKind.Radiator, 1, 1, 1, 1, 4f),
+ new HardpointSpec("rad_rsh", HardpointKind.Radiator, 3, 1, 1, 1, 4f),
+ new HardpointSpec("wpn_larm", HardpointKind.Weapon, 0, 2, 1, 2, 8f),
+ new HardpointSpec("eng_chest", HardpointKind.Engine, 2, 2, 1, 1, 12f),
+ new HardpointSpec("wpn_rarm", HardpointKind.Weapon, 4, 2, 1, 2, 8f)
+ },
+ HullConductivity: 10.5f,
+ BaseCellThermalMass: 14f,
+ BaseCellArmor: 42f,
+ MassKg: 2300f,
+ BaseThrust: 30000f,
+ BaseTurnRate: 4.1f,
+ MaxSpeed: 26f,
+ HalfWidth: 1.35f,
+ HalfHeight: 1.95f,
+ HalfLength: 1.15f,
+ CargoCapacity: 6);
+
+ public static readonly ChassisSpec Paladin = new(
+ Id: "paladin",
+ Name: "Paladin Heavy Biped",
+ Plane: GridPlane.Coronal,
+ Width: 6,
+ Height: 7,
+ Mask: ParseMask(
+ "..##..",
+ ".####.",
+ "######",
+ "######",
+ ".####.",
+ ".#..#.",
+ ".#..#."),
+ Hardpoints: new[]
+ {
+ new HardpointSpec("wpn_lsh", HardpointKind.Weapon, 1, 1, 1, 1, 12f),
+ new HardpointSpec("arm_collar", HardpointKind.Armor, 2, 1, 2, 1, 22f),
+ new HardpointSpec("wpn_rsh", HardpointKind.Weapon, 4, 1, 1, 1, 12f),
+ new HardpointSpec("wpn_larm", HardpointKind.Weapon, 0, 2, 1, 2, 12f),
+ new HardpointSpec("eng_core", HardpointKind.Engine, 2, 2, 2, 2, 16f),
+ new HardpointSpec("wpn_rarm", HardpointKind.Weapon, 5, 2, 1, 2, 12f),
+ new HardpointSpec("rad_l", HardpointKind.Radiator, 1, 4, 1, 1, 6f),
+ new HardpointSpec("arm_waist", HardpointKind.Armor, 2, 4, 2, 1, 20f),
+ new HardpointSpec("rad_r", HardpointKind.Radiator, 4, 4, 1, 1, 6f)
+ },
+ HullConductivity: 11.5f,
+ BaseCellThermalMass: 18f,
+ BaseCellArmor: 58f,
+ MassKg: 4100f,
+ BaseThrust: 41000f,
+ BaseTurnRate: 2.7f,
+ MaxSpeed: 21f,
+ HalfWidth: 1.75f,
+ HalfHeight: 2.35f,
+ HalfLength: 1.4f,
+ CargoCapacity: 9);
+
+ public static readonly IReadOnlyList AllChassis = new[]
+ {
+ Buggy, Technical, Tank, Manticore, Raptor, Paladin
+ };
+
+ // ---------------- HUMAN SALVAGE MODULES (8) ----------------
+
+ public static readonly ModuleSpec Mg762 = new(
+ Id: "mg_762",
+ Name: "7.62 Machine Gun",
+ Kind: HardpointKind.Weapon,
+ Width: 1,
+ Height: 1,
+ IsImperial: false,
+ ThermalMass: 5f,
+ Conductivity: 9f,
+ OptimalTemp: 65f,
+ PlateauWidth: 70f,
+ MinTemp: 0f,
+ MaxTemp: 155f,
+ HeatOutput: 34f,
+ CoolingPower: 0f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 0f,
+ WeaponDamage: 12f,
+ WeaponRange: 75f,
+ FireCooldown: 0.22f,
+ ProjectileSpeed: 220f,
+ SpreadRad: 0.035f,
+ BurstCount: 1);
+
+ public static readonly ModuleSpec Autocannon = new(
+ Id: "autocannon",
+ Name: "Twin 20mm Autocannon",
+ Kind: HardpointKind.Weapon,
+ Width: 1,
+ Height: 2,
+ IsImperial: false,
+ ThermalMass: 10f,
+ Conductivity: 10f,
+ OptimalTemp: 75f,
+ PlateauWidth: 70f,
+ MinTemp: 0f,
+ MaxTemp: 170f,
+ HeatOutput: 75f,
+ CoolingPower: 0f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 0f,
+ WeaponDamage: 22f,
+ WeaponRange: 95f,
+ FireCooldown: 0.34f,
+ ProjectileSpeed: 250f,
+ SpreadRad: 0.025f,
+ BurstCount: 2);
+
+ public static readonly ModuleSpec Flak = new(
+ Id: "flak",
+ Name: "Scrap Flak Scattergun",
+ Kind: HardpointKind.Weapon,
+ Width: 1,
+ Height: 1,
+ IsImperial: false,
+ ThermalMass: 6f,
+ Conductivity: 8f,
+ OptimalTemp: 65f,
+ PlateauWidth: 70f,
+ MinTemp: 0f,
+ MaxTemp: 165f,
+ HeatOutput: 90f,
+ CoolingPower: 0f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 0f,
+ WeaponDamage: 8.5f,
+ WeaponRange: 48f,
+ FireCooldown: 0.65f,
+ ProjectileSpeed: 185f,
+ SpreadRad: 0.14f,
+ BurstCount: 5);
+
+ public static readonly ModuleSpec Recoilless = new(
+ Id: "recoilless",
+ Name: "105mm Recoilless Rifle",
+ Kind: HardpointKind.Weapon,
+ Width: 2,
+ Height: 2,
+ IsImperial: false,
+ ThermalMass: 18f,
+ Conductivity: 11f,
+ OptimalTemp: 75f,
+ PlateauWidth: 80f,
+ MinTemp: 0f,
+ MaxTemp: 185f,
+ HeatOutput: 190f,
+ CoolingPower: 0f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 0f,
+ WeaponDamage: 85f,
+ WeaponRange: 120f,
+ FireCooldown: 1.45f,
+ ProjectileSpeed: 280f,
+ SpreadRad: 0.01f,
+ BurstCount: 1);
+
+ public static readonly ModuleSpec DieselCore = new(
+ Id: "diesel_core",
+ Name: "Salvaged Diesel Core",
+ Kind: HardpointKind.Engine,
+ Width: 1,
+ Height: 1,
+ IsImperial: false,
+ ThermalMass: 9f,
+ Conductivity: 9f,
+ OptimalTemp: 60f,
+ PlateauWidth: 80f,
+ MinTemp: 0f,
+ MaxTemp: 150f,
+ HeatOutput: 45f,
+ CoolingPower: 0f,
+ ThrustBonus: 4500f,
+ TurnBonus: 0.4f,
+ ArmorBonus: 0f,
+ WeaponDamage: 0f,
+ WeaponRange: 0f,
+ FireCooldown: 0f,
+ ProjectileSpeed: 0f,
+ SpreadRad: 0f,
+ BurstCount: 0);
+
+ public static readonly ModuleSpec TurboCore = new(
+ Id: "turbo_core",
+ Name: "Supercharged V8",
+ Kind: HardpointKind.Engine,
+ Width: 1,
+ Height: 2,
+ IsImperial: false,
+ ThermalMass: 14f,
+ Conductivity: 10f,
+ OptimalTemp: 75f,
+ PlateauWidth: 70f,
+ MinTemp: 0f,
+ MaxTemp: 170f,
+ HeatOutput: 85f,
+ CoolingPower: 0f,
+ ThrustBonus: 12500f,
+ TurnBonus: 0.9f,
+ ArmorBonus: 0f,
+ WeaponDamage: 0f,
+ WeaponRange: 0f,
+ FireCooldown: 0f,
+ ProjectileSpeed: 0f,
+ SpreadRad: 0f,
+ BurstCount: 0);
+
+ public static readonly ModuleSpec CopperRad = new(
+ Id: "copper_rad",
+ Name: "Copper Fin Radiator",
+ Kind: HardpointKind.Radiator,
+ Width: 1,
+ Height: 1,
+ IsImperial: false,
+ ThermalMass: 6f,
+ Conductivity: 15f,
+ OptimalTemp: 85f,
+ PlateauWidth: 90f,
+ MinTemp: 0f,
+ MaxTemp: 210f,
+ HeatOutput: 0f,
+ CoolingPower: 120f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 0f,
+ WeaponDamage: 0f,
+ WeaponRange: 0f,
+ FireCooldown: 0f,
+ ProjectileSpeed: 0f,
+ SpreadRad: 0f,
+ BurstCount: 0);
+
+ public static readonly ModuleSpec WeldedPlate = new(
+ Id: "welded_plate",
+ Name: "Welded Scrap Plate",
+ Kind: HardpointKind.Armor,
+ Width: 1,
+ Height: 1,
+ IsImperial: false,
+ ThermalMass: 12f,
+ Conductivity: 6f,
+ OptimalTemp: 60f,
+ PlateauWidth: 120f,
+ MinTemp: -20f,
+ MaxTemp: 240f,
+ HeatOutput: 0f,
+ CoolingPower: 0f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 45f,
+ WeaponDamage: 0f,
+ WeaponRange: 0f,
+ FireCooldown: 0f,
+ ProjectileSpeed: 0f,
+ SpreadRad: 0f,
+ BurstCount: 0);
+
+ // ---------------- IMPERIAL TOURIST HIGH-END MODULES (5) ----------------
+
+ public static readonly ModuleSpec GildedLance = new(
+ Id: "gilded_lance",
+ Name: "Gilded Thermal Lance",
+ Kind: HardpointKind.Weapon,
+ Width: 1,
+ Height: 2,
+ IsImperial: true,
+ ThermalMass: 11f,
+ Conductivity: 14f,
+ OptimalTemp: 90f,
+ PlateauWidth: 80f,
+ MinTemp: 0f,
+ MaxTemp: 210f,
+ HeatOutput: 95f,
+ CoolingPower: 0f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 0f,
+ WeaponDamage: 54f,
+ WeaponRange: 130f,
+ FireCooldown: 0.55f,
+ ProjectileSpeed: 400f,
+ SpreadRad: 0.004f,
+ BurstCount: 1);
+
+ public static readonly ModuleSpec TouringPlasma = new(
+ Id: "touring_plasma",
+ Name: "Touring Plasma Repeater",
+ Kind: HardpointKind.Weapon,
+ Width: 1,
+ Height: 1,
+ IsImperial: true,
+ ThermalMass: 8f,
+ Conductivity: 14f,
+ OptimalTemp: 95f,
+ PlateauWidth: 80f,
+ MinTemp: 0f,
+ MaxTemp: 205f,
+ HeatOutput: 68f,
+ CoolingPower: 0f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 0f,
+ WeaponDamage: 26f,
+ WeaponRange: 95f,
+ FireCooldown: 0.18f,
+ ProjectileSpeed: 310f,
+ SpreadRad: 0.02f,
+ BurstCount: 1);
+
+ public static readonly ModuleSpec GoldRadiator = new(
+ Id: "gold_radiator",
+ Name: "Gold-Leaf Phase Radiator",
+ Kind: HardpointKind.Radiator,
+ Width: 1,
+ Height: 1,
+ IsImperial: true,
+ ThermalMass: 7f,
+ Conductivity: 24f,
+ OptimalTemp: 100f,
+ PlateauWidth: 110f,
+ MinTemp: 0f,
+ MaxTemp: 260f,
+ HeatOutput: 0f,
+ CoolingPower: 290f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 0f,
+ WeaponDamage: 0f,
+ WeaponRange: 0f,
+ FireCooldown: 0f,
+ ProjectileSpeed: 0f,
+ SpreadRad: 0f,
+ BurstCount: 0);
+
+ public static readonly ModuleSpec NobleCore = new(
+ Id: "noble_core",
+ Name: "Overclocked Noble Core",
+ Kind: HardpointKind.Engine,
+ Width: 1,
+ Height: 2,
+ IsImperial: true,
+ ThermalMass: 15f,
+ Conductivity: 16f,
+ OptimalTemp: 105f,
+ PlateauWidth: 90f,
+ MinTemp: 0f,
+ MaxTemp: 225f,
+ HeatOutput: 110f,
+ CoolingPower: 0f,
+ ThrustBonus: 19500f,
+ TurnBonus: 1.45f,
+ ArmorBonus: 0f,
+ WeaponDamage: 0f,
+ WeaponRange: 0f,
+ FireCooldown: 0f,
+ ProjectileSpeed: 0f,
+ SpreadRad: 0f,
+ BurstCount: 0);
+
+ public static readonly ModuleSpec GildedPlate = new(
+ Id: "gilded_plate",
+ Name: "Gilded Ceramic Plate",
+ Kind: HardpointKind.Armor,
+ Width: 1,
+ Height: 1,
+ IsImperial: true,
+ ThermalMass: 16f,
+ Conductivity: 4f,
+ OptimalTemp: 80f,
+ PlateauWidth: 140f,
+ MinTemp: -20f,
+ MaxTemp: 280f,
+ HeatOutput: 0f,
+ CoolingPower: 0f,
+ ThrustBonus: 0f,
+ TurnBonus: 0f,
+ ArmorBonus: 85f,
+ WeaponDamage: 0f,
+ WeaponRange: 0f,
+ FireCooldown: 0f,
+ ProjectileSpeed: 0f,
+ SpreadRad: 0f,
+ BurstCount: 0);
+
+ public static readonly IReadOnlyList HumanModules = new[]
+ {
+ Mg762, Autocannon, Flak, Recoilless, DieselCore, TurboCore, CopperRad, WeldedPlate
+ };
+
+ public static readonly IReadOnlyList ImperialModules = new[]
+ {
+ GildedLance, TouringPlasma, GoldRadiator, NobleCore, GildedPlate
+ };
+
+ public static readonly IReadOnlyList AllModules = new[]
+ {
+ Mg762, Autocannon, Flak, Recoilless, DieselCore, TurboCore, CopperRad, WeldedPlate,
+ GildedLance, TouringPlasma, GoldRadiator, NobleCore, GildedPlate
+ };
+
+ public static ChassisGrid CreateStarterBuggy()
+ {
+ var grid = new ChassisGrid(Buggy);
+ grid.TryMount(Mg762, "wpn_roof");
+ grid.TryMount(DieselCore, "eng_mid");
+ grid.TryMount(CopperRad, "rad_rear");
+ return grid;
+ }
+ }
+}
diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs
new file mode 100644
index 0000000..a48bea4
--- /dev/null
+++ b/src/RustToDust.Core/GridChassis.cs
@@ -0,0 +1,913 @@
+using System;
+using System.Collections.Generic;
+
+namespace RustToDust.Core
+{
+ public enum GridPlane
+ {
+ Dorsal,
+ Coronal
+ }
+
+ public enum HardpointKind
+ {
+ Weapon,
+ Engine,
+ Radiator,
+ Armor,
+ Utility
+ }
+
+ public sealed record HardpointSpec(
+ string Id,
+ HardpointKind Kind,
+ int X,
+ int Y,
+ int Width,
+ int Height,
+ float ArmorBonus);
+
+ public sealed record ModuleSpec(
+ string Id,
+ string Name,
+ HardpointKind Kind,
+ int Width,
+ int Height,
+ bool IsImperial,
+ float ThermalMass,
+ float Conductivity,
+ float OptimalTemp,
+ float PlateauWidth,
+ float MinTemp,
+ float MaxTemp,
+ float HeatOutput,
+ float CoolingPower,
+ float ThrustBonus,
+ float TurnBonus,
+ float ArmorBonus,
+ float WeaponDamage,
+ float WeaponRange,
+ float FireCooldown,
+ float ProjectileSpeed,
+ float SpreadRad,
+ int BurstCount)
+ {
+ ///
+ /// Exact Aetheria trapezoidal plateau curve:
+ /// 0 outside [MinTemp, MaxTemp], 1 on [OptimalTemp - PlateauWidth/2, OptimalTemp + PlateauWidth/2],
+ /// linear ramp between bounds and plateau.
+ ///
+ public float Performance(float temperature)
+ {
+ if (temperature <= MinTemp || temperature >= MaxTemp)
+ {
+ return 0f;
+ }
+
+ float halfPlateau = PlateauWidth * 0.5f;
+ float lowPlateau = OptimalTemp - halfPlateau;
+ float highPlateau = OptimalTemp + halfPlateau;
+
+ if (temperature >= lowPlateau && temperature <= highPlateau)
+ {
+ return 1f;
+ }
+
+ if (temperature < lowPlateau)
+ {
+ float span = MathF.Max(1e-5f, lowPlateau - MinTemp);
+ return Math.Clamp((temperature - MinTemp) / span, 0f, 1f);
+ }
+
+ float upperSpan = MathF.Max(1e-5f, MaxTemp - highPlateau);
+ return Math.Clamp((MaxTemp - temperature) / upperSpan, 0f, 1f);
+ }
+ }
+
+ public sealed record ChassisSpec(
+ string Id,
+ string Name,
+ GridPlane Plane,
+ int Width,
+ int Height,
+ bool[] Mask,
+ HardpointSpec[] Hardpoints,
+ float HullConductivity,
+ float BaseCellThermalMass,
+ float BaseCellArmor,
+ float MassKg,
+ float BaseThrust,
+ float BaseTurnRate,
+ float MaxSpeed,
+ float HalfWidth,
+ float HalfHeight,
+ float HalfLength,
+ int CargoCapacity)
+ {
+ public bool IsActive(int x, int y) =>
+ x >= 0 && x < Width && y >= 0 && y < Height && Mask[y * Width + x];
+ }
+
+ public sealed class MountedModule
+ {
+ public MountedModule(ModuleSpec spec, string hardpointId, float initialTemp)
+ {
+ Spec = spec;
+ HardpointId = hardpointId;
+ CurrentTemp = initialTemp;
+ CurrentPerformance = spec.Performance(initialTemp);
+ }
+
+ public ModuleSpec Spec { get; }
+ public string HardpointId { get; }
+ public float Cooldown { get; set; }
+ public float CurrentTemp { get; set; }
+ public float CurrentPerformance { get; set; }
+ }
+
+ public readonly record struct HitResult(
+ int CellX,
+ int CellY,
+ float ArmorDamage,
+ float CoreDamage,
+ bool CoreDestroyed);
+
+ public sealed class ChassisGrid
+ {
+ public const float AmbientTemp = 20f;
+ public const float RadiationExponent = 1.6f;
+ public const float RadiationMultiplier = 0.015f;
+
+ private static readonly (int Dx, int Dy)[] CardinalOffsets =
+ {
+ (1, 0), (-1, 0), (0, 1), (0, -1)
+ };
+
+ private float[,] _netHeat;
+ private float[,] _cellThermalMass;
+ private float[,] _cellConductivity;
+
+ public ChassisGrid(ChassisSpec spec)
+ {
+ Spec = spec ?? throw new ArgumentNullException(nameof(spec));
+ Temperature = new float[spec.Width, spec.Height];
+ Armor = new float[spec.Width, spec.Height];
+ MaxArmor = new float[spec.Width, spec.Height];
+ BorderCells = new bool[spec.Width, spec.Height];
+ _netHeat = new float[spec.Width, spec.Height];
+ _cellThermalMass = new float[spec.Width, spec.Height];
+ _cellConductivity = new float[spec.Width, spec.Height];
+ InitializeGridState(spec, preserveCoreRatio: false, previousRatio: 1f);
+ }
+
+ public ChassisSpec Spec { get; private set; }
+ public float[,] Temperature { get; private set; }
+ public float[,] Armor { get; private set; }
+ public float[,] MaxArmor { get; private set; }
+ public bool[,] BorderCells { get; private set; }
+ public List Mounted { get; } = new();
+ public List Cargo { get; } = new();
+
+ public float CoreHp { get; private set; }
+ public float MaxCoreHp { get; private set; }
+ public bool IsDestroyed => CoreHp <= 0f;
+
+ public static bool CanFit(HardpointSpec hp, ModuleSpec mod) =>
+ mod.Kind == hp.Kind && mod.Width <= hp.Width && mod.Height <= hp.Height;
+
+ public HardpointSpec? FindHardpoint(string hardpointId)
+ {
+ for (int i = 0; i < Spec.Hardpoints.Length; i++)
+ {
+ if (Spec.Hardpoints[i].Id == hardpointId)
+ {
+ return Spec.Hardpoints[i];
+ }
+ }
+ return null;
+ }
+
+ public MountedModule? GetMountedOn(string hardpointId)
+ {
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ if (Mounted[i].HardpointId == hardpointId)
+ {
+ return Mounted[i];
+ }
+ }
+ return null;
+ }
+
+ public bool TryMount(ModuleSpec mod, string hardpointId, List? displacedOut = null)
+ {
+ var hp = FindHardpoint(hardpointId);
+ if (hp is null || !CanFit(hp, mod))
+ {
+ return false;
+ }
+
+ var existing = GetMountedOn(hardpointId);
+ if (existing is not null)
+ {
+ Mounted.Remove(existing);
+ if (Cargo.Count < Spec.CargoCapacity)
+ {
+ Cargo.Add(existing.Spec);
+ }
+ else
+ {
+ displacedOut?.Add(existing.Spec);
+ }
+ }
+
+ float avgTemp = GetHardpointAverageTemp(hp);
+ Mounted.Add(new MountedModule(mod, hardpointId, avgTemp));
+ RecalculateArmorAndThermal(grantNewArmorDelta: true);
+ return true;
+ }
+
+ public bool TryEquipFromCargo(int cargoIndex, string hardpointId, List? displacedOut = null)
+ {
+ if (cargoIndex < 0 || cargoIndex >= Cargo.Count)
+ {
+ return false;
+ }
+
+ var mod = Cargo[cargoIndex];
+ var hp = FindHardpoint(hardpointId);
+ if (hp is null || !CanFit(hp, mod))
+ {
+ return false;
+ }
+
+ Cargo.RemoveAt(cargoIndex);
+ if (!TryMount(mod, hardpointId, displacedOut))
+ {
+ Cargo.Insert(cargoIndex, mod);
+ return false;
+ }
+ return true;
+ }
+
+ public bool TryAddCargo(ModuleSpec mod)
+ {
+ if (Cargo.Count >= Spec.CargoCapacity)
+ {
+ return false;
+ }
+ Cargo.Add(mod);
+ return true;
+ }
+
+ public void InjectHeat(int x, int y, float heat)
+ {
+ if (!Spec.IsActive(x, y) || heat == 0f)
+ {
+ return;
+ }
+ float tm = MathF.Max(1f, _cellThermalMass[x, y]);
+ Temperature[x, y] = MathF.Max(AmbientTemp, Temperature[x, y] + heat / tm);
+ }
+
+ public void InjectHardpointHeat(string hardpointId, float heat)
+ {
+ var hp = FindHardpoint(hardpointId);
+ if (hp is null || heat == 0f)
+ {
+ return;
+ }
+
+ int activeCells = CountActiveCellsInHardpoint(hp);
+ if (activeCells == 0)
+ {
+ return;
+ }
+
+ float perCell = heat / activeCells;
+ for (int dy = 0; dy < hp.Height; dy++)
+ {
+ for (int dx = 0; dx < hp.Width; dx++)
+ {
+ int x = hp.X + dx;
+ int y = hp.Y + dy;
+ if (Spec.IsActive(x, y))
+ {
+ InjectHeat(x, y, perCell);
+ }
+ }
+ }
+ }
+
+ public void StepHeat(float dt)
+ {
+ if (dt <= 0f)
+ {
+ return;
+ }
+
+ int w = Spec.Width;
+ int h = Spec.Height;
+ int substeps = Math.Max(1, (int)MathF.Ceiling(dt / 0.02f));
+ float subDt = dt / substeps;
+
+ for (int step = 0; step < substeps; step++)
+ {
+ Array.Clear(_netHeat, 0, _netHeat.Length);
+
+ // 4-neighbor weighted conduction (conservative pairwise transfer)
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ if (!Spec.IsActive(x, y))
+ {
+ continue;
+ }
+
+ float t = Temperature[x, y];
+ float c = _cellConductivity[x, y];
+
+ if (x + 1 < w && Spec.IsActive(x + 1, y))
+ {
+ float pairCond = 0.5f * (c + _cellConductivity[x + 1, y]);
+ float flow = pairCond * (Temperature[x + 1, y] - t) * subDt;
+ _netHeat[x, y] += flow;
+ _netHeat[x + 1, y] -= flow;
+ }
+
+ if (y + 1 < h && Spec.IsActive(x, y + 1))
+ {
+ float pairCond = 0.5f * (c + _cellConductivity[x, y + 1]);
+ float flow = pairCond * (Temperature[x, y + 1] - t) * subDt;
+ _netHeat[x, y] += flow;
+ _netHeat[x, y + 1] -= flow;
+ }
+ }
+ }
+
+ // Border-only radiative cooling
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ if (!Spec.IsActive(x, y) || !BorderCells[x, y])
+ {
+ continue;
+ }
+
+ float t = MathF.Max(0f, Temperature[x, y]);
+ float radLoss = MathF.Pow(t, RadiationExponent) * RadiationMultiplier * subDt;
+ _netHeat[x, y] -= radLoss;
+ }
+ }
+
+ // Active radiator cooling scaled by radiator's Performance(temp)
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ var mod = Mounted[i];
+ if (mod.Spec.Kind != HardpointKind.Radiator || mod.Spec.CoolingPower <= 0f)
+ {
+ continue;
+ }
+
+ var hp = FindHardpoint(mod.HardpointId);
+ if (hp is null)
+ {
+ continue;
+ }
+
+ float perf = mod.Spec.Performance(mod.CurrentTemp);
+ if (perf <= 0f)
+ {
+ continue;
+ }
+
+ int activeCells = CountActiveCellsInHardpoint(hp);
+ if (activeCells == 0)
+ {
+ continue;
+ }
+
+ float coolPerCell = (mod.Spec.CoolingPower * perf * subDt) / activeCells;
+ for (int dy = 0; dy < hp.Height; dy++)
+ {
+ for (int dx = 0; dx < hp.Width; dx++)
+ {
+ int cx = hp.X + dx;
+ int cy = hp.Y + dy;
+ if (Spec.IsActive(cx, cy))
+ {
+ _netHeat[cx, cy] -= coolPerCell;
+ }
+ }
+ }
+ }
+
+ // Integrate temperature with desert ambient floor
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ if (!Spec.IsActive(x, y))
+ {
+ Temperature[x, y] = AmbientTemp;
+ continue;
+ }
+
+ float tm = MathF.Max(1f, _cellThermalMass[x, y]);
+ float next = Temperature[x, y] + _netHeat[x, y] / tm;
+ Temperature[x, y] = MathF.Max(AmbientTemp, next);
+ }
+ }
+
+ UpdateMountedTelemetry();
+ }
+ }
+
+ public HitResult ApplyHit(float localRight, float localForward, float localHeightNorm, float damage, float heatTransfer)
+ {
+ (int cx, int cy) = ResolveHitCell(localRight, localForward, localHeightNorm);
+ if (!Spec.IsActive(cx, cy))
+ {
+ return new HitResult(0, 0, 0f, 0f, IsDestroyed);
+ }
+
+ if (heatTransfer > 0f)
+ {
+ InjectHeat(cx, cy, heatTransfer);
+ }
+
+ float absorbed = MathF.Min(Armor[cx, cy], MathF.Max(0f, damage));
+ Armor[cx, cy] -= absorbed;
+ float spill = MathF.Max(0f, damage - absorbed);
+
+ if (spill > 0f && CoreHp > 0f)
+ {
+ CoreHp = MathF.Max(0f, CoreHp - spill);
+ }
+
+ return new HitResult(cx, cy, absorbed, spill, IsDestroyed);
+ }
+
+ public List SwapChassis(ChassisSpec next)
+ {
+ if (next is null)
+ {
+ throw new ArgumentNullException(nameof(next));
+ }
+
+ var previousMounted = new List(Mounted.Count);
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ previousMounted.Add(Mounted[i].Spec);
+ }
+ var previousCargo = new List(Cargo);
+ float coreRatio = MaxCoreHp > 0f ? CoreHp / MaxCoreHp : 1f;
+
+ Mounted.Clear();
+ Cargo.Clear();
+
+ Spec = next;
+ Temperature = new float[next.Width, next.Height];
+ Armor = new float[next.Width, next.Height];
+ MaxArmor = new float[next.Width, next.Height];
+ BorderCells = new bool[next.Width, next.Height];
+ _netHeat = new float[next.Width, next.Height];
+ _cellThermalMass = new float[next.Width, next.Height];
+ _cellConductivity = new float[next.Width, next.Height];
+
+ InitializeGridState(next, preserveCoreRatio: true, previousRatio: MathF.Max(0.75f, coreRatio));
+
+ var dropped = new List();
+
+ // Transfer every mounted module that fits a free hardpoint on the new chassis
+ foreach (var mod in previousMounted)
+ {
+ HardpointSpec? chosen = null;
+ for (int i = 0; i < next.Hardpoints.Length; i++)
+ {
+ var hp = next.Hardpoints[i];
+ if (GetMountedOn(hp.Id) is null && CanFit(hp, mod))
+ {
+ chosen = hp;
+ break;
+ }
+ }
+
+ if (chosen is not null)
+ {
+ Mounted.Add(new MountedModule(mod, chosen.Id, AmbientTemp));
+ }
+ else if (Cargo.Count < next.CargoCapacity)
+ {
+ Cargo.Add(mod);
+ }
+ else
+ {
+ dropped.Add(mod);
+ }
+ }
+
+ foreach (var item in previousCargo)
+ {
+ if (Cargo.Count < next.CargoCapacity)
+ {
+ Cargo.Add(item);
+ }
+ else
+ {
+ dropped.Add(item);
+ }
+ }
+
+ RecalculateArmorAndThermal(grantNewArmorDelta: true);
+ UpdateMountedTelemetry();
+ return dropped;
+ }
+
+ public float LegIntegrity
+ {
+ get
+ {
+ if (Spec.Plane != GridPlane.Coronal)
+ {
+ return 1f;
+ }
+
+ int legStartY = Math.Max(0, Spec.Height - 2);
+ float cur = 0f;
+ float max = 0f;
+ for (int y = legStartY; y < Spec.Height; y++)
+ {
+ for (int x = 0; x < Spec.Width; x++)
+ {
+ if (!Spec.IsActive(x, y))
+ {
+ continue;
+ }
+ cur += Armor[x, y];
+ max += MaxArmor[x, y];
+ }
+ }
+
+ if (max <= 0f)
+ {
+ return 1f;
+ }
+
+ float ratio = Math.Clamp(cur / max, 0f, 1f);
+ return 0.25f + 0.75f * ratio;
+ }
+ }
+
+ public float ComputeDriveThrust()
+ {
+ float engineThrust = 0f;
+ float enginePerfSum = 0f;
+ int engineCount = 0;
+
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ var m = Mounted[i];
+ if (m.Spec.Kind == HardpointKind.Engine)
+ {
+ engineThrust += m.Spec.ThrustBonus * m.CurrentPerformance;
+ enginePerfSum += m.CurrentPerformance;
+ engineCount++;
+ }
+ }
+
+ float baseFactor = engineCount > 0 ? Math.Clamp(enginePerfSum / engineCount, 0.25f, 1f) : 0.4f;
+ return (Spec.BaseThrust * baseFactor + engineThrust) * LegIntegrity;
+ }
+
+ public float ComputeTurnRate()
+ {
+ float bonus = 0f;
+ float enginePerfSum = 0f;
+ int engineCount = 0;
+
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ var m = Mounted[i];
+ if (m.Spec.Kind == HardpointKind.Engine)
+ {
+ bonus += m.Spec.TurnBonus * m.CurrentPerformance;
+ enginePerfSum += m.CurrentPerformance;
+ engineCount++;
+ }
+ }
+
+ float baseFactor = engineCount > 0 ? Math.Clamp(enginePerfSum / engineCount, 0.35f, 1f) : 0.5f;
+ return (Spec.BaseTurnRate * baseFactor + bonus) * (0.5f + 0.5f * LegIntegrity);
+ }
+
+ public float TotalArmorRatio()
+ {
+ float cur = 0f;
+ float max = 0f;
+ for (int y = 0; y < Spec.Height; y++)
+ {
+ for (int x = 0; x < Spec.Width; x++)
+ {
+ if (!Spec.IsActive(x, y))
+ {
+ continue;
+ }
+ cur += Armor[x, y];
+ max += MaxArmor[x, y];
+ }
+ }
+ return max > 0f ? cur / max : 0f;
+ }
+
+ private (int X, int Y) ResolveHitCell(float localRight, float localForward, float localHeightNorm)
+ {
+ int w = Spec.Width;
+ int h = Spec.Height;
+
+ if (Spec.Plane == GridPlane.Coronal)
+ {
+ float targetX = (Math.Clamp(localRight, -1f, 1f) * 0.5f + 0.5f) * (w - 1);
+ float targetY = (1f - Math.Clamp(localHeightNorm, 0f, 1f)) * (h - 1);
+
+ int bestX = 0;
+ int bestY = 0;
+ float bestDistSq = float.PositiveInfinity;
+
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ if (!Spec.IsActive(x, y))
+ {
+ continue;
+ }
+ float dx = x - targetX;
+ float dy = y - targetY;
+ float d2 = dx * dx + dy * dy;
+ if (d2 < bestDistSq)
+ {
+ bestDistSq = d2;
+ bestX = x;
+ bestY = y;
+ }
+ }
+ }
+ return (bestX, bestY);
+ }
+
+ // GridPlane.Dorsal: map (localRight, localForward) onto the outer active cell facing the hit.
+ // Row y=0 is front (+localForward), row y=Height-1 is rear (-localForward).
+ float dirX = localRight;
+ float dirY = -localForward;
+ float len = MathF.Sqrt(dirX * dirX + dirY * dirY);
+ if (len < 1e-4f)
+ {
+ dirX = 0f;
+ dirY = -1f;
+ }
+ else
+ {
+ dirX /= len;
+ dirY /= len;
+ }
+
+ int bestDx = 0;
+ int bestDy = 0;
+ float bestScore = float.NegativeInfinity;
+
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ if (!Spec.IsActive(x, y))
+ {
+ continue;
+ }
+
+ float nx = (x + 0.5f) / w - 0.5f;
+ float ny = (y + 0.5f) / h - 0.5f;
+
+ float proj = nx * dirX + ny * dirY;
+ float alignPenalty = ((nx - dirX * 0.5f) * (nx - dirX * 0.5f) + (ny - dirY * 0.5f) * (ny - dirY * 0.5f)) * 0.05f;
+ float borderBoost = BorderCells[x, y] ? 0.1f : 0f;
+ float score = proj + borderBoost - alignPenalty;
+
+ if (score > bestScore)
+ {
+ bestScore = score;
+ bestDx = x;
+ bestDy = y;
+ }
+ }
+ }
+
+ return (bestDx, bestDy);
+ }
+
+ private void InitializeGridState(ChassisSpec spec, bool preserveCoreRatio, float previousRatio)
+ {
+ int activeCount = 0;
+ for (int y = 0; y < spec.Height; y++)
+ {
+ for (int x = 0; x < spec.Width; x++)
+ {
+ Temperature[x, y] = AmbientTemp;
+ if (!spec.IsActive(x, y))
+ {
+ BorderCells[x, y] = false;
+ continue;
+ }
+
+ activeCount++;
+ bool isBorder = false;
+ for (int i = 0; i < CardinalOffsets.Length; i++)
+ {
+ int nx = x + CardinalOffsets[i].Dx;
+ int ny = y + CardinalOffsets[i].Dy;
+ if (!spec.IsActive(nx, ny))
+ {
+ isBorder = true;
+ break;
+ }
+ }
+ BorderCells[x, y] = isBorder;
+ }
+ }
+
+ MaxCoreHp = 100f + activeCount * 8f + spec.BaseCellArmor * 2.5f;
+ CoreHp = preserveCoreRatio ? MaxCoreHp * Math.Clamp(previousRatio, 0.05f, 1f) : MaxCoreHp;
+
+ RecalculateArmorAndThermal(grantNewArmorDelta: false);
+ for (int y = 0; y < spec.Height; y++)
+ {
+ for (int x = 0; x < spec.Width; x++)
+ {
+ Armor[x, y] = MaxArmor[x, y];
+ }
+ }
+ }
+
+ private void RecalculateArmorAndThermal(bool grantNewArmorDelta)
+ {
+ int w = Spec.Width;
+ int h = Spec.Height;
+
+ float[,] previousMax = (float[,])MaxArmor.Clone();
+
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ if (!Spec.IsActive(x, y))
+ {
+ MaxArmor[x, y] = 0f;
+ Armor[x, y] = 0f;
+ _cellThermalMass[x, y] = 1f;
+ _cellConductivity[x, y] = 0f;
+ continue;
+ }
+
+ MaxArmor[x, y] = Spec.BaseCellArmor;
+ _cellThermalMass[x, y] = Spec.BaseCellThermalMass;
+ _cellConductivity[x, y] = Spec.HullConductivity;
+ }
+ }
+
+ for (int i = 0; i < Spec.Hardpoints.Length; i++)
+ {
+ var hp = Spec.Hardpoints[i];
+ if (hp.ArmorBonus == 0f)
+ {
+ continue;
+ }
+
+ for (int dy = 0; dy < hp.Height; dy++)
+ {
+ for (int dx = 0; dx < hp.Width; dx++)
+ {
+ int x = hp.X + dx;
+ int y = hp.Y + dy;
+ if (Spec.IsActive(x, y))
+ {
+ MaxArmor[x, y] += hp.ArmorBonus;
+ }
+ }
+ }
+ }
+
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ var mod = Mounted[i];
+ var hp = FindHardpoint(mod.HardpointId);
+ if (hp is null)
+ {
+ continue;
+ }
+
+ int activeCells = CountActiveCellsInHardpoint(hp);
+ if (activeCells == 0)
+ {
+ continue;
+ }
+
+ float tmShare = mod.Spec.ThermalMass / activeCells;
+ float armorShare = mod.Spec.ArmorBonus / activeCells;
+
+ for (int dy = 0; dy < hp.Height; dy++)
+ {
+ for (int dx = 0; dx < hp.Width; dx++)
+ {
+ int x = hp.X + dx;
+ int y = hp.Y + dy;
+ if (!Spec.IsActive(x, y))
+ {
+ continue;
+ }
+
+ _cellThermalMass[x, y] += tmShare;
+ _cellConductivity[x, y] = MathF.Max(_cellConductivity[x, y], mod.Spec.Conductivity);
+ MaxArmor[x, y] += armorShare;
+ }
+ }
+ }
+
+ if (grantNewArmorDelta)
+ {
+ for (int y = 0; y < h; y++)
+ {
+ for (int x = 0; x < w; x++)
+ {
+ if (!Spec.IsActive(x, y))
+ {
+ continue;
+ }
+ float delta = MaxArmor[x, y] - previousMax[x, y];
+ if (delta > 0f)
+ {
+ Armor[x, y] = MathF.Min(MaxArmor[x, y], Armor[x, y] + delta);
+ }
+ else
+ {
+ Armor[x, y] = MathF.Min(Armor[x, y], MaxArmor[x, y]);
+ }
+ }
+ }
+ }
+ }
+
+ private int CountActiveCellsInHardpoint(HardpointSpec hp)
+ {
+ int count = 0;
+ for (int dy = 0; dy < hp.Height; dy++)
+ {
+ for (int dx = 0; dx < hp.Width; dx++)
+ {
+ if (Spec.IsActive(hp.X + dx, hp.Y + dy))
+ {
+ count++;
+ }
+ }
+ }
+ return count;
+ }
+
+ private float GetHardpointAverageTemp(HardpointSpec hp)
+ {
+ float sum = 0f;
+ int count = 0;
+ for (int dy = 0; dy < hp.Height; dy++)
+ {
+ for (int dx = 0; dx < hp.Width; dx++)
+ {
+ int x = hp.X + dx;
+ int y = hp.Y + dy;
+ if (Spec.IsActive(x, y))
+ {
+ sum += Temperature[x, y];
+ count++;
+ }
+ }
+ }
+ return count > 0 ? sum / count : AmbientTemp;
+ }
+
+ private void UpdateMountedTelemetry()
+ {
+ for (int i = 0; i < Mounted.Count; i++)
+ {
+ var mod = Mounted[i];
+ var hp = FindHardpoint(mod.HardpointId);
+ if (hp is null)
+ {
+ continue;
+ }
+ float avgTemp = GetHardpointAverageTemp(hp);
+ mod.CurrentTemp = avgTemp;
+ mod.CurrentPerformance = mod.Spec.Performance(avgTemp);
+ }
+ }
+ }
+}
diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs
new file mode 100644
index 0000000..5288b99
--- /dev/null
+++ b/src/RustToDust.Core/MatchRules.cs
@@ -0,0 +1,360 @@
+using System;
+
+namespace RustToDust.Core
+{
+ public static class MatchRules
+ {
+ public static float NormalizeAngle(float rad)
+ {
+ while (rad > MathF.PI) rad -= MathF.Tau;
+ while (rad < -MathF.PI) rad += MathF.Tau;
+ return rad;
+ }
+
+ public static void ApplyPlayerInput(MatchState state, PlayerInput input)
+ {
+ var player = state.Player;
+ if (!player.Alive)
+ {
+ player.ThrottleCmd = 0f;
+ player.SteerCmd = 0f;
+ player.FireCmd = false;
+ player.BrakeCmd = true;
+ return;
+ }
+
+ player.ThrottleCmd = Math.Clamp(input.Throttle, -1f, 1f);
+ player.SteerCmd = Math.Clamp(input.Steer, -1f, 1f);
+ player.AimX = input.AimWorldX;
+ player.AimZ = input.AimWorldZ;
+ player.FireCmd = input.Fire;
+ player.BrakeCmd = input.Brake;
+
+ if (input.InteractPickup)
+ {
+ if (!state.TryPickupNearbyModule(0))
+ {
+ state.TrySwapNearbyChassis(0);
+ }
+ }
+ }
+
+ public static void UpdateAiContenders(MatchState state, float dt)
+ {
+ float safeLimit = MathF.Max(15f, state.Spectators.SafeRadius - 10f);
+
+ for (int i = 0; i < state.Contenders.Count; i++)
+ {
+ var ai = state.Contenders[i];
+ if (ai.IsPlayer || !ai.Alive)
+ {
+ continue;
+ }
+
+ ai.AiScavengeCooldown = MathF.Max(0f, ai.AiScavengeCooldown - dt);
+ AutoEquipAiCargo(state, ai);
+
+ float distFromCenter = MathF.Sqrt(ai.X * ai.X + ai.Z * ai.Z);
+ float goalX = 0f;
+ float goalZ = 0f;
+ bool hasGoal = false;
+ bool wantFire = false;
+ float aimX = ai.X + MathF.Sin(ai.Yaw) * 20f;
+ float aimZ = ai.Z + MathF.Cos(ai.Yaw) * 20f;
+
+ // 1. Stay inside the shrinking Safe Circle
+ if (distFromCenter > safeLimit)
+ {
+ goalX = 0f;
+ goalZ = 0f;
+ hasGoal = true;
+ }
+
+ // 2. Find nearest hostile contender
+ ContenderState? target = null;
+ float bestEnemyDistSq = 90f * 90f;
+ for (int j = 0; j < state.Contenders.Count; j++)
+ {
+ var other = state.Contenders[j];
+ if (other.Id == ai.Id || !other.Alive)
+ {
+ continue;
+ }
+
+ float dx = other.X - ai.X;
+ float dz = other.Z - ai.Z;
+ float d2 = dx * dx + dz * dz;
+ if (d2 < bestEnemyDistSq)
+ {
+ bestEnemyDistSq = d2;
+ target = other;
+ }
+ }
+
+ // 3. Scavenge nearby upgrades when safe
+ if (!hasGoal && ai.AiScavengeCooldown <= 0f)
+ {
+ GroundDrop? bestDrop = null;
+ float bestDropDistSq = 34f * 34f;
+ for (int d = 0; d < state.GroundDrops.Count; d++)
+ {
+ var drop = state.GroundDrops[d];
+ if (drop.PickedUp)
+ {
+ continue;
+ }
+
+ if (drop.Chassis is not null && drop.Chassis.MassKg <= ai.Grid.Spec.MassKg)
+ {
+ continue;
+ }
+
+ float dx = drop.X - ai.X;
+ float dz = drop.Z - ai.Z;
+ float d2 = dx * dx + dz * dz;
+ if (d2 < bestDropDistSq)
+ {
+ bestDropDistSq = d2;
+ bestDrop = drop;
+ }
+ }
+
+ if (bestDrop is not null)
+ {
+ goalX = bestDrop.X;
+ goalZ = bestDrop.Z;
+ hasGoal = true;
+
+ if (bestDropDistSq <= MatchState.PickupRadius * MatchState.PickupRadius)
+ {
+ if (bestDrop.Module is not null)
+ {
+ state.TryPickupNearbyModule(ai.Id);
+ }
+ else if (bestDrop.Chassis is not null)
+ {
+ state.TrySwapNearbyChassis(ai.Id);
+ }
+ ai.AiScavengeCooldown = 2.5f;
+ }
+ }
+ }
+
+ // 4. Combat or third-party gunfire investigation
+ if (target is not null)
+ {
+ aimX = target.X;
+ aimZ = target.Z;
+ float dist = MathF.Sqrt(bestEnemyDistSq);
+ wantFire = dist <= 72f;
+
+ if (!hasGoal)
+ {
+ if (dist > 34f)
+ {
+ goalX = target.X;
+ goalZ = target.Z;
+ }
+ else
+ {
+ // Orbit target instead of ramming headlong
+ float tangentAngle = MathF.Atan2(ai.Z - target.Z, ai.X - target.X) + 0.7f;
+ goalX = target.X + MathF.Cos(tangentAngle) * 26f;
+ goalZ = target.Z + MathF.Sin(tangentAngle) * 26f;
+ }
+ hasGoal = true;
+ }
+ }
+ else if (!hasGoal && state.LastGunfireX.HasValue && state.LastGunfireZ.HasValue &&
+ state.Time - state.LastGunfireTime < 8f)
+ {
+ goalX = state.LastGunfireX.Value;
+ goalZ = state.LastGunfireZ.Value;
+ hasGoal = true;
+ }
+ else if (!hasGoal)
+ {
+ float patrolAngle = ai.Id * 0.9f + state.Time * 0.15f;
+ float r = MathF.Min(safeLimit * 0.65f, 45f);
+ goalX = MathF.Cos(patrolAngle) * r;
+ goalZ = MathF.Sin(patrolAngle) * r;
+ }
+
+ float toGoalX = goalX - ai.X;
+ float toGoalZ = goalZ - ai.Z;
+ float desiredYaw = MathF.Atan2(toGoalX, toGoalZ);
+ float yawError = NormalizeAngle(desiredYaw - ai.Yaw);
+
+ ai.SteerCmd = Math.Clamp(yawError * 1.8f, -1f, 1f);
+ ai.ThrottleCmd = MathF.Abs(yawError) > 1.25f ? 0.35f : 0.85f;
+ ai.BrakeCmd = false;
+ ai.AimX = aimX;
+ ai.AimZ = aimZ;
+ ai.FireCmd = wantFire;
+ }
+ }
+
+ public static void ComputeSpectatorBehavior(
+ SpectatorState spec,
+ MatchState state,
+ out float goalX,
+ out float goalZ,
+ out float aimX,
+ out float aimZ,
+ out bool shouldFire)
+ {
+ if (spec.Stance == SpectatorStance.Neutral || !spec.TargetContenderId.HasValue)
+ {
+ (goalX, goalZ) = state.Spectators.GetPerimeterSlot(spec);
+ aimX = 0f;
+ aimZ = 0f;
+ shouldFire = false;
+ return;
+ }
+
+ ContenderState? target = null;
+ int targetId = spec.TargetContenderId.Value;
+ if (targetId >= 0 && targetId < state.Contenders.Count)
+ {
+ target = state.Contenders[targetId];
+ }
+
+ if (target is null || !target.Alive)
+ {
+ (goalX, goalZ) = state.Spectators.GetPerimeterSlot(spec);
+ aimX = 0f;
+ aimZ = 0f;
+ shouldFire = false;
+ return;
+ }
+
+ aimX = target.X;
+ aimZ = target.Z;
+
+ float dx = target.X - spec.X;
+ float dz = target.Z - spec.Z;
+ float dist = MathF.Sqrt(dx * dx + dz * dz);
+
+ if (dist > spec.PreferredRange)
+ {
+ goalX = target.X;
+ goalZ = target.Z;
+ }
+ else
+ {
+ float angle = MathF.Atan2(spec.Z - target.Z, spec.X - target.X) + (spec.Tier == SpectatorTier.Exemplar ? 0.9f : 0.4f);
+ goalX = target.X + MathF.Cos(angle) * (spec.PreferredRange * 0.85f);
+ goalZ = target.Z + MathF.Sin(angle) * (spec.PreferredRange * 0.85f);
+ }
+
+ shouldFire = dist <= 115f;
+
+ // Tourists self-throttle when their Imperial weapons run hot
+ if (shouldFire && spec.Tier == SpectatorTier.Tourist)
+ {
+ for (int i = 0; i < spec.Grid.Mounted.Count; i++)
+ {
+ var m = spec.Grid.Mounted[i];
+ if (m.Spec.Kind == HardpointKind.Weapon &&
+ m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.45f)
+ {
+ shouldFire = false;
+ break;
+ }
+ }
+ }
+ }
+
+ public static void AdvanceTracers(MatchState state, float dt)
+ {
+ for (int i = state.Tracers.Count - 1; i >= 0; i--)
+ {
+ var t = state.Tracers[i];
+ float nextTtl = t.Ttl - dt;
+ if (nextTtl <= 0f)
+ {
+ state.Tracers.RemoveAt(i);
+ }
+ else
+ {
+ state.Tracers[i] = t with { Ttl = nextTtl };
+ }
+ }
+ }
+
+ public static void UpdateMatchOutcome(MatchState state)
+ {
+ if (state.Phase != MatchPhase.Active)
+ {
+ return;
+ }
+
+ if (!state.Player.Alive)
+ {
+ state.Phase = MatchPhase.Defeat;
+ return;
+ }
+
+ int aliveCount = 0;
+ for (int i = 0; i < state.Contenders.Count; i++)
+ {
+ if (state.Contenders[i].Alive)
+ {
+ aliveCount++;
+ }
+ }
+
+ if (aliveCount <= 1 && state.Player.Alive)
+ {
+ state.Phase = MatchPhase.Victory;
+ state.Broadcast.EmitVictory(state.Time, state.Player.Id);
+ }
+ }
+
+ private static void AutoEquipAiCargo(MatchState state, ContenderState ai)
+ {
+ if (ai.Grid.Cargo.Count == 0)
+ {
+ return;
+ }
+
+ for (int c = ai.Grid.Cargo.Count - 1; c >= 0; c--)
+ {
+ var item = ai.Grid.Cargo[c];
+ for (int h = 0; h < ai.Grid.Spec.Hardpoints.Length; h++)
+ {
+ var hp = ai.Grid.Spec.Hardpoints[h];
+ if (!ChassisGrid.CanFit(hp, item))
+ {
+ continue;
+ }
+
+ var mounted = ai.Grid.GetMountedOn(hp.Id);
+ if (mounted is null || IsBetterModule(item, mounted.Spec))
+ {
+ state.TryEquipCargo(ai.Id, c, hp.Id);
+ break;
+ }
+ }
+ }
+ }
+
+ private static bool IsBetterModule(ModuleSpec candidate, ModuleSpec current)
+ {
+ if (candidate.IsImperial && !current.IsImperial)
+ {
+ return true;
+ }
+
+ return candidate.Kind switch
+ {
+ HardpointKind.Weapon => candidate.WeaponDamage * MathF.Max(1, candidate.BurstCount) >
+ current.WeaponDamage * MathF.Max(1, current.BurstCount),
+ HardpointKind.Engine => candidate.ThrustBonus > current.ThrustBonus,
+ HardpointKind.Radiator => candidate.CoolingPower > current.CoolingPower,
+ HardpointKind.Armor => candidate.ArmorBonus > current.ArmorBonus,
+ _ => false
+ };
+ }
+ }
+}
diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs
new file mode 100644
index 0000000..184c74a
--- /dev/null
+++ b/src/RustToDust.Core/MatchState.cs
@@ -0,0 +1,379 @@
+using System;
+using System.Collections.Generic;
+
+namespace RustToDust.Core
+{
+ public enum MatchPhase
+ {
+ Active,
+ Victory,
+ Defeat
+ }
+
+ public readonly record struct PlayerInput(
+ float Throttle,
+ float Steer,
+ float AimWorldX,
+ float AimWorldZ,
+ bool Fire,
+ bool InteractPickup,
+ bool Brake);
+
+ public readonly record struct TracerEvent(
+ float StartX,
+ float StartY,
+ float StartZ,
+ float EndX,
+ float EndY,
+ float EndZ,
+ uint ColorRgba,
+ float Ttl);
+
+ public readonly record struct ArenaBoxSpec(
+ float X,
+ float Y,
+ float Z,
+ float HalfX,
+ float HalfY,
+ float HalfZ,
+ bool IsBoundary);
+
+ public sealed class GroundDrop
+ {
+ public GroundDrop(int id, float x, float z, ChassisSpec? chassis, ModuleSpec? module)
+ {
+ Id = id;
+ X = x;
+ Z = z;
+ Chassis = chassis;
+ Module = module;
+ }
+
+ public int Id { get; }
+ public float X { get; }
+ public float Z { get; }
+ public ChassisSpec? Chassis { get; }
+ public ModuleSpec? Module { get; }
+ public bool PickedUp { get; set; }
+ }
+
+ public sealed class ContenderState
+ {
+ public ContenderState(int id, string name, bool isPlayer, ChassisGrid grid, float x, float z, float yaw)
+ {
+ Id = id;
+ Name = name;
+ IsPlayer = isPlayer;
+ Grid = grid;
+ X = x;
+ Y = grid.Spec.HalfHeight + 0.1f;
+ Z = z;
+ Yaw = yaw;
+ AimX = x + MathF.Sin(yaw) * 20f;
+ AimZ = z + MathF.Cos(yaw) * 20f;
+ }
+
+ public int Id { get; }
+ public string Name { get; }
+ public bool IsPlayer { get; }
+ public ChassisGrid Grid { get; }
+ public float X { get; set; }
+ public float Y { get; set; }
+ public float Z { get; set; }
+ public float Yaw { get; set; }
+ public float AimX { get; set; }
+ public float AimZ { get; set; }
+ public float Speed { get; set; }
+ public int Kills { get; set; }
+ public bool OverheatWarned { get; set; }
+
+ public float ThrottleCmd { get; set; }
+ public float SteerCmd { get; set; }
+ public bool FireCmd { get; set; }
+ public bool BrakeCmd { get; set; }
+ public float AiScavengeCooldown { get; set; }
+
+ public bool Alive => !Grid.IsDestroyed;
+ }
+
+ public sealed class MatchState
+ {
+ public const int ContenderCount = 8;
+ public const float ArenaHalfExtent = 195f;
+ public const float PickupRadius = 6.5f;
+
+ private int _nextDropId = 1;
+
+ public MatchState(int seed = 42)
+ {
+ Seed = seed;
+ Rng = new Random(seed);
+ Spectators = new SpectatorRing(seed + 101);
+ Broadcast = new BroadcastFeed();
+ ArenaCoverBoxes = BuildCoverBoxes();
+ ArenaBoundaryBoxes = BuildBoundaryBoxes();
+
+ SpawnContenders();
+ ScatterInitialLoot();
+ Broadcast.EmitMatchStart(0f);
+ }
+
+ public int Seed { get; }
+ public Random Rng { get; }
+ public float Time { get; set; }
+ public MatchPhase Phase { get; set; } = MatchPhase.Active;
+
+ public List Contenders { get; } = new();
+ public SpectatorRing Spectators { get; }
+ public List GroundDrops { get; } = new();
+ public List Tracers { get; } = new();
+ public BroadcastFeed Broadcast { get; }
+ public IReadOnlyList ArenaCoverBoxes { get; }
+ public IReadOnlyList ArenaBoundaryBoxes { get; }
+
+ public float? LastGunfireX { get; set; }
+ public float? LastGunfireZ { get; set; }
+ public float LastGunfireTime { get; set; } = -100f;
+
+ public ContenderState Player => Contenders[0];
+
+ public event Action? ChassisSwapped;
+
+ public GroundDrop SpawnModuleDrop(float x, float z, ModuleSpec module)
+ {
+ var drop = new GroundDrop(_nextDropId++, x, z, null, module);
+ GroundDrops.Add(drop);
+ return drop;
+ }
+
+ public GroundDrop SpawnChassisDrop(float x, float z, ChassisSpec chassis)
+ {
+ var drop = new GroundDrop(_nextDropId++, x, z, chassis, null);
+ GroundDrops.Add(drop);
+ return drop;
+ }
+
+ public bool TryEquipCargo(int cargoIndex, string hardpointId) =>
+ TryEquipCargo(0, cargoIndex, hardpointId);
+
+ public bool TryEquipCargo(int contenderId, int cargoIndex, string hardpointId)
+ {
+ if (contenderId < 0 || contenderId >= Contenders.Count)
+ {
+ return false;
+ }
+
+ var contender = Contenders[contenderId];
+ if (!contender.Alive)
+ {
+ return false;
+ }
+
+ var displaced = new List();
+ bool ok = contender.Grid.TryEquipFromCargo(cargoIndex, hardpointId, displaced);
+ if (!ok)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < displaced.Count; i++)
+ {
+ SpawnModuleDrop(contender.X + 1.5f, contender.Z + 1.5f, displaced[i]);
+ }
+ return true;
+ }
+
+ public bool TryPickupNearbyModule(int contenderId = 0)
+ {
+ if (contenderId < 0 || contenderId >= Contenders.Count)
+ {
+ return false;
+ }
+
+ var contender = Contenders[contenderId];
+ if (!contender.Alive)
+ {
+ return false;
+ }
+
+ GroundDrop? nearest = null;
+ float bestDistSq = PickupRadius * PickupRadius;
+
+ for (int i = 0; i < GroundDrops.Count; i++)
+ {
+ var d = GroundDrops[i];
+ if (d.PickedUp || d.Module is null)
+ {
+ continue;
+ }
+
+ float dx = d.X - contender.X;
+ float dz = d.Z - contender.Z;
+ float d2 = dx * dx + dz * dz;
+ if (d2 <= bestDistSq)
+ {
+ bestDistSq = d2;
+ nearest = d;
+ }
+ }
+
+ if (nearest is null || nearest.Module is null)
+ {
+ return false;
+ }
+
+ if (!contender.Grid.TryAddCargo(nearest.Module))
+ {
+ return false;
+ }
+
+ nearest.PickedUp = true;
+ return true;
+ }
+
+ public bool TrySwapNearbyChassis(int contenderId = 0)
+ {
+ if (contenderId < 0 || contenderId >= Contenders.Count)
+ {
+ return false;
+ }
+
+ var contender = Contenders[contenderId];
+ if (!contender.Alive)
+ {
+ return false;
+ }
+
+ GroundDrop? nearest = null;
+ float bestDistSq = PickupRadius * PickupRadius;
+
+ for (int i = 0; i < GroundDrops.Count; i++)
+ {
+ var d = GroundDrops[i];
+ if (d.PickedUp || d.Chassis is null)
+ {
+ continue;
+ }
+
+ float dx = d.X - contender.X;
+ float dz = d.Z - contender.Z;
+ float d2 = dx * dx + dz * dz;
+ if (d2 <= bestDistSq)
+ {
+ bestDistSq = d2;
+ nearest = d;
+ }
+ }
+
+ if (nearest is null || nearest.Chassis is null)
+ {
+ return false;
+ }
+
+ var oldChassis = contender.Grid.Spec;
+ var overflow = contender.Grid.SwapChassis(nearest.Chassis);
+ nearest.PickedUp = true;
+
+ // Leave old hull behind and drop overflow modules around the swap site
+ SpawnChassisDrop(contender.X - 2.2f, contender.Z - 2.2f, oldChassis);
+ for (int i = 0; i < overflow.Count; i++)
+ {
+ SpawnModuleDrop(contender.X + 1.5f + i * 0.7f, contender.Z - 1.5f, overflow[i]);
+ }
+
+ contender.Y = contender.Grid.Spec.HalfHeight + 0.1f;
+ Broadcast.EmitChassisSwap(Time, contender.Id, contender.Grid.Spec.Name);
+ ChassisSwapped?.Invoke(contender);
+ return true;
+ }
+
+ private void SpawnContenders()
+ {
+ // Spawn 8 contenders evenly around an inner ring (radius 95m, well inside SafeRadius = 150m)
+ const float spawnRadius = 95f;
+ for (int i = 0; i < ContenderCount; i++)
+ {
+ float angle = (i / (float)ContenderCount) * MathF.Tau;
+ float x = MathF.Cos(angle) * spawnRadius;
+ float z = MathF.Sin(angle) * spawnRadius;
+ float yaw = MathF.Atan2(-x, -z);
+ string name = i == 0 ? "Contender 01 (You)" : $"Contender {i + 1:00}";
+ Contenders.Add(new ContenderState(i, name, i == 0, Catalog.CreateStarterBuggy(), x, z, yaw));
+ }
+ }
+
+ private void ScatterInitialLoot()
+ {
+ // Deterministic chassis wrecks across arena ruins
+ (ChassisSpec Spec, float X, float Z)[] chassisPlacements =
+ {
+ (Catalog.Technical, 45f, 35f),
+ (Catalog.Technical, -52f, -28f),
+ (Catalog.Tank, 12f, -68f),
+ (Catalog.Manticore, -42f, 54f),
+ (Catalog.Raptor, 64f, -40f),
+ (Catalog.Paladin, 0f, 18f)
+ };
+
+ foreach (var (spec, x, z) in chassisPlacements)
+ {
+ SpawnChassisDrop(x, z, spec);
+ }
+
+ // Deterministic salvage module crates
+ ModuleSpec[] salvagePool =
+ {
+ Catalog.Autocannon, Catalog.Flak, Catalog.Recoilless,
+ Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate,
+ Catalog.Autocannon, Catalog.Flak, Catalog.TurboCore,
+ Catalog.WeldedPlate, Catalog.CopperRad, Catalog.Mg762
+ };
+
+ for (int i = 0; i < salvagePool.Length; i++)
+ {
+ float angle = (i / (float)salvagePool.Length) * MathF.Tau + 0.25f;
+ float r = 24f + (i % 3) * 26f;
+ SpawnModuleDrop(MathF.Cos(angle) * r, MathF.Sin(angle) * r, salvagePool[i]);
+ }
+ }
+
+ private static IReadOnlyList BuildCoverBoxes()
+ {
+ // 16 deterministic ruin walls / cover blocks placed clear of the 95m spawn ring and (0,0) center wreck
+ return new ArenaBoxSpec[]
+ {
+ new(28f, 1.8f, 16f, 4.5f, 1.8f, 1.4f, false),
+ new(-28f, 1.8f, -16f, 4.5f, 1.8f, 1.4f, false),
+ new(16f, 1.8f, -32f, 1.4f, 1.8f, 4.5f, false),
+ new(-16f, 1.8f, 32f, 1.4f, 1.8f, 4.5f, false),
+ new(58f, 2.2f, 18f, 3.2f, 2.2f, 3.2f, false),
+ new(-58f, 2.2f, -18f, 3.2f, 2.2f, 3.2f, false),
+ new(22f, 2.2f, 62f, 5.0f, 2.2f, 1.6f, false),
+ new(-22f, 2.2f, -62f, 5.0f, 2.2f, 1.6f, false),
+ new(72f, 1.6f, -52f, 2.8f, 1.6f, 2.8f, false),
+ new(-72f, 1.6f, 52f, 2.8f, 1.6f, 2.8f, false),
+ new(46f, 2.0f, -72f, 4.0f, 2.0f, 1.5f, false),
+ new(-46f, 2.0f, 72f, 4.0f, 2.0f, 1.5f, false),
+ new(118f, 2.4f, 24f, 3.5f, 2.4f, 3.5f, false),
+ new(-118f, 2.4f, -24f, 3.5f, 2.4f, 3.5f, false),
+ new(24f, 2.4f, -118f, 3.5f, 2.4f, 3.5f, false),
+ new(-24f, 2.4f, 118f, 3.5f, 2.4f, 3.5f, false)
+ };
+ }
+
+ private static IReadOnlyList BuildBoundaryBoxes()
+ {
+ const float wallY = 4f;
+ const float wallHalfH = 4f;
+ const float wallHalfThick = 2f;
+ const float span = ArenaHalfExtent + wallHalfThick;
+ return new ArenaBoxSpec[]
+ {
+ new(0f, wallY, ArenaHalfExtent, span, wallHalfH, wallHalfThick, true),
+ new(0f, wallY, -ArenaHalfExtent, span, wallHalfH, wallHalfThick, true),
+ new(ArenaHalfExtent, wallY, 0f, wallHalfThick, wallHalfH, span, true),
+ new(-ArenaHalfExtent, wallY, 0f, wallHalfThick, wallHalfH, span, true)
+ };
+ }
+ }
+}
diff --git a/src/RustToDust.Core/RustToDust.Core.csproj b/src/RustToDust.Core/RustToDust.Core.csproj
new file mode 100644
index 0000000..ddca8fa
--- /dev/null
+++ b/src/RustToDust.Core/RustToDust.Core.csproj
@@ -0,0 +1,9 @@
+
+
+
+ net8.0
+ enable
+ disable
+
+
+
diff --git a/src/RustToDust.Core/SpectatorRing.cs b/src/RustToDust.Core/SpectatorRing.cs
new file mode 100644
index 0000000..598b790
--- /dev/null
+++ b/src/RustToDust.Core/SpectatorRing.cs
@@ -0,0 +1,396 @@
+using System;
+using System.Collections.Generic;
+
+namespace RustToDust.Core
+{
+ public enum SpectatorTier
+ {
+ Tourist,
+ Patron,
+ Exemplar
+ }
+
+ public enum SpectatorStance
+ {
+ Neutral,
+ Cleared,
+ Provoked
+ }
+
+ public readonly record struct RingContact(int Id, float X, float Z, bool Alive);
+
+ public sealed class SpectatorState
+ {
+ public SpectatorState(
+ int id,
+ SpectatorTier tier,
+ ChassisGrid grid,
+ float ringAngle,
+ float ringOffset,
+ float radarSignature,
+ float aimSpreadRad,
+ float maxSpeed,
+ float preferredRange)
+ {
+ Id = id;
+ Tier = tier;
+ Grid = grid;
+ RingAngle = ringAngle;
+ RingOffset = ringOffset;
+ RadarSignature = radarSignature;
+ AimSpreadRad = aimSpreadRad;
+ MaxSpeed = maxSpeed;
+ PreferredRange = preferredRange;
+ }
+
+ public int Id { get; }
+ public SpectatorTier Tier { get; }
+ public ChassisGrid Grid { get; }
+ public float RingAngle { get; set; }
+ public float RingOffset { get; }
+ public float RadarSignature { get; }
+ public float AimSpreadRad { get; }
+ public float MaxSpeed { get; }
+ public float PreferredRange { get; }
+
+ public SpectatorStance Stance { get; set; } = SpectatorStance.Neutral;
+ public int? TargetContenderId { get; set; }
+ public bool BroadcastWakeupEmitted { get; set; }
+
+ public float X { get; set; }
+ public float Y { get; set; }
+ public float Z { get; set; }
+ public float Yaw { get; set; }
+ public bool Alive => !Grid.IsDestroyed;
+ }
+
+ public sealed class SpectatorRing
+ {
+ public const float InitialRadius = 150f;
+ public const float MinRadius = 35f;
+ public const float GraceDuration = 20f;
+ public const float ShrinkDuration = 240f;
+ public const int DefaultSpectatorCount = 40;
+
+ private readonly List _spectators = new();
+ private readonly Dictionary _aliveById = new();
+
+ public SpectatorRing(int seed = 1337, int count = DefaultSpectatorCount)
+ {
+ var rng = new Random(seed);
+ SafeRadius = InitialRadius;
+ SpawnRing(rng, count);
+ }
+
+ public float SafeRadius { get; private set; }
+ public IReadOnlyList Spectators => _spectators;
+
+ public void UpdateSafeRadius(float matchTime)
+ {
+ if (matchTime <= GraceDuration)
+ {
+ SafeRadius = InitialRadius;
+ return;
+ }
+
+ float t = Math.Clamp((matchTime - GraceDuration) / ShrinkDuration, 0f, 1f);
+ SafeRadius = InitialRadius + (MinRadius - InitialRadius) * t;
+ }
+
+ public void UpdateClearance(ReadOnlySpan contenders)
+ {
+ _aliveById.Clear();
+ for (int i = 0; i < contenders.Length; i++)
+ {
+ _aliveById[contenders[i].Id] = contenders[i].Alive;
+ }
+
+ // Keep Provoked lock while target is alive; reset Cleared to Neutral for clean re-evaluation.
+ for (int i = 0; i < _spectators.Count; i++)
+ {
+ var spec = _spectators[i];
+ if (!spec.Alive)
+ {
+ spec.TargetContenderId = null;
+ continue;
+ }
+
+ if (spec.Stance == SpectatorStance.Provoked)
+ {
+ if (!spec.TargetContenderId.HasValue ||
+ !_aliveById.TryGetValue(spec.TargetContenderId.Value, out bool alive) ||
+ !alive)
+ {
+ spec.Stance = SpectatorStance.Neutral;
+ spec.TargetContenderId = null;
+ }
+ }
+ else
+ {
+ spec.Stance = SpectatorStance.Neutral;
+ spec.TargetContenderId = null;
+ }
+ }
+
+ // Assign Cleared spectators to contenders outside the Safe Circle.
+ for (int c = 0; c < contenders.Length; c++)
+ {
+ var contender = contenders[c];
+ if (!contender.Alive)
+ {
+ continue;
+ }
+
+ float distFromCenter = MathF.Sqrt(contender.X * contender.X + contender.Z * contender.Z);
+ float outsideDist = MathF.Max(0f, distFromCenter - SafeRadius);
+ if (outsideDist <= 0f)
+ {
+ continue;
+ }
+
+ int allowedCleared = Math.Min(8, 1 + (int)(outsideDist / 12f));
+
+ for (int k = 0; k < allowedCleared; k++)
+ {
+ SpectatorState? nearest = null;
+ float bestDistSq = float.PositiveInfinity;
+
+ for (int i = 0; i < _spectators.Count; i++)
+ {
+ var spec = _spectators[i];
+ if (!spec.Alive || spec.Stance != SpectatorStance.Neutral)
+ {
+ continue;
+ }
+
+ float dx = spec.X - contender.X;
+ float dz = spec.Z - contender.Z;
+ float d2 = dx * dx + dz * dz;
+ if (d2 < bestDistSq)
+ {
+ bestDistSq = d2;
+ nearest = spec;
+ }
+ }
+
+ if (nearest is null)
+ {
+ break;
+ }
+
+ nearest.Stance = SpectatorStance.Cleared;
+ nearest.TargetContenderId = contender.Id;
+ }
+ }
+ }
+
+ public bool OnSpectatorDamaged(SpectatorState spectator, int attackerContenderId)
+ {
+ if (!spectator.Alive)
+ {
+ return false;
+ }
+
+ if (spectator.Stance == SpectatorStance.Neutral)
+ {
+ spectator.Stance = SpectatorStance.Provoked;
+ spectator.TargetContenderId = attackerContenderId;
+ return true;
+ }
+
+ return false;
+ }
+
+ public void AdvancePerimeterOrbits(float dt)
+ {
+ for (int i = 0; i < _spectators.Count; i++)
+ {
+ var spec = _spectators[i];
+ if (!spec.Alive || spec.Stance != SpectatorStance.Neutral)
+ {
+ continue;
+ }
+
+ float angularSpeed = spec.Tier == SpectatorTier.Exemplar ? 0.045f : 0.02f;
+ spec.RingAngle += angularSpeed * dt;
+ }
+ }
+
+ public (float X, float Z) GetPerimeterSlot(SpectatorState spec)
+ {
+ float r = SafeRadius + spec.RingOffset;
+ return (MathF.Cos(spec.RingAngle) * r, MathF.Sin(spec.RingAngle) * r);
+ }
+
+ public int CountClearedFor(int contenderId)
+ {
+ int count = 0;
+ for (int i = 0; i < _spectators.Count; i++)
+ {
+ var s = _spectators[i];
+ if (s.Alive && s.Stance == SpectatorStance.Cleared && s.TargetContenderId == contenderId)
+ {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ public int CountProvokedFor(int contenderId)
+ {
+ int count = 0;
+ for (int i = 0; i < _spectators.Count; i++)
+ {
+ var s = _spectators[i];
+ if (s.Alive && s.Stance == SpectatorStance.Provoked && s.TargetContenderId == contenderId)
+ {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ public static List RollSalvageDrops(SpectatorState spec, Random rng)
+ {
+ var drops = new List();
+ switch (spec.Tier)
+ {
+ case SpectatorTier.Tourist:
+ {
+ // Guaranteed 1-2 Imperial high-end modules
+ int count = rng.Next(1, 3);
+ for (int i = 0; i < count; i++)
+ {
+ drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]);
+ }
+ break;
+ }
+ case SpectatorTier.Patron:
+ {
+ // Mixed salvage: 1 module (50% imperial, 50% human upgraded)
+ if (rng.NextDouble() < 0.5)
+ {
+ drops.Add(Catalog.ImperialModules[rng.Next(Catalog.ImperialModules.Count)]);
+ }
+ else
+ {
+ drops.Add(Catalog.HumanModules[rng.Next(Catalog.HumanModules.Count)]);
+ }
+ break;
+ }
+ case SpectatorTier.Exemplar:
+ {
+ // Minimal/no high-end loot: only an occasional modest scrap trophy (never IsImperial)
+ if (rng.NextDouble() < 0.4)
+ {
+ drops.Add(Catalog.WeldedPlate);
+ }
+ break;
+ }
+ }
+ return drops;
+ }
+
+ private void SpawnRing(Random rng, int count)
+ {
+ // ~45% Tourists, ~35% Patrons, ~20% Exemplars
+ int touristCount = (int)MathF.Round(count * 0.45f);
+ int patronCount = (int)MathF.Round(count * 0.35f);
+
+ var tiers = new List(count);
+ for (int i = 0; i < count; i++)
+ {
+ if (i < touristCount) tiers.Add(SpectatorTier.Tourist);
+ else if (i < touristCount + patronCount) tiers.Add(SpectatorTier.Patron);
+ else tiers.Add(SpectatorTier.Exemplar);
+ }
+
+ // Deterministic shuffle so tiers are evenly distributed around the perimeter
+ for (int i = tiers.Count - 1; i > 0; i--)
+ {
+ int j = rng.Next(i + 1);
+ (tiers[i], tiers[j]) = (tiers[j], tiers[i]);
+ }
+
+ for (int i = 0; i < count; i++)
+ {
+ float angle = (i / (float)count) * MathF.Tau;
+ float ringOffset = 10f + (float)rng.NextDouble() * 16f;
+ var tier = tiers[i];
+
+ var spec = CreateSpectator(1000 + i, tier, angle, ringOffset);
+ (float px, float pz) = GetPerimeterSlot(spec);
+ spec.X = px;
+ spec.Y = spec.Grid.Spec.HalfHeight + 0.1f;
+ spec.Z = pz;
+ spec.Yaw = MathF.Atan2(-px, -pz);
+ _spectators.Add(spec);
+ }
+ }
+
+ private static SpectatorState CreateSpectator(int id, SpectatorTier tier, float angle, float ringOffset)
+ {
+ switch (tier)
+ {
+ case SpectatorTier.Tourist:
+ {
+ var grid = new ChassisGrid(Catalog.Paladin);
+ grid.TryMount(Catalog.GildedLance, "wpn_larm");
+ grid.TryMount(Catalog.TouringPlasma, "wpn_lsh");
+ grid.TryMount(Catalog.NobleCore, "eng_core");
+ grid.TryMount(Catalog.GoldRadiator, "rad_l");
+ grid.TryMount(Catalog.GildedPlate, "arm_collar");
+ return new SpectatorState(
+ id, tier, grid, angle, ringOffset,
+ radarSignature: 1.0f,
+ aimSpreadRad: 0.14f,
+ maxSpeed: 16f,
+ preferredRange: 42f);
+ }
+ case SpectatorTier.Patron:
+ {
+ var grid = new ChassisGrid(Catalog.Raptor);
+ grid.TryMount(Catalog.Autocannon, "wpn_larm");
+ grid.TryMount(Catalog.Flak, "wpn_rarm");
+ grid.TryMount(Catalog.TurboCore, "eng_chest");
+ grid.TryMount(Catalog.CopperRad, "rad_lsh");
+ return new SpectatorState(
+ id, tier, grid, angle, ringOffset,
+ radarSignature: 0.6f,
+ aimSpreadRad: 0.055f,
+ maxSpeed: 24f,
+ preferredRange: 36f);
+ }
+ default: // Exemplar
+ {
+ // Lightly armored, lethal precision, blazing speed
+ var exemplarSpec = Catalog.Raptor with
+ {
+ Id = "exemplar_frame",
+ Name = "Exemplar Frame",
+ BaseCellArmor = 22f,
+ MassKg = 1150f,
+ BaseThrust = 26000f,
+ BaseTurnRate = 6.2f,
+ MaxSpeed = 38f,
+ HalfWidth = 0.8f,
+ HalfHeight = 1.55f,
+ HalfLength = 0.8f
+ };
+ var grid = new ChassisGrid(exemplarSpec);
+ grid.TryMount(Catalog.GildedLance, "wpn_rarm");
+ grid.TryMount(Catalog.TouringPlasma, "wpn_larm");
+ grid.TryMount(Catalog.NobleCore, "eng_chest");
+ grid.TryMount(Catalog.GoldRadiator, "rad_lsh");
+ grid.TryMount(Catalog.GoldRadiator, "rad_rsh");
+ return new SpectatorState(
+ id, tier, grid, angle, ringOffset,
+ radarSignature: 0.22f,
+ aimSpreadRad: 0.006f,
+ maxSpeed: 38f,
+ preferredRange: 24f);
+ }
+ }
+ }
+ }
+}
diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs
new file mode 100644
index 0000000..6fade16
--- /dev/null
+++ b/src/RustToDust.Ymir/ArenaSession.cs
@@ -0,0 +1,795 @@
+using System;
+using System.Collections.Generic;
+using System.Numerics;
+using RustToDust.Core;
+using Ymir.Box3D;
+
+namespace RustToDust.Ymir
+{
+ public sealed class ArenaSession : IDisposable
+ {
+ public const float FixedDt = 1f / 60f;
+ public const int SubStepCount = 4;
+ public const int WorldBodyCapacity = 256;
+
+ private const ulong GroundStableId = 1;
+ private const ulong StaticBoxStableIdBase = 10;
+ private const ulong ContenderStableIdBase = 1000;
+ private const ulong SpectatorStableIdBase = 3000;
+
+ private readonly Box3DSoaWorld _world;
+ private readonly Dictionary _contenderBodies = new();
+ private readonly Dictionary _spectatorBodies = new();
+ private readonly Dictionary _entityByStableId = new();
+ private bool _disposed;
+
+ public ArenaSession(int seed = 42)
+ {
+ State = new MatchState(seed);
+ State.ChassisSwapped += OnContenderChassisSwapped;
+
+ _world = new Box3DSoaWorld(
+ capacity: WorldBodyCapacity,
+ gravityX: 0f,
+ gravityY: -20f,
+ gravityZ: 0f);
+
+ BuildStaticArena();
+ SpawnContenderBodies();
+ SpawnSpectatorBodies();
+ }
+
+ public MatchState State { get; }
+ public Box3DSoaWorld World => _world;
+
+ public bool TryEquipCargo(int cargoIndex, string hardpointId) =>
+ State.TryEquipCargo(cargoIndex, hardpointId);
+
+ public bool TrySwapNearbyChassis() =>
+ State.TrySwapNearbyChassis(0);
+
+ public Box3DSoaBodyHandle? GetContenderBody(int contenderId) =>
+ _contenderBodies.TryGetValue(contenderId, out var h) ? h : null;
+
+ public Box3DSoaBodyHandle? GetSpectatorBody(int spectatorId) =>
+ _spectatorBodies.TryGetValue(spectatorId, out var h) ? h : null;
+
+ public void Step(PlayerInput input)
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+
+ State.Time += FixedDt;
+ MatchRules.AdvanceTracers(State, FixedDt);
+ State.Spectators.UpdateSafeRadius(State.Time);
+ State.Spectators.AdvancePerimeterOrbits(FixedDt);
+
+ UpdateRingClearance();
+ MatchRules.ApplyPlayerInput(State, input);
+ MatchRules.UpdateAiContenders(State, FixedDt);
+
+ ApplyPhysicsDrives();
+ _world.Step(FixedDt, SubStepCount);
+ SyncBodiesFromWorld();
+
+ StepThermalAndCooldowns();
+ ProcessWeapons();
+ MatchRules.UpdateMatchOutcome(State);
+ }
+
+ private void BuildStaticArena()
+ {
+ // Large 420m x 420m ground slab with top surface at y = 0
+ _world.AddStaticBox(
+ GroundStableId,
+ (0f, -1f, 0f),
+ (210f, 1f, 210f),
+ friction: 0.25f,
+ restitution: 0.05f);
+
+ ulong nextId = StaticBoxStableIdBase;
+ for (int i = 0; i < State.ArenaBoundaryBoxes.Count; i++)
+ {
+ var b = State.ArenaBoundaryBoxes[i];
+ _world.AddStaticBox(
+ nextId++,
+ (b.X, b.Y, b.Z),
+ (b.HalfX, b.HalfY, b.HalfZ),
+ friction: 0.35f,
+ restitution: 0.1f);
+ }
+
+ for (int i = 0; i < State.ArenaCoverBoxes.Count; i++)
+ {
+ var b = State.ArenaCoverBoxes[i];
+ _world.AddStaticBox(
+ nextId++,
+ (b.X, b.Y, b.Z),
+ (b.HalfX, b.HalfY, b.HalfZ),
+ friction: 0.4f,
+ restitution: 0.05f);
+ }
+ }
+
+ private void SpawnContenderBodies()
+ {
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ var c = State.Contenders[i];
+ SpawnContenderBody(c);
+ }
+ }
+
+ private void SpawnContenderBody(ContenderState c)
+ {
+ var spec = c.Grid.Spec;
+ float volume = 8f * spec.HalfWidth * spec.HalfHeight * spec.HalfLength;
+ float density = spec.MassKg / MathF.Max(0.1f, volume);
+ var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw);
+ ulong stableId = ContenderStableIdBase + (ulong)c.Id;
+
+ var handle = _world.AddBox(
+ stableId,
+ (c.X, spec.HalfHeight + 0.1f, c.Z),
+ (spec.HalfWidth, spec.HalfHeight, spec.HalfLength),
+ density,
+ (q.X, q.Y, q.Z, q.W),
+ friction: 0.2f,
+ restitution: 0.1f);
+
+ _contenderBodies[c.Id] = handle;
+ _entityByStableId[stableId] = (true, c.Id);
+ }
+
+ private void OnContenderChassisSwapped(ContenderState c)
+ {
+ if (_contenderBodies.TryGetValue(c.Id, out var oldHandle))
+ {
+ _world.RemoveBody(oldHandle);
+ _contenderBodies.Remove(c.Id);
+ }
+ if (c.Alive)
+ {
+ SpawnContenderBody(c);
+ }
+ }
+
+ private void SpawnSpectatorBodies()
+ {
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ {
+ var s = State.Spectators.Spectators[i];
+ var spec = s.Grid.Spec;
+ float volume = 8f * spec.HalfWidth * spec.HalfHeight * spec.HalfLength;
+ float density = spec.MassKg / MathF.Max(0.1f, volume);
+ var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, s.Yaw);
+ ulong stableId = SpectatorStableIdBase + (ulong)s.Id;
+
+ var handle = _world.AddBox(
+ stableId,
+ (s.X, spec.HalfHeight + 0.1f, s.Z),
+ (spec.HalfWidth, spec.HalfHeight, spec.HalfLength),
+ density,
+ (q.X, q.Y, q.Z, q.W),
+ friction: 0.2f,
+ restitution: 0.1f);
+
+ _spectatorBodies[s.Id] = handle;
+ _entityByStableId[stableId] = (false, i);
+ }
+ }
+
+ private void UpdateRingClearance()
+ {
+ Span contacts = stackalloc RingContact[State.Contenders.Count];
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ var c = State.Contenders[i];
+ contacts[i] = new RingContact(c.Id, c.X, c.Z, c.Alive);
+ }
+ State.Spectators.UpdateClearance(contacts);
+
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ {
+ var s = State.Spectators.Spectators[i];
+ if (s.Alive && s.Stance != SpectatorStance.Neutral && !s.BroadcastWakeupEmitted && s.TargetContenderId.HasValue)
+ {
+ s.BroadcastWakeupEmitted = true;
+ if (s.Stance == SpectatorStance.Provoked)
+ {
+ if (s.Tier == SpectatorTier.Tourist)
+ {
+ State.Broadcast.EmitTouristPull(State.Time, s.TargetContenderId.Value);
+ }
+ else if (s.Tier == SpectatorTier.Exemplar)
+ {
+ State.Broadcast.EmitExemplarWakeup(State.Time, s.TargetContenderId.Value);
+ }
+ }
+ else if (s.Tier == SpectatorTier.Patron)
+ {
+ State.Broadcast.EmitPatronClearance(State.Time, s.TargetContenderId.Value);
+ }
+ }
+ else if (s.Stance == SpectatorStance.Neutral)
+ {
+ s.BroadcastWakeupEmitted = false;
+ }
+ }
+ }
+
+ private void ApplyPhysicsDrives()
+ {
+ var view = _world.View;
+
+ // Contenders
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ var c = State.Contenders[i];
+ if (!c.Alive || !_contenderBodies.TryGetValue(c.Id, out var handle))
+ {
+ continue;
+ }
+
+ int lane = handle.Lane;
+ float mass = view.Mass[lane];
+ if (mass <= 0f)
+ {
+ continue;
+ }
+
+ var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]);
+ var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]);
+ var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]);
+
+ var forward = Vector3.Transform(Vector3.UnitZ, q);
+ forward.Y = 0f;
+ if (forward.LengthSquared() < 1e-4f) forward = Vector3.UnitZ;
+ else forward = Vector3.Normalize(forward);
+
+ var right = Vector3.Cross(forward, Vector3.UnitY);
+ var up = Vector3.Transform(Vector3.UnitY, q);
+
+ float thrust = c.Grid.ComputeDriveThrust();
+ float maxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed);
+ float forwardSpeed = Vector3.Dot(vel, forward);
+ float lateralSpeed = Vector3.Dot(vel, right);
+
+ Vector3 force = Vector3.Zero;
+ // Drive thrust with smooth terminal velocity drag at MaxSpeed
+ force += forward * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed);
+ // Lateral tire / stride grip
+ force -= right * (lateralSpeed * mass * 8.5f);
+
+ if (c.BrakeCmd)
+ {
+ var horizVel = new Vector3(vel.X, 0f, vel.Z);
+ force -= horizVel * (mass * 7f);
+ }
+
+ // Engine heat from throttle
+ if (MathF.Abs(c.ThrottleCmd) > 0.05f)
+ {
+ for (int m = 0; m < c.Grid.Mounted.Count; m++)
+ {
+ var mod = c.Grid.Mounted[m];
+ if (mod.Spec.Kind == HardpointKind.Engine && mod.Spec.HeatOutput > 0f)
+ {
+ c.Grid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput * MathF.Abs(c.ThrottleCmd) * FixedDt);
+ }
+ }
+ }
+
+ float turnRate = c.Grid.ComputeTurnRate();
+ // Steer > 0 turns right (clockwise looking from +Y down => negative Y torque when +Z is forward)
+ float targetYawVel = -c.SteerCmd * turnRate;
+ float hx = view.Size0[lane];
+ float hz = view.Size2[lane];
+ float iy = mass * (hx * hx + hz * hz) / 3f;
+
+ Vector3 tiltAxis = Vector3.Cross(up, Vector3.UnitY);
+ Vector3 torque = tiltAxis * (mass * 28f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f);
+ torque.Y = iy * (targetYawVel - angVel.Y) * 8f;
+
+ view.ForceX[lane] = force.X;
+ view.ForceY[lane] = force.Y;
+ view.ForceZ[lane] = force.Z;
+ view.TorqueX[lane] = torque.X;
+ view.TorqueY[lane] = torque.Y;
+ view.TorqueZ[lane] = torque.Z;
+ }
+
+ // Spectators
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ {
+ var s = State.Spectators.Spectators[i];
+ if (!s.Alive || !_spectatorBodies.TryGetValue(s.Id, out var handle))
+ {
+ continue;
+ }
+
+ int lane = handle.Lane;
+ float mass = view.Mass[lane];
+ if (mass <= 0f)
+ {
+ continue;
+ }
+
+ MatchRules.ComputeSpectatorBehavior(s, State, out float goalX, out float goalZ, out float aimX, out float aimZ, out _);
+
+ var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]);
+ var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]);
+ var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]);
+ var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]);
+ var up = Vector3.Transform(Vector3.UnitY, q);
+
+ Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z);
+ float dist = toGoal.Length();
+ Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero;
+ Vector3 horizVel = new Vector3(vel.X, 0f, vel.Z);
+ Vector3 force = (desiredVel - horizVel) * (mass * 4.5f);
+
+ float desiredYaw = s.Stance == SpectatorStance.Neutral
+ ? MathF.Atan2(-pos.X, -pos.Z)
+ : MathF.Atan2(aimX - pos.X, aimZ - pos.Z);
+ var forward = Vector3.Transform(Vector3.UnitZ, q);
+ float currentYaw = MathF.Atan2(forward.X, forward.Z);
+ float yawErr = MatchRules.NormalizeAngle(desiredYaw - currentYaw);
+
+ float hx = view.Size0[lane];
+ float hz = view.Size2[lane];
+ float iy = mass * (hx * hx + hz * hz) / 3f;
+
+ Vector3 tiltAxis = Vector3.Cross(up, Vector3.UnitY);
+ Vector3 torque = tiltAxis * (mass * 26f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f);
+ torque.Y = iy * (Math.Clamp(yawErr * 3f, -5f, 5f) - angVel.Y) * 8f;
+
+ view.ForceX[lane] = force.X;
+ view.ForceY[lane] = force.Y;
+ view.ForceZ[lane] = force.Z;
+ view.TorqueX[lane] = torque.X;
+ view.TorqueY[lane] = torque.Y;
+ view.TorqueZ[lane] = torque.Z;
+ }
+ }
+
+ private void SyncBodiesFromWorld()
+ {
+ var view = _world.View;
+
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ var c = State.Contenders[i];
+ if (!c.Alive || !_contenderBodies.TryGetValue(c.Id, out var handle))
+ {
+ continue;
+ }
+
+ int lane = handle.Lane;
+ c.X = view.PositionX[lane];
+ c.Y = view.PositionY[lane];
+ c.Z = view.PositionZ[lane];
+ var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]);
+ var forward = Vector3.Transform(Vector3.UnitZ, q);
+ c.Yaw = MathF.Atan2(forward.X, forward.Z);
+ float vx = view.VelocityX[lane];
+ float vz = view.VelocityZ[lane];
+ c.Speed = MathF.Sqrt(vx * vx + vz * vz);
+ }
+
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ {
+ var s = State.Spectators.Spectators[i];
+ if (!s.Alive || !_spectatorBodies.TryGetValue(s.Id, out var handle))
+ {
+ continue;
+ }
+
+ int lane = handle.Lane;
+ s.X = view.PositionX[lane];
+ s.Y = view.PositionY[lane];
+ s.Z = view.PositionZ[lane];
+ var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]);
+ var forward = Vector3.Transform(Vector3.UnitZ, q);
+ s.Yaw = MathF.Atan2(forward.X, forward.Z);
+ }
+ }
+
+ private void StepThermalAndCooldowns()
+ {
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ var c = State.Contenders[i];
+ if (!c.Alive)
+ {
+ continue;
+ }
+
+ c.Grid.StepHeat(FixedDt);
+ bool anyOverheat = false;
+ for (int m = 0; m < c.Grid.Mounted.Count; m++)
+ {
+ var mod = c.Grid.Mounted[m];
+ if (mod.Cooldown > 0f)
+ {
+ mod.Cooldown = MathF.Max(0f, mod.Cooldown - FixedDt);
+ }
+ if (mod.CurrentTemp > mod.Spec.OptimalTemp + mod.Spec.PlateauWidth * 0.6f)
+ {
+ anyOverheat = true;
+ }
+ }
+
+ if (anyOverheat && !c.OverheatWarned)
+ {
+ c.OverheatWarned = true;
+ State.Broadcast.EmitOverheat(State.Time, c.Id);
+ }
+ else if (!anyOverheat)
+ {
+ c.OverheatWarned = false;
+ }
+ }
+
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ {
+ var s = State.Spectators.Spectators[i];
+ if (!s.Alive)
+ {
+ continue;
+ }
+
+ s.Grid.StepHeat(FixedDt);
+ for (int m = 0; m < s.Grid.Mounted.Count; m++)
+ {
+ if (s.Grid.Mounted[m].Cooldown > 0f)
+ {
+ s.Grid.Mounted[m].Cooldown = MathF.Max(0f, s.Grid.Mounted[m].Cooldown - FixedDt);
+ }
+ }
+ }
+ }
+
+ private void ProcessWeapons()
+ {
+ var view = _world.View;
+
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ var c = State.Contenders[i];
+ if (!c.Alive || !c.FireCmd || !_contenderBodies.TryGetValue(c.Id, out var handle))
+ {
+ continue;
+ }
+
+ ulong shooterStableId = ContenderStableIdBase + (ulong)c.Id;
+ FireMountedWeapons(
+ shooterStableId,
+ shooterContender: c,
+ shooterLabel: c.Name,
+ isSpectatorShooter: false,
+ shooterGrid: c.Grid,
+ shooterPos: new Vector3(c.X, c.Y, c.Z),
+ aimX: c.AimX,
+ aimZ: c.AimZ,
+ extraSpread: 0f,
+ view: view);
+ }
+
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ {
+ var s = State.Spectators.Spectators[i];
+ if (!s.Alive || s.Stance == SpectatorStance.Neutral || !_spectatorBodies.TryGetValue(s.Id, out _))
+ {
+ continue;
+ }
+
+ MatchRules.ComputeSpectatorBehavior(s, State, out _, out _, out float aimX, out float aimZ, out bool shouldFire);
+ if (!shouldFire)
+ {
+ continue;
+ }
+
+ ulong shooterStableId = SpectatorStableIdBase + (ulong)s.Id;
+ FireMountedWeapons(
+ shooterStableId,
+ shooterContender: null,
+ shooterLabel: $"{s.Tier} Spectator",
+ isSpectatorShooter: true,
+ shooterGrid: s.Grid,
+ shooterPos: new Vector3(s.X, s.Y, s.Z),
+ aimX: aimX,
+ aimZ: aimZ,
+ extraSpread: s.AimSpreadRad,
+ view: view);
+ }
+ }
+
+ private void FireMountedWeapons(
+ ulong shooterStableId,
+ ContenderState? shooterContender,
+ string shooterLabel,
+ bool isSpectatorShooter,
+ ChassisGrid shooterGrid,
+ Vector3 shooterPos,
+ float aimX,
+ float aimZ,
+ float extraSpread,
+ Box3DSoaView view)
+ {
+ float targetY = ResolveAimTargetY(aimX, aimZ, shooterStableId);
+
+ for (int m = 0; m < shooterGrid.Mounted.Count; m++)
+ {
+ var mod = shooterGrid.Mounted[m];
+ if (mod.Spec.Kind != HardpointKind.Weapon || mod.Cooldown > 0f || mod.CurrentPerformance <= 0.05f)
+ {
+ continue;
+ }
+
+ Vector3 horizDir = new Vector3(aimX - shooterPos.X, 0f, aimZ - shooterPos.Z);
+ if (horizDir.LengthSquared() < 1e-3f)
+ {
+ horizDir = Vector3.UnitZ;
+ }
+ else
+ {
+ horizDir = Vector3.Normalize(horizDir);
+ }
+
+ float clearance = MathF.Max(shooterGrid.Spec.HalfWidth, shooterGrid.Spec.HalfLength) + 0.55f;
+ Vector3 muzzle = new Vector3(
+ shooterPos.X + horizDir.X * clearance,
+ shooterPos.Y + shooterGrid.Spec.HalfHeight * 0.25f,
+ shooterPos.Z + horizDir.Z * clearance);
+
+ Vector3 baseAim = new Vector3(aimX - muzzle.X, targetY - muzzle.Y, aimZ - muzzle.Z);
+ if (baseAim.LengthSquared() < 1e-4f)
+ {
+ baseAim = horizDir;
+ }
+ else
+ {
+ baseAim = Vector3.Normalize(baseAim);
+ }
+
+ int burst = Math.Max(1, mod.Spec.BurstCount);
+ float totalSpread = mod.Spec.SpreadRad + extraSpread;
+ float range = MathF.Max(5f, mod.Spec.WeaponRange);
+ uint tracerColor = mod.Spec.IsImperial ? 0xFFD966FFu : 0xFF8833FFu;
+
+ for (int b = 0; b < burst; b++)
+ {
+ float yawJitter = ((float)State.Rng.NextDouble() * 2f - 1f) * totalSpread;
+ float pitchJitter = ((float)State.Rng.NextDouble() * 2f - 1f) * (totalSpread * 0.35f);
+ var dir = ApplyAimSpread(baseAim, yawJitter, pitchJitter);
+
+ var hit = _world.CastRayClosest(
+ (muzzle.X, muzzle.Y, muzzle.Z),
+ (dir.X * range, dir.Y * range, dir.Z * range));
+
+ Vector3 endPt = hit.Hit
+ ? new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z)
+ : muzzle + dir * range;
+
+ State.Tracers.Add(new TracerEvent(
+ muzzle.X, muzzle.Y, muzzle.Z,
+ endPt.X, endPt.Y, endPt.Z,
+ tracerColor,
+ 0.09f));
+
+ if (hit.Hit && hit.StableId != shooterStableId && _entityByStableId.TryGetValue(hit.StableId, out var targetRef))
+ {
+ ApplyHitToTarget(
+ targetRef,
+ hit.Point,
+ mod.Spec.WeaponDamage * mod.CurrentPerformance,
+ mod.Spec.HeatOutput * 0.25f,
+ shooterContender,
+ shooterLabel,
+ isSpectatorShooter,
+ view);
+ }
+ }
+
+ shooterGrid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput);
+ mod.Cooldown = mod.Spec.FireCooldown;
+
+ if (shooterContender is not null)
+ {
+ State.LastGunfireX = shooterPos.X;
+ State.LastGunfireZ = shooterPos.Z;
+ State.LastGunfireTime = State.Time;
+ }
+ }
+ }
+
+ private void ApplyHitToTarget(
+ (bool IsContender, int Index) targetRef,
+ (float X, float Y, float Z) hitPoint,
+ float damage,
+ float heatTransfer,
+ ContenderState? shooterContender,
+ string shooterLabel,
+ bool isSpectatorShooter,
+ Box3DSoaView view)
+ {
+ if (targetRef.IsContender)
+ {
+ var target = State.Contenders[targetRef.Index];
+ if (!target.Alive || !_contenderBodies.TryGetValue(target.Id, out var body))
+ {
+ return;
+ }
+
+ var (localRight, localForward, localHeightNorm) = ComputeLocalHitCoords(hitPoint, body.Lane, target.Grid.Spec, view);
+ var result = target.Grid.ApplyHit(localRight, localForward, localHeightNorm, damage, heatTransfer);
+ if (result.CoreDestroyed)
+ {
+ HandleContenderEliminated(target, shooterContender, shooterLabel, isSpectatorShooter);
+ }
+ }
+ else
+ {
+ var spec = State.Spectators.Spectators[targetRef.Index];
+ if (!spec.Alive || !_spectatorBodies.TryGetValue(spec.Id, out var body))
+ {
+ return;
+ }
+
+ if (shooterContender is not null)
+ {
+ bool newlyProvoked = State.Spectators.OnSpectatorDamaged(spec, shooterContender.Id);
+ if (newlyProvoked)
+ {
+ spec.BroadcastWakeupEmitted = true;
+ if (spec.Tier == SpectatorTier.Tourist)
+ {
+ State.Broadcast.EmitTouristPull(State.Time, shooterContender.Id);
+ }
+ else if (spec.Tier == SpectatorTier.Exemplar)
+ {
+ State.Broadcast.EmitExemplarWakeup(State.Time, shooterContender.Id);
+ }
+ }
+ }
+
+ var (localRight, localForward, localHeightNorm) = ComputeLocalHitCoords(hitPoint, body.Lane, spec.Grid.Spec, view);
+ var result = spec.Grid.ApplyHit(localRight, localForward, localHeightNorm, damage, heatTransfer);
+ if (result.CoreDestroyed)
+ {
+ HandleSpectatorDestroyed(spec, shooterContender, shooterLabel);
+ }
+ }
+ }
+
+ private void HandleContenderEliminated(
+ ContenderState victim,
+ ContenderState? shooterContender,
+ string shooterLabel,
+ bool isSpectatorShooter)
+ {
+ if (_contenderBodies.TryGetValue(victim.Id, out var handle))
+ {
+ _world.RemoveBody(handle);
+ _contenderBodies.Remove(victim.Id);
+ }
+
+ if (shooterContender is not null)
+ {
+ shooterContender.Kills++;
+ }
+
+ State.SpawnChassisDrop(victim.X, victim.Z, victim.Grid.Spec);
+ for (int i = 0; i < victim.Grid.Mounted.Count; i++)
+ {
+ State.SpawnModuleDrop(victim.X + (i - 1) * 0.9f, victim.Z + 1.2f, victim.Grid.Mounted[i].Spec);
+ }
+
+ State.Broadcast.EmitElimination(State.Time, shooterLabel, victim.Name, isSpectatorShooter);
+ }
+
+ private void HandleSpectatorDestroyed(SpectatorState spec, ContenderState? shooterContender, string shooterLabel)
+ {
+ if (_spectatorBodies.TryGetValue(spec.Id, out var handle))
+ {
+ _world.RemoveBody(handle);
+ _spectatorBodies.Remove(spec.Id);
+ }
+
+ if (shooterContender is not null)
+ {
+ shooterContender.Kills++;
+ }
+
+ var drops = SpectatorRing.RollSalvageDrops(spec, State.Rng);
+ for (int i = 0; i < drops.Count; i++)
+ {
+ State.SpawnModuleDrop(spec.X + (i - 0.5f) * 1.1f, spec.Z, drops[i]);
+ }
+
+ State.Broadcast.EmitElimination(State.Time, shooterLabel, $"{spec.Tier} Spectator", false);
+ }
+
+ private static (float LocalRight, float LocalForward, float LocalHeightNorm) ComputeLocalHitCoords(
+ (float X, float Y, float Z) hitPoint,
+ int lane,
+ ChassisSpec spec,
+ Box3DSoaView view)
+ {
+ var bodyPos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]);
+ var bodyQuat = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]);
+ var local = Vector3.Transform(new Vector3(hitPoint.X, hitPoint.Y, hitPoint.Z) - bodyPos, Quaternion.Conjugate(bodyQuat));
+
+ float localRight = Math.Clamp(-local.X / MathF.Max(0.1f, spec.HalfWidth), -1f, 1f);
+ float localForward = Math.Clamp(local.Z / MathF.Max(0.1f, spec.HalfLength), -1f, 1f);
+ float localHeightNorm = Math.Clamp((local.Y / MathF.Max(0.1f, spec.HalfHeight)) * 0.5f + 0.5f, 0f, 1f);
+ return (localRight, localForward, localHeightNorm);
+ }
+
+ private float ResolveAimTargetY(float aimX, float aimZ, ulong shooterStableId)
+ {
+ float bestDistSq = 9f * 9f;
+ float bestY = 0.9f;
+
+ for (int i = 0; i < State.Contenders.Count; i++)
+ {
+ var c = State.Contenders[i];
+ if (!c.Alive || ContenderStableIdBase + (ulong)c.Id == shooterStableId)
+ {
+ continue;
+ }
+ float dx = c.X - aimX;
+ float dz = c.Z - aimZ;
+ float d2 = dx * dx + dz * dz;
+ if (d2 < bestDistSq)
+ {
+ bestDistSq = d2;
+ bestY = c.Y;
+ }
+ }
+
+ for (int i = 0; i < State.Spectators.Spectators.Count; i++)
+ {
+ var s = State.Spectators.Spectators[i];
+ if (!s.Alive || SpectatorStableIdBase + (ulong)s.Id == shooterStableId)
+ {
+ continue;
+ }
+ float dx = s.X - aimX;
+ float dz = s.Z - aimZ;
+ float d2 = dx * dx + dz * dz;
+ if (d2 < bestDistSq)
+ {
+ bestDistSq = d2;
+ bestY = s.Y;
+ }
+ }
+
+ return bestY;
+ }
+
+ private static Vector3 ApplyAimSpread(Vector3 baseDir, float yawOffset, float pitchOffset)
+ {
+ var yawQ = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawOffset);
+ var rotated = Vector3.Transform(baseDir, yawQ);
+ var right = Vector3.Cross(rotated, Vector3.UnitY);
+ if (right.LengthSquared() > 1e-4f)
+ {
+ var pitchQ = Quaternion.CreateFromAxisAngle(Vector3.Normalize(right), pitchOffset);
+ rotated = Vector3.Transform(rotated, pitchQ);
+ }
+ return Vector3.Normalize(rotated);
+ }
+
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+ _disposed = true;
+ State.ChassisSwapped -= OnContenderChassisSwapped;
+ _world.Dispose();
+ }
+ }
+}
diff --git a/src/RustToDust.Ymir/RustToDust.Ymir.csproj b/src/RustToDust.Ymir/RustToDust.Ymir.csproj
new file mode 100644
index 0000000..ad53000
--- /dev/null
+++ b/src/RustToDust.Ymir/RustToDust.Ymir.csproj
@@ -0,0 +1,14 @@
+
+
+
+ net8.0
+ enable
+ disable
+
+
+
+
+
+
+
+
diff --git a/tests/RustToDust.Tests/ArenaSessionTests.cs b/tests/RustToDust.Tests/ArenaSessionTests.cs
new file mode 100644
index 0000000..1a3fc4e
--- /dev/null
+++ b/tests/RustToDust.Tests/ArenaSessionTests.cs
@@ -0,0 +1,91 @@
+using System;
+using RustToDust.Core;
+using RustToDust.Ymir;
+using Xunit;
+
+namespace RustToDust.Tests
+{
+ public sealed class ArenaSessionTests
+ {
+ [Fact]
+ public void DrivingAndFiring_MovesBuggyInYmirAndBuildsWeaponHeat()
+ {
+ using var session = new ArenaSession(seed: 42);
+ var player = session.State.Player;
+ float startX = player.X;
+ float startZ = player.Z;
+ float startYaw = player.Yaw;
+
+ for (int tick = 0; tick < 120; tick++)
+ {
+ session.Step(new PlayerInput(
+ Throttle: 1f,
+ Steer: 0.45f,
+ AimWorldX: player.X + 40f,
+ AimWorldZ: player.Z + 10f,
+ Fire: true,
+ InteractPickup: false,
+ Brake: false));
+ }
+
+ float dx = player.X - startX;
+ float dz = player.Z - startZ;
+ float displacement = MathF.Sqrt(dx * dx + dz * dz);
+ float yawDelta = MathF.Abs(MatchRules.NormalizeAngle(player.Yaw - startYaw));
+
+ Assert.True(displacement > 10f, $"Expected >10m displacement, got {displacement:F2}m");
+ Assert.True(yawDelta > 0.2f, $"Expected yaw change >0.2 rad, got {yawDelta:F2} rad");
+
+ var weapon = player.Grid.GetMountedOn("wpn_roof");
+ Assert.NotNull(weapon);
+ Assert.True(weapon!.CurrentTemp > ChassisGrid.AmbientTemp + 5f);
+ Assert.NotEmpty(session.State.Tracers);
+ }
+
+ [Fact]
+ public void ChassisSwap_ToManticoreAndRaptor_ReplacesBodyWithoutLeakingYmirLanes()
+ {
+ using var session = new ArenaSession(seed: 77);
+ var player = session.State.Player;
+ int initialFreeSlots = session.World.FreeBodySlots;
+
+ // Step once to settle world
+ session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false));
+
+ // Spawn Manticore (Dorsal) right beside player and swap
+ session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Manticore);
+ Assert.True(session.TrySwapNearbyChassis());
+ Assert.Equal("manticore", player.Grid.Spec.Id);
+ Assert.Equal(GridPlane.Dorsal, player.Grid.Spec.Plane);
+
+ // Step so Ymir reclaims old tombstone lane
+ session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false));
+ Assert.Equal(initialFreeSlots, session.World.FreeBodySlots);
+
+ // Now spawn Raptor (Coronal) beside player and swap
+ session.State.SpawnChassisDrop(player.X + 1f, player.Z + 1f, Catalog.Raptor);
+ Assert.True(session.TrySwapNearbyChassis());
+ Assert.Equal("raptor", player.Grid.Spec.Id);
+ Assert.Equal(GridPlane.Coronal, player.Grid.Spec.Plane);
+
+ session.Step(new PlayerInput(0f, 0f, 0f, 0f, false, false, false));
+ Assert.Equal(initialFreeSlots, session.World.FreeBodySlots);
+ }
+
+ [Fact]
+ public void Raycast_RespectsStaticCoverWalls()
+ {
+ using var session = new ArenaSession(seed: 12);
+ // Cover block #0 sits at (28, 1.8, 16) with half-extents (4.5, 1.8, 1.4).
+ // A ray from one side (28, 1.0, 10) to the other side (28, 1.0, 22) must hit the static cover wall!
+ var blockedHit = session.World.CastRayClosest((28f, 1.0f, 10f), (0f, 0f, 15f));
+ Assert.True(blockedHit.Hit);
+ Assert.True(blockedHit.Point.Z < 16f, $"Expected cover hit before z=16, got z={blockedHit.Point.Z:F2}");
+ Assert.InRange(blockedHit.StableId, 10UL, 99UL); // Static cover StableId range
+
+ // Ray high above the cover block (y = 5.0 > 3.6 top) passes unobstructed
+ var clearHit = session.World.CastRayClosest((28f, 5.0f, 10f), (0f, 0f, 15f));
+ Assert.False(clearHit.Hit);
+ }
+ }
+}
diff --git a/tests/RustToDust.Tests/GridHeatTests.cs b/tests/RustToDust.Tests/GridHeatTests.cs
new file mode 100644
index 0000000..d15a001
--- /dev/null
+++ b/tests/RustToDust.Tests/GridHeatTests.cs
@@ -0,0 +1,128 @@
+using System.Collections.Generic;
+using RustToDust.Core;
+using Xunit;
+
+namespace RustToDust.Tests
+{
+ public sealed class GridHeatTests
+ {
+ [Fact]
+ public void Conduction_SpreadsHeatFromHotHardpointToNeighbors()
+ {
+ var grid = Catalog.CreateStarterBuggy();
+ // wpn_roof is at (1, 0). Neighbor (0, 0) and (1, 1) start at ambient 20f.
+ grid.InjectHardpointHeat("wpn_roof", 600f);
+ float hotBefore = grid.Temperature[1, 0];
+ Assert.True(hotBefore > ChassisGrid.AmbientTemp + 20f);
+ Assert.Equal(ChassisGrid.AmbientTemp, grid.Temperature[0, 0]);
+ Assert.Equal(ChassisGrid.AmbientTemp, grid.Temperature[1, 1]);
+
+ for (int i = 0; i < 30; i++)
+ {
+ grid.StepHeat(1f / 60f);
+ }
+
+ Assert.True(grid.Temperature[0, 0] > ChassisGrid.AmbientTemp + 1f);
+ Assert.True(grid.Temperature[1, 1] > ChassisGrid.AmbientTemp + 1f);
+ Assert.True(grid.Temperature[1, 0] < hotBefore);
+ }
+
+ [Fact]
+ public void Radiation_CoolsBorderCellsWhileInteriorCellsDoNotRadiateDirectly()
+ {
+ var grid = new ChassisGrid(Catalog.Tank); // 4x5 full grid: interior cells exist at (1..2, 1..3)
+ for (int y = 0; y < grid.Spec.Height; y++)
+ {
+ for (int x = 0; x < grid.Spec.Width; x++)
+ {
+ grid.Temperature[x, y] = 120f;
+ }
+ }
+
+ // Single 60Hz substep: neighbors are all 120f so net conduction is 0.
+ // Only BorderCells lose heat to radiation; interior cell (1, 2) must stay at 120f.
+ grid.StepHeat(1f / 60f);
+
+ Assert.True(grid.BorderCells[0, 0]);
+ Assert.False(grid.BorderCells[1, 2]);
+ Assert.True(grid.Temperature[0, 0] < 120f);
+ Assert.Equal(120f, grid.Temperature[1, 2], precision: 5);
+ }
+
+ [Fact]
+ public void ModulePerformance_MatchesTrapezoidalPlateauCurve()
+ {
+ var mod = Catalog.Mg762; // Min=0, Optimal=65, Plateau=70 => [30, 100], Max=155
+
+ Assert.Equal(0f, mod.Performance(-5f));
+ Assert.Equal(0f, mod.Performance(0f));
+ Assert.Equal(0.5f, mod.Performance(15f), precision: 4);
+ Assert.Equal(1f, mod.Performance(30f), precision: 4);
+ Assert.Equal(1f, mod.Performance(65f), precision: 4);
+ Assert.Equal(1f, mod.Performance(100f), precision: 4);
+ Assert.Equal(0.5f, mod.Performance(127.5f), precision: 4);
+ Assert.Equal(0f, mod.Performance(155f));
+ Assert.Equal(0f, mod.Performance(210f));
+ }
+
+ [Fact]
+ public void DorsalHit_FrontStrikesFrontRowAndRearStrikesRearRow()
+ {
+ var grid = new ChassisGrid(Catalog.Tank);
+
+ var frontHit = grid.ApplyHit(localRight: 0f, localForward: 1f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f);
+ var rearHit = grid.ApplyHit(localRight: 0f, localForward: -1f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f);
+ var leftHit = grid.ApplyHit(localRight: -1f, localForward: 0f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f);
+ var rightHit = grid.ApplyHit(localRight: 1f, localForward: 0f, localHeightNorm: 0.5f, damage: 15f, heatTransfer: 0f);
+
+ Assert.Equal(0, frontHit.CellY);
+ Assert.Equal(grid.Spec.Height - 1, rearHit.CellY);
+ Assert.Equal(0, leftHit.CellX);
+ Assert.Equal(grid.Spec.Width - 1, rightHit.CellX);
+ }
+
+ [Fact]
+ public void CoronalHit_HighVsLowElevationStrikesUpperVsLowerBipedCells()
+ {
+ var grid = new ChassisGrid(Catalog.Raptor);
+ float initialLegs = grid.LegIntegrity;
+ Assert.Equal(1f, initialLegs);
+
+ var highHit = grid.ApplyHit(localRight: 0f, localForward: 1f, localHeightNorm: 0.95f, damage: 20f, heatTransfer: 0f);
+ var lowHit = grid.ApplyHit(localRight: -0.4f, localForward: 1f, localHeightNorm: 0.05f, damage: 35f, heatTransfer: 0f);
+
+ Assert.True(highHit.CellY <= 1);
+ Assert.True(lowHit.CellY >= grid.Spec.Height - 2);
+ Assert.True(grid.LegIntegrity < initialLegs);
+ }
+
+ [Fact]
+ public void LooseFitAndSwapChassis_PreservesCompatibleGearAndStowsOverflow()
+ {
+ // Tank has 2x2 turret hardpoint: smaller 1x1 weapon fits loosely; 2x2 weapon must NOT fit 1x1 buggy roof.
+ var tankGrid = new ChassisGrid(Catalog.Tank);
+ Assert.True(tankGrid.TryMount(Catalog.Recoilless, "wpn_turret")); // 2x2 into 2x2
+ Assert.True(tankGrid.TryMount(Catalog.Mg762, "wpn_coax")); // 1x1 into 1x1
+ Assert.True(tankGrid.TryMount(Catalog.TurboCore, "eng_rear")); // 1x2 into 2x2
+ Assert.True(tankGrid.TryMount(Catalog.GoldRadiator, "rad_deck")); // 1x1 into 1x1
+ Assert.True(tankGrid.TryMount(Catalog.WeldedPlate, "arm_glacis")); // 1x1 into 2x1
+ Assert.True(tankGrid.TryMount(Catalog.GildedPlate, "arm_skirt")); // 1x1 into 1x1
+
+ // Fill cargo near buggy capacity (4) so swapping down to Buggy overflows to ground!
+ Assert.True(tankGrid.TryAddCargo(Catalog.Flak));
+ Assert.True(tankGrid.TryAddCargo(Catalog.CopperRad));
+
+ List dropped = tankGrid.SwapChassis(Catalog.Buggy);
+
+ // Buggy has 1x1 Weapon (mg_762 fits, recoilless 2x2 does not!), 1x1 Engine (turbo_core 1x2 does not fit!), 1x1 Radiator (gold_radiator fits!), 0 Armor hardpoints.
+ Assert.Equal("buggy", tankGrid.Spec.Id);
+ Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "mg_762");
+ Assert.Contains(tankGrid.Mounted, m => m.Spec.Id == "gold_radiator");
+ Assert.DoesNotContain(tankGrid.Mounted, m => m.Spec.Id == "recoilless");
+
+ // 6 mounted on Tank: 2 transferred (mg_762, gold_radiator), 4 leftover + 2 cargo = 6 items -> 4 in Buggy Cargo, 2 dropped!
+ Assert.Equal(Catalog.Buggy.CargoCapacity, tankGrid.Cargo.Count);
+ Assert.Equal(2, dropped.Count);
+ }
+ }
+}
diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj
new file mode 100644
index 0000000..95cfcf3
--- /dev/null
+++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj
@@ -0,0 +1,21 @@
+
+
+
+ net10.0
+ enable
+ disable
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/RustToDust.Tests/SpectatorRingTests.cs b/tests/RustToDust.Tests/SpectatorRingTests.cs
new file mode 100644
index 0000000..4fc09b9
--- /dev/null
+++ b/tests/RustToDust.Tests/SpectatorRingTests.cs
@@ -0,0 +1,94 @@
+using System;
+using System.Linq;
+using RustToDust.Core;
+using Xunit;
+
+namespace RustToDust.Tests
+{
+ public sealed class SpectatorRingTests
+ {
+ [Fact]
+ public void Clearance_ZeroInsideSafeCircle_MonotonicOutside()
+ {
+ var ring = new SpectatorRing(seed: 101);
+ float r = ring.SafeRadius; // 150f
+
+ // Inside safe circle -> 0 cleared
+ ring.UpdateClearance(new[] { new RingContact(0, r - 20f, 0f, true) });
+ Assert.Equal(0, ring.CountClearedFor(0));
+
+ // Just outside safe circle (+5m) -> 1 cleared
+ ring.UpdateClearance(new[] { new RingContact(0, r + 5f, 0f, true) });
+ int clearedNear = ring.CountClearedFor(0);
+ Assert.Equal(1, clearedNear);
+
+ // Further outside (+30m) -> 1 + floor(30/12) = 3 cleared
+ ring.UpdateClearance(new[] { new RingContact(0, r + 30f, 0f, true) });
+ int clearedMid = ring.CountClearedFor(0);
+ Assert.True(clearedMid > clearedNear);
+
+ // Far outside (+100m) -> capped at 8 cleared
+ ring.UpdateClearance(new[] { new RingContact(0, r + 100f, 0f, true) });
+ int clearedFar = ring.CountClearedFor(0);
+ Assert.Equal(8, clearedFar);
+
+ // Stepping back inside safe circle revokes non-provoked clearance back to 0
+ ring.UpdateClearance(new[] { new RingContact(0, 0f, 0f, true) });
+ Assert.Equal(0, ring.CountClearedFor(0));
+ }
+
+ [Fact]
+ public void Provocation_AttackingNeutralSpectatorLocksOntoAttackerEvenInsideSafeCircle()
+ {
+ var ring = new SpectatorRing(seed: 202);
+ var targetSpec = ring.Spectators[0];
+ Assert.Equal(SpectatorStance.Neutral, targetSpec.Stance);
+
+ // Contender 0 is dead center (well inside SafeRadius)
+ var contenders = new[] { new RingContact(0, 0f, 0f, true) };
+ ring.UpdateClearance(contenders);
+ Assert.Equal(0, ring.CountClearedFor(0));
+
+ bool provoked = ring.OnSpectatorDamaged(targetSpec, attackerContenderId: 0);
+ Assert.True(provoked);
+ Assert.Equal(SpectatorStance.Provoked, targetSpec.Stance);
+ Assert.Equal(0, targetSpec.TargetContenderId);
+
+ // Subsequent clearance updates inside the safe circle must NOT clear Provoked lock
+ ring.UpdateClearance(contenders);
+ Assert.Equal(SpectatorStance.Provoked, targetSpec.Stance);
+ Assert.Equal(1, ring.CountProvokedFor(0));
+
+ // Once attacker dies, provocation reverts to Neutral
+ ring.UpdateClearance(new[] { new RingContact(0, 0f, 0f, false) });
+ Assert.Equal(SpectatorStance.Neutral, targetSpec.Stance);
+ Assert.Null(targetSpec.TargetContenderId);
+ }
+
+ [Fact]
+ public void SalvageDrops_TouristDropsImperialGearWhileExemplarDoesNot()
+ {
+ var ring = new SpectatorRing(seed: 303);
+ var rng = new Random(99);
+
+ var tourists = ring.Spectators.Where(s => s.Tier == SpectatorTier.Tourist).ToList();
+ var exemplars = ring.Spectators.Where(s => s.Tier == SpectatorTier.Exemplar).ToList();
+
+ Assert.NotEmpty(tourists);
+ Assert.NotEmpty(exemplars);
+
+ foreach (var tourist in tourists)
+ {
+ var drops = SpectatorRing.RollSalvageDrops(tourist, rng);
+ Assert.InRange(drops.Count, 1, 2);
+ Assert.All(drops, d => Assert.True(d.IsImperial));
+ }
+
+ foreach (var exemplar in exemplars)
+ {
+ var drops = SpectatorRing.RollSalvageDrops(exemplar, rng);
+ Assert.DoesNotContain(drops, d => d.IsImperial);
+ }
+ }
+ }
+}