sion: 3072m Sion map loader, Ymir heightfield+trimesh physics, LOD1/LOD2 renderer, and tests

This commit is contained in:
Meta Vens 2026-12-05 01:18:46 +01:00
commit 1864acecb7
14 changed files with 2242 additions and 183 deletions

View file

@ -227,7 +227,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _vfxBeamMm,
MaterialOverride = _vfxMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -247,7 +247,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _vfxSphereMm,
MaterialOverride = _vfxMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -267,7 +267,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _vfxRingMm,
MaterialOverride = _vfxMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 220f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -287,7 +287,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _dropDiscMm,
MaterialOverride = _vfxMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -307,7 +307,7 @@ public partial class ArenaRenderer : Node3D
Multimesh = _dropPillarMm,
MaterialOverride = _imperialBeaconMat,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};
@ -460,7 +460,7 @@ public partial class ArenaRenderer : Node3D
_safeRingImm.SurfaceBegin(Mesh.PrimitiveType.Triangles);
const int segments = 160;
const float halfThick = 1.1f;
float halfThick = terrain.MapSize > 2000f ? 2.2f : 1.1f;
float rInner = MathF.Max(2f, safeRadius - halfThick);
float rOuter = safeRadius + halfThick;
@ -832,7 +832,7 @@ public partial class ArenaRenderer : Node3D
if (!_dropVisuals.TryGetValue(d.Id, out var entry))
{
TerrainField.WorldToTile(d.X, d.Z, out int tx, out int tz);
state.Terrain.MapWorldToTile(d.X, d.Z, out int tx, out int tz);
float baseY = state.Terrain.SampleHeight(d.X, d.Z);
if (d.Module is { } mod)
{

View file

@ -41,6 +41,8 @@ public partial class Hud : CanvasLayer
private Label _controlsHint = null!;
private RadarWidget _radar = null!;
private Label _radarTitle = null!;
private Label _mapAttribLabel = null!;
private CrosshairOverlay _crosshair = null!;
private InventoryGridControl _schematic = null!;
private Label _hoverLabel = null!;
@ -169,14 +171,21 @@ public partial class Hud : CanvasLayer
{
float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z));
_statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALT {agl:F1}m | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}";
_controlsHint.Text = "WASD Fly | Space/C Climb/Descend | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage";
_controlsHint.Text = "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage | M Map";
}
else
{
_statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}";
_controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage | Wheel Zoom";
_controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt/Swap | Tab Garage | M Map | Wheel Zoom";
}
_radarTitle.Text = state.MapKind == ArenaMapKind.Sion
? "SION 3KM • RADAR"
: "DESERT RING • RADAR";
_mapAttribLabel.Text = state.MapKind == ArenaMapKind.Sion
? "Data: swisstopo | [M] Switch Map"
: "[M] Switch to Sion 3 km";
float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z);
float outside = distCenter - state.Spectators.SafeRadius;
int cleared = state.Spectators.CountClearedFor(player.Id);
@ -346,16 +355,21 @@ public partial class Hud : CanvasLayer
vbox.AddThemeConstantOverride("separation", 4);
panel.AddChild(vbox);
var title = new Label { Text = "GALLERY & ARENA RADAR", HorizontalAlignment = HorizontalAlignment.Center };
title.AddThemeColorOverride("font_color", OrangeCol);
title.AddThemeFontSizeOverride("font_size", 12);
vbox.AddChild(title);
_radarTitle = new Label { Text = "SION 3KM • RADAR", HorizontalAlignment = HorizontalAlignment.Center };
_radarTitle.AddThemeColorOverride("font_color", OrangeCol);
_radarTitle.AddThemeFontSizeOverride("font_size", 12);
vbox.AddChild(_radarTitle);
_radar = new RadarWidget
{
CustomMinimumSize = new Vector2(214f, 214f)
};
vbox.AddChild(_radar);
_mapAttribLabel = new Label { Text = "Data: swisstopo | [M] Switch Map", HorizontalAlignment = HorizontalAlignment.Center };
_mapAttribLabel.AddThemeColorOverride("font_color", TextMuted);
_mapAttribLabel.AddThemeFontSizeOverride("font_size", 10);
vbox.AddChild(_mapAttribLabel);
}
private void BuildBottomLeftSchematic()
@ -1023,7 +1037,8 @@ public partial class Hud : CanvasLayer
Vector2 center = Size * 0.5f;
float radius = MathF.Min(Size.X, Size.Y) * 0.47f;
float maxBlipRadius = MathF.Max(4f, radius - 3f);
float scale = radius / MatchState.ArenaHalfExtent;
float arenaHalf = MathF.Max(1f, _state?.Terrain.MapHalfExtent ?? MatchState.ArenaHalfExtent);
float scale = radius / arenaHalf;
DrawCircle(center, radius, BgInner);
DrawArc(center, radius, 0f, MathF.Tau, 48, BorderCol, 1.5f);

View file

@ -14,14 +14,19 @@ namespace RustToDust.Client;
public partial class Main : Node3D
{
private TerrainRenderer _terrain = null!;
private SionMapRenderer _sionMap = null!;
private ArenaRenderer _arena = null!;
private Camera3D _camera = null!;
private Hud _hud = null!;
private DirectionalLight3D _sun = null!;
private ProceduralSkyMaterial _skyMat = null!;
private Godot.Environment _env = null!;
private ArenaSession? _session;
private ArenaMapKind _mapKind = ArenaMapKind.Sion;
private PlayerInput? _scriptedInput;
private float _cameraYaw;
private float _cameraPitch = Mathf.DegToRad(12f);
private float _cameraPitch = Mathf.DegToRad(5f);
private float _cameraZoom = 1.0f;
private Vector3 _cameraSmoothedAnchor = Vector3.Zero;
private float _elapsedSeconds;
@ -53,8 +58,11 @@ public partial class Main : Node3D
public ArenaSession Session => _session ?? throw new InvalidOperationException($"No active ArenaSession ({Failure ?? "uninitialized"})");
public TerrainRenderer Terrain => _terrain;
public SionMapRenderer SionMap => _sionMap;
public ArenaRenderer Arena => _arena;
public Hud Hud => _hud;
public ArenaMapKind MapKind => _mapKind;
public ArenaMapKind? InitialMapKindOverride { get; set; }
public string? Failure { get; private set; }
public int Seed => _seed;
public float CameraYaw => _cameraYaw;
@ -66,6 +74,9 @@ public partial class Main : Node3D
_terrain = new TerrainRenderer { Name = "Terrain" };
AddChild(_terrain);
_sionMap = new SionMapRenderer { Name = "SionMap" };
AddChild(_sionMap);
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
@ -74,20 +85,32 @@ public partial class Main : Node3D
Name = "ShoulderCamera",
Current = true,
Fov = 58f,
Far = 1800f
Far = 4200f
};
AddChild(_camera);
_hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" };
AddChild(_hud);
if (InitialMapKindOverride.HasValue)
{
_mapKind = InitialMapKindOverride.Value;
}
else
{
string? envMap = System.Environment.GetEnvironmentVariable("RTD_MAP");
_mapKind = string.Equals(envMap, "desert", StringComparison.OrdinalIgnoreCase)
? ArenaMapKind.Desert
: ArenaMapKind.Sion;
}
if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0)
{
_perfTargetFrames = perfFrames;
ArenaSession.PerfEnabled = true;
}
Reset(_seed);
Reset(_seed, _mapKind);
if (_perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1" && _session is not null)
{
SetupPerfCombatScenario(_session);
@ -149,26 +172,49 @@ public partial class Main : Node3D
_session = null;
}
public void Reset(int seed)
public void Reset(int seed, ArenaMapKind? mapKind = null)
{
_seed = seed;
if (mapKind.HasValue)
{
_mapKind = mapKind.Value;
}
_session?.Dispose();
_session = null;
Failure = null;
try
{
_session = new ArenaSession(seed);
_session = new ArenaSession(seed, _mapKind);
var p = _session.State.Player;
_cameraYaw = p.Yaw;
_cameraPitch = Mathf.DegToRad(12f);
_cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f);
_cameraZoom = 1.0f;
_cameraSmoothedAnchor = ComputeTargetAnchor(p);
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f;
ApplyEnvironmentForMap(_mapKind);
if (_mapKind == ArenaMapKind.Sion)
{
_terrain.Visible = false;
_sionMap.Visible = true;
_sionMap.EnsureBuilt(_session.State.SionMap!, _session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f);
UpdateCamera(1f);
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_sionMap.Visible = false;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f);
UpdateCamera(1f);
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
_terrain.InvalidateAll();
_terrain.Sync(_session.State.Terrain);
_arena.Sync(_session, _elapsedSeconds, 0f);
UpdateCamera(1f);
_hud.Sync(_session);
if (DisplayServer.GetName() != "headless" && !_hud.GarageExpanded && _perfTargetFrames == 0)
@ -214,7 +260,10 @@ public partial class Main : Node3D
}
break;
case Key.R:
Reset(_seed + 1);
Reset(_seed + 1, _mapKind);
break;
case Key.M:
Reset(_seed, _mapKind == ArenaMapKind.Sion ? ArenaMapKind.Desert : ArenaMapKind.Sion);
break;
case Key.Escape:
if (_hud.GarageExpanded)
@ -292,7 +341,10 @@ public partial class Main : Node3D
{
double toMs = 1000.0 / Stopwatch.Frequency;
long tt0 = Stopwatch.GetTimestamp();
_terrain.Sync(_session.State.Terrain);
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.State.Terrain);
}
long tt1 = Stopwatch.GetTimestamp();
_arena.Sync(_session, _elapsedSeconds, (float)delta);
long ta1 = Stopwatch.GetTimestamp();
@ -301,7 +353,14 @@ public partial class Main : Node3D
long tc0 = Stopwatch.GetTimestamp();
UpdateCamera((float)delta);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
long th0 = Stopwatch.GetTimestamp();
_hud.Sync(_session);
long th1 = Stopwatch.GetTimestamp();
@ -340,10 +399,20 @@ public partial class Main : Node3D
}
else
{
_terrain.Sync(_session.State.Terrain);
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.State.Terrain);
}
_arena.Sync(_session, _elapsedSeconds, (float)delta);
UpdateCamera((float)delta);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
_hud.Sync(_session);
}
}
@ -395,6 +464,10 @@ public partial class Main : Node3D
GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}");
GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / _perfPhysicsTicks:F2} ai={ArenaSession.PerfAiMs / _perfPhysicsTicks:F2} drive={ArenaSession.PerfDriveMs / _perfPhysicsTicks:F2} world={ArenaSession.PerfWorldMs / _perfPhysicsTicks:F2} sync={ArenaSession.PerfBodySyncMs / _perfPhysicsTicks:F2} detect={ArenaSession.PerfDetectMs / _perfPhysicsTicks:F2} weapons={ArenaSession.PerfWeaponsMs / _perfPhysicsTicks:F2}");
GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} tracers={_session?.State.Tracers.Count ?? 0}");
if (_mapKind == ArenaMapKind.Sion)
{
GD.Print($"SionMap: chunks={_sionMap.TerrainChunkCount} tiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}");
}
foreach (var kv in _arena.AssetCache.Vehicles)
{
int tris = 0;
@ -617,7 +690,7 @@ public partial class Main : Node3D
private void SetupLightingAndSky()
{
var sun = new DirectionalLight3D
_sun = new DirectionalLight3D
{
Name = "DesertSun",
LightColor = new Color(1.0f, 0.92f, 0.78f),
@ -627,19 +700,19 @@ public partial class Main : Node3D
DirectionalShadowMaxDistance = 88f,
RotationDegrees = new Vector3(-48f, 32f, 0f)
};
AddChild(sun);
AddChild(_sun);
var skyMat = new ProceduralSkyMaterial
_skyMat = new ProceduralSkyMaterial
{
SkyTopColor = new Color(0.24f, 0.34f, 0.44f),
SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f),
GroundBottomColor = new Color(0.32f, 0.22f, 0.14f),
GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f)
};
var env = new Godot.Environment
_env = new Godot.Environment
{
BackgroundMode = Godot.Environment.BGMode.Sky,
Sky = new Sky { SkyMaterial = skyMat },
Sky = new Sky { SkyMaterial = _skyMat },
AmbientLightSource = Godot.Environment.AmbientSource.Sky,
AmbientLightEnergy = 0.55f,
FogEnabled = true,
@ -649,6 +722,46 @@ public partial class Main : Node3D
FogDepthBegin = 380f,
FogDepthEnd = 1100f
};
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env });
AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = _env });
}
private void ApplyEnvironmentForMap(ArenaMapKind mapKind)
{
if (mapKind == ArenaMapKind.Sion)
{
_sun.LightColor = new Color(1.0f, 0.95f, 0.87f);
_sun.LightEnergy = 1.25f;
_sun.DirectionalShadowMaxDistance = 160f;
_sun.RotationDegrees = new Vector3(-42f, 28f, 0f);
_skyMat.SkyTopColor = new Color(0.18f, 0.36f, 0.62f);
_skyMat.SkyHorizonColor = new Color(0.68f, 0.79f, 0.89f);
_skyMat.GroundBottomColor = new Color(0.24f, 0.26f, 0.22f);
_skyMat.GroundHorizonColor = new Color(0.58f, 0.67f, 0.74f);
_env.AmbientLightEnergy = 0.42f;
_env.FogLightColor = new Color(0.70f, 0.79f, 0.88f);
_env.FogDensity = 0.42f;
_env.FogDepthBegin = 850f;
_env.FogDepthEnd = 3000f;
}
else
{
_sun.LightColor = new Color(1.0f, 0.92f, 0.78f);
_sun.LightEnergy = 1.45f;
_sun.DirectionalShadowMaxDistance = 88f;
_sun.RotationDegrees = new Vector3(-48f, 32f, 0f);
_skyMat.SkyTopColor = new Color(0.24f, 0.34f, 0.44f);
_skyMat.SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f);
_skyMat.GroundBottomColor = new Color(0.32f, 0.22f, 0.14f);
_skyMat.GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f);
_env.AmbientLightEnergy = 0.55f;
_env.FogLightColor = new Color(0.76f, 0.57f, 0.39f);
_env.FogDensity = 0.72f;
_env.FogDepthBegin = 380f;
_env.FogDepthEnd = 1100f;
}
}
}

View file

@ -92,7 +92,7 @@ public partial class PomDecalPool : Node3D
Multimesh = _multiMesh,
MaterialOverride = _material,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off,
CustomAabb = new Aabb(new Vector3(-900f, -60f, -900f), new Vector3(1800f, 180f, 1800f)),
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
Visible = false
};

502
client/SionMapRenderer.cs Normal file
View file

@ -0,0 +1,502 @@
using System;
using System.Collections.Generic;
using System.IO;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Renders the 3072m x 3072m Sion, Switzerland arena:
/// - 6x6 (512m) seam-free chunked terrain ArrayMeshes from heightmap.f32 textured with terrain_surface.png + micro-grain shader.
/// - 36 spatial building tiles swapping cleanly between LOD1 (&lt;= 650m), LOD2 (650m..2200m), and culled (&gt; 2200m),
/// with shadow casting restricted to &lt;= 450m and shared PBR materials across all tiles.
/// </summary>
public partial class SionMapRenderer : Node3D
{
public const float Lod1DistanceM = 650f;
public const float CullDistanceM = 2200f;
public const float ShadowDistanceM = 450f;
private const int ChunkGridVerts = 65; // 64 quads per 512m chunk (8m spacing)
private sealed class BuildingTileEntry
{
public int Tx;
public int Tz;
public float CenterX;
public float CenterZ;
public required ArrayMesh Lod1Mesh;
public required ArrayMesh Lod2Mesh;
public required MeshInstance3D Instance;
}
private readonly List<MeshInstance3D> _terrainChunks = new(36);
private readonly List<BuildingTileEntry> _buildingTiles = new(36);
private readonly Dictionary<string, StandardMaterial3D> _sharedBuildingMaterials = new(StringComparer.Ordinal);
private string? _builtForDir;
private ShaderMaterial? _terrainMat;
private ImageTexture? _surfaceTex;
public bool IsBuilt { get; private set; }
public int TerrainChunkCount => _terrainChunks.Count;
public int BuildingTileCount => _buildingTiles.Count;
public int ActiveLod1TileCount { get; private set; }
public int ActiveLod2TileCount { get; private set; }
public int CulledTileCount { get; private set; }
public void EnsureBuilt(SionMapData sion, TerrainField terrain)
{
if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase))
{
return;
}
ClearBuilt();
_builtForDir = sion.DirectoryPath;
BuildTerrainMaterial(sion);
BuildTerrainChunks(sion, terrain);
BuildBuildingTiles(sion);
IsBuilt = true;
}
public void UpdateLod(Vector3 camPos)
{
if (!IsBuilt)
{
return;
}
const float lod1Sq = Lod1DistanceM * Lod1DistanceM;
const float cullSq = CullDistanceM * CullDistanceM;
const float shadowSq = ShadowDistanceM * ShadowDistanceM;
int lod1Count = 0;
int lod2Count = 0;
int culledCount = 0;
for (int i = 0; i < _buildingTiles.Count; i++)
{
var t = _buildingTiles[i];
float dx = t.CenterX - camPos.X;
float dz = t.CenterZ - camPos.Z;
float d2 = dx * dx + dz * dz;
if (d2 > cullSq)
{
if (t.Instance.Visible)
{
t.Instance.Visible = false;
}
culledCount++;
continue;
}
if (!t.Instance.Visible)
{
t.Instance.Visible = true;
}
ArrayMesh desired = d2 <= lod1Sq ? t.Lod1Mesh : t.Lod2Mesh;
if (!ReferenceEquals(t.Instance.Mesh, desired))
{
t.Instance.Mesh = desired;
}
if (d2 <= lod1Sq) lod1Count++;
else lod2Count++;
var desiredShadow = d2 <= shadowSq
? GeometryInstance3D.ShadowCastingSetting.On
: GeometryInstance3D.ShadowCastingSetting.Off;
if (t.Instance.CastShadow != desiredShadow)
{
t.Instance.CastShadow = desiredShadow;
}
}
ActiveLod1TileCount = lod1Count;
ActiveLod2TileCount = lod2Count;
CulledTileCount = culledCount;
}
private void BuildTerrainMaterial(SionMapData sion)
{
string surfPath = Path.Combine(sion.DirectoryPath, sion.Metadata.SurfaceTexture);
if (!File.Exists(surfPath))
{
throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath);
}
var img = Image.LoadFromFile(surfPath);
if (img is null || img.IsEmpty())
{
throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}");
}
img.GenerateMipmaps();
_surfaceTex = ImageTexture.CreateFromImage(img);
var shader = new Shader
{
Code = """
shader_type spatial;
render_mode cull_back, depth_draw_opaque;
uniform sampler2D surface_tex : source_color, filter_linear_mipmap, repeat_disable;
varying vec3 v_world_pos;
varying vec3 v_world_normal;
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float value_noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
float a = hash21(i);
float b = hash21(i + vec2(1.0, 0.0));
float c = hash21(i + vec2(0.0, 1.0));
float d = hash21(i + vec2(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
void vertex() {
v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
v_world_normal = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz);
}
void fragment() {
vec3 base_col = texture(surface_tex, UV).rgb;
// Multi-scale crisp world-space micro-grain for up-close ground readability
float dist = length((INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz - v_world_pos);
float near_fade = clamp(1.0 - smoothstep(140.0, 520.0, dist), 0.12, 1.0);
float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07;
float micro = (value_noise(v_world_pos.xz * 2.4) - 0.5) * 0.06;
float grit = (hash21(floor(v_world_pos.xz * 12.0)) - 0.5) * 0.035;
float slope = 1.0 - clamp(v_world_normal.y, 0.0, 1.0);
float strata = (value_noise(vec2(v_world_pos.x * 0.15 + v_world_pos.z * 0.15, v_world_pos.y * 0.9)) - 0.5) * 0.10 * smoothstep(0.10, 0.35, slope);
vec3 col = clamp(base_col + vec3(macro + (micro + grit) * near_fade + strata), vec3(0.0), vec3(1.0));
ALBEDO = col;
ROUGHNESS = mix(0.88, 0.96, slope);
METALLIC = 0.03;
}
"""
};
_terrainMat = new ShaderMaterial { Shader = shader };
_terrainMat.SetShaderParameter("surface_tex", _surfaceTex);
}
private void BuildTerrainChunks(SionMapData sion, TerrainField terrain)
{
int grid = sion.Metadata.TileGrid;
float sizeM = sion.Metadata.SizeMeters;
float tileSize = sion.Metadata.TileSizeMeters;
float half = sizeM * 0.5f;
int n = ChunkGridVerts;
float step = tileSize / (n - 1);
// Precompute shared index buffer for every 65x65 chunk (Godot ArrayMesh cull_back uses CW front-facing winding)
int quadCount = (n - 1) * (n - 1);
var indices = new int[quadCount * 6];
int ii = 0;
for (int gz = 0; gz < n - 1; gz++)
{
for (int gx = 0; gx < n - 1; gx++)
{
int i00 = gz * n + gx;
int i10 = i00 + 1;
int i01 = i00 + n;
int i11 = i01 + 1;
indices[ii++] = i00;
indices[ii++] = i10;
indices[ii++] = i01;
indices[ii++] = i10;
indices[ii++] = i11;
indices[ii++] = i01;
}
}
int vertCount = n * n;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
float x0 = -half + tx * tileSize;
float z0 = -half + tz * tileSize;
float cx = x0 + tileSize * 0.5f;
float cz = z0 + tileSize * 0.5f;
var verts = new Vector3[vertCount];
var normals = new Vector3[vertCount];
var uvs = new Vector2[vertCount];
for (int gz = 0; gz < n; gz++)
{
float wz = z0 + gz * step;
float lx = 0f;
float lz = wz - cz;
float v = (wz + half) / sizeM;
for (int gx = 0; gx < n; gx++)
{
float wx = x0 + gx * step;
lx = wx - cx;
float h = terrain.SampleHeight(wx, wz);
var (nx, ny, nz) = terrain.SampleNormal(wx, wz);
int idx = gz * n + gx;
verts[idx] = new Vector3(lx, h, lz);
normals[idx] = new Vector3(nx, ny, nz);
uvs[idx] = new Vector2((wx + half) / sizeM, v);
}
}
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = verts;
arrays[(int)Mesh.ArrayType.Normal] = normals;
arrays[(int)Mesh.ArrayType.TexUV] = uvs;
arrays[(int)Mesh.ArrayType.Index] = indices;
var mesh = new ArrayMesh();
mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
var chunkNode = new MeshInstance3D
{
Name = $"SionTerrain_{tx}_{tz}",
Mesh = mesh,
MaterialOverride = _terrainMat,
Position = new Vector3(cx, 0f, cz),
CastShadow = GeometryInstance3D.ShadowCastingSetting.On
};
AddChild(chunkNode);
_terrainChunks.Add(chunkNode);
}
}
}
private void BuildBuildingTiles(SionMapData sion)
{
var tiles = sion.Metadata.Tiles;
for (int i = 0; i < tiles.Count; i++)
{
var tm = tiles[i];
string lod1Path = Path.Combine(sion.DirectoryPath, tm.Lod1RelativePath.Replace('/', Path.DirectorySeparatorChar));
string lod2Path = Path.Combine(sion.DirectoryPath, tm.Lod2RelativePath.Replace('/', Path.DirectorySeparatorChar));
ArrayMesh lod1Mesh = LoadMergedTileGlb(lod1Path);
ArrayMesh lod2Mesh = LoadMergedTileGlb(lod2Path);
var mi = new MeshInstance3D
{
Name = $"SionBuildings_{tm.Tx}_{tm.Tz}",
Mesh = lod2Mesh,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
AddChild(mi);
_buildingTiles.Add(new BuildingTileEntry
{
Tx = tm.Tx,
Tz = tm.Tz,
CenterX = tm.Center.X,
CenterZ = tm.Center.Z,
Lod1Mesh = lod1Mesh,
Lod2Mesh = lod2Mesh,
Instance = mi
});
}
}
private ArrayMesh LoadMergedTileGlb(string glbPath)
{
if (!File.Exists(glbPath))
{
throw new FileNotFoundException($"Missing Sion building GLB: {glbPath}", glbPath);
}
var doc = new GltfDocument();
var state = new GltfState();
Error err = doc.AppendFromFile(glbPath, state);
if (err != Error.Ok)
{
throw new InvalidOperationException($"GltfDocument failed to load '{glbPath}': {err}");
}
Node? root = doc.GenerateScene(state);
if (root is null)
{
throw new InvalidOperationException($"GltfDocument generated null scene for '{glbPath}'.");
}
try
{
var byMat = new Dictionary<string, (StandardMaterial3D Mat, List<Vector3> Pos, List<Vector3> Norm, List<int> Idx)>(StringComparer.Ordinal);
CollectMeshesRecursive(root, Transform3D.Identity, byMat);
var outMesh = new ArrayMesh();
foreach (var kv in byMat)
{
var entry = kv.Value;
if (entry.Pos.Count == 0 || entry.Idx.Count == 0)
{
continue;
}
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = entry.Pos.ToArray();
arrays[(int)Mesh.ArrayType.Normal] = entry.Norm.ToArray();
arrays[(int)Mesh.ArrayType.Index] = entry.Idx.ToArray();
int surfIdx = outMesh.GetSurfaceCount();
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
outMesh.SurfaceSetMaterial(surfIdx, entry.Mat);
}
return outMesh;
}
finally
{
root.Free();
}
}
private void CollectMeshesRecursive(
Node node,
Transform3D parentXf,
Dictionary<string, (StandardMaterial3D Mat, List<Vector3> Pos, List<Vector3> Norm, List<int> Idx)> byMat)
{
Transform3D xf = node is Node3D n3 ? parentXf * n3.Transform : parentXf;
if (node is MeshInstance3D mi && mi.Mesh is not null)
{
Basis normalBasis = xf.Basis.Inverse().Transposed();
int surfCount = mi.Mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arr = mi.Mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Vertex)
{
continue;
}
Vector3[] posArr = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
if (posArr.Length == 0)
{
continue;
}
Vector3[]? normArr = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array
? arr[(int)Mesh.ArrayType.Normal].AsVector3Array()
: null;
int[]? idxArr = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array
? arr[(int)Mesh.ArrayType.Index].AsInt32Array()
: null;
Material? srcMat = mi.Mesh.SurfaceGetMaterial(s);
(string matKey, StandardMaterial3D sharedMat) = GetOrShareBuildingMaterial(srcMat);
if (!byMat.TryGetValue(matKey, out var bucket))
{
bucket = (sharedMat, new List<Vector3>(posArr.Length), new List<Vector3>(posArr.Length), new List<int>(idxArr?.Length ?? posArr.Length));
byMat[matKey] = bucket;
}
int baseVert = bucket.Pos.Count;
for (int v = 0; v < posArr.Length; v++)
{
bucket.Pos.Add(xf * posArr[v]);
Vector3 n = normArr is not null && v < normArr.Length
? (normalBasis * normArr[v]).Normalized()
: Vector3.Up;
bucket.Norm.Add(n);
}
if (idxArr is not null && idxArr.Length > 0)
{
for (int k = 0; k < idxArr.Length; k++)
{
bucket.Idx.Add(baseVert + idxArr[k]);
}
}
else
{
for (int k = 0; k < posArr.Length; k++)
{
bucket.Idx.Add(baseVert + k);
}
}
}
}
for (int i = 0; i < node.GetChildCount(); i++)
{
CollectMeshesRecursive(node.GetChild(i), xf, byMat);
}
}
private (string Key, StandardMaterial3D Mat) GetOrShareBuildingMaterial(Material? srcMat)
{
if (srcMat is StandardMaterial3D std)
{
Color c = std.AlbedoColor;
string key = $"{std.ResourceName}|{c.R:F3},{c.G:F3},{c.B:F3},{c.A:F3}|{std.Roughness:F2}|{std.Metallic:F2}";
if (!_sharedBuildingMaterials.TryGetValue(key, out var cached))
{
cached = new StandardMaterial3D
{
AlbedoColor = c,
Roughness = std.Roughness,
Metallic = std.Metallic,
CullMode = BaseMaterial3D.CullModeEnum.Back
};
_sharedBuildingMaterials[key] = cached;
}
return (key, cached);
}
const string defaultKey = "__default_building";
if (!_sharedBuildingMaterials.TryGetValue(defaultKey, out var defMat))
{
defMat = new StandardMaterial3D
{
AlbedoColor = new Color(0.55f, 0.52f, 0.48f),
Roughness = 0.88f,
Metallic = 0.04f
};
_sharedBuildingMaterials[defaultKey] = defMat;
}
return (defaultKey, defMat);
}
private void ClearBuilt()
{
for (int i = 0; i < _terrainChunks.Count; i++)
{
_terrainChunks[i].QueueFree();
}
_terrainChunks.Clear();
for (int i = 0; i < _buildingTiles.Count; i++)
{
_buildingTiles[i].Instance.QueueFree();
}
_buildingTiles.Clear();
_sharedBuildingMaterials.Clear();
_terrainMat = null;
_surfaceTex = null;
_builtForDir = null;
IsBuilt = false;
ActiveLod1TileCount = 0;
ActiveLod2TileCount = 0;
CulledTileCount = 0;
}
}

View file

@ -13,7 +13,7 @@ namespace RustToDust.Client.Tests;
/// </summary>
public partial class Smoke : Node
{
private const double WatchdogSeconds = 60.0;
private const double WatchdogSeconds = 90.0;
private readonly List<string> _failures = new();
private Main _main = null!;
@ -35,6 +35,7 @@ public partial class Smoke : Node
try
{
_main = GD.Load<PackedScene>("res://Main.tscn").Instantiate<Main>();
_main.InitialMapKindOverride = ArenaMapKind.Desert;
AddChild(_main);
if (_main.Failure is { } failure)
@ -270,6 +271,7 @@ public partial class Smoke : Node
await VerifyCut3bVehiclesAndMechanismsAsync();
await MaybeCapturePreviewAsync(isHeadless);
await VerifyMaxLoadPaladinGarageAsync();
await VerifySionMapAsync();
}
private async Task VerifyHudAndShadersAsync(bool isHeadless)
@ -1404,6 +1406,70 @@ public partial class Smoke : Node
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}
private async Task VerifySionMapAsync()
{
_main.Reset(42, ArenaMapKind.Sion);
Check(_main.Failure is null, $"Sion Reset failed: {_main.Failure}");
if (_main.Failure is not null)
{
return;
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var sionState = _main.Session.State;
Check(_main.MapKind == ArenaMapKind.Sion && sionState.MapKind == ArenaMapKind.Sion, "Expected Sion map kind after Reset");
Check(_main.SionMap.Visible && !_main.Terrain.Visible, "Expected SionMapRenderer visible and Desert TerrainRenderer hidden");
Check(_main.SionMap.IsBuilt, "Expected SionMapRenderer.IsBuilt == true");
Check(_main.SionMap.TerrainChunkCount == 36, $"Expected 36 Sion terrain chunks, got {_main.SionMap.TerrainChunkCount}");
Check(_main.SionMap.BuildingTileCount == 36, $"Expected 36 Sion building tiles, got {_main.SionMap.BuildingTileCount}");
Check(_main.SionMap.ActiveLod1TileCount > 0, $"Expected > 0 LOD1 tiles near Sion spawn, got {_main.SionMap.ActiveLod1TileCount}");
Check(_main.SionMap.ActiveLod2TileCount > 0, $"Expected > 0 LOD2 tiles in Sion valley, got {_main.SionMap.ActiveLod2TileCount}");
var cam = _main.GetViewport().GetCamera3D();
Check(cam is not null && cam.Far >= 3600f, $"Expected Camera3D.Far >= 3600m on Sion, got {cam?.Far ?? 0f}");
var sionMap = sionState.SionMap!;
foreach (var c in sionState.Contenders)
{
Check(!sionMap.IsInsideAnyBuildingXz(c.X, c.Z, 0f), $"Contender {c.Id} spawned inside building at ({c.X:F1}, {c.Z:F1})");
}
foreach (var d in sionState.GroundDrops)
{
Check(!sionMap.IsInsideAnyBuildingXz(d.X, d.Z, 0f), $"GroundDrop {d.Id} spawned inside building at ({d.X:F1}, {d.Z:F1})");
}
Vector2 vpSize = GetViewport().GetVisibleRect().Size;
Check(!_main.Hud.HasPanelOverlapOrClip(vpSize), $"Sion HUD panels overlapped or clipped at {vpSize}");
var player = sionState.Player;
float startX = player.X;
float startZ = player.Z;
_main.SetScriptedInput(new PlayerInput(
Throttle: 1f,
Steer: 0f,
AimWorldX: startX + MathF.Sin(player.Yaw) * 50f,
AimWorldZ: startZ + MathF.Cos(player.Yaw) * 50f,
Fire: false,
InteractPickup: false,
Brake: false));
for (int i = 0; i < 30; i++)
{
await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);
Check(float.IsFinite(player.X) && float.IsFinite(player.Y) && float.IsFinite(player.Z),
$"Sion player pose non-finite at frame {i}");
float gh = sionState.Terrain.SampleHeight(player.X, player.Z);
Check(player.Y - player.Grid.Spec.HalfHeight >= gh - 0.8f,
$"Sion player fell below terrain at frame {i}: bottom={player.Y - player.Grid.Spec.HalfHeight:F2}m < ground={gh:F2}m");
}
_main.SetScriptedInput(null);
float disp = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ));
Check(disp > 1.5f, $"Expected player displacement > 1.5m on Sion after 30 frames, got {disp:F2}m");
GD.Print($"SMOKE INFO: Sion verified (chunks={_main.SionMap.TerrainChunkCount}, tiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m)");
}
private static int CountPremulViolations(Image img, float tolerance)
{
int count = 0;

View file

@ -0,0 +1,8 @@
namespace RustToDust.Core
{
public enum ArenaMapKind
{
Desert,
Sion
}
}

View file

@ -103,36 +103,60 @@ namespace RustToDust.Core
hasGoal = true;
}
// 2. Find nearest hostile contender with actual live line-of-sight every tick
// 2. Find nearest hostile contender with actual live line-of-sight (staggered on Sion when tickIndex >= 0)
ContenderState? target = null;
float bestEnemyDistSq = 215f * 215f;
float aiEyeY = GetObserverEyeY(ai.Y, ai.Grid.Spec.HalfHeight);
for (int j = 0; j < state.Contenders.Count; j++)
bool reusePriorTarget = state.MapKind == ArenaMapKind.Sion &&
tickIndex >= 0 &&
((tickIndex + i) & 1) != 0 &&
ai.AiTargetContenderId.HasValue;
if (reusePriorTarget)
{
var other = state.Contenders[j];
if (other.Id == ai.Id || !other.Alive)
int tid = ai.AiTargetContenderId!.Value;
if (tid >= 0 && tid < state.Contenders.Count && state.Contenders[tid].Alive)
{
continue;
var prior = state.Contenders[tid];
float dx = prior.X - ai.X;
float dz = prior.Z - ai.Z;
float d2 = dx * dx + dz * dz;
if (d2 < bestEnemyDistSq &&
(hasLos is null || hasLos(ai.X, aiEyeY, ai.Z, prior.X, GetTargetAimY(prior.Y, prior.Grid.Spec.HalfHeight), prior.Z)))
{
bestEnemyDistSq = d2;
target = prior;
}
}
float dx = other.X - ai.X;
float dz = other.Z - ai.Z;
float d2 = dx * dx + dz * dz;
if (d2 >= bestEnemyDistSq)
{
continue;
}
if (hasLos is not null &&
!hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z))
{
continue;
}
bestEnemyDistSq = d2;
target = other;
}
ai.AiTargetContenderId = target?.Id;
else
{
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)
{
continue;
}
if (hasLos is not null &&
!hasLos(ai.X, aiEyeY, ai.Z, other.X, GetTargetAimY(other.Y, other.Grid.Spec.HalfHeight), other.Z))
{
continue;
}
bestEnemyDistSq = d2;
target = other;
}
ai.AiTargetContenderId = target?.Id;
}
// 3. Scavenge nearby upgrades when safe
if (!hasGoal && ai.AiScavengeCooldown <= 0f)
@ -224,7 +248,7 @@ namespace RustToDust.Core
if (!hasGoal)
{
float patrolAngle = ai.Id * 0.9f + state.Time * 0.12f;
float r = MathF.Min(safeLimit * 0.65f, 190f);
float r = MathF.Min(safeLimit * 0.65f, state.MapKind == ArenaMapKind.Sion ? 480f : 190f);
goalX = MathF.Cos(patrolAngle) * r;
goalZ = MathF.Sin(patrolAngle) * r;
}
@ -268,7 +292,7 @@ namespace RustToDust.Core
{
if (spec.Stance == SpectatorStance.Neutral || !spec.TargetContenderId.HasValue)
{
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes);
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes, state.SionMap);
aimX = 0f;
aimZ = 0f;
shouldFire = false;
@ -284,7 +308,7 @@ namespace RustToDust.Core
if (target is null || !target.Alive)
{
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes);
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes, state.SionMap);
aimX = 0f;
aimZ = 0f;
shouldFire = false;
@ -303,7 +327,7 @@ namespace RustToDust.Core
if (!hasMemory)
{
var (anchorX, anchorZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes);
var (anchorX, anchorZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes, state.SionMap);
float toFocusX = focusX - spec.X;
float toFocusZ = focusZ - spec.Z;
float toFocusLen = MathF.Sqrt(toFocusX * toFocusX + toFocusZ * toFocusZ);
@ -314,12 +338,16 @@ namespace RustToDust.Core
float bestX = centerX;
float bestZ = centerZ;
float bestH = state.Terrain.SampleHeight(bestX, bestZ);
float maxBound = TerrainField.HalfExtent - 18f;
float maxBound = state.Terrain.MapHalfExtent - 18f;
for (int k = 0; k < 4; k++)
{
float ang = spec.Id * 0.7f + k * (MathF.PI * 0.5f);
float cx = Math.Clamp(centerX + MathF.Cos(ang) * 26f, -maxBound, maxBound);
float cz = Math.Clamp(centerZ + MathF.Sin(ang) * 26f, -maxBound, maxBound);
if (state.SionMap is not null && state.SionMap.IsInsideAnyBuildingXz(cx, cz, 3.5f))
{
continue;
}
float h = state.Terrain.SampleHeight(cx, cz);
if (h > bestH)
{
@ -339,7 +367,7 @@ namespace RustToDust.Core
float fLen = MathF.Sqrt(fdx * fdx + fdz * fdz);
if (fLen < 1f)
{
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes);
(goalX, goalZ) = state.Spectators.GetNeutralGoal(spec, state.Terrain, state.ArenaCoverBoxes, state.SionMap);
return;
}

View file

@ -164,27 +164,62 @@ namespace RustToDust.Core
public const float ContactGhostDuration = 5.0f;
public const float TouristHorizonMaxRange = 420f;
public const float SionInitialSafeRadius = 1150f;
public const float SionMinSafeRadius = 120f;
private int _nextDropId = 1;
private long _nextHitEventId = 1;
private int _nextTracerId = 1;
public MatchState(int seed = 42)
public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert)
{
Seed = seed;
MapKind = mapKind;
Rng = new Random(seed);
Spectators = new SpectatorRing(seed + 101);
Broadcast = new BroadcastFeed();
var rawCover = BuildCoverBoxes();
Terrain = TerrainField.Generate((ulong)seed, rawCover);
ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain);
ArenaBoundaryBoxes = BuildBoundaryBoxes();
SpawnContenders();
ScatterInitialLoot();
if (mapKind == ArenaMapKind.Sion)
{
SionMap = SionMapLoader.Load();
Terrain = TerrainField.LoadHeightmap(
SionMap.Metadata.SizeMeters,
SionMap.Metadata.GridRes,
SionMap.Heights,
SionMap.Metadata.MinY,
SionMap.Metadata.MaxY,
(ulong)seed);
Spectators = new SpectatorRing(
seed + 101,
SpectatorRing.DefaultSpectatorCount,
initialRadius: SionInitialSafeRadius,
minRadius: SionMinSafeRadius,
arenaHalfExtent: Terrain.MapHalfExtent);
ArenaCoverBoxes = Array.Empty<ArenaBoxSpec>();
ArenaBoundaryBoxes = BuildBoundaryBoxes(
Terrain.MapHalfExtent + 4f,
SionMap.Metadata.MinY - 12f,
SionMap.Metadata.MaxY + 140f);
SeatSpectatorsOnSion();
SpawnContendersSion();
ScatterInitialLootSion();
}
else
{
Spectators = new SpectatorRing(seed + 101);
var rawCover = BuildCoverBoxes();
Terrain = TerrainField.Generate((ulong)seed, rawCover);
ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain);
ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f);
SpawnContenders();
ScatterInitialLoot();
}
Broadcast.EmitMatchStart(0f);
}
public int Seed { get; }
public ArenaMapKind MapKind { get; }
public SionMapData? SionMap { get; }
public Random Rng { get; }
public float Time { get; set; }
public MatchPhase Phase { get; set; } = MatchPhase.Active;
@ -636,18 +671,240 @@ namespace RustToDust.Core
return seated;
}
private static IReadOnlyList<ArenaBoxSpec> BuildBoundaryBoxes()
private void SeatSpectatorsOnSion()
{
const float wallY = 12f;
const float wallHalfH = 60f;
for (int i = 0; i < Spectators.Spectators.Count; i++)
{
var spec = Spectators.Spectators[i];
float pad = MathF.Max(spec.Grid.Spec.HalfWidth, spec.Grid.Spec.HalfLength) + 2.0f;
(float sx, float sz) = FindClearSionPoint(spec.X, spec.Z, pad, minNy: 0.76f, maxSearchRadius: 220f);
spec.X = sx;
spec.Z = sz;
spec.Y = Terrain.SampleHeight(sx, sz) + spec.Grid.Spec.HalfHeight + 0.15f;
spec.Yaw = MathF.Atan2(-sx, -sz);
}
}
private void SpawnContendersSion()
{
var aiRoster = new List<ChassisSpec>(Catalog.AllChassis);
for (int k = aiRoster.Count - 1; k > 0; k--)
{
int j = Rng.Next(k + 1);
(aiRoster[k], aiRoster[j]) = (aiRoster[j], aiRoster[k]);
}
// Player starts in the open Sion Old Town / Rhone plaza facing Basilique de Valere & Chateau de Tourbillon.
var playerGrid = Catalog.CreateStarterBuggy();
float playerPad = MathF.Max(playerGrid.Spec.HalfWidth, playerGrid.Spec.HalfLength) + 2.0f;
(float px, float pz) = FindClearSionPoint(-60f, 360f, playerPad, minNy: 0.84f, maxSearchRadius: 120f);
float pYaw = MathF.Atan2(150f - px, -260f - pz);
var player = new ContenderState(0, "Contender 01 (You)", true, playerGrid, px, pz, pYaw);
player.Y = Terrain.SampleHeight(px, pz) + playerGrid.Spec.HalfHeight + 0.15f;
player.AimY = player.Y;
Contenders.Add(player);
for (int i = 1; i < ContenderCount; i++)
{
var spec = aiRoster[(i - 1) % aiRoster.Count];
var grid = Catalog.CreateWithDefaultLoadout(spec);
float pad = MathF.Max(spec.HalfWidth, spec.HalfLength) + 2.0f;
float minNy = spec.IsVtol ? 0f : 0.84f;
float candX;
float candZ;
if (i <= 2)
{
// Put two visible rivals along the Old Town avenue ahead of the player so action is immediate.
float fwdX = MathF.Sin(pYaw);
float fwdZ = MathF.Cos(pYaw);
float rightX = -fwdZ;
float rightZ = fwdX;
float dist = i == 1 ? 105f : 175f;
float lat = i == 1 ? -18f : 28f;
candX = px + fwdX * dist + rightX * lat;
candZ = pz + fwdZ * dist + rightZ * lat;
}
else
{
float angle = ((i - 3) / (float)(ContenderCount - 3)) * MathF.Tau + (float)(Rng.NextDouble() - 0.5) * 0.25f;
float r = 240f + (float)Rng.NextDouble() * 680f;
candX = MathF.Cos(angle) * r;
candZ = MathF.Sin(angle) * r;
}
(float x, float z) = FindClearSionPoint(candX, candZ, pad, minNy, maxSearchRadius: 280f, avoidContenders: true);
float yaw = MathF.Atan2(-x, -z);
var contender = new ContenderState(i, $"Contender {i + 1:00}", false, grid, x, z, yaw);
if (spec.IsVtol)
{
contender.TargetHoverAltAgl = 10f;
}
contender.Y = Terrain.SampleHeight(x, z) + spec.HalfHeight +
(spec.IsVtol ? contender.TargetHoverAltAgl : 0.15f);
contender.AimY = contender.Y;
Contenders.Add(contender);
ContenderContacts[i] = new PlayerContactMemory();
}
for (int i = 0; i < Spectators.Spectators.Count; i++)
{
SpectatorContacts[Spectators.Spectators[i].Id] = new PlayerContactMemory();
}
}
private void ScatterInitialLootSion()
{
var chassisPool = new List<ChassisSpec>(Catalog.AllChassis.Count);
for (int i = 0; i < Catalog.AllChassis.Count; i++)
{
var c = Catalog.AllChassis[i];
if (!string.Equals(c.Id, Catalog.Jackal.Id, StringComparison.OrdinalIgnoreCase))
{
chassisPool.Add(c);
}
}
var p = Player;
float pYaw = p.Yaw;
for (int i = 0; i < chassisPool.Count; i++)
{
float pad = MathF.Max(chassisPool[i].HalfWidth, chassisPool[i].HalfLength) + 3.5f;
float candX;
float candZ;
if (i >= chassisPool.Count - 3)
{
int localIdx = i - (chassisPool.Count - 3);
float localAng = pYaw + (localIdx - 1) * 0.65f;
float localR = 26f + localIdx * 10f;
candX = p.X + MathF.Sin(localAng) * localR;
candZ = p.Z + MathF.Cos(localAng) * localR;
}
else
{
float angle = (i / (float)(chassisPool.Count - 3)) * MathF.Tau + 0.35f;
float r = 180f + (i % 4) * 190f;
candX = MathF.Cos(angle) * r;
candZ = MathF.Sin(angle) * r;
}
(float dx, float dz) = FindClearSionPoint(candX, candZ, pad, minNy: 0.84f, maxSearchRadius: 240f);
SpawnChassisDrop(dx, dz, chassisPool[i]);
}
ModuleSpec[] salvagePool =
{
Catalog.Autocannon, Catalog.Flak, Catalog.PointDefenseFlak, Catalog.Recoilless,
Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762,
Catalog.DieselCore, Catalog.PointDefenseFlak, Catalog.Autocannon, Catalog.Flak,
Catalog.Recoilless, Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate,
Catalog.Autocannon, Catalog.PointDefenseFlak, Catalog.Recoilless, Catalog.Flak,
Catalog.TurboCore, Catalog.CopperRad, Catalog.WeldedPlate, Catalog.Mg762,
Catalog.Autocannon, Catalog.ImperialAegisPd
};
for (int i = 0; i < salvagePool.Length; i++)
{
float candX;
float candZ;
if (i < 2)
{
float ang = pYaw + (i == 0 ? -0.4f : 0.4f);
candX = p.X + MathF.Sin(ang) * 20f;
candZ = p.Z + MathF.Cos(ang) * 20f;
}
else
{
float angle = (i / (float)salvagePool.Length) * MathF.Tau + 0.19f;
float r = 130f + (i % 5) * 180f;
candX = MathF.Cos(angle) * r;
candZ = MathF.Sin(angle) * r;
}
(float mx, float mz) = FindClearSionPoint(candX, candZ, pad: 2.5f, minNy: 0.84f, maxSearchRadius: 220f);
SpawnModuleDrop(mx, mz, salvagePool[i]);
}
}
private (float X, float Z) FindClearSionPoint(
float targetX,
float targetZ,
float pad,
float minNy,
float maxSearchRadius = 240f,
bool avoidContenders = false)
{
float maxB = Terrain.MapHalfExtent - 28f;
float baseX = Math.Clamp(targetX, -maxB, maxB);
float baseZ = Math.Clamp(targetZ, -maxB, maxB);
bool IsValid(float cx, float cz)
{
if (MathF.Abs(cx) > maxB || MathF.Abs(cz) > maxB)
{
return false;
}
if (SionMap is not null && SionMap.IsInsideAnyBuildingXz(cx, cz, pad))
{
return false;
}
if (minNy > 0f && Terrain.SampleNormal(cx, cz).Ny < minNy)
{
return false;
}
if (avoidContenders)
{
for (int k = 0; k < Contenders.Count; k++)
{
float dx = cx - Contenders[k].X;
float dz = cz - Contenders[k].Z;
if (dx * dx + dz * dz < 22f * 22f)
{
return false;
}
}
}
return true;
}
if (IsValid(baseX, baseZ))
{
return (baseX, baseZ);
}
for (float r = 8f; r <= maxSearchRadius; r += 8f)
{
for (int a = 0; a < 16; a++)
{
float ang = (a / 16f) * MathF.Tau;
float cx = Math.Clamp(baseX + MathF.Cos(ang) * r, -maxB, maxB);
float cz = Math.Clamp(baseZ + MathF.Sin(ang) * r, -maxB, maxB);
if (IsValid(cx, cz))
{
return (cx, cz);
}
}
}
// Fallback without minNy slope filter if tightly boxed in
if (minNy > 0f)
{
return FindClearSionPoint(baseX, baseZ, pad, minNy: 0f, maxSearchRadius: maxSearchRadius + 160f, avoidContenders: false);
}
return (baseX, baseZ);
}
private static IReadOnlyList<ArenaBoxSpec> BuildBoundaryBoxes(float halfExtent, float minY, float maxY)
{
float wallY = 0.5f * (minY + maxY);
float wallHalfH = MathF.Max(60f, 0.5f * (maxY - minY));
const float wallHalfThick = 4f;
const float span = ArenaHalfExtent + wallHalfThick;
float span = halfExtent + 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)
new(0f, wallY, halfExtent, span, wallHalfH, wallHalfThick, true),
new(0f, wallY, -halfExtent, span, wallHalfH, wallHalfThick, true),
new(halfExtent, wallY, 0f, wallHalfThick, wallHalfH, span, true),
new(-halfExtent, wallY, 0f, wallHalfThick, wallHalfH, span, true)
};
}
}

View file

@ -0,0 +1,534 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Text.Json;
namespace RustToDust.Core
{
public sealed record SionTileMeta(
int Tx,
int Tz,
string Lod2RelativePath,
string Lod1RelativePath,
string CollisionRelativePath,
int BuildingCount,
Vector3 Center,
Vector3 BoundsMin,
Vector3 BoundsMax);
public sealed record SionMetadata(
string Name,
string Attribution,
float SizeMeters,
int TileGrid,
float TileSizeMeters,
int GridRes,
float CellSizeMeters,
float MinY,
float MaxY,
string SurfaceTexture,
IReadOnlyList<SionTileMeta> Tiles);
public readonly record struct SionBuildingAabb(
string Id,
string Name,
string Class,
string ArchStyle,
int TileX,
int TileZ,
float CenterX,
float CenterY,
float CenterZ,
float HalfX,
float HalfY,
float HalfZ,
float GroundY,
float RoofY)
{
public bool ContainsXz(float x, float z, float padding = 0f) =>
MathF.Abs(x - CenterX) <= HalfX + padding &&
MathF.Abs(z - CenterZ) <= HalfZ + padding;
}
public sealed class SionCollisionMesh
{
public SionCollisionMesh(int tx, int tz, Vector3[] vertices, int[] indices, Vector3 boundsMin, Vector3 boundsMax)
{
Tx = tx;
Tz = tz;
Vertices = vertices;
Indices = indices;
BoundsMin = boundsMin;
BoundsMax = boundsMax;
}
public int Tx { get; }
public int Tz { get; }
public Vector3[] Vertices { get; }
public int[] Indices { get; }
public Vector3 BoundsMin { get; }
public Vector3 BoundsMax { get; }
}
public sealed class SionMapData
{
private const int SpatialGridRes = 64;
private readonly float[] _heights;
private readonly SionBuildingAabb[] _buildings;
private readonly List<int>[] _cellBuildings;
private readonly float[] _cellMinGroundY;
private readonly float[] _cellMaxRoofY;
private readonly float _halfExtent;
private readonly float _cellSize;
internal SionMapData(
string directoryPath,
SionMetadata metadata,
float[] heights,
SionBuildingAabb[] buildings,
SionCollisionMesh[] collisionMeshes)
{
DirectoryPath = directoryPath;
Metadata = metadata;
_heights = heights;
_buildings = buildings;
CollisionMeshes = collisionMeshes;
_halfExtent = metadata.SizeMeters * 0.5f;
_cellSize = metadata.SizeMeters / SpatialGridRes;
int cellCount = SpatialGridRes * SpatialGridRes;
_cellBuildings = new List<int>[cellCount];
_cellMinGroundY = new float[cellCount];
_cellMaxRoofY = new float[cellCount];
for (int i = 0; i < cellCount; i++)
{
_cellBuildings[i] = new List<int>(2);
_cellMinGroundY[i] = float.PositiveInfinity;
_cellMaxRoofY[i] = float.NegativeInfinity;
}
for (int bIdx = 0; bIdx < _buildings.Length; bIdx++)
{
ref readonly var b = ref _buildings[bIdx];
WorldToCell(b.CenterX - b.HalfX, b.CenterZ - b.HalfZ, out int minCx, out int minCz);
WorldToCell(b.CenterX + b.HalfX, b.CenterZ + b.HalfZ, out int maxCx, out int maxCz);
for (int cz = minCz; cz <= maxCz; cz++)
{
for (int cx = minCx; cx <= maxCx; cx++)
{
int cell = cz * SpatialGridRes + cx;
_cellBuildings[cell].Add(bIdx);
if (b.GroundY < _cellMinGroundY[cell]) _cellMinGroundY[cell] = b.GroundY;
if (b.RoofY > _cellMaxRoofY[cell]) _cellMaxRoofY[cell] = b.RoofY;
}
}
}
}
public string DirectoryPath { get; }
public SionMetadata Metadata { get; }
public ReadOnlySpan<float> Heights => _heights;
public IReadOnlyList<SionBuildingAabb> Buildings => _buildings;
public IReadOnlyList<SionCollisionMesh> CollisionMeshes { get; }
public bool IsInsideAnyBuildingXz(float x, float z, float padding = 0f)
{
float pad = MathF.Max(0f, padding);
WorldToCell(x - pad, z - pad, out int minCx, out int minCz);
WorldToCell(x + pad, z + pad, out int maxCx, out int maxCz);
for (int cz = minCz; cz <= maxCz; cz++)
{
for (int cx = minCx; cx <= maxCx; cx++)
{
var list = _cellBuildings[cz * SpatialGridRes + cx];
for (int i = 0; i < list.Count; i++)
{
if (_buildings[list[i]].ContainsXz(x, z, pad))
{
return true;
}
}
}
}
return false;
}
public bool IntersectsAnyBuildingAabb(
float ox, float oy, float oz,
float dx, float dy, float dz,
float maxDist)
{
if (_buildings.Length == 0 || maxDist <= 0f)
{
return false;
}
// Clip ray to arena XZ bounds so DDA stays strictly inside [0, SpatialGridRes - 1].
float tMin = 0f;
float tMax = maxDist;
if (!SlabClip(ox, dx, -_halfExtent, _halfExtent, ref tMin, ref tMax)) return false;
if (!SlabClip(oz, dz, -_halfExtent, _halfExtent, ref tMin, ref tMax)) return false;
float sx = ox + dx * tMin;
float sz = oz + dz * tMin;
WorldToCell(sx, sz, out int cx, out int cz);
float ex = ox + dx * tMax;
float ez = oz + dz * tMax;
WorldToCell(ex, ez, out int endCx, out int endCz);
int stepX = dx > 1e-6f ? 1 : (dx < -1e-6f ? -1 : 0);
int stepZ = dz > 1e-6f ? 1 : (dz < -1e-6f ? -1 : 0);
float tDeltaX = stepX != 0 ? _cellSize / MathF.Abs(dx) : float.PositiveInfinity;
float tDeltaZ = stepZ != 0 ? _cellSize / MathF.Abs(dz) : float.PositiveInfinity;
float nextBoundaryX = -_halfExtent + (cx + (stepX > 0 ? 1 : 0)) * _cellSize;
float nextBoundaryZ = -_halfExtent + (cz + (stepZ > 0 ? 1 : 0)) * _cellSize;
float tMaxX = stepX != 0 ? tMin + MathF.Max(0f, (nextBoundaryX - sx) / dx) : float.PositiveInfinity;
float tMaxZ = stepZ != 0 ? tMin + MathF.Max(0f, (nextBoundaryZ - sz) / dz) : float.PositiveInfinity;
float curT = tMin;
int maxSteps = SpatialGridRes * 2 + 4;
for (int iter = 0; iter < maxSteps; iter++)
{
float nextT = MathF.Min(tMax, MathF.Min(tMaxX, tMaxZ));
int cellIdx = cz * SpatialGridRes + cx;
var list = _cellBuildings[cellIdx];
if (list.Count > 0)
{
float y0 = oy + dy * curT;
float y1 = oy + dy * nextT;
float segMinY = MathF.Min(y0, y1);
float segMaxY = MathF.Max(y0, y1);
if (segMaxY >= _cellMinGroundY[cellIdx] - 0.5f && segMinY <= _cellMaxRoofY[cellIdx] + 0.5f)
{
for (int i = 0; i < list.Count; i++)
{
ref readonly var b = ref _buildings[list[i]];
if (RayIntersectsBuilding(ox, oy, oz, dx, dy, dz, maxDist, in b))
{
return true;
}
}
}
}
if (cx == endCx && cz == endCz)
{
break;
}
if (tMaxX <= tMaxZ)
{
curT = tMaxX;
tMaxX += tDeltaX;
cx += stepX;
}
else
{
curT = tMaxZ;
tMaxZ += tDeltaZ;
cz += stepZ;
}
if (cx < 0 || cx >= SpatialGridRes || cz < 0 || cz >= SpatialGridRes || curT > tMax)
{
break;
}
}
return false;
}
private void WorldToCell(float x, float z, out int cx, out int cz)
{
float nx = (x + _halfExtent) / _cellSize;
float nz = (z + _halfExtent) / _cellSize;
cx = Math.Clamp((int)MathF.Floor(nx), 0, SpatialGridRes - 1);
cz = Math.Clamp((int)MathF.Floor(nz), 0, SpatialGridRes - 1);
}
private static bool RayIntersectsBuilding(
float ox, float oy, float oz,
float dx, float dy, float dz,
float maxDist,
in SionBuildingAabb b)
{
float tMin = 0f;
float tMax = maxDist;
if (!SlabClip(ox, dx, b.CenterX - b.HalfX, b.CenterX + b.HalfX, ref tMin, ref tMax)) return false;
if (!SlabClip(oy, dy, b.GroundY, b.RoofY, ref tMin, ref tMax)) return false;
if (!SlabClip(oz, dz, b.CenterZ - b.HalfZ, b.CenterZ + b.HalfZ, ref tMin, ref tMax)) return false;
return tMax >= tMin;
}
private static bool SlabClip(float o, float d, float minB, float maxB, ref float tMin, ref float tMax)
{
if (MathF.Abs(d) < 1e-6f)
{
return o >= minB && o <= maxB;
}
float invD = 1f / d;
float t1 = (minB - o) * invD;
float t2 = (maxB - o) * invD;
if (t1 > t2) (t1, t2) = (t2, t1);
tMin = MathF.Max(tMin, t1);
tMax = MathF.Min(tMax, t2);
return tMax >= tMin;
}
}
public static class SionMapLoader
{
private static readonly object CacheLock = new();
private static readonly Dictionary<string, SionMapData> Cache = new(StringComparer.OrdinalIgnoreCase);
public static string LocateSionDirectory()
{
string? envRoot = Environment.GetEnvironmentVariable("RTD_ASSETS_DIR");
if (!string.IsNullOrWhiteSpace(envRoot))
{
string envSion = Path.Combine(envRoot, "maps", "sion");
if (IsValidSionDirectory(envSion))
{
return Path.GetFullPath(envSion);
}
}
foreach (string start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() })
{
if (string.IsNullOrWhiteSpace(start) || !Directory.Exists(start))
{
continue;
}
var dir = new DirectoryInfo(Path.GetFullPath(start));
while (dir is not null)
{
string candidate = Path.Combine(dir.FullName, "assets", "maps", "sion");
if (IsValidSionDirectory(candidate))
{
return Path.GetFullPath(candidate);
}
dir = dir.Parent;
}
}
throw new DirectoryNotFoundException(
$"Could not locate 'assets/maps/sion' containing metadata.json and heightmap.f32 from BaseDirectory '{AppContext.BaseDirectory}' or CurrentDirectory '{Directory.GetCurrentDirectory()}'.");
}
private static bool IsValidSionDirectory(string dir) =>
Directory.Exists(dir) &&
File.Exists(Path.Combine(dir, "metadata.json")) &&
File.Exists(Path.Combine(dir, "heightmap.f32")) &&
File.Exists(Path.Combine(dir, "buildings_manifest.json"));
public static SionMapData Load(string? sionDirectory = null)
{
string root = Path.GetFullPath(sionDirectory ?? LocateSionDirectory());
lock (CacheLock)
{
if (Cache.TryGetValue(root, out var cached))
{
return cached;
}
}
var meta = LoadMetadata(Path.Combine(root, "metadata.json"));
float[] heights = LoadHeightmap(Path.Combine(root, "heightmap.f32"), meta.GridRes);
SionBuildingAabb[] buildings = LoadBuildingsManifest(Path.Combine(root, "buildings_manifest.json"));
var colMeshes = new SionCollisionMesh[meta.Tiles.Count];
for (int i = 0; i < meta.Tiles.Count; i++)
{
var t = meta.Tiles[i];
string colPath = Path.Combine(root, t.CollisionRelativePath.Replace('/', Path.DirectorySeparatorChar));
colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz);
}
var data = new SionMapData(root, meta, heights, buildings, colMeshes);
lock (CacheLock)
{
Cache[root] = data;
}
return data;
}
private static SionMetadata LoadMetadata(string path)
{
using var stream = File.OpenRead(path);
using var doc = JsonDocument.Parse(stream);
var r = doc.RootElement;
var tilesElem = r.GetProperty("tiles");
var tiles = new List<SionTileMeta>(tilesElem.GetArrayLength());
foreach (var te in tilesElem.EnumerateArray())
{
tiles.Add(new SionTileMeta(
Tx: te.GetProperty("tx").GetInt32(),
Tz: te.GetProperty("tz").GetInt32(),
Lod2RelativePath: te.GetProperty("lod2").GetString() ?? "",
Lod1RelativePath: te.GetProperty("lod1").GetString() ?? "",
CollisionRelativePath: te.GetProperty("collision").GetString() ?? "",
BuildingCount: te.GetProperty("buildingCount").GetInt32(),
Center: ReadVec3(te.GetProperty("center")),
BoundsMin: ReadVec3(te.GetProperty("boundsMin")),
BoundsMax: ReadVec3(te.GetProperty("boundsMax"))));
}
return new SionMetadata(
Name: r.GetProperty("name").GetString() ?? "Sion",
Attribution: r.GetProperty("attribution").GetString() ?? "Federal Office of Topography swisstopo",
SizeMeters: r.GetProperty("sizeMeters").GetSingle(),
TileGrid: r.GetProperty("tileGrid").GetInt32(),
TileSizeMeters: r.GetProperty("tileSizeMeters").GetSingle(),
GridRes: r.GetProperty("gridRes").GetInt32(),
CellSizeMeters: r.GetProperty("cellSizeMeters").GetSingle(),
MinY: r.GetProperty("minY").GetSingle(),
MaxY: r.GetProperty("maxY").GetSingle(),
SurfaceTexture: r.GetProperty("surfaceTexture").GetString() ?? "terrain_surface.png",
Tiles: tiles);
}
private static float[] LoadHeightmap(string path, int gridRes)
{
byte[] raw = File.ReadAllBytes(path);
int expectedCount = gridRes * gridRes;
if (raw.Length != expectedCount * 4)
{
throw new InvalidDataException(
$"Expected heightmap.f32 byte length {expectedCount * 4} ({gridRes}x{gridRes}), got {raw.Length}.");
}
var heights = new float[expectedCount];
ReadOnlySpan<byte> span = raw;
for (int i = 0; i < expectedCount; i++)
{
float v = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(i * 4, 4));
if (!float.IsFinite(v))
{
throw new InvalidDataException($"Non-finite heightmap value at index {i}: {v}");
}
heights[i] = v;
}
return heights;
}
private static SionBuildingAabb[] LoadBuildingsManifest(string path)
{
using var stream = File.OpenRead(path);
using var doc = JsonDocument.Parse(stream);
var arr = doc.RootElement.GetProperty("buildings");
var result = new SionBuildingAabb[arr.GetArrayLength()];
int idx = 0;
foreach (var b in arr.EnumerateArray())
{
var tile = b.GetProperty("tile");
var center = b.GetProperty("center");
var size = b.GetProperty("size");
result[idx++] = new SionBuildingAabb(
Id: b.GetProperty("id").GetString() ?? "",
Name: b.GetProperty("name").GetString() ?? "",
Class: b.GetProperty("class").GetString() ?? "",
ArchStyle: b.GetProperty("archStyle").GetString() ?? "",
TileX: tile[0].GetInt32(),
TileZ: tile[1].GetInt32(),
CenterX: center[0].GetSingle(),
CenterY: center[1].GetSingle(),
CenterZ: center[2].GetSingle(),
HalfX: size[0].GetSingle() * 0.5f,
HalfY: size[1].GetSingle() * 0.5f,
HalfZ: size[2].GetSingle() * 0.5f,
GroundY: b.GetProperty("groundY").GetSingle(),
RoofY: b.GetProperty("roofY").GetSingle());
}
return result;
}
public static SionCollisionMesh LoadRcolFile(string path, int expectedTx = -1, int expectedTz = -1)
{
byte[] raw = File.ReadAllBytes(path);
if (raw.Length < 48)
{
throw new InvalidDataException($"RCOL file '{path}' too small ({raw.Length} bytes).");
}
ReadOnlySpan<byte> s = raw;
if (s[0] != (byte)'R' || s[1] != (byte)'C' || s[2] != (byte)'O' || s[3] != (byte)'L')
{
throw new InvalidDataException($"Invalid RCOL magic in '{path}'.");
}
uint version = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(4, 4));
if (version != 1)
{
throw new InvalidDataException($"Unsupported RCOL version {version} in '{path}'.");
}
int tx = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(8, 4));
int tz = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(12, 4));
if ((expectedTx >= 0 && tx != expectedTx) || (expectedTz >= 0 && tz != expectedTz))
{
throw new InvalidDataException($"RCOL tile mismatch in '{path}': header=({tx},{tz}), expected=({expectedTx},{expectedTz}).");
}
int vertexCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(16, 4)));
int indexCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(20, 4)));
if (vertexCount < 3 || indexCount < 3 || indexCount % 3 != 0)
{
throw new InvalidDataException($"Invalid RCOL counts in '{path}': verts={vertexCount}, indices={indexCount}.");
}
var bmin = new Vector3(
BinaryPrimitives.ReadSingleLittleEndian(s.Slice(24, 4)),
BinaryPrimitives.ReadSingleLittleEndian(s.Slice(28, 4)),
BinaryPrimitives.ReadSingleLittleEndian(s.Slice(32, 4)));
var bmax = new Vector3(
BinaryPrimitives.ReadSingleLittleEndian(s.Slice(36, 4)),
BinaryPrimitives.ReadSingleLittleEndian(s.Slice(40, 4)),
BinaryPrimitives.ReadSingleLittleEndian(s.Slice(44, 4)));
int expectedBytes = 48 + vertexCount * 12 + indexCount * 4;
if (raw.Length != expectedBytes)
{
throw new InvalidDataException($"RCOL byte length mismatch in '{path}': expected {expectedBytes}, got {raw.Length}.");
}
var vertices = new Vector3[vertexCount];
int offset = 48;
for (int i = 0; i < vertexCount; i++)
{
float x = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset, 4));
float y = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 4, 4));
float z = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 8, 4));
vertices[i] = new Vector3(x, y, z);
offset += 12;
}
var indices = new int[indexCount];
for (int i = 0; i < indexCount; i++)
{
int idx = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(offset, 4));
if ((uint)idx >= (uint)vertexCount)
{
throw new InvalidDataException($"RCOL index {idx} out of range [0..{vertexCount}) in '{path}'.");
}
indices[i] = idx;
offset += 4;
}
return new SionCollisionMesh(tx, tz, vertices, indices, bmin, bmax);
}
private static Vector3 ReadVec3(JsonElement arr) =>
new(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle());
}
}

View file

@ -97,13 +97,24 @@ namespace RustToDust.Core
private readonly Dictionary<int, bool> _aliveById = new();
private readonly Dictionary<int, ContenderAwareness> _awarenessByContender = new();
public SpectatorRing(int seed = 1337, int count = DefaultSpectatorCount)
public SpectatorRing(
int seed = 1337,
int count = DefaultSpectatorCount,
float initialRadius = InitialRadius,
float minRadius = MinRadius,
float arenaHalfExtent = TerrainField.HalfExtent)
{
var rng = new Random(seed);
SafeRadius = InitialRadius;
StartRadius = initialRadius;
EndRadius = minRadius;
ArenaHalfExtent = arenaHalfExtent;
SafeRadius = StartRadius;
SpawnRing(rng, count);
}
public float StartRadius { get; }
public float EndRadius { get; }
public float ArenaHalfExtent { get; }
public float SafeRadius { get; private set; }
public IReadOnlyList<SpectatorState> Spectators => _spectators;
@ -111,12 +122,12 @@ namespace RustToDust.Core
{
if (matchTime <= GraceDuration)
{
SafeRadius = InitialRadius;
SafeRadius = StartRadius;
return;
}
float t = Math.Clamp((matchTime - GraceDuration) / ShrinkDuration, 0f, 1f);
SafeRadius = InitialRadius + (MinRadius - InitialRadius) * t;
SafeRadius = StartRadius + (EndRadius - StartRadius) * t;
}
public void UpdateClearance(ReadOnlySpan<RingContact> contenders) =>
@ -559,12 +570,45 @@ namespace RustToDust.Core
public (float X, float Z) GetNeutralGoal(
SpectatorState spec,
TerrainField? terrain,
IReadOnlyList<ArenaBoxSpec>? coverBoxes)
IReadOnlyList<ArenaBoxSpec>? coverBoxes,
SionMapData? sionMap = null)
{
if (spec.Tier == SpectatorTier.Tourist || terrain is null)
if (spec.Tier == SpectatorTier.Tourist && sionMap is null)
{
return GetPerimeterSlot(spec);
}
if (terrain is null)
{
return GetPerimeterSlot(spec);
}
if (spec.Tier == SpectatorTier.Tourist)
{
// On Sion, keep Tourist perimeter slots clear of buildings as the ring moves
var (px, pz) = GetPerimeterSlot(spec);
float maxB = ArenaHalfExtent - 18f;
px = Math.Clamp(px, -maxB, maxB);
pz = Math.Clamp(pz, -maxB, maxB);
if (!sionMap!.IsInsideAnyBuildingXz(px, pz, 4.0f))
{
return (px, pz);
}
for (int rStep = 0; rStep <= 4; rStep++)
{
float rr = SafeRadius + spec.RingOffset + rStep * 12f;
for (int aSign = -1; aSign <= 1; aSign += 2)
{
float ang = spec.RingAngle + aSign * (rStep + 1) * 0.03f;
float cx = Math.Clamp(MathF.Cos(ang) * rr, -maxB, maxB);
float cz = Math.Clamp(MathF.Sin(ang) * rr, -maxB, maxB);
if (!sionMap.IsInsideAnyBuildingXz(cx, cz, 4.0f))
{
return (cx, cz);
}
}
}
return (px, pz);
}
if (spec.HasNeutralAnchor && MathF.Abs(SafeRadius - spec.NeutralAnchorSafeRadius) < 8f)
{
@ -574,7 +618,7 @@ namespace RustToDust.Core
float bestX = MathF.Cos(spec.RingAngle) * (SafeRadius + spec.RingOffset);
float bestZ = MathF.Sin(spec.RingAngle) * (SafeRadius + spec.RingOffset);
float bestScore = float.NegativeInfinity;
float maxBound = TerrainField.HalfExtent - 18f;
float maxBound = ArenaHalfExtent - 18f;
for (int ai = -3; ai <= 3; ai++)
{
@ -588,6 +632,18 @@ namespace RustToDust.Core
float cx = Math.Clamp(cosA * r, -maxBound, maxBound);
float cz = Math.Clamp(sinA * r, -maxBound, maxBound);
if (sionMap is not null)
{
if (sionMap.IsInsideAnyBuildingXz(cx, cz, 3.8f))
{
continue;
}
if (terrain.SampleNormal(cx, cz).Ny < 0.78f)
{
continue;
}
}
float distLen = MathF.Sqrt(cx * cx + cz * cz);
float inX = distLen > 1f ? -cx / distLen : 0f;
float inZ = distLen > 1f ? -cz / distLen : -1f;

View file

@ -37,7 +37,6 @@ namespace RustToDust.Core
public const int TileGridCount = 8;
public const float TileSize = ArenaSize / TileGridCount; // 192m
private const int AccelGridCount = 64;
private const float AccelCellSize = ArenaSize / AccelGridCount; // 24m
private const int AccelCellCount = AccelGridCount * AccelGridCount;
public const float MinWorldHeight = -18f;
public const float MaxWorldHeight = 52f;
@ -68,7 +67,9 @@ namespace RustToDust.Core
private readonly List<int>[,] _tileBrushIndices = new List<int>[TileGridCount, TileGridCount];
private readonly List<int>[] _cellBrushIndices = new List<int>[AccelCellCount];
private readonly float[] _cellMaxHeight = new float[AccelCellCount];
private readonly float[] _cellBaseMaxHeight = new float[AccelCellCount];
private readonly Queue<int> _dynamicDecalSlots = new();
private float[]? _heightmap;
private int _nextBrushId = 1;
public TerrainField(ulong seed)
@ -89,11 +90,105 @@ namespace RustToDust.Core
}
public ulong Seed { get; }
public bool IsHeightmapMode { get; private set; }
public float MapSize { get; private set; } = ArenaSize;
public float MapHalfExtent { get; private set; } = HalfExtent;
public float MapTileSize { get; private set; } = TileSize;
public float MapMinHeight { get; private set; } = MinWorldHeight;
public float MapMaxHeight { get; private set; } = MaxWorldHeight;
public int HeightmapRes { get; private set; }
public float HeightmapCellSize { get; private set; }
private float AccelCellSize => MapSize / AccelGridCount;
public IReadOnlyList<TerrainBrush> Brushes => _brushes;
public int[,] TileVersions { get; }
public ulong DirtyTileMask { get; private set; }
public ulong StructuralDirtyTileMask { get; private set; }
public static TerrainField LoadHeightmap(
float sizeMeters,
int gridRes,
ReadOnlySpan<float> heights,
float minY,
float maxY,
ulong seed = 0UL)
{
if (sizeMeters <= 0f || !float.IsFinite(sizeMeters))
{
throw new ArgumentOutOfRangeException(nameof(sizeMeters));
}
if (gridRes < 2)
{
throw new ArgumentOutOfRangeException(nameof(gridRes));
}
if (heights.Length != gridRes * gridRes)
{
throw new ArgumentException($"Expected {gridRes * gridRes} height samples, got {heights.Length}.", nameof(heights));
}
var field = new TerrainField(seed)
{
IsHeightmapMode = true,
MapSize = sizeMeters,
MapHalfExtent = sizeMeters * 0.5f,
MapTileSize = sizeMeters / TileGridCount,
MapMinHeight = minY - 8f,
MapMaxHeight = maxY + 4f,
HeightmapRes = gridRes,
HeightmapCellSize = sizeMeters / (gridRes - 1),
_heightmap = heights.ToArray()
};
float half = field.MapHalfExtent;
float cellSize = field.AccelCellSize;
float invDemStep = 1f / field.HeightmapCellSize;
for (int cz = 0; cz < AccelGridCount; cz++)
{
float minZ = -half + cz * cellSize;
float maxZ = minZ + cellSize;
int iz0 = Math.Clamp((int)MathF.Floor((minZ + half) * invDemStep) - 1, 0, gridRes - 1);
int iz1 = Math.Clamp((int)MathF.Ceiling((maxZ + half) * invDemStep) + 1, 0, gridRes - 1);
for (int cx = 0; cx < AccelGridCount; cx++)
{
float minX = -half + cx * cellSize;
float maxX = minX + cellSize;
int ix0 = Math.Clamp((int)MathF.Floor((minX + half) * invDemStep) - 1, 0, gridRes - 1);
int ix1 = Math.Clamp((int)MathF.Ceiling((maxX + half) * invDemStep) + 1, 0, gridRes - 1);
float cellMax = float.NegativeInfinity;
for (int iz = iz0; iz <= iz1; iz++)
{
int row = iz * gridRes;
for (int ix = ix0; ix <= ix1; ix++)
{
float h = field._heightmap[row + ix];
if (h > cellMax)
{
cellMax = h;
}
}
}
int cellIdx = cz * AccelGridCount + cx;
float boundedMax = float.IsNegativeInfinity(cellMax) ? 0f : cellMax + 0.05f;
field._cellBaseMaxHeight[cellIdx] = boundedMax;
field._cellMaxHeight[cellIdx] = boundedMax;
}
}
for (int tz = 0; tz < TileGridCount; tz++)
{
for (int tx = 0; tx < TileGridCount; tx++)
{
field.TileVersions[tx, tz] = 1;
field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx);
}
}
return field;
}
public void ClearDirtyMask()
{
DirtyTileMask = 0UL;
@ -379,17 +474,31 @@ namespace RustToDust.Core
public float SampleHeight(float x, float z)
{
float cx = Math.Clamp(x, -HalfExtent, HalfExtent);
float cz = Math.Clamp(z, -HalfExtent, HalfExtent);
WorldToAccelCell(cx, cz, out int acx, out int acz);
var indices = _cellBrushIndices[acz * AccelGridCount + acx];
if (indices.Count == 0)
{
return 0f;
}
float half = MapHalfExtent;
float cx = Math.Clamp(x, -half, half);
float cz = Math.Clamp(z, -half, half);
float h = 0f;
if (_heightmap is not null)
{
int res = HeightmapRes;
float fx = Math.Clamp((cx + half) / HeightmapCellSize, 0f, res - 1f);
float fz = Math.Clamp((cz + half) / HeightmapCellSize, 0f, res - 1f);
int ix = Math.Clamp((int)fx, 0, res - 2);
int iz = Math.Clamp((int)fz, 0, res - 2);
float tx = Math.Clamp(fx - ix, 0f, 1f);
float tz = Math.Clamp(fz - iz, 0f, 1f);
int row0 = iz * res;
int row1 = row0 + res;
float h00 = _heightmap[row0 + ix];
float h10 = _heightmap[row0 + ix + 1];
float h01 = _heightmap[row1 + ix];
float h11 = _heightmap[row1 + ix + 1];
h = (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz;
}
WorldToAccelCell(cx, cz, out int acx, out int acz);
var indices = _cellBrushIndices[acz * AccelGridCount + acx];
for (int i = 0; i < indices.Count; i++)
{
int idx = indices[i];
@ -397,7 +506,7 @@ namespace RustToDust.Core
h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz);
}
return Math.Clamp(h, MinWorldHeight, MaxWorldHeight);
return Math.Clamp(h, MapMinHeight, MapMaxHeight);
}
public (float Nx, float Ny, float Nz) SampleNormal(float x, float z)
@ -425,6 +534,9 @@ namespace RustToDust.Core
float maxDistance,
out float hitX, out float hitY, out float hitZ, out float hitDist)
{
float half = MapHalfExtent;
float accelSize = AccelCellSize;
float prevT = 0f;
float prevDiff = oy - SampleHeight(ox, oz);
if (prevDiff <= 0f)
@ -444,21 +556,21 @@ namespace RustToDust.Core
float py = oy + dy * ct;
float pz = oz + dz * ct;
float cx = Math.Clamp(px, -HalfExtent, HalfExtent);
float cz = Math.Clamp(pz, -HalfExtent, HalfExtent);
float cx = Math.Clamp(px, -half, half);
float cz = Math.Clamp(pz, -half, half);
WorldToAccelCell(cx, cz, out int acx, out int acz);
float cellMax = _cellMaxHeight[acz * AccelGridCount + acx] + 0.02f;
// Fast-skip consecutive cells strictly below the ray without sampling brushes
while (py > cellMax + 0.02f &&
ct < maxDistance &&
px >= -HalfExtent && px <= HalfExtent &&
pz >= -HalfExtent && pz <= HalfExtent)
px >= -half && px <= half &&
pz >= -half && pz <= half)
{
float cellMinX = -HalfExtent + acx * AccelCellSize;
float cellMaxX = cellMinX + AccelCellSize;
float cellMinZ = -HalfExtent + acz * AccelCellSize;
float cellMaxZ = cellMinZ + AccelCellSize;
float cellMinX = -half + acx * accelSize;
float cellMaxX = cellMinX + accelSize;
float cellMinZ = -half + acz * accelSize;
float cellMaxZ = cellMinZ + accelSize;
float txExit = dx > 1e-6f ? (cellMaxX - px) / dx : (dx < -1e-6f ? (cellMinX - px) / dx : float.PositiveInfinity);
float tzExit = dz > 1e-6f ? (cellMaxZ - pz) / dz : (dz < -1e-6f ? (cellMinZ - pz) / dz : float.PositiveInfinity);
float tExit = MathF.Min(txExit, tzExit);
@ -477,8 +589,8 @@ namespace RustToDust.Core
px = ox + dx * ct;
py = oy + dy * ct;
pz = oz + dz * ct;
cx = Math.Clamp(px, -HalfExtent, HalfExtent);
cz = Math.Clamp(pz, -HalfExtent, HalfExtent);
cx = Math.Clamp(px, -half, half);
cz = Math.Clamp(pz, -half, half);
WorldToAccelCell(cx, cz, out acx, out acz);
cellMax = _cellMaxHeight[acz * AccelGridCount + acx] + 0.02f;
}
@ -649,16 +761,18 @@ namespace RustToDust.Core
return brush;
}
private static bool TryGetBrushCellBounds(
private bool TryGetBrushCellBounds(
in TerrainBrush b,
in BrushPrecomp p,
int cx, int cz,
out float cellMaxPositiveHeight)
{
float minX = -HalfExtent + cx * AccelCellSize;
float maxX = minX + AccelCellSize;
float minZ = -HalfExtent + cz * AccelCellSize;
float maxZ = minZ + AccelCellSize;
float half = MapHalfExtent;
float accelSize = AccelCellSize;
float minX = -half + cx * accelSize;
float maxX = minX + accelSize;
float minZ = -half + cz * accelSize;
float maxZ = minZ + accelSize;
// Project all 4 cell corners into brush local (lx, lz)
float dx0 = minX - b.X, dx1 = maxX - b.X;
@ -750,8 +864,8 @@ namespace RustToDust.Core
private void RecomputeCellMaxHeight(int cx, int cz)
{
float sum = 0f;
int cellIdx = cz * AccelGridCount + cx;
float sum = _cellBaseMaxHeight[cellIdx];
var indices = _cellBrushIndices[cellIdx];
for (int i = 0; i < indices.Count; i++)
{
@ -761,7 +875,7 @@ namespace RustToDust.Core
sum += h;
}
}
_cellMaxHeight[cellIdx] = Math.Min(MaxWorldHeight, sum);
_cellMaxHeight[cellIdx] = Math.Min(MapMaxHeight, sum);
}
private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion)
@ -798,7 +912,7 @@ namespace RustToDust.Core
{
int cellIdx = cz * AccelGridCount + cx;
_cellBrushIndices[cellIdx].Add(index);
_cellMaxHeight[cellIdx] = Math.Min(MaxWorldHeight, _cellMaxHeight[cellIdx] + cellMaxPos);
_cellMaxHeight[cellIdx] = Math.Min(MapMaxHeight, _cellMaxHeight[cellIdx] + cellMaxPos);
}
}
}
@ -839,32 +953,44 @@ namespace RustToDust.Core
}
}
private static void GetBrushAccelBounds(in TerrainBrush brush, out int minCx, out int maxCx, out int minCz, out int maxCz)
private void GetBrushAccelBounds(in TerrainBrush brush, out int minCx, out int maxCx, out int minCz, out int maxCz)
{
float half = MapHalfExtent;
float extent = MathF.Max(0.1f, MathF.Max(brush.RadiusX, brush.RadiusZ)) + 0.1f;
WorldToAccelCell(Math.Clamp(brush.X - extent, -HalfExtent, HalfExtent), Math.Clamp(brush.Z - extent, -HalfExtent, HalfExtent), out minCx, out minCz);
WorldToAccelCell(Math.Clamp(brush.X + extent, -HalfExtent, HalfExtent), Math.Clamp(brush.Z + extent, -HalfExtent, HalfExtent), out maxCx, out maxCz);
WorldToAccelCell(Math.Clamp(brush.X - extent, -half, half), Math.Clamp(brush.Z - extent, -half, half), out minCx, out minCz);
WorldToAccelCell(Math.Clamp(brush.X + extent, -half, half), Math.Clamp(brush.Z + extent, -half, half), out maxCx, out maxCz);
}
private static void WorldToAccelCell(float x, float z, out int cx, out int cz)
private void WorldToAccelCell(float x, float z, out int cx, out int cz)
{
float nx = (x + HalfExtent) / AccelCellSize;
float nz = (z + HalfExtent) / AccelCellSize;
float half = MapHalfExtent;
float accelSize = AccelCellSize;
float nx = (x + half) / accelSize;
float nz = (z + half) / accelSize;
cx = Math.Clamp((int)MathF.Floor(nx), 0, AccelGridCount - 1);
cz = Math.Clamp((int)MathF.Floor(nz), 0, AccelGridCount - 1);
}
private static void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz)
private void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz)
{
const float gutterPaddingMeters = 3.5f;
float half = MapHalfExtent;
float extent = MathF.Sqrt(brush.RadiusX * brush.RadiusX + brush.RadiusZ * brush.RadiusZ) + gutterPaddingMeters;
float minX = brush.X - extent;
float maxX = brush.X + extent;
float minZ = brush.Z - extent;
float maxZ = brush.Z + extent;
WorldToTile(Math.Clamp(minX, -HalfExtent, HalfExtent), Math.Clamp(minZ, -HalfExtent, HalfExtent), out minTx, out minTz);
WorldToTile(Math.Clamp(maxX, -HalfExtent, HalfExtent), Math.Clamp(maxZ, -HalfExtent, HalfExtent), out maxTx, out maxTz);
MapWorldToTile(Math.Clamp(minX, -half, half), Math.Clamp(minZ, -half, half), out minTx, out minTz);
MapWorldToTile(Math.Clamp(maxX, -half, half), Math.Clamp(maxZ, -half, half), out maxTx, out maxTz);
}
public void MapWorldToTile(float x, float z, out int tx, out int tz)
{
float nx = (x + MapHalfExtent) / MapTileSize;
float nz = (z + MapHalfExtent) / MapTileSize;
tx = Math.Clamp((int)MathF.Floor(nx), 0, TileGridCount - 1);
tz = Math.Clamp((int)MathF.Floor(nz), 0, TileGridCount - 1);
}
public static void WorldToTile(float x, float z, out int tx, out int tz)

View file

@ -15,6 +15,7 @@ namespace RustToDust.Ymir
private const ulong GroundStableId = 1;
private const ulong StaticBoxStableIdBase = 10;
private const ulong StaticMeshStableIdBase = 100;
public const ulong ContenderStableIdBase = 1000;
private const ulong SpectatorStableIdBase = 3000;
@ -23,11 +24,12 @@ namespace RustToDust.Ymir
private readonly Dictionary<int, Box3DSoaBodyHandle> _spectatorBodies = new();
private readonly Dictionary<ulong, (bool IsContender, int Index)> _entityByStableId = new();
private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount];
private int _tickCount;
private bool _disposed;
public ArenaSession(int seed = 42)
public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert)
{
State = new MatchState(seed);
State = new MatchState(seed, mapKind);
State.ChassisSwapped += OnContenderChassisSwapped;
_world = new Box3DSoaWorld(
@ -131,17 +133,48 @@ namespace RustToDust.Ymir
}
Vector3 dir = delta / dist;
// Only static cover/boundary boxes and terrain block LOS; check fast static AABBs first.
// Only static cover/boundary boxes, terrain, and Sion building meshes block LOS.
if (IntersectsAnyStaticBox(ax, ay, az, dir.X, dir.Y, dir.Z, dist))
{
return false;
}
return !State.Terrain.Raycast(
if (State.Terrain.Raycast(
ax, ay, az,
dir.X, dir.Y, dir.Z,
MathF.Max(0.1f, dist - 0.5f),
out _, out _, out _, out _);
out _, out _, out _, out _))
{
return false;
}
if (State.SionMap is { } sionMap &&
sionMap.IntersectsAnyBuildingAabb(ax, ay, az, dir.X, dir.Y, dir.Z, dist))
{
Vector3 castOrigin = new(ax, ay, az);
float remaining = dist;
for (int hop = 0; hop < 4 && remaining > 0.25f; hop++)
{
var hit = _world.CastRayClosest(
(castOrigin.X, castOrigin.Y, castOrigin.Z),
(dir.X * remaining, dir.Y * remaining, dir.Z * remaining));
if (!hit.Hit)
{
break;
}
if (hit.StableId < ContenderStableIdBase)
{
return false;
}
var hitPt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z);
float step = Vector3.Distance(castOrigin, hitPt) + 0.25f;
castOrigin += dir * step;
remaining -= step;
}
}
return true;
}
private bool IntersectsAnyStaticBox(float ox, float oy, float oz, float dx, float dy, float dz, float maxDist)
@ -202,19 +235,22 @@ namespace RustToDust.Ymir
ObjectDisposedException.ThrowIf(_disposed, this);
State.Time += FixedDt;
_tickCount++;
MatchRules.AdvanceTracers(State, FixedDt);
MatchRules.AdvanceHitEvents(State, FixedDt);
State.Spectators.UpdateSafeRadius(State.Time);
State.Spectators.AdvancePerimeterOrbits(FixedDt);
int subSteps = State.MapKind == ArenaMapKind.Sion ? 1 : SubStepCount;
if (!PerfEnabled)
{
UpdateRingClearance();
MatchRules.ApplyPlayerInput(State, input);
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _tickCount);
ApplyPhysicsDrives();
_world.Step(FixedDt, SubStepCount);
_world.Step(FixedDt, subSteps);
SyncBodiesFromWorld();
UpdatePlayerDetectionMemory();
@ -229,11 +265,11 @@ namespace RustToDust.Ymir
UpdateRingClearance();
long t1 = Stopwatch.GetTimestamp();
MatchRules.ApplyPlayerInput(State, input);
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight, _tickCount);
long t2 = Stopwatch.GetTimestamp();
ApplyPhysicsDrives();
long t3 = Stopwatch.GetTimestamp();
_world.Step(FixedDt, SubStepCount);
_world.Step(FixedDt, subSteps);
long t4 = Stopwatch.GetTimestamp();
SyncBodiesFromWorld();
long t5 = Stopwatch.GetTimestamp();
@ -255,7 +291,49 @@ namespace RustToDust.Ymir
private void BuildStaticArena()
{
// Safety floor slab at y = -20m below the lowest possible terrain valley (-18m);
if (State.MapKind == ArenaMapKind.Sion && State.SionMap is { } sion)
{
var meta = sion.Metadata;
float half = State.Terrain.MapHalfExtent;
_world.AddStaticHeightField(
GroundStableId,
(-half, 0f, -half),
sion.Heights,
meta.GridRes,
meta.GridRes,
(meta.CellSizeMeters, 1.0f, meta.CellSizeMeters),
meta.MinY - 2f,
meta.MaxY + 2f,
friction: 0.15f,
restitution: 0.0f);
ulong boxId = StaticBoxStableIdBase;
for (int i = 0; i < State.ArenaBoundaryBoxes.Count; i++)
{
var b = State.ArenaBoundaryBoxes[i];
_world.AddStaticBox(
boxId++,
(b.X, b.Y, b.Z),
(b.HalfX, b.HalfY, b.HalfZ),
friction: 0.35f,
restitution: 0.1f);
}
for (int i = 0; i < sion.CollisionMeshes.Count; i++)
{
var col = sion.CollisionMeshes[i];
_world.AddStaticMesh(
StaticMeshStableIdBase + (ulong)i,
(0f, 0f, 0f),
col.Vertices,
col.Indices,
friction: 0.5f,
restitution: 0.05f);
}
return;
}
// Desert safety floor slab at y = -20m below the lowest possible terrain valley (-18m);
// primary terrain support comes from 4-corner spring-damper sampling of State.Terrain.
_world.AddStaticBox(
GroundStableId,
@ -558,6 +636,27 @@ namespace RustToDust.Ymir
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();
// On Sion, StaticHeightField supports settled Neutral Patrons/Exemplars directly so Box3D can sleep them.
if (State.MapKind == ArenaMapKind.Sion &&
s.Stance == SpectatorStance.Neutral &&
s.Tier != SpectatorTier.Tourist &&
dist < 0.9f &&
vel.LengthSquared() < 0.16f &&
angVel.LengthSquared() < 0.09f &&
up.Y > 0.90f)
{
view.ForceX[lane] = 0f;
view.ForceY[lane] = 0f;
view.ForceZ[lane] = 0f;
view.TorqueX[lane] = 0f;
view.TorqueY[lane] = 0f;
view.TorqueZ[lane] = 0f;
continue;
}
ComputeTerrainSupport(
pos, q, vel, angVel, mass, s.Grid.Spec,
out Vector3 supportForce,
@ -565,8 +664,6 @@ namespace RustToDust.Ymir
out Vector3 terrainNormal,
out _);
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 = supportForce + (desiredVel - horizVel) * (mass * 4.5f);
@ -901,12 +998,13 @@ namespace RustToDust.Ymir
Vector3 supportDir = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, slopeBlend));
float orthoScale = MathF.Max(0.35f, terrainNormal.Y);
bool isSion = State.MapKind == ArenaMapKind.Sion;
float hx = MathF.Min(spec.HalfWidth * 0.9f, 2.4f);
float hz = MathF.Min(spec.HalfLength * 0.9f, 2.8f);
float bottomY = -spec.HalfHeight;
const float restTravel = 0.20f;
float kSpring = mass * 85f;
float cDamp = mass * 10.5f;
float restTravel = isSion ? 0.22f : 0.20f;
float kSpring = mass * (isSion ? 95f : 85f);
float cDamp = mass * (isSion ? 12.0f : 10.5f);
float torqueScale = spec.IsWalker ? 0.12f : 1.0f;
float maxPen = 0f;
@ -930,8 +1028,8 @@ namespace RustToDust.Ymir
maxPen = MathF.Max(maxPen, pen);
float vCornerN = Vector3.Dot(vel + Vector3.Cross(angVel, r), supportDir);
float penEff = pen * orthoScale;
float bumpExtra = pen > 0.20f ? mass * 220f * (pen - 0.20f) : 0f;
float fN = Math.Clamp(kSpring * penEff + bumpExtra - cDamp * vCornerN, 0f, mass * 65f);
float bumpExtra = (!isSion && pen > 0.20f) ? mass * 220f * (pen - 0.20f) : 0f;
float fN = Math.Clamp(kSpring * penEff + bumpExtra - cDamp * vCornerN, 0f, mass * (isSion ? 42f : 65f));
Vector3 cornerForce = supportDir * fN;
supportForce += cornerForce;
supportTorque += Vector3.Cross(r, cornerForce) * torqueScale;
@ -942,7 +1040,7 @@ namespace RustToDust.Ymir
float ghCenter = State.Terrain.SampleHeight(pos.X, pos.Z);
float centerGap = (pos.Y - spec.HalfHeight) - ghCenter;
float centerPen = (ghCenter + 0.08f) - (pos.Y - spec.HalfHeight);
if (centerPen > 0f)
if (!isSion && centerPen > 0f)
{
groundedCorners = Math.Max(groundedCorners, 1);
maxPen = MathF.Max(maxPen, centerPen);
@ -951,6 +1049,10 @@ namespace RustToDust.Ymir
float fCenter = Math.Clamp(mass * 120f * (centerPen * orthoScale) + centerExtra - mass * 10f * vCenterN, 0f, mass * 65f);
supportForce += supportDir * fCenter;
}
else if (isSion && centerPen > 0f)
{
groundedCorners = Math.Max(groundedCorners, 1);
}
// Prevent large overhangs from catapulting the chassis when the belly center is already well above ground
if (centerGap > 1.2f && supportForce.Y > 0f)
@ -964,15 +1066,15 @@ namespace RustToDust.Ymir
// climbs (vDotN <= 0) retain full support while separating crests (vDotN > 2.0) don't sky-launch.
float vDotN = Vector3.Dot(vel, terrainNormal);
float sepScale = vDotN > 2.0f ? Math.Clamp(1f - (vDotN - 2.0f) / 2.0f, 0f, 1f) : 1f;
float maxSpringY = vDotN > 2.0f ? mass * 20f * sepScale : mass * 75f;
float maxSpringY = vDotN > 2.0f ? mass * 20f * sepScale : mass * (isSion ? 48f : 75f);
if (supportForce.Y > maxSpringY && supportForce.Y > 1e-4f)
{
supportForce *= maxSpringY / supportForce.Y;
}
// Steep-slope normal velocity projection: when contacting terrain and moving inward (vDotN < 0),
// arrest inward normal velocity up to vDotN = 0 regardless of upward world vel.Y.
if (maxPen > 0f && vDotN < 0f)
// On Desert (flat safety slab only), arrest inward velocity into sloped terrain.
// On Sion, Ymir's StaticHeightField handles rigid normal contact directly without double-bouncing.
if (!isSion && maxPen > 0f && vDotN < 0f)
{
float deflectMag = MathF.Min(-vDotN * mass * 42f, -vDotN * mass / FixedDt);
supportForce += terrainNormal * deflectMag;
@ -1048,6 +1150,7 @@ namespace RustToDust.Ymir
float pTargetY = MatchRules.GetTargetAimY(p.Y, p.Grid.Spec.HalfHeight);
int detectedBy = 0;
bool isSion = State.MapKind == ArenaMapKind.Sion;
for (int i = 0; i < State.Contenders.Count; i++)
{
var c = State.Contenders[i];
@ -1069,27 +1172,35 @@ namespace RustToDust.Ymir
float dzC = c.Z - p.Z;
float distSqC = dxC * dxC + dzC * dzC;
bool playerSees = HasLineOfSight(
p.X, pEyeY, p.Z,
c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z);
bool checkPlayerSees = !isSion || distSqC <= 350f * 350f || (((_tickCount + i) & 3) == 0);
if (checkPlayerSees)
{
bool playerSees = HasLineOfSight(
p.X, pEyeY, p.Z,
c.X, MatchRules.GetTargetAimY(c.Y, c.Grid.Spec.HalfHeight), c.Z);
if (playerSees)
{
mem.VisibleToPlayer = true;
mem.FaintHorizonPing = false;
mem.LastSeenAge = 0f;
mem.LastSeenX = c.X;
mem.LastSeenZ = c.Z;
mem.HasEverBeenSeen = true;
}
else
{
mem.VisibleToPlayer = false;
mem.FaintHorizonPing = false;
if (mem.HasEverBeenSeen)
if (playerSees)
{
mem.LastSeenAge += FixedDt;
mem.VisibleToPlayer = true;
mem.FaintHorizonPing = false;
mem.LastSeenAge = 0f;
mem.LastSeenX = c.X;
mem.LastSeenZ = c.Z;
mem.HasEverBeenSeen = true;
}
else
{
mem.VisibleToPlayer = false;
mem.FaintHorizonPing = false;
if (mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
}
}
else if (!mem.VisibleToPlayer && mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
if (distSqC <= 240f * 240f &&
@ -1111,42 +1222,57 @@ namespace RustToDust.Ymir
continue;
}
bool playerSees = HasLineOfSight(
p.X, pEyeY, p.Z,
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z);
float sdx = s.X - p.X;
float sdz = s.Z - p.Z;
float sDistSq = sdx * sdx + sdz * sdz;
if (playerSees)
{
mem.VisibleToPlayer = true;
mem.FaintHorizonPing = false;
mem.LastSeenAge = 0f;
mem.LastSeenX = s.X;
mem.LastSeenZ = s.Z;
mem.HasEverBeenSeen = true;
}
else
if (isSion && sDistSq > 950f * 950f)
{
mem.VisibleToPlayer = false;
mem.FaintHorizonPing = false;
if (mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
}
else if (!isSion || (sDistSq <= 450f * 450f ? (((_tickCount + i) & 3) == 0) : (((_tickCount + i) & 7) == 0)))
{
bool playerSees = HasLineOfSight(
p.X, pEyeY, p.Z,
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight), s.Z);
// Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range;
// low-signature Exemplars vanish completely when terrain-occluded.
bool horizonPing = false;
if (s.RadarSignature >= 0.9f)
if (playerSees)
{
float dx = s.X - p.X;
float dz = s.Z - p.Z;
if (dx * dx + dz * dz <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange)
mem.VisibleToPlayer = true;
mem.FaintHorizonPing = false;
mem.LastSeenAge = 0f;
mem.LastSeenX = s.X;
mem.LastSeenZ = s.Z;
mem.HasEverBeenSeen = true;
}
else
{
mem.VisibleToPlayer = false;
if (mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
// Spectator wall horizon rule: gaudy Tourists (RadarSignature >= 0.9) ping faintly over moderate crests at medium range;
// low-signature Exemplars vanish completely when terrain-occluded.
bool horizonPing = false;
if (s.RadarSignature >= 0.9f && sDistSq <= MatchState.TouristHorizonMaxRange * MatchState.TouristHorizonMaxRange)
{
horizonPing = HasLineOfSight(
p.X, pEyeY + 14f, p.Z,
s.X, MatchRules.GetTargetAimY(s.Y, s.Grid.Spec.HalfHeight) + 14f, s.Z);
}
mem.FaintHorizonPing = horizonPing;
}
mem.FaintHorizonPing = horizonPing;
}
else if (!mem.VisibleToPlayer && mem.HasEverBeenSeen)
{
mem.LastSeenAge += FixedDt;
}
if (s.Stance != SpectatorStance.Neutral &&

View file

@ -0,0 +1,228 @@
using System;
using System.Numerics;
using RustToDust.Core;
using RustToDust.Ymir;
using Xunit;
using Ymir.Box3D;
namespace RustToDust.Tests
{
public sealed class SionMapTests
{
[Fact]
public void SionMapLoader_LoadsMetadataHeightmapBuildingsAndRcolMeshesWithExactParity()
{
var sion = SionMapLoader.Load();
var meta = sion.Metadata;
Assert.Equal(3072f, meta.SizeMeters);
Assert.Equal(6, meta.TileGrid);
Assert.Equal(512f, meta.TileSizeMeters);
Assert.Equal(1025, meta.GridRes);
Assert.Equal(3.0f, meta.CellSizeMeters);
Assert.Contains("swisstopo", meta.Attribution, StringComparison.OrdinalIgnoreCase);
Assert.Equal(1025 * 1025, sion.Heights.Length);
Assert.Equal(2319, sion.Buildings.Count);
Assert.Equal(36, sion.CollisionMeshes.Count);
var terrain = TerrainField.LoadHeightmap(
meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY);
// Verify Basilique de Valere and valley buildings align cleanly with heightmap.f32 (0.00m coordinate drift)
bool foundValere = false;
int flatAlignChecked = 0;
int closeAlignCount = 0;
for (int i = 0; i < sion.Buildings.Count; i++)
{
var b = sion.Buildings[i];
if (b.Name.Contains("Val", StringComparison.OrdinalIgnoreCase))
{
foundValere = true;
float hValere = terrain.SampleHeight(b.CenterX, b.CenterZ);
Assert.InRange(hValere, 90f, 150f);
}
if (b.Class == "Gebaeude Einzelhaus" &&
b.HalfX < 10f && b.HalfZ < 10f &&
terrain.SampleNormal(b.CenterX, b.CenterZ).Ny > 0.98f)
{
float hTerrain = terrain.SampleHeight(b.CenterX, b.CenterZ);
// Buildings include a ~4m foundation skirt below ground level; sloped/stepped lots can vary slightly around center.
Assert.InRange(hTerrain, b.GroundY - 5.0f, b.RoofY + 2.0f);
if (MathF.Abs(hTerrain - (b.GroundY + 3.5f)) <= 2.5f)
{
closeAlignCount++;
}
flatAlignChecked++;
}
}
Assert.True(foundValere, "Expected Basilique de Valere in Sion buildings_manifest.json");
Assert.True(flatAlignChecked > 200, $"Expected > 200 flat-ground buildings matching DEM, got {flatAlignChecked}");
Assert.True(closeAlignCount > flatAlignChecked * 0.90f,
$"Expected >90% of flat-lot buildings to sit within 2.5m of skirted DEM ({closeAlignCount}/{flatAlignChecked})");
// Verify RCOL collision mesh bounds match metadata tile bounds
for (int i = 0; i < sion.CollisionMeshes.Count; i++)
{
var cm = sion.CollisionMeshes[i];
var tm = meta.Tiles[i];
Assert.Equal(tm.Tx, cm.Tx);
Assert.Equal(tm.Tz, cm.Tz);
Assert.True(cm.Vertices.Length >= 3);
Assert.True(cm.Indices.Length >= 3 && cm.Indices.Length % 3 == 0);
Assert.True(Vector3.Distance(tm.BoundsMin, cm.BoundsMin) < 0.05f);
Assert.True(Vector3.Distance(tm.BoundsMax, cm.BoundsMax) < 0.05f);
}
}
[Fact]
public void SionTerrainField_SupportsBilinearSamplingNormalsRaycastAndCraters()
{
var sion = SionMapLoader.Load();
var meta = sion.Metadata;
var terrain = TerrainField.LoadHeightmap(
meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY);
Assert.True(terrain.IsHeightmapMode);
Assert.Equal(3072f, terrain.MapSize);
Assert.Equal(1536f, terrain.MapHalfExtent);
// Grid vertex exactness at (-1536, -1536) and (0, 0)
Assert.Equal(sion.Heights[0], terrain.SampleHeight(-1536f, -1536f), precision: 4);
Assert.Equal(sion.Heights[512 * 1025 + 512], terrain.SampleHeight(0f, 0f), precision: 4);
// Plaza spawn area is flat; Valere hill rises > 100m
var (_, plazaNy, _) = terrain.SampleNormal(-60f, 360f);
Assert.True(plazaNy >= 0.95f, $"Expected flat plaza normal.Y >= 0.95, got {plazaNy:F3}");
float valerePeakH = terrain.SampleHeight(113f, -211f);
Assert.True(valerePeakH > 100f, $"Expected Valere hill height > 100m, got {valerePeakH:F2}m");
// Raycast hits Valere hill at low elevation and clears above peak
bool blocked = terrain.Raycast(113f, 35f, -350f, 0f, 0f, 1f, 280f, out _, out float hitY, out float hitZ, out _);
Assert.True(blocked, "Expected terrain raycast through Valere ridge to hit");
Assert.InRange(hitZ, -350f, -70f);
Assert.True(hitY >= 34f);
bool clear = terrain.Raycast(113f, meta.MaxY + 10f, -350f, 0f, 0f, 1f, 280f, out _, out _, out _, out _);
Assert.False(clear, "Expected high raycast above Valere peak to clear");
// Dynamic crater lowers height on top of DEM
float before = terrain.SampleHeight(-60f, 360f);
terrain.StampCrater(-60f, 360f, radius: 5f, depth: 1.5f);
float after = terrain.SampleHeight(-60f, 360f);
Assert.True(after < before - 1.0f, $"Expected crater to depress Sion DEM (before={before:F2}, after={after:F2})");
}
[Fact]
public void ArenaSession_SionLoadsHeightfieldAndMeshesSpawnsClearBlocksLosAndStepsCleanly()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion);
var state = session.State;
var sion = state.SionMap!;
Assert.Equal(ArenaMapKind.Sion, state.MapKind);
Assert.Empty(state.ArenaCoverBoxes);
Assert.Equal(MatchState.SionInitialSafeRadius, state.Spectators.SafeRadius);
// Verify StaticHeightField (1) + StaticMesh (36) exist in Ymir
int hfCount = 0;
int meshCount = 0;
var view = session.World.View;
for (int lane = 0; lane < view.Count; lane++)
{
var kind = (Box3DSoaKind)view.Kind[lane];
if (kind == Box3DSoaKind.StaticHeightField) hfCount++;
else if (kind == Box3DSoaKind.StaticMesh) meshCount++;
}
Assert.Equal(1, hfCount);
Assert.Equal(36, meshCount);
// Verify zero contenders, spectators, or drops spawned inside any building
foreach (var c in state.Contenders)
{
float pad = MathF.Max(c.Grid.Spec.HalfWidth, c.Grid.Spec.HalfLength) + 1.5f;
Assert.False(sion.IsInsideAnyBuildingXz(c.X, c.Z, pad),
$"Contender {c.Id} ({c.Grid.Spec.Id}) spawned inside building at ({c.X:F2}, {c.Z:F2})");
}
foreach (var s in state.Spectators.Spectators)
{
Assert.False(sion.IsInsideAnyBuildingXz(s.X, s.Z, 1.5f),
$"Spectator {s.Id} spawned inside building at ({s.X:F2}, {s.Z:F2})");
}
foreach (var d in state.GroundDrops)
{
Assert.False(sion.IsInsideAnyBuildingXz(d.X, d.Z, 1.5f),
$"GroundDrop {d.Id} spawned inside building at ({d.X:F2}, {d.Z:F2})");
}
// LOS blocked by Valere hill
Assert.False(session.HasLineOfSight(113f, 35f, -350f, 113f, 35f, -70f),
"Expected HasLineOfSight to be blocked by Valere hill");
// LOS blocked by a real Old Town solid building mesh (and clear over its roof)
SionBuildingAabb? testBldg = null;
for (int i = 0; i < sion.Buildings.Count; i++)
{
var b = sion.Buildings[i];
if (b.Class == "Gebaeude Einzelhaus" &&
b.HalfX >= 5f && b.HalfZ >= 5f &&
(b.RoofY - b.GroundY) >= 8f &&
MathF.Abs(b.CenterX) < 500f && MathF.Abs(b.CenterZ) < 500f)
{
testBldg = b;
break;
}
}
Assert.NotNull(testBldg);
var tb = testBldg!.Value;
float midY = tb.GroundY + (tb.RoofY - tb.GroundY) * 0.45f;
float zA = tb.CenterZ - tb.HalfZ - 4f;
float zB = tb.CenterZ + tb.HalfZ + 4f;
Assert.False(session.HasLineOfSight(tb.CenterX, midY, zA, tb.CenterX, midY, zB),
$"Expected HasLineOfSight to be blocked by Sion building {tb.Id} at ({tb.CenterX:F1}, {midY:F1}, {tb.CenterZ:F1})");
Assert.True(session.HasLineOfSight(tb.CenterX, tb.RoofY + 6f, zA, tb.CenterX, tb.RoofY + 6f, zB),
$"Expected HasLineOfSight above Sion building {tb.Id} roof ({tb.RoofY:F1}m) to be clear");
// Step 180 ticks (3 seconds) driving & firing: zero NaNs, zero underground falls, player moves cleanly
var player = state.Player;
float pStartX = player.X;
float pStartZ = player.Z;
for (int tick = 0; tick < 180; tick++)
{
session.Step(new PlayerInput(
Throttle: 1f,
Steer: MathF.Sin(tick * 0.04f) * 0.25f,
AimWorldX: player.X + MathF.Sin(player.Yaw) * 60f,
AimWorldZ: player.Z + MathF.Cos(player.Yaw) * 60f,
Fire: tick % 10 == 0,
InteractPickup: false,
Brake: false));
for (int cIdx = 0; cIdx < state.Contenders.Count; cIdx++)
{
var c = state.Contenders[cIdx];
if (!c.Alive) continue;
Assert.True(float.IsFinite(c.X) && float.IsFinite(c.Y) && float.IsFinite(c.Z),
$"Non-finite contender {c.Id} pose at tick {tick}");
float gh = state.Terrain.SampleHeight(c.X, c.Z);
float bottomY = c.Y - c.Grid.Spec.HalfHeight;
Assert.True(bottomY >= gh - 0.85f,
$"Contender {c.Id} ({c.Grid.Spec.Id}) fell below Sion terrain at tick {tick}: bottom={bottomY:F2}m < ground={gh:F2}m");
}
for (int sIdx = 0; sIdx < state.Spectators.Spectators.Count; sIdx++)
{
var s = state.Spectators.Spectators[sIdx];
if (!s.Alive) continue;
Assert.True(float.IsFinite(s.X) && float.IsFinite(s.Y) && float.IsFinite(s.Z),
$"Non-finite spectator {s.Id} pose at tick {tick}");
}
}
float pDisp = MathF.Sqrt((player.X - pStartX) * (player.X - pStartX) + (player.Z - pStartZ) * (player.Z - pStartZ));
Assert.True(pDisp > 5f, $"Expected player displacement > 5m on Sion after 180 ticks, got {pDisp:F2}m");
}
}
}