Cut 13a: 0.5m Sion DEM, compute TerrainRenderer, tiled Box3D heightfields, and scar ledger

This commit is contained in:
Meta Vens 2026-12-05 23:28:05 +01:00
commit e86fee31da
34 changed files with 3360 additions and 1033 deletions

Binary file not shown.

Binary file not shown.

View file

@ -2,7 +2,7 @@
"name": "Sion, Valais, Switzerland", "name": "Sion, Valais, Switzerland",
"attribution": "Federal Office of Topography swisstopo", "attribution": "Federal Office of Topography swisstopo",
"sources": [ "sources": [
"ch.swisstopo.swissalti3d (2m DTM, Open Government Data)", "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)",
"ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)" "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)"
], ],
"stacItems": [ "stacItems": [
@ -27,24 +27,33 @@
"swissbuildings3d_3_0_2020_1306-21", "swissbuildings3d_3_0_2020_1306-21",
"swissbuildings3d_3_0_2020_1306-23" "swissbuildings3d_3_0_2020_1306-23"
], ],
"demAssetHash": "a0dae3310058004e43a071290b3972ae4e0919e0958be5ec56320ea1a204c5de",
"crs": "EPSG:2056", "crs": "EPSG:2056",
"originE": 2592614.0, "originE": 2592614.0,
"originN": 1118514.0, "originN": 1118514.0,
"centerE": 2594150.0, "centerE": 2594150.0,
"centerN": 1120050.0, "centerN": 1120050.0,
"baseElevationM": 483.41, "baseElevationM": 483.41,
"minY": -5.863, "minY": -5.885,
"maxY": 304.92, "maxY": 304.957,
"reliefM": 310.783, "reliefM": 310.841,
"sizeMeters": 3072.0, "sizeMeters": 3072.0,
"tileGrid": 6, "tileGrid": 16,
"tileSizeMeters": 512.0, "tileSizeMeters": 192.0,
"gridRes": 1025, "buildingTileGrid": 6,
"cellSizeMeters": 3.0, "buildingTileSizeMeters": 512.0,
"heightmapFormat": "float32_le_row_major", "gridRes": 6145,
"cellSizeMeters": 0.5,
"heightmapFile": "heightmap_05m.u16z",
"heightmapFormat": "rdhm_v2_u16_zigzag_zlib",
"heightmapMinY": -5.884674072265625,
"heightmapScale": 0.004743136931210756,
"surfaceTexture": "terrain_surface.png", "surfaceTexture": "terrain_surface.png",
"surfaceTextureSize": 2048, "surfaceTextureSize": 4096,
"surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east",
"surfaceMaskTexture": "terrain_surface_mask.png",
"surfaceMaskTextureSize": 2048,
"surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water",
"collisionFormat": { "collisionFormat": {
"magic": "RCOL", "magic": "RCOL",
"version": 1, "version": 1,

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

After

Width:  |  Height:  |  Size: 9.7 MiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 MiB

View file

@ -508,22 +508,27 @@ public partial class Main : Node3D
private void EnsureMenuSionBackdrop() private void EnsureMenuSionBackdrop()
{ {
_menuSionData ??= SionMapLoader.Load(); _menuSionData ??= SionMapLoader.Load();
_menuSionTerrain ??= TerrainField.LoadHeightmap( _menuSionTerrain ??= TerrainField.LoadSharedHeightmap(
_menuSionData.Metadata.SizeMeters, _menuSionData.Metadata.SizeMeters,
_menuSionData.Metadata.GridRes, _menuSionData.Metadata.GridRes,
_menuSionData.Heights, _menuSionData.Metadata.TileGrid,
_menuSionData.BaseDem,
_menuSionData.BaseDemMinY,
_menuSionData.BaseDemScale,
_menuSionData.Metadata.MinY, _menuSionData.Metadata.MinY,
_menuSionData.Metadata.MaxY, _menuSionData.Metadata.MaxY,
42UL); 42UL);
_terrain.Visible = false; _terrain.Visible = true;
_terrain.Sync(_menuSionTerrain, _menuSionData);
_sionMap.Visible = true; _sionMap.Visible = true;
_arena.Visible = false; _arena.Visible = false;
_dropReticleMesh.Visible = false; _dropReticleMesh.Visible = false;
_camera.Far = 4200f; _camera.Far = 4200f;
_atmosphere.ApplyMap(ArenaMapKind.Sion); _atmosphere.ApplyMap(ArenaMapKind.Sion);
_sionMap.EnsureBuilt(_menuSionData, _menuSionTerrain); _sionMap.EnsureBuilt(_menuSionData);
UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain); UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain);
_terrain.UpdateTileLod(_camera.GlobalPosition);
_sionMap.UpdateLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition);
} }
@ -870,11 +875,14 @@ public partial class Main : Node3D
bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby; bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.Sync(state.Terrain, state.SionMap);
if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null) if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null)
{ {
_terrain.Visible = false;
_sionMap.Visible = true; _sionMap.Visible = true;
_sionMap.EnsureBuilt(state.SionMap, state.Terrain); _sionMap.EnsureBuilt(state.SionMap);
if (!inLobby) if (!inLobby)
{ {
_arena.Sync(_session, _elapsedSeconds, 0f, 1f); _arena.Sync(_session, _elapsedSeconds, 0f, 1f);
@ -884,14 +892,12 @@ public partial class Main : Node3D
{ {
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain); UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
} }
_terrain.UpdateTileLod(_camera.GlobalPosition);
_sionMap.UpdateLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition);
} }
else else
{ {
_sionMap.Visible = false; _sionMap.Visible = false;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.Sync(state.Terrain);
if (!inLobby) if (!inLobby)
{ {
_arena.Sync(_session, _elapsedSeconds, 0f, 1f); _arena.Sync(_session, _elapsedSeconds, 0f, 1f);
@ -1334,19 +1340,13 @@ public partial class Main : Node3D
{ {
_frameEvents.Clear(); _frameEvents.Clear();
_session.DrainSimEvents(_frameEvents); _session.DrainSimEvents(_frameEvents);
if (_mapKind == ArenaMapKind.Desert) _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
{
_terrain.Sync(_session.ViewState.Terrain);
}
UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain); UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion) if (_mapKind == ArenaMapKind.Sion)
{ {
_sionMap.UpdateLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition);
} }
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
_lobbyScreen.Sync(_session); _lobbyScreen.Sync(_session);
return; return;
} }
@ -1361,10 +1361,7 @@ public partial class Main : Node3D
} }
double toMs = 1000.0 / Stopwatch.Frequency; double toMs = 1000.0 / Stopwatch.Frequency;
long tt0 = Stopwatch.GetTimestamp(); long tt0 = Stopwatch.GetTimestamp();
if (_mapKind == ArenaMapKind.Desert) _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
{
_terrain.Sync(_session.ViewState.Terrain);
}
long tt1 = Stopwatch.GetTimestamp(); long tt1 = Stopwatch.GetTimestamp();
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha); DrainAndFanSimEvents((float)delta, alpha);
@ -1375,14 +1372,11 @@ public partial class Main : Node3D
long tc0 = Stopwatch.GetTimestamp(); long tc0 = Stopwatch.GetTimestamp();
UpdateCamera((float)delta, alpha); UpdateCamera((float)delta, alpha);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion) if (_mapKind == ArenaMapKind.Sion)
{ {
_sionMap.UpdateLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition);
} }
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
long th0 = Stopwatch.GetTimestamp(); long th0 = Stopwatch.GetTimestamp();
var localP = _session.LocalContender; var localP = _session.LocalContender;
float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f; float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f;
@ -1424,22 +1418,16 @@ public partial class Main : Node3D
} }
else else
{ {
if (_mapKind == ArenaMapKind.Desert) _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
{
_terrain.Sync(_session.ViewState.Terrain);
}
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha); DrainAndFanSimEvents((float)delta, alpha);
UpdateCamera((float)delta, alpha); UpdateCamera((float)delta, alpha);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion) if (_mapKind == ArenaMapKind.Sion)
{ {
_sionMap.UpdateLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition);
} }
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
var localP = _session.LocalContender; var localP = _session.LocalContender;
float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f; float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f;
_hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio); _hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio);
@ -1513,7 +1501,7 @@ public partial class Main : Node3D
internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) => internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) =>
_mapKind == ArenaMapKind.Sion _mapKind == ArenaMapKind.Sion
? _sionMap.SampleGroundTint(worldX, worldZ) ? _terrain.SampleGroundTint(worldX, worldZ)
: DesertDustTint; : DesertDustTint;
private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex) private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex)
@ -1601,7 +1589,7 @@ public partial class Main : Node3D
} }
if (_mapKind == ArenaMapKind.Sion) if (_mapKind == ArenaMapKind.Sion)
{ {
GD.Print($"SionMap: chunks={_sionMap.TerrainChunkCount} tiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}"); GD.Print($"SionMap: terrainTiles={_terrain.BakedTileCount} gpuScarSlots={_terrain.ActiveGpuScarSlots} bldgTiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}");
} }
foreach (var kv in _arena.AssetCache.Vehicles) foreach (var kv in _arena.AssetCache.Vehicles)
{ {
@ -2076,7 +2064,7 @@ public partial class Main : Node3D
var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z); var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z);
float distFromOrigin = origin.DistanceTo(pt); float distFromOrigin = origin.DistanceTo(pt);
if (hit.StableId < ContenderStableIdBase) if (ArenaSession.IsStaticWorldStableId(hit.StableId))
{ {
if (distFromOrigin < hitDist) if (distFromOrigin < hitDist)
{ {

View file

@ -7,17 +7,15 @@ using RustToDust.Core;
namespace RustToDust.Client; namespace RustToDust.Client;
/// <summary> /// <summary>
/// Renders the 3072m x 3072m Sion, Switzerland arena: /// Renders Sion, Switzerland legacy building tiles (swapping cleanly between LOD1 &lt;= 520m, LOD2 520..2200m,
/// - 6x6 (512m) seam-free chunked terrain ArrayMeshes from heightmap.f32 textured with terrain_surface.png + micro-grain shader. /// and culled &gt; 2200m). Terrain rendering is unified in <see cref="TerrainRenderer"/>.
/// - 36 spatial building tiles swapping cleanly between LOD1 (&lt;= 650m), LOD2 (650m..2200m), and culled (&gt; 2200m), /// (This class is scheduled for deletion in Cut 13c when <c>WorldCityRenderer</c> lands.)
/// with shadow casting restricted to &lt;= 450m and shared PBR materials across all tiles.
/// </summary> /// </summary>
public partial class SionMapRenderer : Node3D public partial class SionMapRenderer : Node3D
{ {
public const float Lod1DistanceM = 520f; public const float Lod1DistanceM = 520f;
public const float CullDistanceM = 2200f; public const float CullDistanceM = 2200f;
public const float ShadowDistanceM = 360f; public const float ShadowDistanceM = 360f;
private const int ChunkGridVerts = 129; // 128 quads per 512m chunk (4m spacing)
private sealed class BuildingTileEntry private sealed class BuildingTileEntry
{ {
@ -30,26 +28,17 @@ public partial class SionMapRenderer : Node3D
public required MeshInstance3D Instance; public required MeshInstance3D Instance;
} }
private const int GroundTintGridSize = 128;
private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f);
private readonly List<MeshInstance3D> _terrainChunks = new(36);
private readonly List<BuildingTileEntry> _buildingTiles = new(36); private readonly List<BuildingTileEntry> _buildingTiles = new(36);
private readonly Dictionary<string, StandardMaterial3D> _sharedBuildingMaterials = new(StringComparer.Ordinal); private readonly Dictionary<string, StandardMaterial3D> _sharedBuildingMaterials = new(StringComparer.Ordinal);
private string? _builtForDir; private string? _builtForDir;
private ShaderMaterial? _terrainMat;
private ImageTexture? _surfaceTex;
private Color[]? _groundTintGrid;
private float _groundTintSizeM;
public bool IsBuilt { get; private set; } public bool IsBuilt { get; private set; }
public int TerrainChunkCount => _terrainChunks.Count;
public int BuildingTileCount => _buildingTiles.Count; public int BuildingTileCount => _buildingTiles.Count;
public int ActiveLod1TileCount { get; private set; } public int ActiveLod1TileCount { get; private set; }
public int ActiveLod2TileCount { get; private set; } public int ActiveLod2TileCount { get; private set; }
public int CulledTileCount { get; private set; } public int CulledTileCount { get; private set; }
public void EnsureBuilt(SionMapData sion, TerrainField terrain) public void EnsureBuilt(SionMapData sion)
{ {
if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase)) if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase))
{ {
@ -58,9 +47,6 @@ public partial class SionMapRenderer : Node3D
ClearBuilt(); ClearBuilt();
_builtForDir = sion.DirectoryPath; _builtForDir = sion.DirectoryPath;
BuildTerrainMaterial(sion);
BuildTerrainChunks(sion, terrain);
BuildBuildingTiles(sion); BuildBuildingTiles(sion);
IsBuilt = true; IsBuilt = true;
} }
@ -124,186 +110,6 @@ public partial class SionMapRenderer : Node3D
CulledTileCount = culledCount; 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}");
}
// Downsample CPU copy once for zero-readback terrain-tinted dust & impact plumes
var tintImg = (Image)img.Duplicate();
tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear);
var grid = new Color[GroundTintGridSize * GroundTintGridSize];
for (int y = 0; y < GroundTintGridSize; y++)
{
for (int x = 0; x < GroundTintGridSize; x++)
{
Color c = tintImg.GetPixel(x, y);
grid[y * GroundTintGridSize + x] = new Color(
Math.Clamp(c.R + 0.11f, 0.20f, 0.90f),
Math.Clamp(c.G + 0.11f, 0.20f, 0.88f),
Math.Clamp(c.B + 0.10f, 0.18f, 0.84f),
1.0f);
}
}
_groundTintGrid = grid;
_groundTintSizeM = sion.Metadata.SizeMeters;
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;
// 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, 480.0, dist), 0.12, 1.0);
float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07;
float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045;
float slope = 1.0 - clamp(v_world_normal.y, 0.0, 1.0);
vec3 col = clamp(base_col * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), vec3(0.0), vec3(1.0));
ALBEDO = col;
ROUGHNESS = mix(0.88, 0.96, slope);
METALLIC = 0.02;
}
"""
};
_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 terrain 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) private void BuildBuildingTiles(SionMapData sion)
{ {
var tiles = sion.Metadata.Tiles; var tiles = sion.Metadata.Tiles;
@ -498,47 +304,8 @@ public partial class SionMapRenderer : Node3D
return (defaultKey, defMat); return (defaultKey, defMat);
} }
public Color SampleGroundTint(float worldX, float worldZ)
{
Color[]? grid = _groundTintGrid;
float sizeM = _groundTintSizeM;
if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ))
{
return NeutralAlpineDustTint;
}
float half = sizeM * 0.5f;
float u = (worldX + half) / sizeM;
float v = (worldZ + half) / sizeM;
if (u < 0f || u > 1f || v < 0f || v > 1f)
{
return NeutralAlpineDustTint;
}
float fx = u * (GroundTintGridSize - 1);
float fy = v * (GroundTintGridSize - 1);
int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1);
int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1);
int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1);
int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1);
float tx = fx - x0;
float ty = fy - y0;
Color c00 = grid[y0 * GroundTintGridSize + x0];
Color c10 = grid[y0 * GroundTintGridSize + x1];
Color c01 = grid[y1 * GroundTintGridSize + x0];
Color c11 = grid[y1 * GroundTintGridSize + x1];
return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty);
}
private void ClearBuilt() private void ClearBuilt()
{ {
for (int i = 0; i < _terrainChunks.Count; i++)
{
_terrainChunks[i].QueueFree();
}
_terrainChunks.Clear();
for (int i = 0; i < _buildingTiles.Count; i++) for (int i = 0; i < _buildingTiles.Count; i++)
{ {
_buildingTiles[i].Instance.QueueFree(); _buildingTiles[i].Instance.QueueFree();
@ -546,10 +313,6 @@ public partial class SionMapRenderer : Node3D
_buildingTiles.Clear(); _buildingTiles.Clear();
_sharedBuildingMaterials.Clear(); _sharedBuildingMaterials.Clear();
_terrainMat = null;
_surfaceTex = null;
_groundTintGrid = null;
_groundTintSizeM = 0f;
_builtForDir = null; _builtForDir = null;
IsBuilt = false; IsBuilt = false;
ActiveLod1TileCount = 0; ActiveLod1TileCount = 0;

File diff suppressed because it is too large Load diff

View file

@ -1,67 +0,0 @@
shader_type canvas_item;
render_mode blend_add;
// Encodes positive height deltas into R ([-18m, +52m] => span 70m),
// roughness delta into G, scorch/track wear into B, and ALWAYS A = 1.0
// (required for TransparentBg=false UseHdr2D=true blend equations in forward_plus).
uniform int brush_kind = 0;
uniform float height_delta = 0.0;
uniform float height_span = 70.0;
void fragment() {
vec2 uv_local = UV * 2.0 - 1.0;
float u = uv_local.x;
float v = uv_local.y;
float r2 = u * u + v * v;
if (r2 >= 1.0) {
discard;
}
float pos_dh = 0.0;
float pos_dg = 0.0;
float d_scorch = 0.0;
if (brush_kind == 0) {
// DuneRidge (positive)
float env = 1.0 - r2;
env *= env;
float ridge = max(0.0, 1.0 - u * u);
float asym = 1.0 + 0.32 * u;
pos_dh = max(0.0, height_delta) * env * (0.35 + 0.65 * ridge) * asym;
pos_dg = 0.02 * env;
} else if (brush_kind == 1) {
// Mesa
float r = sqrt(r2);
float t = clamp((1.0 - r) / 0.45, 0.0, 1.0);
float plateau = t * t * (3.0 - 2.0 * t);
pos_dh = max(0.0, height_delta) * plateau;
} else if (brush_kind == 2) {
// SalvagePad (positive part)
float env = 1.0 - r2;
env *= env;
pos_dh = max(0.0, height_delta) * env;
pos_dg = 0.03 * env;
} else if (brush_kind == 4) {
// Crater ejecta rim + slag/scorch
float r = sqrt(r2);
float depth = abs(height_delta);
float rim_t = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0));
pos_dh = 0.32 * depth * rim_t * rim_t;
pos_dg = 0.04 * (1.0 - r);
d_scorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0);
} else if (brush_kind == 5) {
// Track wear
float env = 1.0 - r2;
env *= env;
d_scorch = 0.32 * env;
} else if (brush_kind == 6) {
// Scorch
float r = sqrt(r2);
float mask = clamp(1.0 - r, 0.0, 1.0);
mask = mask * mask;
pos_dg = 0.02 * mask;
d_scorch = 0.85 * mask;
}
COLOR = vec4(pos_dh / height_span, pos_dg, d_scorch, 1.0);
}

View file

@ -1,73 +0,0 @@
shader_type canvas_item;
render_mode blend_mix;
uniform int brush_kind = 0;
uniform vec3 brush_albedo = vec3(0.72, 0.53, 0.33);
uniform float height_delta = 0.0;
void fragment() {
vec2 uv_local = UV * 2.0 - 1.0;
float u = uv_local.x;
float v = uv_local.y;
float r2 = u * u + v * v;
if (r2 >= 1.0) {
discard;
}
vec3 col = brush_albedo;
float alpha = 0.0;
if (brush_kind == 0) {
// DuneRidge: windward sunlit crest vs dry wash
float env = 1.0 - r2;
env *= env;
float ridge = max(0.0, 1.0 - u * u);
col = mix(brush_albedo * 0.90, brush_albedo * 1.12, ridge);
alpha = env * 0.72;
} else if (brush_kind == 1) {
// Mesa: rust-basalt plateau + stratified skirt
float r = sqrt(r2);
float t = clamp((1.0 - r) / 0.45, 0.0, 1.0);
float plateau = t * t * (3.0 - 2.0 * t);
float cliff_band = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0);
col = mix(brush_albedo, brush_albedo * 0.68, cliff_band);
alpha = clamp(plateau + cliff_band * 0.5, 0.0, 0.94);
} else if (brush_kind == 2) {
// SalvagePad: compacted gravel & weathered concrete slab
float env = 1.0 - r2;
env *= env;
float border = smoothstep(0.75, 0.92, sqrt(r2));
col = mix(brush_albedo, vec3(0.32, 0.28, 0.24), border * 0.45);
alpha = clamp(env * 1.15, 0.0, 0.88);
} else if (brush_kind == 3) {
// Road: twin packed dirt ruts running longitudinally along u (cross-track offset abs(v))
float env = 1.0 - r2;
env *= env;
float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v)));
col = mix(brush_albedo, brush_albedo * 0.76, rut);
alpha = env * (0.45 + 0.35 * rut);
} else if (brush_kind == 4) {
// Crater: charred pit center + bright rust ejecta rim
float r = sqrt(r2);
float pit = clamp(1.0 - r / 0.62, 0.0, 1.0);
float rim = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0));
vec3 ejecta = vec3(0.62, 0.38, 0.22);
col = mix(ejecta, brush_albedo, clamp(pit * 1.3, 0.0, 1.0));
alpha = clamp(max(pit * 0.94, rim * rim * 0.72), 0.0, 0.95);
} else if (brush_kind == 5) {
// Track: twin tire ruts along local X
float env = 1.0 - r2;
env *= env;
float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v)));
col = brush_albedo;
alpha = env * treads * 0.62;
} else if (brush_kind == 6) {
// Scorch
float r = sqrt(r2);
float mask = clamp(1.0 - r, 0.0, 1.0);
col = brush_albedo;
alpha = mask * mask * 0.88;
}
COLOR = vec4(col, alpha);
}

View file

@ -1,41 +0,0 @@
shader_type canvas_item;
render_mode blend_sub;
// Encodes negative height deltas (crater pits, dry washes, road ruts, tire ruts) into R.
uniform int brush_kind = 0;
uniform float height_delta = 0.0;
uniform float height_span = 70.0;
void fragment() {
vec2 uv_local = UV * 2.0 - 1.0;
float u = uv_local.x;
float v = uv_local.y;
float r2 = u * u + v * v;
if (r2 >= 1.0) {
discard;
}
float neg_dh = 0.0;
float neg_dg = 0.0;
if (brush_kind == 0) {
// Dry wash (negative DuneRidge)
float env = 1.0 - r2;
env *= env;
float ridge = max(0.0, 1.0 - u * u);
float asym = 1.0 + 0.32 * u;
neg_dh = max(0.0, -height_delta) * env * (0.35 + 0.65 * ridge) * asym;
} else if (brush_kind == 2 || brush_kind == 3 || brush_kind == 5) {
// SalvagePad (<0), Road, Track rut
float env = 1.0 - r2;
env *= env;
neg_dh = max(0.0, -height_delta) * env;
} else if (brush_kind == 4) {
// Crater pit
float r = sqrt(r2);
float depth = abs(height_delta);
float pit_t = clamp(1.0 - r / 0.62, 0.0, 1.0);
neg_dh = depth * pit_t * pit_t * (3.0 - 2.0 * pit_t);
}
COLOR = vec4(neg_dh / height_span, neg_dg, 0.0, 1.0);
}

View file

@ -1,18 +1,29 @@
shader_type spatial; shader_type spatial;
render_mode cull_back, depth_draw_opaque; render_mode cull_back, depth_draw_opaque;
uniform sampler2D height_tex : filter_linear, repeat_disable; uniform sampler2D base_dem_tex : filter_linear, repeat_disable;
uniform sampler2D albedo_tex : source_color, filter_linear, repeat_disable; uniform sampler2D base_surface_tex : source_color, filter_linear_mipmap, repeat_disable;
uniform sampler2D base_mask_tex : filter_linear_mipmap, repeat_disable;
uniform sampler2D delta_height_tex : filter_linear, repeat_disable;
uniform sampler2D delta_albedo_tex : source_color, filter_linear, repeat_disable;
uniform float dem_min_y = 0.0;
uniform float dem_scale_span = 0.0;
uniform float dem_grid_res = 6145.0;
uniform float height_min = -18.0; uniform float height_min = -18.0;
uniform float height_max = 52.0; uniform float height_max = 52.0;
uniform float map_size = 1536.0;
uniform float tile_origin_x = 0.0;
uniform float tile_origin_z = 0.0;
uniform float tile_size = 192.0; uniform float tile_size = 192.0;
uniform float inner_span = 253.0; uniform float inner_span = 384.0;
uniform float tex_size = 256.0; uniform float tex_size = 388.0;
uniform float gutter_offset = 1.5; uniform float gutter_center = 2.5;
uniform float is_sion = 0.0;
uniform float tile_quads = 192.0;
uniform vec4 neighbor_quads = vec4(192.0, 192.0, 192.0, 192.0); // (-X, +X, -Z, +Z)
float decode_height(float h_norm) { varying vec3 v_world_pos;
return mix(height_min, height_max, clamp(h_norm, 0.0, 1.0));
}
float hash21(vec2 p) { float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21)); p = fract(p * vec2(123.34, 456.21));
@ -20,37 +31,117 @@ float hash21(vec2 p) {
return fract(p.x * p.y); 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);
}
vec2 to_baked_uv(vec2 mesh_uv) { vec2 to_baked_uv(vec2 mesh_uv) {
return (mesh_uv * inner_span + gutter_offset) / tex_size; return (mesh_uv * inner_span + gutter_center) / tex_size;
}
float sample_total_height(vec2 mesh_uv) {
vec2 world_xz = vec2(tile_origin_x, tile_origin_z) + mesh_uv * tile_size;
float base_h = 0.0;
if (is_sion > 0.5) {
float max_idx = dem_grid_res - 1.0;
vec2 dem_uv = ((world_xz + map_size * 0.5) / map_size * max_idx + 0.5) / dem_grid_res;
base_h = dem_min_y + textureLod(base_dem_tex, dem_uv, 0.0).r * dem_scale_span;
}
float delta_h = textureLod(delta_height_tex, to_baked_uv(mesh_uv), 0.0).r;
return clamp(base_h + delta_h, height_min, height_max);
}
float sample_edge_snapped_height(vec2 uv) {
// Zero T-junction cracks: if an adjacent tile is coarser, snap edge vertex height
// onto the exact linear segment connecting the neighbor's coarse edge vertices.
if (uv.x < 0.0005 && neighbor_quads.x < tile_quads - 0.5) {
float nq = neighbor_quads.x;
float t = uv.y * nq;
float i0 = floor(t);
float u0 = i0 / nq;
float u1 = min(1.0, (i0 + 1.0) / nq);
return mix(sample_total_height(vec2(0.0, u0)), sample_total_height(vec2(0.0, u1)), t - i0);
}
if (uv.x > 0.9995 && neighbor_quads.y < tile_quads - 0.5) {
float nq = neighbor_quads.y;
float t = uv.y * nq;
float i0 = floor(t);
float u0 = i0 / nq;
float u1 = min(1.0, (i0 + 1.0) / nq);
return mix(sample_total_height(vec2(1.0, u0)), sample_total_height(vec2(1.0, u1)), t - i0);
}
if (uv.y < 0.0005 && neighbor_quads.z < tile_quads - 0.5) {
float nq = neighbor_quads.z;
float t = uv.x * nq;
float i0 = floor(t);
float u0 = i0 / nq;
float u1 = min(1.0, (i0 + 1.0) / nq);
return mix(sample_total_height(vec2(u0, 0.0)), sample_total_height(vec2(u1, 0.0)), t - i0);
}
if (uv.y > 0.9995 && neighbor_quads.w < tile_quads - 0.5) {
float nq = neighbor_quads.w;
float t = uv.x * nq;
float i0 = floor(t);
float u0 = i0 / nq;
float u1 = min(1.0, (i0 + 1.0) / nq);
return mix(sample_total_height(vec2(u0, 1.0)), sample_total_height(vec2(u1, 1.0)), t - i0);
}
return sample_total_height(uv);
} }
void vertex() { void vertex() {
float h_norm = textureLod(height_tex, to_baked_uv(UV), 0.0).r; float h = sample_edge_snapped_height(UV);
VERTEX.y += decode_height(h_norm); VERTEX.y += h;
v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
} }
void fragment() { void fragment() {
vec2 uv_baked = to_baked_uv(UV); float world_step = tile_size / inner_span; // 0.5m
float texel_step = 1.0 / tex_size; float uv_step = world_step / tile_size;
float world_step = tile_size / inner_span;
float hL = decode_height(texture(height_tex, uv_baked - vec2(texel_step, 0.0)).r); float hL = sample_total_height(UV - vec2(uv_step, 0.0));
float hR = decode_height(texture(height_tex, uv_baked + vec2(texel_step, 0.0)).r); float hR = sample_total_height(UV + vec2(uv_step, 0.0));
float hD = decode_height(texture(height_tex, uv_baked - vec2(0.0, texel_step)).r); float hD = sample_total_height(UV - vec2(0.0, uv_step));
float hU = decode_height(texture(height_tex, uv_baked + vec2(0.0, texel_step)).r); float hU = sample_total_height(UV + vec2(0.0, uv_step));
vec3 world_normal = normalize(vec3(hL - hR, 2.0 * world_step, hD - hU)); vec3 world_normal = normalize(vec3(hL - hR, 2.0 * world_step, hD - hU));
NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz); NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz);
vec4 mat = texture(height_tex, uv_baked); vec2 uv_baked = to_baked_uv(UV);
vec3 alb = texture(albedo_tex, uv_baked).rgb; vec4 mat = texture(delta_height_tex, uv_baked);
vec3 delta_alb = texture(delta_albedo_tex, uv_baked).rgb;
// Subtle desert sand grain so dunes read crisply under sunlight (multiplicative in linear HDR)
float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045;
float scorch = clamp(mat.b, 0.0, 1.0); float scorch = clamp(mat.b, 0.0, 1.0);
alb = clamp(alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch);
vec3 alb;
float rough = clamp(mat.g, 0.35, 1.0);
if (is_sion > 0.5) {
vec2 world_uv = (v_world_pos.xz + map_size * 0.5) / map_size;
vec3 base_col = texture(base_surface_tex, world_uv).rgb;
vec4 cls = texture(base_mask_tex, world_uv);
alb = mix(base_col, delta_alb, clamp(mat.a, 0.0, 1.0));
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, 480.0, dist), 0.12, 1.0);
float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07;
float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045;
alb = clamp(alb * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), 0.0, 1.0) * (1.0 - 0.32 * scorch);
float base_rough = cls.r * 0.94 + cls.g * 0.90 + cls.b * 0.80 + cls.a * 0.26;
float cls_sum = max(0.001, cls.r + cls.g + cls.b + cls.a);
rough = mix(clamp(base_rough / cls_sum, 0.26, 0.96), rough, clamp(mat.a, 0.0, 1.0));
} else {
float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045;
alb = clamp(delta_alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch);
}
ALBEDO = alb; ALBEDO = alb;
ROUGHNESS = clamp(mat.g, 0.35, 1.0); ROUGHNESS = rough;
METALLIC = 0.02; METALLIC = 0.02;
} }

View file

@ -0,0 +1,176 @@
#version 450
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
struct GpuBrush {
vec4 posRot; // x, z, cosR, sinR
vec4 radDelta; // invRx, invRz, heightDelta, maxRadiusSq
vec4 matColor; // albedoR, albedoG, albedoB, float(kind)
};
layout(set = 0, binding = 0, rgba16f) uniform writeonly image2D u_delta_height;
layout(set = 0, binding = 1, rgba8) uniform writeonly image2D u_delta_albedo;
layout(set = 0, binding = 2, std430) readonly buffer BrushBuffer {
GpuBrush brushes[];
} u_brushes;
layout(push_constant, std430) uniform TileBakeParams {
vec4 tileOriginAndSpan; // x=tileMinX, y=tileMinZ, z=tileSize(192), w=innerSpan(384)
vec4 baseColorAndGutter; // rgb=clearAlbedo, w=gutterStart(2.0)
uvec4 counts; // x=brushStart, y=brushCount, z=texSize(388), w=isSion
} u_params;
void main() {
ivec2 gid = ivec2(gl_GlobalInvocationID.xy);
int texSize = int(u_params.counts.z);
if (gid.x >= texSize || gid.y >= texSize) {
return;
}
float tileMinX = u_params.tileOriginAndSpan.x;
float tileMinZ = u_params.tileOriginAndSpan.y;
float tileSize = u_params.tileOriginAndSpan.z;
float innerSpan = u_params.tileOriginAndSpan.w;
float gutterStart = u_params.baseColorAndGutter.w;
float stepM = tileSize / innerSpan;
float wx = tileMinX + (float(gid.x) - gutterStart) * stepM;
float wz = tileMinZ + (float(gid.y) - gutterStart) * stepM;
bool isSion = u_params.counts.w != 0u;
uint brushStart = u_params.counts.x;
uint brushEnd = brushStart + u_params.counts.y;
float totalDh = 0.0;
float totalDg = 0.0;
float totalScorch = 0.0;
vec3 albedoAcc = u_params.baseColorAndGutter.rgb;
float deltaBlendAcc = isSion ? 0.0 : 1.0;
for (uint i = brushStart; i < brushEnd; i++) {
GpuBrush b = u_brushes.brushes[i];
float dx = wx - b.posRot.x;
float dz = wz - b.posRot.y;
if (dx * dx + dz * dz >= b.radDelta.w) {
continue;
}
float cosR = b.posRot.z;
float sinR = b.posRot.w;
float lx = dx * cosR + dz * sinR;
float lz = -dx * sinR + dz * cosR;
float u = lx * b.radDelta.x;
float v = lz * b.radDelta.y;
float r2 = u * u + v * v;
if (r2 >= 1.0) {
continue;
}
int kind = int(b.matColor.w + 0.5);
float heightDelta = b.radDelta.z;
vec3 bCol = b.matColor.rgb;
float dh = 0.0;
float dg = 0.0;
float dScorch = 0.0;
vec3 col = bCol;
float alpha = 0.0;
if (kind == 0) {
// DuneRidge
float env = 1.0 - r2;
env *= env;
float ridge = max(0.0, 1.0 - u * u);
float asym = 1.0 + 0.32 * u;
dh = heightDelta * env * (0.35 + 0.65 * ridge) * asym;
if (heightDelta > 0.0) {
dg = 0.02 * env;
}
col = mix(bCol * 0.90, bCol * 1.12, ridge);
alpha = env * 0.72;
} else if (kind == 1) {
// Mesa
float r = sqrt(r2);
float t = clamp((1.0 - r) / 0.45, 0.0, 1.0);
float plateau = t * t * (3.0 - 2.0 * t);
dh = heightDelta * plateau;
float cliffBand = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0);
col = mix(bCol, bCol * 0.68, cliffBand);
alpha = clamp(plateau + cliffBand * 0.5, 0.0, 0.94);
} else if (kind == 2) {
// SalvagePad
float env = 1.0 - r2;
env *= env;
dh = heightDelta * env;
if (heightDelta > 0.0) {
dg = 0.03 * env;
}
float border = smoothstep(0.75, 0.92, sqrt(r2));
col = mix(bCol, vec3(0.32, 0.28, 0.24), border * 0.45);
alpha = clamp(env * 1.15, 0.0, 0.88);
} else if (kind == 3) {
// Road
float env = 1.0 - r2;
env *= env;
dh = heightDelta * env;
float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v)));
col = mix(bCol, bCol * 0.76, rut);
alpha = env * (0.45 + 0.35 * rut);
} else if (kind == 4) {
// Crater
float r = sqrt(r2);
float depth = abs(heightDelta);
float pitT = clamp(1.0 - r / 0.62, 0.0, 1.0);
float pit = -depth * pitT * pitT * (3.0 - 2.0 * pitT);
float rimT = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0));
float rim = 0.32 * depth * rimT * rimT;
dh = pit + rim;
dg = 0.04 * (1.0 - r);
dScorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0);
vec3 ejecta = isSion ? vec3(0.34, 0.31, 0.27) : vec3(0.62, 0.38, 0.22);
col = mix(ejecta, bCol, clamp(pitT * 1.3, 0.0, 1.0));
alpha = clamp(max(pitT * 0.94, rimT * rimT * 0.72), 0.0, 0.95);
} else if (kind == 5) {
// Track
float env = 1.0 - r2;
env *= env;
dh = heightDelta * env;
dScorch = 0.32 * env;
float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v)));
col = bCol;
alpha = env * treads * 0.62;
} else if (kind == 6) {
// Scorch
float r = sqrt(r2);
float mask = clamp(1.0 - r, 0.0, 1.0);
float mask2 = mask * mask;
dg = 0.02 * mask2;
dScorch = 0.85 * mask2;
col = bCol;
alpha = mask2 * 0.88;
} else if (kind == 7) {
// Rubble
float env = 1.0 - r2;
env *= env;
float mound = 0.72 + 0.28 * cos(u * 3.14159265 * 2.5);
dh = heightDelta * env * mound;
dg = 0.08 * env;
dScorch = 0.35 * env;
float chunk = fract(sin(dot(floor(vec2(wx, wz) * 1.5), vec2(12.9898, 78.233))) * 43758.5453);
col = mix(bCol * 0.80, bCol * 1.15, chunk);
alpha = clamp(env * 1.2, 0.0, 0.96);
}
totalDh += dh;
totalDg += dg;
totalScorch += dScorch;
albedoAcc = mix(albedoAcc, col, alpha);
deltaBlendAcc = max(deltaBlendAcc, alpha);
}
float roughness = clamp(0.88 + totalDg, 0.35, 1.0);
float scorch = clamp(totalScorch, 0.0, 1.0);
imageStore(u_delta_height, gid, vec4(totalDh, roughness, scorch, clamp(deltaBlendAcc, 0.0, 1.0)));
imageStore(u_delta_albedo, gid, vec4(clamp(albedoAcc, 0.0, 1.0), 1.0));
}

View file

@ -203,11 +203,11 @@ public partial class Smoke : Node
} }
} }
// Regression check (Finding 4): 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants) // Regression check: 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants)
// and passive Track throttling preserves DirtyTileMask until all tiles are baked without skipping via _rebakeCursor. // and passive Track throttling (MaxDirtyRebakesPerSync=4) preserves pending visual versions until all tiles are baked without skipping via _rebakeCursor.
{ {
// Flush any lingering track rebakes first so baseline is clean // Flush any lingering track rebakes first so baseline is clean
for (int flush = 0; flush < 32 && _main.Session.ViewState.Terrain.DirtyTileMask != 0UL; flush++) for (int flush = 0; flush < 32 && _main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) > 0; flush++)
{ {
_main.Terrain.Sync(_main.Session.ViewState.Terrain); _main.Terrain.Sync(_main.Session.ViewState.Terrain);
} }
@ -229,8 +229,8 @@ public partial class Smoke : Node
_main.Terrain.Sync(_main.Session.ViewState.Terrain); // Sync#1 _main.Terrain.Sync(_main.Session.ViewState.Terrain); // Sync#1
Check(_main.Terrain.DirtyRebakes == rebakes4Before + 4, Check(_main.Terrain.DirtyRebakes == rebakes4Before + 4,
$"Expected 4-tile boundary crater at (0,0) to bake all 4 tiles on Sync#1, got {_main.Terrain.DirtyRebakes - rebakes4Before}"); $"Expected 4-tile boundary crater at (0,0) to bake all 4 tiles on Sync#1, got {_main.Terrain.DirtyRebakes - rebakes4Before}");
Check(_main.Session.ViewState.Terrain.StructuralDirtyTileMask == 0UL, Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0,
"Expected StructuralDirtyTileMask == 0 after Sync#1 on 4-tile boundary crater"); "Expected 0 pending dirty tiles after Sync#1 on 4-tile boundary crater");
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
@ -252,21 +252,23 @@ public partial class Smoke : Node
} }
} }
// Stamp 3 passive tracks in adjacent tiles so _rebakeCursor must advance across Sync#1 and Sync#2 without skipping // Stamp 5 passive tracks in distinct tiles so _rebakeCursor advances across Sync#1 (4) and Sync#2 (1) without skipping
int rebakesTrackBefore = _main.Terrain.DirtyRebakes; int rebakesTrackBefore = _main.Terrain.DirtyRebakes;
_main.Session.ViewState.Terrain.StampTrack(-480f, -480f, 0f, 2f, 3f); _main.Session.ViewState.Terrain.StampTrack(-480f, -480f, 0f, 2f, 3f);
_main.Session.ViewState.Terrain.StampTrack(-288f, -480f, 0f, 2f, 3f); _main.Session.ViewState.Terrain.StampTrack(-288f, -480f, 0f, 2f, 3f);
_main.Session.ViewState.Terrain.StampTrack(-96f, -480f, 0f, 2f, 3f); _main.Session.ViewState.Terrain.StampTrack(-96f, -480f, 0f, 2f, 3f);
_main.Session.ViewState.Terrain.StampTrack(96f, -480f, 0f, 2f, 3f);
_main.Session.ViewState.Terrain.StampTrack(288f, -480f, 0f, 2f, 3f);
_main.Terrain.Sync(_main.Session.ViewState.Terrain); _main.Terrain.Sync(_main.Session.ViewState.Terrain);
Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 2, Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 4,
$"Expected Sync#1 to throttle 3 passive tracks to 2 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); $"Expected Sync#1 to throttle 5 passive tracks to 4 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}");
Check(_main.Session.ViewState.Terrain.DirtyTileMask != 0UL, Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 1,
"Expected DirtyTileMask to stay non-zero while 1 passive track tile remains dirty"); "Expected 1 pending dirty track tile remaining after Sync#1");
_main.Terrain.Sync(_main.Session.ViewState.Terrain); _main.Terrain.Sync(_main.Session.ViewState.Terrain);
Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 3, Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 5,
$"Expected Sync#2 to bake remaining 3rd passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); $"Expected Sync#2 to bake remaining 5th passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}");
Check(_main.Session.ViewState.Terrain.DirtyTileMask == 0UL, Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0,
"Expected DirtyTileMask == 0 after all passive track tiles baked"); "Expected 0 pending dirty tiles after all passive track tiles baked");
} }
_main.SetPhysicsProcess(true); _main.SetPhysicsProcess(true);
@ -1864,9 +1866,10 @@ public partial class Smoke : Node
var sionState = _main.Session.ViewState; var sionState = _main.Session.ViewState;
Check(_main.MapKind == ArenaMapKind.Sion && sionState.MapKind == ArenaMapKind.Sion, "Expected Sion map kind after Reset"); 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.Terrain.Visible && _main.SionMap.Visible, "Expected unified TerrainRenderer and SionMapRenderer buildings visible on Sion");
Check(_main.Terrain.BakedTileCount == 256, $"Expected 256 unified Sion terrain tiles (16x16), got {_main.Terrain.BakedTileCount}");
Check(_main.Terrain.ActiveGpuScarSlots == 0, $"Expected 0 active GPU scar slots on clean Sion start, got {_main.Terrain.ActiveGpuScarSlots}");
Check(_main.SionMap.IsBuilt, "Expected SionMapRenderer.IsBuilt == true"); 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.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.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}"); Check(_main.SionMap.ActiveLod2TileCount > 0, $"Expected > 0 LOD2 tiles in Sion valley, got {_main.SionMap.ActiveLod2TileCount}");
@ -1913,14 +1916,31 @@ public partial class Smoke : Node
float disp = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ)); 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"); Check(disp > 1.5f, $"Expected player displacement > 1.5m on Sion after 30 frames, got {disp:F2}m");
Color inBoundsTint = _main.SionMap.SampleGroundTint(player.X, player.Z); Color inBoundsTint = _main.Terrain.SampleGroundTint(player.X, player.Z);
Color outBoundsTint = _main.SionMap.SampleGroundTint(9999f, 9999f); Color outBoundsTint = _main.Terrain.SampleGroundTint(9999f, 9999f);
Check(float.IsFinite(inBoundsTint.R) && float.IsFinite(inBoundsTint.G) && float.IsFinite(inBoundsTint.B) && inBoundsTint.R > 0.1f, Check(float.IsFinite(inBoundsTint.R) && float.IsFinite(inBoundsTint.G) && float.IsFinite(inBoundsTint.B) && inBoundsTint.R > 0.1f,
$"Expected valid Sion SampleGroundTint at player pos, got {inBoundsTint}"); $"Expected valid Sion SampleGroundTint at player pos, got {inBoundsTint}");
Check(MathF.Abs(outBoundsTint.R - 0.56f) < 0.01f && MathF.Abs(outBoundsTint.G - 0.53f) < 0.01f, Check(MathF.Abs(outBoundsTint.R - 0.56f) < 0.01f && MathF.Abs(outBoundsTint.G - 0.53f) < 0.01f,
$"Expected neutral alpine fallback tint outside Sion bounds, got {outBoundsTint}"); $"Expected neutral alpine fallback tint outside Sion bounds, got {outBoundsTint}");
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, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))"); // Verify live crater brush on Sion allocates sparse GPU scar slot & depresses GPU height
float sionCpuPre = sionState.Terrain.SampleHeight(player.X, player.Z);
sionState.Terrain.StampCrater(player.X, player.Z, radius: 5.0f, depth: 1.5f);
_main.Terrain.Sync(sionState.Terrain, sionState.SionMap);
Check(_main.Terrain.ActiveGpuScarSlots >= 1, $"Expected >= 1 active GPU scar slot on Sion after crater, got {_main.Terrain.ActiveGpuScarSlots}");
if (DisplayServer.GetName() != "headless")
{
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
Check(_main.Terrain.TrySampleBakedHeight(player.X, player.Z, out float sionGpuPost),
"Expected TrySampleBakedHeight to succeed on Sion crater tile");
float sionCpuPost = sionState.Terrain.SampleHeight(player.X, player.Z);
Check(MathF.Abs(sionGpuPost - sionCpuPost) <= 0.25f,
$"Expected Sion GPU crater height ({sionGpuPost:F3}m) to match CPU ({sionCpuPost:F3}m) within 0.25m");
Check(sionGpuPost < sionCpuPre - 0.8f,
$"Expected Sion GPU crater height ({sionGpuPost:F3}m) to depress below pre-crater ({sionCpuPre:F3}m)");
}
GD.Print($"SMOKE INFO: Sion verified (terrainTiles={_main.Terrain.BakedTileCount}, gpuScarSlots={_main.Terrain.ActiveGpuScarSlots}, bldgTiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))");
} }
private async Task VerifyOrbitalDropSequenceAsync() private async Task VerifyOrbitalDropSequenceAsync()

View file

@ -0,0 +1,378 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
namespace RustToDust.Core
{
[MessagePackObject]
public sealed class TerrainScarEntry
{
[Key(0)] public byte Kind { get; set; }
[Key(1)] public float X { get; set; }
[Key(2)] public float Z { get; set; }
[Key(3)] public float Radius { get; set; }
[Key(4)] public float Depth { get; set; }
[Key(5)] public float Yaw { get; set; }
[Key(6)] public uint Rgb8 { get; set; }
[Key(7), CultElementId] public string ElementId { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class BuildingScarEntry
{
[Key(0)] public ushort BldgId { get; set; }
[Key(1)] public ulong CollapsedMask { get; set; }
[Key(2)] public ulong DamagedMask { get; set; }
[Key(3), CultElementId(nameof(BldgId))] public string ElementId { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class TreeScarEntry
{
[Key(0)] public ushort TreeId { get; set; }
[Key(1)] public byte State { get; set; }
[Key(2), CultElementId(nameof(TreeId))] public string ElementId { get; set; } = string.Empty;
}
[CultDocument("rtd.arena_scar_ledger", "1"), MessagePackObject]
public sealed class ArenaScarLedgerSnapshot
{
[CultName, Key(0)] public string AssetFingerprint { get; set; } = string.Empty;
[Key(1)] public List<TerrainScarEntry> Terrain { get; set; } = new();
[Key(2)] public List<BuildingScarEntry> Buildings { get; set; } = new();
[Key(3)] public List<TreeScarEntry> Trees { get; set; } = new();
[Key(4)] public uint LedgerRevision { get; set; }
}
public sealed class ArenaScarLedger
{
public const int MaxPersistentTerrainScars = 4096;
public const float CraterCoalesceRadiusMeters = 0.75f;
private readonly List<TerrainScarEntry> _terrain = new();
private readonly Dictionary<ushort, BuildingScarEntry> _buildings = new();
private readonly Dictionary<ushort, TreeScarEntry> _trees = new();
public ArenaScarLedger(string assetFingerprint = "")
{
AssetFingerprint = assetFingerprint;
}
public string AssetFingerprint { get; set; }
public uint LedgerRevision { get; private set; }
public bool IsDirty { get; set; }
public IReadOnlyList<TerrainScarEntry> Terrain => _terrain;
public IReadOnlyDictionary<ushort, BuildingScarEntry> Buildings => _buildings;
public IReadOnlyDictionary<ushort, TreeScarEntry> Trees => _trees;
public void RecordTerrainStamp(TerrainStampEvent stamp) =>
RecordTerrainStamp(stamp.Kind, stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw);
public void RecordTerrainStamp(byte kind, float x, float z, float radius, float depth, float yaw, uint rgb8 = 0)
{
var stampKind = (TerrainStampKind)kind;
if (stampKind == TerrainStampKind.Track)
{
return;
}
float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters;
if (stampKind == TerrainStampKind.Crater || stampKind == TerrainStampKind.Scorch)
{
for (int i = _terrain.Count - 1; i >= 0; i--)
{
var existing = _terrain[i];
if (existing.Kind != kind)
{
continue;
}
float dx = existing.X - x;
float dz = existing.Z - z;
if (dx * dx + dz * dz < coalesceSq)
{
existing.Radius = MathF.Max(existing.Radius, radius);
existing.Depth = MathF.Max(existing.Depth, depth);
LedgerRevision++;
IsDirty = true;
return;
}
}
}
if (_terrain.Count >= MaxPersistentTerrainScars)
{
int evictIdx = -1;
for (int i = 0; i < _terrain.Count; i++)
{
if (_terrain[i].Kind == (byte)TerrainStampKind.Scorch)
{
evictIdx = i;
break;
}
}
_terrain.RemoveAt(evictIdx >= 0 ? evictIdx : 0);
}
_terrain.Add(new TerrainScarEntry
{
Kind = kind,
X = x,
Z = z,
Radius = radius,
Depth = depth,
Yaw = yaw,
Rgb8 = rgb8
});
LedgerRevision++;
IsDirty = true;
}
public void Clear()
{
_terrain.Clear();
_buildings.Clear();
_trees.Clear();
LedgerRevision++;
IsDirty = true;
}
public ArenaScarLedgerSnapshot ToSnapshot()
{
var snap = new ArenaScarLedgerSnapshot
{
AssetFingerprint = AssetFingerprint,
LedgerRevision = LedgerRevision,
Terrain = new List<TerrainScarEntry>(_terrain.Count),
Buildings = new List<BuildingScarEntry>(_buildings.Count),
Trees = new List<TreeScarEntry>(_trees.Count)
};
for (int i = 0; i < _terrain.Count; i++)
{
var t = _terrain[i];
snap.Terrain.Add(new TerrainScarEntry
{
Kind = t.Kind,
X = t.X,
Z = t.Z,
Radius = t.Radius,
Depth = t.Depth,
Yaw = t.Yaw,
Rgb8 = t.Rgb8
});
}
foreach (var b in _buildings.Values)
{
snap.Buildings.Add(new BuildingScarEntry
{
BldgId = b.BldgId,
CollapsedMask = b.CollapsedMask,
DamagedMask = b.DamagedMask
});
}
foreach (var tr in _trees.Values)
{
snap.Trees.Add(new TreeScarEntry
{
TreeId = tr.TreeId,
State = tr.State
});
}
return snap;
}
public void LoadFromSnapshot(ArenaScarLedgerSnapshot snapshot)
{
_terrain.Clear();
_buildings.Clear();
_trees.Clear();
if (!string.IsNullOrEmpty(AssetFingerprint) &&
!string.Equals(snapshot.AssetFingerprint, AssetFingerprint, StringComparison.Ordinal))
{
return;
}
for (int i = 0; i < snapshot.Terrain.Count && i < MaxPersistentTerrainScars; i++)
{
var t = snapshot.Terrain[i];
_terrain.Add(new TerrainScarEntry
{
Kind = t.Kind,
X = t.X,
Z = t.Z,
Radius = t.Radius,
Depth = t.Depth,
Yaw = t.Yaw,
Rgb8 = t.Rgb8
});
}
for (int i = 0; i < snapshot.Buildings.Count; i++)
{
var b = snapshot.Buildings[i];
_buildings[b.BldgId] = new BuildingScarEntry
{
BldgId = b.BldgId,
CollapsedMask = b.CollapsedMask,
DamagedMask = b.DamagedMask
};
}
for (int i = 0; i < snapshot.Trees.Count; i++)
{
var tr = snapshot.Trees[i];
_trees[tr.TreeId] = new TreeScarEntry
{
TreeId = tr.TreeId,
State = tr.State
};
}
LedgerRevision = snapshot.LedgerRevision;
IsDirty = false;
}
public void ApplyToTerrain(TerrainField terrain)
{
for (int i = 0; i < _terrain.Count; i++)
{
var t = _terrain[i];
switch ((TerrainStampKind)t.Kind)
{
case TerrainStampKind.Crater:
terrain.StampCrater(t.X, t.Z, t.Radius, t.Depth);
break;
case TerrainStampKind.Scorch:
terrain.StampScorch(t.X, t.Z, t.Radius);
break;
case TerrainStampKind.Rubble:
terrain.StampRubble(t.X, t.Z, t.Radius, t.Depth, t.Yaw);
break;
}
}
}
public static byte[] CompressSnapshot(ArenaScarLedgerSnapshot snapshot)
{
byte[] raw = MessagePackSerializer.Serialize(snapshot);
using var ms = new MemoryStream();
using (var zlib = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true))
{
zlib.Write(raw, 0, raw.Length);
}
return ms.ToArray();
}
public static ArenaScarLedgerSnapshot DecompressSnapshot(byte[] compressed)
{
using var src = new MemoryStream(compressed);
using var zlib = new ZLibStream(src, CompressionMode.Decompress);
using var dst = new MemoryStream();
zlib.CopyTo(dst);
return MessagePackSerializer.Deserialize<ArenaScarLedgerSnapshot>(dst.ToArray());
}
}
public static class ArenaScarLedgerStore
{
public static CultDocumentRegistry Registry { get; } =
CultDocumentRegistry.ForTypes(new[] { typeof(ArenaScarLedgerSnapshot) });
public static CultRecordKey LedgerKey(string profile = "default") => new("scars:" + profile);
public static string GetDefaultPath(ArenaMapKind mapKind, string profile = "default")
{
string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (string.IsNullOrWhiteSpace(baseDir))
{
baseDir = AppContext.BaseDirectory;
}
string mapTag = mapKind == ArenaMapKind.Sion ? "sion" : "desert";
string safeProfile = string.IsNullOrWhiteSpace(profile) ? "default" : profile.Trim();
return Path.Combine(baseDir, "RustToDust", "scars", $"{mapTag}_scars_{safeProfile}.cultcache");
}
public static CultCache Open(string path, bool writable = false)
{
var options = new CultCacheOpenOptions
{
Registry = Registry,
ReadOnly = !writable,
FlushOnDispose = false,
StoreFlushOnDispose = false,
UseDirectoryStore = false
};
return CultCacheMessagePack.Create(path, options);
}
public static ArenaScarLedgerSnapshot Load(string path, string expectedAssetFingerprint)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
{
return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint };
}
try
{
using var cache = Open(path, writable: false);
var records = cache.GetAll<ArenaScarLedgerSnapshot>().ToArray();
if (records.Length == 0)
{
return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint };
}
var snap = records[0];
if (!string.IsNullOrEmpty(expectedAssetFingerprint) &&
!string.Equals(snap.AssetFingerprint, expectedAssetFingerprint, StringComparison.Ordinal))
{
return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint };
}
return snap;
}
catch
{
return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint };
}
}
public static void Save(string path, ArenaScarLedgerSnapshot snapshot, string profile = "default")
{
if (snapshot is null) throw new ArgumentNullException(nameof(snapshot));
if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Path cannot be empty.", nameof(path));
string fullPath = Path.GetFullPath(path);
string dir = Path.GetDirectoryName(fullPath) ?? ".";
Directory.CreateDirectory(dir);
string workspace = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
string tempFile = Path.Combine(workspace, "scars.cultcache");
try
{
Directory.CreateDirectory(workspace);
using (var cache = Open(tempFile, writable: true))
{
cache.UpsertAsync(typeof(ArenaScarLedgerSnapshot), snapshot, LedgerKey(profile)).GetAwaiter().GetResult();
cache.FlushAsync().GetAwaiter().GetResult();
}
if (File.Exists(fullPath))
{
File.Replace(tempFile, fullPath, null);
}
else
{
File.Move(tempFile, fullPath);
}
}
finally
{
if (Directory.Exists(workspace))
{
Directory.Delete(workspace, recursive: true);
}
}
}
}
}

View file

@ -352,7 +352,8 @@ namespace RustToDust.Core
ArenaMapKind mapKind = ArenaMapKind.Desert, ArenaMapKind mapKind = ArenaMapKind.Desert,
bool skipInitialDrop = false, bool skipInitialDrop = false,
bool startInLobby = false, bool startInLobby = false,
byte squadSize = 1) byte squadSize = 1,
ArenaScarLedgerSnapshot? initialScars = null)
{ {
Seed = seed; Seed = seed;
MapKind = mapKind; MapKind = mapKind;
@ -367,13 +368,21 @@ namespace RustToDust.Core
if (mapKind == ArenaMapKind.Sion) if (mapKind == ArenaMapKind.Sion)
{ {
SionMap = SionMapLoader.Load(); SionMap = SionMapLoader.Load();
Terrain = TerrainField.LoadHeightmap( Terrain = TerrainField.LoadSharedHeightmap(
SionMap.Metadata.SizeMeters, SionMap.Metadata.SizeMeters,
SionMap.Metadata.GridRes, SionMap.Metadata.GridRes,
SionMap.Heights, SionMap.Metadata.TileGrid,
SionMap.BaseDem,
SionMap.BaseDemMinY,
SionMap.BaseDemScale,
SionMap.Metadata.MinY, SionMap.Metadata.MinY,
SionMap.Metadata.MaxY, SionMap.Metadata.MaxY,
(ulong)seed); (ulong)seed);
ScarLedger = new ArenaScarLedger(SionMap.AssetFingerprint);
if (initialScars is not null)
{
ApplyPersistentScars(initialScars);
}
Spectators = new SpectatorRing( Spectators = new SpectatorRing(
seed + 101, seed + 101,
SpectatorRing.DefaultSpectatorCount, SpectatorRing.DefaultSpectatorCount,
@ -396,6 +405,11 @@ namespace RustToDust.Core
Spectators = new SpectatorRing(seed + 101); Spectators = new SpectatorRing(seed + 101);
var rawCover = BuildCoverBoxes(); var rawCover = BuildCoverBoxes();
Terrain = TerrainField.Generate((ulong)seed, rawCover); Terrain = TerrainField.Generate((ulong)seed, rawCover);
ScarLedger = new ArenaScarLedger($"desert:{seed}");
if (initialScars is not null)
{
ApplyPersistentScars(initialScars);
}
ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain); ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain);
ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f); ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f);
SpawnContenders(); SpawnContenders();
@ -531,7 +545,46 @@ namespace RustToDust.Core
public int? WinnerContenderId { get; set; } public int? WinnerContenderId { get; set; }
public TerrainField Terrain { get; } public TerrainField Terrain { get; }
public ArenaScarLedger ScarLedger { get; }
public List<ContenderState> Contenders { get; } = new(); public List<ContenderState> Contenders { get; } = new();
public void ApplyPersistentScars(ArenaScarLedgerSnapshot snapshot)
{
ScarLedger.LoadFromSnapshot(snapshot);
ScarLedger.ApplyToTerrain(Terrain);
}
public void ApplyTerrainStamp(TerrainStampEvent stamp, bool recordInLedger = true)
{
switch ((TerrainStampKind)stamp.Kind)
{
case TerrainStampKind.Crater:
Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth);
break;
case TerrainStampKind.Scorch:
Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius);
break;
case TerrainStampKind.Track:
Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length);
return;
case TerrainStampKind.Rubble:
Terrain.StampRubble(stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw);
break;
}
if (recordInLedger)
{
ScarLedger.RecordTerrainStamp(stamp);
}
}
public void RepairArenaScars()
{
Terrain.ClearDynamicScars();
ScarLedger.Clear();
}
public bool IsSolidBuildingAtXz(float x, float z, float padding = 0f) =>
SionMap is not null && SionMap.IsInsideAnyBuildingXz(x, z, padding);
public SpectatorRing Spectators { get; } public SpectatorRing Spectators { get; }
public List<GroundDrop> GroundDrops { get; } = new(); public List<GroundDrop> GroundDrops { get; } = new();
public List<TracerEvent> Tracers { get; } = new(); public List<TracerEvent> Tracers { get; } = new();

View file

@ -1475,8 +1475,21 @@ namespace RustToDust.Core
{ {
if (emitEvents && !touchSample.IsBuildingRoof) if (emitEvents && !touchSample.IsBuildingRoof)
{ {
_state.Terrain.StampCrater(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f, 0.32f); _state.ApplyTerrainStamp(new TerrainStampEvent
_state.Terrain.StampScorch(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f); {
Kind = (byte)TerrainStampKind.Crater,
X = pod.X,
Z = pod.Z,
Radius = pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f,
Depth = 0.32f
});
_state.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Scorch,
X = pod.X,
Z = pod.Z,
Radius = pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f
});
} }
// Re-sample ground height after crater stamp // Re-sample ground height after crater stamp

View file

@ -8,7 +8,8 @@ namespace RustToDust.Core
{ {
Crater = 0, Crater = 0,
Scorch = 1, Scorch = 1,
Track = 2 Track = 2,
Rubble = 3
} }
public enum SlotControlReason : byte public enum SlotControlReason : byte
@ -34,6 +35,7 @@ namespace RustToDust.Core
[Union(12, typeof(DropPodEvent))] [Union(12, typeof(DropPodEvent))]
[Union(13, typeof(OrdnanceNodeEvent))] [Union(13, typeof(OrdnanceNodeEvent))]
[Union(14, typeof(MatchStartedEvent))] [Union(14, typeof(MatchStartedEvent))]
[Union(17, typeof(ArenaRepairEvent))]
public interface ISimEvent public interface ISimEvent
{ {
} }
@ -323,6 +325,7 @@ namespace RustToDust.Core
[Key(15)] public LobbySnapshotDto? Lobby { get; set; } [Key(15)] public LobbySnapshotDto? Lobby { get; set; }
[Key(16)] public byte SquadSize { get; set; } = 1; [Key(16)] public byte SquadSize { get; set; } = 1;
[Key(17)] public byte[]? ContenderSquadIds { get; set; } [Key(17)] public byte[]? ContenderSquadIds { get; set; }
[Key(18)] public byte[]? PersistentScars { get; set; }
} }
[MessagePackObject] [MessagePackObject]
@ -381,6 +384,7 @@ namespace RustToDust.Core
[Union(12, typeof(LobbySnapshotMsg))] [Union(12, typeof(LobbySnapshotMsg))]
[Union(13, typeof(ClientKeepaliveMsg))] [Union(13, typeof(ClientKeepaliveMsg))]
[Union(14, typeof(LobbySquadCmdMsg))] [Union(14, typeof(LobbySquadCmdMsg))]
[Union(15, typeof(RepairArenaCmdMsg))]
public interface ISchemaWireMessage public interface ISchemaWireMessage
{ {
} }
@ -499,6 +503,18 @@ namespace RustToDust.Core
[Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new(); [Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new();
} }
[MessagePackObject]
public sealed class ArenaRepairEvent : ISimEvent
{
[Key(0)] public uint LedgerRevision { get; set; }
}
[MessagePackObject]
public sealed class RepairArenaCmdMsg : ISchemaWireMessage
{
[Key(0)] public uint ReqSeq { get; set; }
}
[MessagePackObject] [MessagePackObject]
public sealed class ClientKeepaliveMsg : ISchemaWireMessage public sealed class ClientKeepaliveMsg : ISchemaWireMessage
{ {

View file

@ -2,6 +2,7 @@ using System;
using System.Buffers.Binary; using System.Buffers.Binary;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.IO.Compression;
using System.Numerics; using System.Numerics;
using System.Text.Json; using System.Text.Json;
@ -29,7 +30,14 @@ namespace RustToDust.Core
float MinY, float MinY,
float MaxY, float MaxY,
string SurfaceTexture, string SurfaceTexture,
IReadOnlyList<SionTileMeta> Tiles); IReadOnlyList<SionTileMeta> Tiles,
string DemAssetHash = "",
string HeightmapFile = "heightmap_05m.u16z",
float HeightmapMinY = 0f,
float HeightmapScale = 1f,
string SurfaceMaskTexture = "terrain_surface_mask.png",
int BuildingTileGrid = 6,
float BuildingTileSizeMeters = 512f);
public readonly record struct SionBuildingAabb( public readonly record struct SionBuildingAabb(
string Id, string Id,
@ -76,7 +84,7 @@ namespace RustToDust.Core
{ {
private const int SpatialGridRes = 64; private const int SpatialGridRes = 64;
private readonly float[] _heights; private readonly ushort[] _baseDem;
private readonly SionBuildingAabb[] _buildings; private readonly SionBuildingAabb[] _buildings;
private readonly List<int>[] _cellBuildings; private readonly List<int>[] _cellBuildings;
private readonly float[] _cellMinGroundY; private readonly float[] _cellMinGroundY;
@ -87,13 +95,20 @@ namespace RustToDust.Core
internal SionMapData( internal SionMapData(
string directoryPath, string directoryPath,
SionMetadata metadata, SionMetadata metadata,
float[] heights, ushort[] baseDem,
float baseDemMinY,
float baseDemScale,
SionBuildingAabb[] buildings, SionBuildingAabb[] buildings,
SionCollisionMesh[] collisionMeshes) SionCollisionMesh[] collisionMeshes)
{ {
DirectoryPath = directoryPath; DirectoryPath = directoryPath;
Metadata = metadata; Metadata = metadata;
_heights = heights; _baseDem = baseDem;
BaseDemMinY = baseDemMinY;
BaseDemScale = baseDemScale;
AssetFingerprint = !string.IsNullOrWhiteSpace(metadata.DemAssetHash)
? $"sion:{metadata.DemAssetHash}"
: $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}";
_buildings = buildings; _buildings = buildings;
CollisionMeshes = collisionMeshes; CollisionMeshes = collisionMeshes;
@ -131,7 +146,11 @@ namespace RustToDust.Core
public string DirectoryPath { get; } public string DirectoryPath { get; }
public SionMetadata Metadata { get; } public SionMetadata Metadata { get; }
public ReadOnlySpan<float> Heights => _heights; public ushort[] BaseDem => _baseDem;
public float BaseDemMinY { get; }
public float BaseDemScale { get; }
public string AssetFingerprint { get; }
public float SampleBaseDemAtIndex(int index) => BaseDemMinY + _baseDem[index] * BaseDemScale;
public IReadOnlyList<SionBuildingAabb> Buildings => _buildings; public IReadOnlyList<SionBuildingAabb> Buildings => _buildings;
public IReadOnlyList<SionCollisionMesh> CollisionMeshes { get; } public IReadOnlyList<SionCollisionMesh> CollisionMeshes { get; }
@ -324,12 +343,12 @@ namespace RustToDust.Core
AssetPathResolver.LocateSubdirectory( AssetPathResolver.LocateSubdirectory(
Path.Combine("maps", "sion"), Path.Combine("maps", "sion"),
IsValidSionDirectory, IsValidSionDirectory,
"containing metadata.json and heightmap.f32"); "containing metadata.json and heightmap_05m.u16z");
private static bool IsValidSionDirectory(string dir) => private static bool IsValidSionDirectory(string dir) =>
Directory.Exists(dir) && Directory.Exists(dir) &&
File.Exists(Path.Combine(dir, "metadata.json")) && File.Exists(Path.Combine(dir, "metadata.json")) &&
File.Exists(Path.Combine(dir, "heightmap.f32")) && File.Exists(Path.Combine(dir, "heightmap_05m.u16z")) &&
File.Exists(Path.Combine(dir, "buildings_manifest.json")); File.Exists(Path.Combine(dir, "buildings_manifest.json"));
public static SionMapData Load(string? sionDirectory = null) public static SionMapData Load(string? sionDirectory = null)
@ -344,7 +363,12 @@ namespace RustToDust.Core
} }
var meta = LoadMetadata(Path.Combine(root, "metadata.json")); var meta = LoadMetadata(Path.Combine(root, "metadata.json"));
float[] heights = LoadHeightmap(Path.Combine(root, "heightmap.f32"), meta.GridRes); string hmFile = string.IsNullOrWhiteSpace(meta.HeightmapFile) ? "heightmap_05m.u16z" : meta.HeightmapFile;
ushort[] baseDem = LoadHeightmapU16z(
Path.Combine(root, hmFile),
meta.GridRes,
out float demMinY,
out float demScale);
SionBuildingAabb[] buildings = LoadBuildingsManifest(Path.Combine(root, "buildings_manifest.json")); SionBuildingAabb[] buildings = LoadBuildingsManifest(Path.Combine(root, "buildings_manifest.json"));
var colMeshes = new SionCollisionMesh[meta.Tiles.Count]; var colMeshes = new SionCollisionMesh[meta.Tiles.Count];
for (int i = 0; i < meta.Tiles.Count; i++) for (int i = 0; i < meta.Tiles.Count; i++)
@ -354,7 +378,7 @@ namespace RustToDust.Core
colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz); colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz);
} }
var data = new SionMapData(root, meta, heights, buildings, colMeshes); var data = new SionMapData(root, meta, baseDem, demMinY, demScale, buildings, colMeshes);
lock (CacheLock) lock (CacheLock)
{ {
Cache[root] = data; Cache[root] = data;
@ -395,29 +419,82 @@ namespace RustToDust.Core
MinY: r.GetProperty("minY").GetSingle(), MinY: r.GetProperty("minY").GetSingle(),
MaxY: r.GetProperty("maxY").GetSingle(), MaxY: r.GetProperty("maxY").GetSingle(),
SurfaceTexture: r.GetProperty("surfaceTexture").GetString() ?? "terrain_surface.png", SurfaceTexture: r.GetProperty("surfaceTexture").GetString() ?? "terrain_surface.png",
Tiles: tiles); Tiles: tiles,
DemAssetHash: r.TryGetProperty("demAssetHash", out var dh) ? (dh.GetString() ?? "") : "",
HeightmapFile: r.TryGetProperty("heightmapFile", out var hf) ? (hf.GetString() ?? "heightmap_05m.u16z") : "heightmap_05m.u16z",
HeightmapMinY: r.TryGetProperty("heightmapMinY", out var hmin) ? hmin.GetSingle() : 0f,
HeightmapScale: r.TryGetProperty("heightmapScale", out var hsc) ? hsc.GetSingle() : 1f,
SurfaceMaskTexture: r.TryGetProperty("surfaceMaskTexture", out var sm) ? (sm.GetString() ?? "terrain_surface_mask.png") : "terrain_surface_mask.png",
BuildingTileGrid: r.TryGetProperty("buildingTileGrid", out var btg) ? btg.GetInt32() : 6,
BuildingTileSizeMeters: r.TryGetProperty("buildingTileSizeMeters", out var bts) ? bts.GetSingle() : 512f);
} }
private static float[] LoadHeightmap(string path, int gridRes) private static ushort[] LoadHeightmapU16z(string path, int expectedGridRes, out float minY, out float scale)
{ {
byte[] raw = File.ReadAllBytes(path); byte[] fileBytes = File.ReadAllBytes(path);
int expectedCount = gridRes * gridRes; if (fileBytes.Length < 24)
if (raw.Length != expectedCount * 4)
{ {
throw new InvalidDataException( throw new InvalidDataException($"Heightmap file '{path}' too small ({fileBytes.Length} bytes).");
$"Expected heightmap.f32 byte length {expectedCount * 4} ({gridRes}x{gridRes}), got {raw.Length}.");
} }
var heights = new float[expectedCount]; ReadOnlySpan<byte> hdr = fileBytes.AsSpan(0, 24);
ReadOnlySpan<byte> span = raw; if (hdr[0] != (byte)'R' || hdr[1] != (byte)'D' || hdr[2] != (byte)'H' || hdr[3] != (byte)'M')
for (int i = 0; i < expectedCount; i++)
{ {
float v = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(i * 4, 4)); throw new InvalidDataException($"Invalid RDHM magic in '{path}'.");
if (!float.IsFinite(v)) }
uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4));
if (version != 2)
{
throw new InvalidDataException($"Unsupported RDHM version {version} in '{path}'.");
}
int gridRes = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(8, 4)));
if (gridRes != expectedGridRes)
{
throw new InvalidDataException($"RDHM gridRes mismatch in '{path}': header={gridRes}, metadata={expectedGridRes}.");
}
minY = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(12, 4));
scale = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(16, 4));
int rawByteCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(20, 4)));
int expectedSamples = gridRes * gridRes;
if (rawByteCount != expectedSamples * 2)
{
throw new InvalidDataException($"RDHM rawByteCount mismatch in '{path}': {rawByteCount} != {expectedSamples * 2}.");
}
byte[] raw = new byte[rawByteCount];
using (var ms = new MemoryStream(fileBytes, 24, fileBytes.Length - 24, writable: false))
using (var zlib = new ZLibStream(ms, CompressionMode.Decompress))
{
int totalRead = 0;
while (totalRead < rawByteCount)
{ {
throw new InvalidDataException($"Non-finite heightmap value at index {i}: {v}"); int read = zlib.Read(raw, totalRead, rawByteCount - totalRead);
if (read <= 0)
{
throw new InvalidDataException($"Unexpected EOF decompressing RDHM payload in '{path}' at {totalRead}/{rawByteCount}.");
}
totalRead += read;
}
}
var heights = new ushort[expectedSamples];
ReadOnlySpan<byte> span = raw;
for (int r = 0; r < gridRes; r++)
{
int rowStart = r * gridRes;
ushort pred = r > 0 ? heights[(r - 1) * gridRes] : (ushort)0;
for (int c = 0; c < gridRes; c++)
{
int idx = rowStart + c;
ushort zz = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(idx * 2, 2));
short d = unchecked((short)((zz >> 1) ^ -(zz & 1)));
ushort val = unchecked((ushort)(pred + d));
heights[idx] = val;
pred = val;
} }
heights[i] = v;
} }
return heights; return heights;
} }

View file

@ -11,7 +11,8 @@ namespace RustToDust.Core
Road, Road,
Crater, Crater,
Track, Track,
Scorch Scorch,
Rubble
} }
public readonly record struct TerrainBrush( public readonly record struct TerrainBrush(
@ -34,8 +35,8 @@ namespace RustToDust.Core
{ {
public const float ArenaSize = 1536f; public const float ArenaSize = 1536f;
public const float HalfExtent = 768f; public const float HalfExtent = 768f;
public const int TileGridCount = 8; public const int DesertTileGridCount = 8;
public const float TileSize = ArenaSize / TileGridCount; // 192m public const float TileSize = ArenaSize / DesertTileGridCount; // 192m
private const int AccelGridCount = 64; private const int AccelGridCount = 64;
private const int AccelCellCount = AccelGridCount * AccelGridCount; private const int AccelCellCount = AccelGridCount * AccelGridCount;
public const float MinWorldHeight = -18f; public const float MinWorldHeight = -18f;
@ -64,21 +65,33 @@ namespace RustToDust.Core
private readonly List<TerrainBrush> _brushes = new(); private readonly List<TerrainBrush> _brushes = new();
private readonly List<BrushPrecomp> _brushPrecomps = new(); private readonly List<BrushPrecomp> _brushPrecomps = new();
private readonly List<int>[,] _tileBrushIndices = new List<int>[TileGridCount, TileGridCount]; private readonly List<int>[,] _tileBrushIndices;
private readonly List<int>[] _cellBrushIndices = new List<int>[AccelCellCount]; private readonly List<int>[] _cellBrushIndices = new List<int>[AccelCellCount];
private readonly float[] _cellMaxHeight = new float[AccelCellCount]; private readonly float[] _cellMaxHeight = new float[AccelCellCount];
private readonly float[] _cellBaseMaxHeight = new float[AccelCellCount]; private readonly float[] _cellBaseMaxHeight = new float[AccelCellCount];
private readonly Queue<int> _dynamicDecalSlots = new(); private readonly Queue<int> _dynamicDecalSlots = new();
private float[]? _heightmap; private float[]? _heightmap;
private ushort[]? _sharedU16Heights;
private float _baseMinY;
private float _baseScale;
private readonly float[]?[,] _scarredTileHeights;
private int _nextBrushId = 1; private int _nextBrushId = 1;
public TerrainField(ulong seed) public TerrainField(ulong seed, int tileGridCount = DesertTileGridCount)
{ {
Seed = seed; if (tileGridCount <= 0)
TileVersions = new int[TileGridCount, TileGridCount];
for (int tz = 0; tz < TileGridCount; tz++)
{ {
for (int tx = 0; tx < TileGridCount; tx++) throw new ArgumentOutOfRangeException(nameof(tileGridCount));
}
Seed = seed;
TileGridCount = tileGridCount;
StructuralTileVersions = new int[tileGridCount, tileGridCount];
VisualTileVersions = new int[tileGridCount, tileGridCount];
_tileBrushIndices = new List<int>[tileGridCount, tileGridCount];
_scarredTileHeights = new float[tileGridCount, tileGridCount][];
for (int tz = 0; tz < tileGridCount; tz++)
{
for (int tx = 0; tx < tileGridCount; tx++)
{ {
_tileBrushIndices[tx, tz] = new List<int>(32); _tileBrushIndices[tx, tz] = new List<int>(32);
} }
@ -90,6 +103,7 @@ namespace RustToDust.Core
} }
public ulong Seed { get; } public ulong Seed { get; }
public int TileGridCount { get; }
public bool IsHeightmapMode { get; private set; } public bool IsHeightmapMode { get; private set; }
public float MapSize { get; private set; } = ArenaSize; public float MapSize { get; private set; } = ArenaSize;
public float MapHalfExtent { get; private set; } = HalfExtent; public float MapHalfExtent { get; private set; } = HalfExtent;
@ -98,11 +112,15 @@ namespace RustToDust.Core
public float MapMaxHeight { get; private set; } = MaxWorldHeight; public float MapMaxHeight { get; private set; } = MaxWorldHeight;
public int HeightmapRes { get; private set; } public int HeightmapRes { get; private set; }
public float HeightmapCellSize { get; private set; } public float HeightmapCellSize { get; private set; }
public int PhysicsTileResolution => IsHeightmapMode ? ((HeightmapRes - 1) / TileGridCount + 1) : 0;
public ushort[]? SharedU16Heights => _sharedU16Heights;
public float BaseMinY => _baseMinY;
public float BaseScale => _baseScale;
private float AccelCellSize => MapSize / AccelGridCount; private float AccelCellSize => MapSize / AccelGridCount;
public IReadOnlyList<TerrainBrush> Brushes => _brushes; public IReadOnlyList<TerrainBrush> Brushes => _brushes;
public int[,] TileVersions { get; } public int[,] StructuralTileVersions { get; }
public ulong DirtyTileMask { get; private set; } public int[,] VisualTileVersions { get; }
public ulong StructuralDirtyTileMask { get; private set; } public int[,] TileVersions => VisualTileVersions;
public static TerrainField LoadHeightmap( public static TerrainField LoadHeightmap(
float sizeMeters, float sizeMeters,
@ -125,12 +143,13 @@ namespace RustToDust.Core
throw new ArgumentException($"Expected {gridRes * gridRes} height samples, got {heights.Length}.", nameof(heights)); throw new ArgumentException($"Expected {gridRes * gridRes} height samples, got {heights.Length}.", nameof(heights));
} }
var field = new TerrainField(seed) int tileGridCount = Math.Max(1, (int)MathF.Round(sizeMeters / TileSize));
var field = new TerrainField(seed, tileGridCount)
{ {
IsHeightmapMode = true, IsHeightmapMode = true,
MapSize = sizeMeters, MapSize = sizeMeters,
MapHalfExtent = sizeMeters * 0.5f, MapHalfExtent = sizeMeters * 0.5f,
MapTileSize = sizeMeters / TileGridCount, MapTileSize = sizeMeters / tileGridCount,
MapMinHeight = minY - 8f, MapMinHeight = minY - 8f,
MapMaxHeight = maxY + 4f, MapMaxHeight = maxY + 4f,
HeightmapRes = gridRes, HeightmapRes = gridRes,
@ -138,9 +157,58 @@ namespace RustToDust.Core
_heightmap = heights.ToArray() _heightmap = heights.ToArray()
}; };
float half = field.MapHalfExtent; field.InitializeAccelGridFromHeightmap(gridRes);
float cellSize = field.AccelCellSize; return field;
float invDemStep = 1f / field.HeightmapCellSize; }
public static TerrainField LoadSharedHeightmap(
float sizeMeters,
int gridRes,
int tileGridCount,
ushort[] sharedU16Heights,
float baseMinY,
float baseScale,
float worldMinY,
float worldMaxY,
ulong seed = 0UL)
{
if (sizeMeters <= 0f || !float.IsFinite(sizeMeters))
{
throw new ArgumentOutOfRangeException(nameof(sizeMeters));
}
if (gridRes < 2)
{
throw new ArgumentOutOfRangeException(nameof(gridRes));
}
if (sharedU16Heights is null || sharedU16Heights.Length != gridRes * gridRes)
{
throw new ArgumentException($"Expected {gridRes * gridRes} u16 height samples, got {sharedU16Heights?.Length ?? 0}.", nameof(sharedU16Heights));
}
var field = new TerrainField(seed, tileGridCount)
{
IsHeightmapMode = true,
MapSize = sizeMeters,
MapHalfExtent = sizeMeters * 0.5f,
MapTileSize = sizeMeters / tileGridCount,
MapMinHeight = worldMinY - 8f,
MapMaxHeight = worldMaxY + 4f,
HeightmapRes = gridRes,
HeightmapCellSize = sizeMeters / (gridRes - 1),
_sharedU16Heights = sharedU16Heights,
_baseMinY = baseMinY,
_baseScale = baseScale
};
field.InitializeAccelGridFromHeightmap(gridRes);
return field;
}
private void InitializeAccelGridFromHeightmap(int gridRes)
{
float half = MapHalfExtent;
float cellSize = AccelCellSize;
float invDemStep = 1f / HeightmapCellSize;
for (int cz = 0; cz < AccelGridCount; cz++) for (int cz = 0; cz < AccelGridCount; cz++)
{ {
@ -162,7 +230,9 @@ namespace RustToDust.Core
int row = iz * gridRes; int row = iz * gridRes;
for (int ix = ix0; ix <= ix1; ix++) for (int ix = ix0; ix <= ix1; ix++)
{ {
float h = field._heightmap[row + ix]; float h = _sharedU16Heights is not null
? _baseMinY + _sharedU16Heights[row + ix] * _baseScale
: _heightmap![row + ix];
if (h > cellMax) if (h > cellMax)
{ {
cellMax = h; cellMax = h;
@ -172,8 +242,8 @@ namespace RustToDust.Core
int cellIdx = cz * AccelGridCount + cx; int cellIdx = cz * AccelGridCount + cx;
float boundedMax = float.IsNegativeInfinity(cellMax) ? 0f : cellMax + 0.05f; float boundedMax = float.IsNegativeInfinity(cellMax) ? 0f : cellMax + 0.05f;
field._cellBaseMaxHeight[cellIdx] = boundedMax; _cellBaseMaxHeight[cellIdx] = boundedMax;
field._cellMaxHeight[cellIdx] = boundedMax; _cellMaxHeight[cellIdx] = boundedMax;
} }
} }
@ -181,23 +251,12 @@ namespace RustToDust.Core
{ {
for (int tx = 0; tx < TileGridCount; tx++) for (int tx = 0; tx < TileGridCount; tx++)
{ {
field.TileVersions[tx, tz] = 1; StructuralTileVersions[tx, tz] = 1;
field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx); VisualTileVersions[tx, tz] = 1;
} }
} }
return field;
} }
public void ClearDirtyMask()
{
DirtyTileMask = 0UL;
StructuralDirtyTileMask = 0UL;
}
public void ClearStructuralDirtyTile(int tx, int tz) =>
StructuralDirtyTileMask &= ~(1UL << (tz * TileGridCount + tx));
public IReadOnlyList<int> GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz]; public IReadOnlyList<int> GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz];
public static TerrainField Generate(ulong seed, IReadOnlyList<ArenaBoxSpec> coverBoxes) public static TerrainField Generate(ulong seed, IReadOnlyList<ArenaBoxSpec> coverBoxes)
@ -400,12 +459,12 @@ namespace RustToDust.Core
} }
// Bump all initial tile versions to 1 so clients detect initial bake needed // Bump all initial tile versions to 1 so clients detect initial bake needed
for (int tz = 0; tz < TileGridCount; tz++) for (int tz = 0; tz < field.TileGridCount; tz++)
{ {
for (int tx = 0; tx < TileGridCount; tx++) for (int tx = 0; tx < field.TileGridCount; tx++)
{ {
field.TileVersions[tx, tz] = 1; field.StructuralTileVersions[tx, tz] = 1;
field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx); field.VisualTileVersions[tx, tz] = 1;
} }
} }
@ -433,6 +492,27 @@ namespace RustToDust.Core
Dynamic: true)); Dynamic: true));
} }
public void StampRubble(float x, float z, float radius, float heightDelta, float yaw = 0f)
{
float clampedR = Math.Clamp(radius, 1.5f, 18f);
float clampedH = Math.Clamp(MathF.Abs(heightDelta), 0.15f, 2.5f);
AddBrush(new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.Rubble,
X: x,
Z: z,
RotationRad: yaw,
RadiusX: clampedR,
RadiusZ: clampedR,
HeightDelta: clampedH,
Roughness: 0.97f,
Metallic: 0.05f,
AlbedoR: 0.42f,
AlbedoG: 0.39f,
AlbedoB: 0.35f,
Dynamic: true));
}
public void StampTrack(float x, float z, float yaw, float width, float length) public void StampTrack(float x, float z, float yaw, float width, float length)
{ {
SetDynamicDecal(new TerrainBrush( SetDynamicDecal(new TerrainBrush(
@ -472,13 +552,30 @@ namespace RustToDust.Core
Dynamic: true)); Dynamic: true));
} }
public float SampleHeight(float x, float z) public float SampleBaseHeight(float x, float z)
{ {
float half = MapHalfExtent; float half = MapHalfExtent;
float cx = Math.Clamp(x, -half, half); float cx = Math.Clamp(x, -half, half);
float cz = Math.Clamp(z, -half, half); float cz = Math.Clamp(z, -half, half);
float h = 0f; if (_sharedU16Heights 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 = _baseMinY + _sharedU16Heights[row0 + ix] * _baseScale;
float h10 = _baseMinY + _sharedU16Heights[row0 + ix + 1] * _baseScale;
float h01 = _baseMinY + _sharedU16Heights[row1 + ix] * _baseScale;
float h11 = _baseMinY + _sharedU16Heights[row1 + ix + 1] * _baseScale;
return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz;
}
if (_heightmap is not null) if (_heightmap is not null)
{ {
int res = HeightmapRes; int res = HeightmapRes;
@ -494,9 +591,20 @@ namespace RustToDust.Core
float h10 = _heightmap[row0 + ix + 1]; float h10 = _heightmap[row0 + ix + 1];
float h01 = _heightmap[row1 + ix]; float h01 = _heightmap[row1 + ix];
float h11 = _heightmap[row1 + ix + 1]; float h11 = _heightmap[row1 + ix + 1];
h = (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz;
} }
return 0f;
}
public float SampleHeight(float x, float z)
{
float half = MapHalfExtent;
float cx = Math.Clamp(x, -half, half);
float cz = Math.Clamp(z, -half, half);
float h = SampleBaseHeight(cx, cz);
WorldToAccelCell(cx, cz, out int acx, out int acz); WorldToAccelCell(cx, cz, out int acx, out int acz);
var indices = _cellBrushIndices[acz * AccelGridCount + acx]; var indices = _cellBrushIndices[acz * AccelGridCount + acx];
for (int i = 0; i < indices.Count; i++) for (int i = 0; i < indices.Count; i++)
@ -509,6 +617,165 @@ namespace RustToDust.Core
return Math.Clamp(h, MapMinHeight, MapMaxHeight); return Math.Clamp(h, MapMinHeight, MapMaxHeight);
} }
public void ExtractTilePhysicsHeights(int tx, int tz, Span<float> dst, out float minY, out float maxY)
{
if ((uint)tx >= (uint)TileGridCount || (uint)tz >= (uint)TileGridCount)
{
throw new ArgumentOutOfRangeException(nameof(tx));
}
if (!IsHeightmapMode)
{
throw new InvalidOperationException("ExtractTilePhysicsHeights requires heightmap mode.");
}
int samplesPerTile = (HeightmapRes - 1) / TileGridCount;
int side = samplesPerTile + 1;
int count = side * side;
if (dst.Length < count)
{
throw new ArgumentException($"Destination span too small: need {count}, got {dst.Length}.", nameof(dst));
}
int gx0 = tx * samplesPerTile;
int gz0 = tz * samplesPerTile;
var tileBrushes = _tileBrushIndices[tx, tz];
bool hasStructuralBrushes = false;
for (int i = 0; i < tileBrushes.Count; i++)
{
var k = _brushes[tileBrushes[i]].Kind;
if (k != TerrainBrushKind.Track && k != TerrainBrushKind.Scorch)
{
hasStructuralBrushes = true;
break;
}
}
float minVal = float.PositiveInfinity;
float maxVal = float.NegativeInfinity;
float half = MapHalfExtent;
float step = HeightmapCellSize;
int res = HeightmapRes;
for (int lz = 0; lz < side; lz++)
{
int gz = gz0 + lz;
int globalRow = gz * res + gx0;
int localRow = lz * side;
float wz = -half + gz * step;
for (int lx = 0; lx < side; lx++)
{
float h = _sharedU16Heights is not null
? _baseMinY + _sharedU16Heights[globalRow + lx] * _baseScale
: _heightmap![globalRow + lx];
if (hasStructuralBrushes)
{
float wx = -half + (gx0 + lx) * step;
for (int bi = 0; bi < tileBrushes.Count; bi++)
{
int bIdx = tileBrushes[bi];
var b = _brushes[bIdx];
if (b.Kind == TerrainBrushKind.Track || b.Kind == TerrainBrushKind.Scorch)
{
continue;
}
h += EvaluateBrushHeightFast(in b, _brushPrecomps[bIdx], wx, wz);
}
}
float clamped = Math.Clamp(h, MapMinHeight, MapMaxHeight);
dst[localRow + lx] = clamped;
if (clamped < minVal) minVal = clamped;
if (clamped > maxVal) maxVal = clamped;
}
}
if (hasStructuralBrushes)
{
var cached = _scarredTileHeights[tx, tz];
if (cached is null || cached.Length != count)
{
cached = new float[count];
_scarredTileHeights[tx, tz] = cached;
}
dst.Slice(0, count).CopyTo(cached);
}
else
{
_scarredTileHeights[tx, tz] = null;
}
minY = float.IsPositiveInfinity(minVal) ? 0f : minVal;
maxY = float.IsNegativeInfinity(maxVal) ? 0f : maxVal;
}
public void ClearDynamicScars()
{
if (_brushes.Count == 0)
{
return;
}
bool anyDynamic = false;
var staticBrushes = new List<TerrainBrush>(_brushes.Count);
for (int i = 0; i < _brushes.Count; i++)
{
if (_brushes[i].Dynamic)
{
anyDynamic = true;
GetBrushTileBounds(_brushes[i], out int minTx, out int maxTx, out int minTz, out int maxTz);
bool isStructural = _brushes[i].Kind != TerrainBrushKind.Track && _brushes[i].Kind != TerrainBrushKind.Scorch;
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
VisualTileVersions[tx, tz]++;
if (isStructural)
{
StructuralTileVersions[tx, tz]++;
}
_scarredTileHeights[tx, tz] = null;
}
}
}
else
{
staticBrushes.Add(_brushes[i]);
}
}
if (!anyDynamic)
{
return;
}
_brushes.Clear();
_brushPrecomps.Clear();
_dynamicDecalSlots.Clear();
for (int tz = 0; tz < TileGridCount; tz++)
{
for (int tx = 0; tx < TileGridCount; tx++)
{
_tileBrushIndices[tx, tz].Clear();
}
}
for (int c = 0; c < AccelCellCount; c++)
{
_cellBrushIndices[c].Clear();
_cellMaxHeight[c] = _cellBaseMaxHeight[c];
}
for (int i = 0; i < staticBrushes.Count; i++)
{
int idx = _brushes.Count;
var b = staticBrushes[i];
_brushes.Add(b);
_brushPrecomps.Add(BrushPrecomp.From(in b));
RegisterBrushInTiles(idx, in b, incrementTileVersion: false);
}
}
public (float Nx, float Ny, float Nz) SampleNormal(float x, float z) public (float Nx, float Ny, float Nz) SampleNormal(float x, float z)
{ {
const float eps = 0.5f; const float eps = 0.5f;
@ -723,6 +990,13 @@ namespace RustToDust.Core
float rim = (0.32f * depth) * rimT * rimT; float rim = (0.32f * depth) * rimT * rimT;
return pit + rim; return pit + rim;
} }
case TerrainBrushKind.Rubble:
{
float env = 1f - r2;
env *= env;
float mound = 0.72f + 0.28f * MathF.Cos(u * MathF.PI * 2.5f);
return b.HeightDelta * env * mound;
}
default: default:
return 0f; return 0f;
} }
@ -854,6 +1128,12 @@ namespace RustToDust.Core
case TerrainBrushKind.Crater: case TerrainBrushKind.Crater:
cellMaxPositiveHeight = 0.33f * MathF.Abs(b.HeightDelta); cellMaxPositiveHeight = 0.33f * MathF.Abs(b.HeightDelta);
break; break;
case TerrainBrushKind.Rubble:
{
float env = 1f - minR2;
cellMaxPositiveHeight = MathF.Max(0f, b.HeightDelta) * env * env;
break;
}
default: default:
cellMaxPositiveHeight = 0f; cellMaxPositiveHeight = 0f;
break; break;
@ -889,12 +1169,11 @@ namespace RustToDust.Core
_tileBrushIndices[tx, tz].Add(index); _tileBrushIndices[tx, tz].Add(index);
if (incrementTileVersion) if (incrementTileVersion)
{ {
TileVersions[tx, tz]++; VisualTileVersions[tx, tz]++;
ulong bit = 1UL << (tz * TileGridCount + tx);
DirtyTileMask |= bit;
if (isStructural) if (isStructural)
{ {
StructuralDirtyTileMask |= bit; StructuralTileVersions[tx, tz]++;
_scarredTileHeights[tx, tz] = null;
} }
} }
} }
@ -928,12 +1207,11 @@ namespace RustToDust.Core
for (int tx = minTx; tx <= maxTx; tx++) for (int tx = minTx; tx <= maxTx; tx++)
{ {
_tileBrushIndices[tx, tz].Remove(index); _tileBrushIndices[tx, tz].Remove(index);
TileVersions[tx, tz]++; VisualTileVersions[tx, tz]++;
ulong bit = 1UL << (tz * TileGridCount + tx);
DirtyTileMask |= bit;
if (isStructural) if (isStructural)
{ {
StructuralDirtyTileMask |= bit; StructuralTileVersions[tx, tz]++;
_scarredTileHeights[tx, tz] = null;
} }
} }
} }
@ -997,8 +1275,8 @@ namespace RustToDust.Core
{ {
float nx = (x + HalfExtent) / TileSize; float nx = (x + HalfExtent) / TileSize;
float nz = (z + HalfExtent) / TileSize; float nz = (z + HalfExtent) / TileSize;
tx = Math.Clamp((int)MathF.Floor(nx), 0, TileGridCount - 1); tx = Math.Clamp((int)MathF.Floor(nx), 0, DesertTileGridCount - 1);
tz = Math.Clamp((int)MathF.Floor(nz), 0, TileGridCount - 1); tz = Math.Clamp((int)MathF.Floor(nz), 0, DesertTileGridCount - 1);
} }
private static bool IsBrushClearOfCover(in TerrainBrush candidate, IReadOnlyList<ArenaBoxSpec> coverBoxes) private static bool IsBrushClearOfCover(in TerrainBrush candidate, IReadOnlyList<ArenaBoxSpec> coverBoxes)

View file

@ -114,7 +114,7 @@ namespace RustToDust.Net
public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{ {
var hit = _host.Session.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); var hit = _host.Session.CastWorldRayClosest(origin, translation);
return new ClientRayHit( return new ClientRayHit(
hit.Hit, hit.Hit,
hit.StableId, hit.StableId,

View file

@ -52,10 +52,13 @@ namespace RustToDust.Net
private MatchState _viewState; private MatchState _viewState;
private Box3DSoaWorld? _predWorld; private Box3DSoaWorld? _predWorld;
private readonly Box3DPhysicsTileSync _predTileSync = new();
private Box3DSoaBodyHandle? _predBody; private Box3DSoaBodyHandle? _predBody;
private WalkerState? _predWalker; private WalkerState? _predWalker;
private string _predChassisId = string.Empty; private string _predChassisId = string.Empty;
public Box3DPhysicsTileSync PredTileSync => _predTileSync;
private Vector3 _predErrorPos; private Vector3 _predErrorPos;
private Quaternion _predErrorRot = Quaternion.Identity; private Quaternion _predErrorRot = Quaternion.Identity;
private bool _pendingChassisSwapSnap; private bool _pendingChassisSwapSnap;
@ -518,7 +521,7 @@ namespace RustToDust.Net
var staticHit = _predWorld.CastRayClosest( var staticHit = _predWorld.CastRayClosest(
(origin.X, origin.Y, origin.Z), (origin.X, origin.Y, origin.Z),
(translation.X, translation.Y, translation.Z)); (translation.X, translation.Y, translation.Z));
if (staticHit.Hit && staticHit.StableId < ArenaSession.ContenderStableIdBase) if (staticHit.Hit && ArenaSession.IsStaticWorldStableId(staticHit.StableId))
{ {
bestFrac = staticHit.Fraction; bestFrac = staticHit.Fraction;
best = new ClientRayHit( best = new ClientRayHit(
@ -854,6 +857,12 @@ namespace RustToDust.Net
_timeSinceLastPhysicsPodStep = 0f; _timeSinceLastPhysicsPodStep = 0f;
_physicsPodSteppingActive = false; _physicsPodSteppingActive = false;
if (dto.PersistentScars is { Length: > 0 })
{
var snap = ArenaScarLedger.DecompressSnapshot(dto.PersistentScars);
_viewState.ApplyPersistentScars(snap);
}
for (int i = 0; i < dto.TerrainStamps.Count; i++) for (int i = 0; i < dto.TerrainStamps.Count; i++)
{ {
ApplyTerrainStamp(dto.TerrainStamps[i]); ApplyTerrainStamp(dto.TerrainStamps[i]);
@ -948,12 +957,17 @@ namespace RustToDust.Net
{ {
_predWorld?.Dispose(); _predWorld?.Dispose();
_predWorld = new Box3DSoaWorld(capacity: 256, gravityX: 0f, gravityY: -20f, gravityZ: 0f); _predWorld = new Box3DSoaWorld(capacity: 256, gravityX: 0f, gravityY: -20f, gravityZ: 0f);
ArenaSession.BuildStaticArena(_predWorld, _viewState); _predTileSync.Reset();
ArenaSession.BuildStaticArena(_predWorld, _viewState, _predTileSync, warmAllActors: false);
var local = LocalContender;
if (_viewState.Terrain.IsHeightmapMode)
{
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
}
_predBody = null; _predBody = null;
_predWalker = null; _predWalker = null;
_predChassisId = string.Empty; _predChassisId = string.Empty;
var local = LocalContender;
var q = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW)); var q = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW));
SpawnLocalPredictionBody(new Vector3(local.X, local.Y, local.Z), q, Vector3.Zero, Vector3.Zero); SpawnLocalPredictionBody(new Vector3(local.X, local.Y, local.Z), q, Vector3.Zero, Vector3.Zero);
} }
@ -1184,6 +1198,10 @@ namespace RustToDust.Net
ArenaSession.FixedDt, ArenaSession.FixedDt,
injectEngineHeat: false, injectEngineHeat: false,
world: _predWorld); world: _predWorld);
if (_viewState.Terrain.IsHeightmapMode)
{
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
}
_predWorld.Step(ArenaSession.FixedDt, subSteps); _predWorld.Step(ArenaSession.FixedDt, subSteps);
ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker); ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker);
} }
@ -1273,6 +1291,10 @@ namespace RustToDust.Net
local.VelY = pkt.LocalVel.Y; local.VelY = pkt.LocalVel.Y;
local.VelZ = pkt.LocalVel.Z; local.VelZ = pkt.LocalVel.Z;
local.TargetHoverAltAgl = pkt.LocalTargetHoverAltAgl; local.TargetHoverAltAgl = pkt.LocalTargetHoverAltAgl;
if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode)
{
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
}
SpawnLocalPredictionBody(pkt.LocalPos, pkt.LocalRot, pkt.LocalVel, pkt.LocalAngVel); SpawnLocalPredictionBody(pkt.LocalPos, pkt.LocalRot, pkt.LocalVel, pkt.LocalAngVel);
if (local.Lifecycle == ContenderLifecycle.Deploying && if (local.Lifecycle == ContenderLifecycle.Deploying &&
@ -1631,6 +1653,13 @@ namespace RustToDust.Net
case TerrainStampEvent stamp: case TerrainStampEvent stamp:
ApplyTerrainStamp(stamp); ApplyTerrainStamp(stamp);
break; break;
case ArenaRepairEvent:
_viewState.RepairArenaScars();
if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode)
{
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1);
}
break;
case DropSpawnedEvent ds: case DropSpawnedEvent ds:
_viewState.ApplyReplicatedDropSpawned( _viewState.ApplyReplicatedDropSpawned(
ds.DropId, ds.X, ds.Z, ds.DropId, ds.X, ds.Z,
@ -1792,17 +1821,10 @@ namespace RustToDust.Net
private void ApplyTerrainStamp(TerrainStampEvent stamp) private void ApplyTerrainStamp(TerrainStampEvent stamp)
{ {
switch ((TerrainStampKind)stamp.Kind) _viewState.ApplyTerrainStamp(stamp, recordInLedger: true);
if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode)
{ {
case TerrainStampKind.Crater: _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1);
_viewState.Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth);
break;
case TerrainStampKind.Scorch:
_viewState.Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius);
break;
case TerrainStampKind.Track:
_viewState.Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length);
break;
} }
} }

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Numerics; using System.Numerics;
@ -32,6 +33,8 @@ namespace RustToDust.Net
public readonly HashSet<int> SentDropIds = new(); public readonly HashSet<int> SentDropIds = new();
public readonly HashSet<int> SentPodIds = new(); public readonly HashSet<int> SentPodIds = new();
public readonly HashSet<int> SentOrdnanceIds = new(); public readonly HashSet<int> SentOrdnanceIds = new();
public readonly HashSet<int> SentTerrainStampIndices = new();
public readonly int[,] SentTileVersions = new int[16, 16];
} }
private struct EntityPvsTracker private struct EntityPvsTracker
@ -51,6 +54,9 @@ namespace RustToDust.Net
private readonly List<ISimEvent> _stepEvents = new(); private readonly List<ISimEvent> _stepEvents = new();
private readonly List<ISimEvent> _hostPendingEvents = new(); private readonly List<ISimEvent> _hostPendingEvents = new();
private readonly List<TerrainStampEvent> _terrainStampHistory = new(); private readonly List<TerrainStampEvent> _terrainStampHistory = new();
private readonly List<int>[,] _tileStampHistory = new List<int>[16, 16];
private readonly string? _scarFilePath;
private readonly bool _persistScars;
private readonly int _maxHumans; private readonly int _maxHumans;
private readonly double _autoRestartSec; private readonly double _autoRestartSec;
private readonly bool _allowClientReset; private readonly bool _allowClientReset;
@ -72,6 +78,7 @@ namespace RustToDust.Net
private uint _nextPeerId = 1; private uint _nextPeerId = 1;
private float _roundCompletedElapsed; private float _roundCompletedElapsed;
private int _lastBroadcastCountdownSec = -1; private int _lastBroadcastCountdownSec = -1;
private uint _lastScarSaveTick;
private bool _disposed; private bool _disposed;
public ServerMatchHost( public ServerMatchHost(
@ -87,7 +94,10 @@ namespace RustToDust.Net
string serverName = "Rust to Dust", string serverName = "Rust to Dust",
int minHumansToStart = 1, int minHumansToStart = 1,
bool restartToLobby = false, bool restartToLobby = false,
byte squadSize = 1) byte squadSize = 1,
string? scarFilePath = null,
bool persistScars = false,
bool repairScarsOnStart = false)
{ {
_maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount); _maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount);
_autoRestartSec = autoRestartSec; _autoRestartSec = autoRestartSec;
@ -97,6 +107,17 @@ namespace RustToDust.Net
_minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans); _minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans);
_restartToLobby = restartToLobby; _restartToLobby = restartToLobby;
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
_persistScars = persistScars;
_scarFilePath = persistScars
? (string.IsNullOrWhiteSpace(scarFilePath) ? ArenaScarLedgerStore.GetDefaultPath(mapKind) : scarFilePath)
: null;
for (int tz = 0; tz < 16; tz++)
{
for (int tx = 0; tx < 16; tx++)
{
_tileStampHistory[tx, tz] = new List<int>(4);
}
}
_socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp) _socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
{ {
@ -117,7 +138,25 @@ namespace RustToDust.Net
}); });
_server.PeerDisconnected += OnTransportPeerDisconnected; _server.PeerDisconnected += OnTransportPeerDisconnected;
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize); ArenaScarLedgerSnapshot? initialScars = null;
if (_persistScars && _scarFilePath is not null)
{
if (repairScarsOnStart)
{
var emptySnap = new ArenaScarLedgerSnapshot
{
AssetFingerprint = mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}"
};
ArenaScarLedgerStore.Save(_scarFilePath, emptySnap);
}
else
{
string fp = mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}";
initialScars = ArenaScarLedgerStore.Load(_scarFilePath, fp);
}
}
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: initialScars);
if (hostContenderId.HasValue) if (hostContenderId.HasValue)
{ {
_session.SetHumanSlot(hostContenderId.Value, true, "Host"); _session.SetHumanSlot(hostContenderId.Value, true, "Host");
@ -170,19 +209,33 @@ namespace RustToDust.Net
public void ResetMatch(int seed, ArenaMapKind mapKind) => public void ResetMatch(int seed, ArenaMapKind mapKind) =>
ResetMatch(seed, mapKind, startInLobby: false); ResetMatch(seed, mapKind, startInLobby: false);
public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) =>
ResetMatch(seed, mapKind, startInLobby, repairScars: false);
public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby, bool repairScars)
{ {
if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count) if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count)
{ {
_hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name; _hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name;
} }
ArenaScarLedgerSnapshot? preservedScars = null;
if (mapKind == _session.State.MapKind)
{
if (repairScars)
{
_session.State.RepairArenaScars();
}
preservedScars = _session.State.ScarLedger.ToSnapshot();
}
FlushScarLedgerIfDirty();
_session.Dispose(); _session.Dispose();
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize); _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: preservedScars);
_matchGeneration++; _matchGeneration++;
_simTick = 0; _simTick = 0;
_roundCompletedElapsed = 0f; _roundCompletedElapsed = 0f;
_lastBroadcastCountdownSec = -1; _lastBroadcastCountdownSec = -1;
_terrainStampHistory.Clear(); _terrainStampHistory.Clear();
ClearTileStampHistory();
_stepEvents.Clear(); _stepEvents.Clear();
_hostPendingEvents.Clear(); _hostPendingEvents.Clear();
_reconnectTokens.Clear(); _reconnectTokens.Clear();
@ -588,12 +641,19 @@ namespace RustToDust.Net
{ {
if (_stepEvents[i] is TerrainStampEvent ts) if (_stepEvents[i] is TerrainStampEvent ts)
{ {
int stampIdx = _terrainStampHistory.Count;
_terrainStampHistory.Add(ts); _terrainStampHistory.Add(ts);
_session.State.Terrain.MapWorldToTile(ts.X, ts.Z, out int tx, out int tz);
_tileStampHistory[tx, tz].Add(stampIdx);
} }
} }
FlushEventsAndPvsEnter(); FlushEventsAndPvsEnter();
BroadcastSnapshots(); BroadcastSnapshots();
if (_persistScars && (_simTick - _lastScarSaveTick) >= 1800)
{
FlushScarLedgerIfDirty();
}
try try
{ {
_server.PollResends(); _server.PollResends();
@ -700,6 +760,16 @@ namespace RustToDust.Net
} }
} }
break; break;
case RepairArenaCmdMsg:
if (_peersByEndpoint.TryGetValue(epKey, out var repPeer) && repPeer.Active && ReferenceEquals(repPeer.TransportPeer, transportPeer))
{
repPeer.LastHeardUtcMs = nowUtcMs;
if (_allowClientReset || (_hostContenderId.HasValue && _hostContenderId.Value == repPeer.AssignedContenderId))
{
RepairArenaScars();
}
}
break;
case InteractCmdMsg interactCmd: case InteractCmdMsg interactCmd:
if (_peersByEndpoint.TryGetValue(epKey, out var intPeer) && intPeer.Active && ReferenceEquals(intPeer.TransportPeer, transportPeer)) if (_peersByEndpoint.TryGetValue(epKey, out var intPeer) && intPeer.Active && ReferenceEquals(intPeer.TransportPeer, transportPeer))
{ {
@ -996,6 +1066,20 @@ namespace RustToDust.Net
} }
peer.SentPodIds.Clear(); peer.SentPodIds.Clear();
peer.SentOrdnanceIds.Clear(); peer.SentOrdnanceIds.Clear();
peer.SentTerrainStampIndices.Clear();
Array.Clear(peer.SentTileVersions);
for (int i = 0; i < _terrainStampHistory.Count; i++)
{
peer.SentTerrainStampIndices.Add(i);
}
var terrain = _session.State.Terrain;
for (int tz = 0; tz < terrain.TileGridCount; tz++)
{
for (int tx = 0; tx < terrain.TileGridCount; tx++)
{
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
}
}
var activePods = _session.State.OrbitalDrop.ActivePods; var activePods = _session.State.OrbitalDrop.ActivePods;
for (int i = 0; i < activePods.Count; i++) for (int i = 0; i < activePods.Count; i++)
{ {
@ -1187,11 +1271,9 @@ namespace RustToDust.Net
: new DropPickedUpEvent { DropId = dp.DropId, ContenderId = -1 }); : new DropPickedUpEvent { DropId = dp.DropId, ContenderId = -1 });
} }
break; break;
case TerrainStampEvent stamp: case TerrainStampEvent:
if (_session.IsPointInPeerPvs(obsId, stamp.X, _session.State.Terrain.SampleHeight(stamp.X, stamp.Z) + 0.5f, stamp.Z)) // Delivered via 576m local geometry bubble sync below so distant live fire is never leaked
{ // while _predWorld stays 1:1 physics-synchronized before the player enters tile range.
filtered.Add(stamp);
}
break; break;
case OverheatAlertEvent oh: case OverheatAlertEvent oh:
if (oh.ContenderId == obsId) if (oh.ContenderId == obsId)
@ -1306,6 +1388,8 @@ namespace RustToDust.Net
} }
} }
SyncPeerLocalGeometryBubble(peer, obsId, filtered);
if (enteredPvsMask != 0) if (enteredPvsMask != 0)
{ {
var activePods = _session.State.OrbitalDrop.ActivePods; var activePods = _session.State.OrbitalDrop.ActivePods;
@ -1753,13 +1837,10 @@ namespace RustToDust.Net
}); });
} }
for (int i = 0; i < _terrainStampHistory.Count; i++) var scarSnap = _session.State.ScarLedger.ToSnapshot();
if (scarSnap.Terrain.Count > 0 || scarSnap.Buildings.Count > 0 || scarSnap.Trees.Count > 0)
{ {
var ts = _terrainStampHistory[i]; dto.PersistentScars = ArenaScarLedger.CompressSnapshot(scarSnap);
if (_session.IsPointInPeerPvs(forContenderId, ts.X, _session.State.Terrain.SampleHeight(ts.X, ts.Z) + 0.5f, ts.Z))
{
dto.TerrainStamps.Add(ts);
}
} }
for (int i = 0; i < _session.State.Contenders.Count; i++) for (int i = 0; i < _session.State.Contenders.Count; i++)
@ -1865,10 +1946,124 @@ namespace RustToDust.Net
} }
} }
public void RepairArenaScars()
{
_session.RepairArenaScars();
_terrainStampHistory.Clear();
ClearTileStampHistory();
FlushScarLedgerIfDirty();
uint rev = _session.State.ScarLedger.LedgerRevision;
var repairEv = new ArenaRepairEvent { LedgerRevision = rev };
if (_hostContenderId.HasValue)
{
_hostPendingEvents.Add(repairEv);
}
foreach (var peer in _peersByEndpoint.Values)
{
if (!peer.Active) continue;
peer.SentTerrainStampIndices.Clear();
Array.Clear(peer.SentTileVersions);
SendSchemaToPeer(peer, new SimEventBatchMsg
{
BatchSeq = _eventBatchSeq++,
SimTick = _simTick,
SimTime = _session.State.Time,
MatchGeneration = _matchGeneration,
Events = new List<ISimEvent> { repairEv }
});
}
}
private void SyncPeerLocalGeometryBubble(ConnectedPeer peer, int obsId, List<ISimEvent> filtered)
{
if (_terrainStampHistory.Count == 0 || obsId < 0 || obsId >= _session.State.Contenders.Count)
{
return;
}
var obs = _session.State.Contenders[obsId];
var terrain = _session.State.Terrain;
terrain.MapWorldToTile(obs.X, obs.Z, out int cx, out int cz);
int grid = terrain.TileGridCount;
int minTx = Math.Max(0, cx - 4);
int maxTx = Math.Min(grid - 1, cx + 4);
int minTz = Math.Max(0, cz - 4);
int maxTz = Math.Min(grid - 1, cz + 4);
const float bubbleRadiusSq = 576f * 576f;
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
var list = _tileStampHistory[tx, tz];
if (list.Count == 0)
{
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
continue;
}
bool allSent = true;
for (int i = 0; i < list.Count; i++)
{
int stampIdx = list[i];
if (peer.SentTerrainStampIndices.Contains(stampIdx))
{
continue;
}
var ts = _terrainStampHistory[stampIdx];
float dx = obs.X - ts.X;
float dz = obs.Z - ts.Z;
if (dx * dx + dz * dz <= bubbleRadiusSq)
{
peer.SentTerrainStampIndices.Add(stampIdx);
filtered.Add(ts);
}
else
{
allSent = false;
}
}
if (allSent)
{
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
}
}
}
}
private void ClearTileStampHistory()
{
for (int tz = 0; tz < 16; tz++)
{
for (int tx = 0; tx < 16; tx++)
{
_tileStampHistory[tx, tz].Clear();
}
}
}
private void FlushScarLedgerIfDirty()
{
if (!_persistScars || string.IsNullOrWhiteSpace(_scarFilePath))
{
return;
}
if (!_session.State.ScarLedger.IsDirty && File.Exists(_scarFilePath))
{
return;
}
ArenaScarLedgerStore.Save(_scarFilePath, _session.State.ScarLedger.ToSnapshot());
_session.State.ScarLedger.IsDirty = false;
_lastScarSaveTick = _simTick;
}
public void Dispose() public void Dispose()
{ {
if (_disposed) return; if (_disposed) return;
_disposed = true; _disposed = true;
FlushScarLedgerIfDirty();
_server.PeerDisconnected -= OnTransportPeerDisconnected; _server.PeerDisconnected -= OnTransportPeerDisconnected;
_server.Dispose(); _server.Dispose();
_socket.Dispose(); _socket.Dispose();

View file

@ -28,6 +28,9 @@ namespace RustToDust.Server
int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1); int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1);
bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false); bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false);
int squadSize = Math.Clamp(TryParseInt(Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), 3), 1, 4); int squadSize = Math.Clamp(TryParseInt(Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), 3), 1, 4);
string? scarFilePath = Environment.GetEnvironmentVariable("RTD_SCAR_FILE");
bool persistScars = TryParseBool(Environment.GetEnvironmentVariable("RTD_PERSIST_SCARS"), true);
bool repairScars = false;
for (int i = 0; i < args.Length; i++) for (int i = 0; i < args.Length; i++)
{ {
@ -61,6 +64,10 @@ namespace RustToDust.Server
else if (a == "--restart-to-lobby") restartToLobby = true; else if (a == "--restart-to-lobby") restartToLobby = true;
else if (a == "--squad-size" && i + 1 < args.Length) squadSize = Math.Clamp(TryParseInt(args[++i], squadSize), 1, 4); else if (a == "--squad-size" && i + 1 < args.Length) squadSize = Math.Clamp(TryParseInt(args[++i], squadSize), 1, 4);
else if (a.StartsWith("--squad-size=", StringComparison.Ordinal)) squadSize = Math.Clamp(TryParseInt(a.Substring("--squad-size=".Length), squadSize), 1, 4); else if (a.StartsWith("--squad-size=", StringComparison.Ordinal)) squadSize = Math.Clamp(TryParseInt(a.Substring("--squad-size=".Length), squadSize), 1, 4);
else if (a == "--scar-file" && i + 1 < args.Length) scarFilePath = args[++i];
else if (a.StartsWith("--scar-file=", StringComparison.Ordinal)) scarFilePath = a.Substring("--scar-file=".Length);
else if (a == "--no-persist-scars") persistScars = false;
else if (a == "--repair-scars") repairScars = true;
} }
if (!IPAddress.TryParse(bindStr, out var bindIp)) if (!IPAddress.TryParse(bindStr, out var bindIp))
@ -99,7 +106,10 @@ namespace RustToDust.Server
serverName: serverName, serverName: serverName,
minHumansToStart: minHumansToStart, minHumansToStart: minHumansToStart,
restartToLobby: restartToLobby, restartToLobby: restartToLobby,
squadSize: (byte)squadSize); squadSize: (byte)squadSize,
scarFilePath: scarFilePath,
persistScars: persistScars,
repairScarsOnStart: repairScars);
host.LogMessage += msg => Console.WriteLine(msg); host.LogMessage += msg => Console.WriteLine(msg);
static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) => static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) =>

View file

@ -11,7 +11,7 @@ namespace RustToDust.Ymir
{ {
public const float FixedDt = 1f / 60f; public const float FixedDt = 1f / 60f;
public const int SubStepCount = 4; public const int SubStepCount = 4;
public const int WorldBodyCapacity = 384; public const int WorldBodyCapacity = 1024;
private const ulong GroundStableId = 1; private const ulong GroundStableId = 1;
private const ulong StaticBoxStableIdBase = 10; private const ulong StaticBoxStableIdBase = 10;
@ -20,6 +20,7 @@ namespace RustToDust.Ymir
private const ulong SpectatorStableIdBase = 3000; private const ulong SpectatorStableIdBase = 3000;
private readonly Box3DSoaWorld _world; private readonly Box3DSoaWorld _world;
private readonly Box3DPhysicsTileSync _tileSync = new();
private readonly Dictionary<int, Box3DSoaBodyHandle> _contenderBodies = new(); private readonly Dictionary<int, Box3DSoaBodyHandle> _contenderBodies = new();
private readonly Dictionary<int, Box3DSoaBodyHandle> _spectatorBodies = new(); private readonly Dictionary<int, Box3DSoaBodyHandle> _spectatorBodies = new();
private readonly Dictionary<int, WalkerState> _contenderWalkers = new(); private readonly Dictionary<int, WalkerState> _contenderWalkers = new();
@ -35,9 +36,9 @@ namespace RustToDust.Ymir
private long _forwardedPodEventId; private long _forwardedPodEventId;
private bool _disposed; private bool _disposed;
public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1) public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1, ArenaScarLedgerSnapshot? initialScars = null)
{ {
State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize); State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize, initialScars);
Ordnance = new OrdnanceRuntime(this); Ordnance = new OrdnanceRuntime(this);
_spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count]; _spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count];
_forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0; _forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0;
@ -73,7 +74,7 @@ namespace RustToDust.Ymir
gravityY: -20f, gravityY: -20f,
gravityZ: 0f); gravityZ: 0f);
BuildStaticArena(_world, State); BuildStaticArena(_world, State, _tileSync, warmAllActors: true);
SpawnContenderBodies(); SpawnContenderBodies();
SpawnSpectatorBodies(); SpawnSpectatorBodies();
UpdateObserverDetectionMemories(); UpdateObserverDetectionMemories();
@ -91,8 +92,33 @@ namespace RustToDust.Ymir
public MatchState State { get; } public MatchState State { get; }
public OrdnanceRuntime Ordnance { get; } public OrdnanceRuntime Ordnance { get; }
public Box3DSoaWorld World => _world; public Box3DSoaWorld World => _world;
public Box3DPhysicsTileSync TileSync => _tileSync;
public bool EnableNetworkPvs { get; set; } = true; public bool EnableNetworkPvs { get; set; } = true;
public void RepairArenaScars()
{
State.RepairArenaScars();
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: Box3DPhysicsTileSync.MaxTiles);
}
public static bool IsStaticWorldStableId(ulong stableId) =>
stableId < ContenderStableIdBase || stableId >= Box3DPhysicsTileSync.HeightfieldTileStableIdBase;
public static bool IsStaticBuildingOrCoverStableId(ulong stableId) =>
(stableId >= StaticMeshStableIdBase && stableId < ContenderStableIdBase) ||
(stableId >= Box3DPhysicsTileSync.BuildingTileStableIdBase && stableId < Box3DPhysicsTileSync.TreeTileStableIdBase);
public Box3DSoaRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{
float len = translation.Length();
if (len > 1e-4f && State.Terrain.IsHeightmapMode)
{
Vector3 dir = translation / len;
_tileSync.EnsureTilesAlongRay(_world, State.Terrain, origin.X, origin.Z, dir.X, dir.Z, len);
}
return _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
}
public void SetHumanSlot(int contenderId, bool isHuman, string? callsign = null) public void SetHumanSlot(int contenderId, bool isHuman, string? callsign = null)
{ {
if (contenderId < 0 || contenderId >= State.Contenders.Count) if (contenderId < 0 || contenderId >= State.Contenders.Count)
@ -322,6 +348,10 @@ namespace RustToDust.Ymir
_contenderBodies.Remove(contenderId); _contenderBodies.Remove(contenderId);
} }
_contenderWalkers.Remove(contenderId); _contenderWalkers.Remove(contenderId);
if (State.Terrain.IsHeightmapMode)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, x, z, halfTileRadius: 1);
}
if (c.IsGroundedActive) if (c.IsGroundedActive)
{ {
SpawnContenderBody(c); SpawnContenderBody(c);
@ -508,6 +538,7 @@ namespace RustToDust.Ymir
if (State.SionMap is { } sionMap && if (State.SionMap is { } sionMap &&
sionMap.IntersectsAnyBuildingAabb(ax, ay, az, dir.X, dir.Y, dir.Z, dist)) sionMap.IntersectsAnyBuildingAabb(ax, ay, az, dir.X, dir.Y, dir.Z, dist))
{ {
_tileSync.EnsureTilesAlongRay(_world, State.Terrain, ax, az, dir.X, dir.Z, dist);
Vector3 castOrigin = new(ax, ay, az); Vector3 castOrigin = new(ax, ay, az);
float remaining = dist; float remaining = dist;
for (int hop = 0; hop < 4 && remaining > 0.25f; hop++) for (int hop = 0; hop < 4 && remaining > 0.25f; hop++)
@ -519,7 +550,7 @@ namespace RustToDust.Ymir
{ {
break; break;
} }
if (hit.StableId < ContenderStableIdBase) if (IsStaticWorldStableId(hit.StableId))
{ {
return false; return false;
} }
@ -659,6 +690,7 @@ namespace RustToDust.Ymir
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown);
EnsureActivePhysicsTilesAndFlush();
ApplyPhysicsDrives(); ApplyPhysicsDrives();
_world.Step(FixedDt, subSteps); _world.Step(FixedDt, subSteps);
SyncBodiesFromWorld(); SyncBodiesFromWorld();
@ -679,6 +711,7 @@ namespace RustToDust.Ymir
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown);
long t2 = Stopwatch.GetTimestamp(); long t2 = Stopwatch.GetTimestamp();
EnsureActivePhysicsTilesAndFlush();
ApplyPhysicsDrives(); ApplyPhysicsDrives();
long t3 = Stopwatch.GetTimestamp(); long t3 = Stopwatch.GetTimestamp();
_world.Step(FixedDt, subSteps); _world.Step(FixedDt, subSteps);
@ -734,23 +767,28 @@ namespace RustToDust.Ymir
return true; return true;
} }
public static void BuildStaticArena(Box3DSoaWorld world, MatchState state) public static void BuildStaticArena(Box3DSoaWorld world, MatchState state, Box3DPhysicsTileSync? tileSync = null, bool warmAllActors = true)
{ {
if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion) if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion)
{ {
var meta = sion.Metadata; if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode)
float half = state.Terrain.MapHalfExtent; {
world.AddStaticHeightField( for (int i = 0; i < state.Contenders.Count; i++)
GroundStableId, {
(-half, 0f, -half), var c = state.Contenders[i];
sion.Heights, tileSync.EnsureTileRegion(world, state.Terrain, c.X, c.Z, halfTileRadius: 1);
meta.GridRes, }
meta.GridRes, for (int i = 0; i < state.Spectators.Spectators.Count; i++)
(meta.CellSizeMeters, 1.0f, meta.CellSizeMeters), {
meta.MinY - 2f, var s = state.Spectators.Spectators[i];
meta.MaxY + 2f, tileSync.EnsureTileRegion(world, state.Terrain, s.X, s.Z, halfTileRadius: 1);
friction: 0.15f, }
restitution: 0.0f); for (int i = 0; i < state.OrbitalDrop.ActivePods.Count; i++)
{
var pod = state.OrbitalDrop.ActivePods[i];
tileSync.EnsureTileRegion(world, state.Terrain, pod.X, pod.Z, halfTileRadius: 0);
}
}
ulong boxId = StaticBoxStableIdBase; ulong boxId = StaticBoxStableIdBase;
for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++)
@ -886,8 +924,44 @@ namespace RustToDust.Ymir
} }
} }
public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY) => private void EnsureActivePhysicsTilesAndFlush()
QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY); {
if (!State.Terrain.IsHeightmapMode)
{
return;
}
for (int i = 0; i < State.Contenders.Count; i++)
{
var c = State.Contenders[i];
if (c.Alive)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 1);
}
}
for (int i = 0; i < State.Spectators.Spectators.Count; i++)
{
var s = State.Spectators.Spectators[i];
if (s.Alive)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, s.X, s.Z, halfTileRadius: 1);
}
}
for (int i = 0; i < State.OrbitalDrop.ActivePods.Count; i++)
{
var pod = State.OrbitalDrop.ActivePods[i];
_tileSync.EnsureTileRegion(_world, State.Terrain, pod.X, pod.Z, halfTileRadius: 0);
}
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4);
}
public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY)
{
if (State.Terrain.IsHeightmapMode)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, x, z, halfTileRadius: 0);
}
return QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY);
}
public static DropSurfaceSample QueryDropSurface( public static DropSurfaceSample QueryDropSurface(
MatchState state, MatchState state,
@ -2996,11 +3070,13 @@ namespace RustToDust.Ymir
State.SpawnModuleDrop(victim.X + (i - 1) * 0.9f, victim.Z + 1.2f, victim.Grid.Mounted[i].Spec); State.SpawnModuleDrop(victim.X + (i - 1) * 0.9f, victim.Z + 1.2f, victim.Grid.Mounted[i].Spec);
} }
State.Terrain.StampCrater(victim.X, victim.Z, radius: 5.2f, depth: 1.3f); var craterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f };
State.Terrain.StampScorch(victim.X, victim.Z, radius: 6.2f); var scorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f };
State.ApplyTerrainStamp(craterEv, recordInLedger: true);
State.ApplyTerrainStamp(scorchEv, recordInLedger: true);
State.OrbitalDrop.OnContenderEliminated(victim); State.OrbitalDrop.OnContenderEliminated(victim);
_stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f }); _stepEvents.Add(craterEv);
_stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f }); _stepEvents.Add(scorchEv);
_stepEvents.Add(new ContenderEliminatedEvent _stepEvents.Add(new ContenderEliminatedEvent
{ {
VictimId = victim.Id, VictimId = victim.Id,
@ -3032,10 +3108,12 @@ namespace RustToDust.Ymir
State.SpawnModuleDrop(spec.X + (i - 0.5f) * 1.1f, spec.Z, drops[i]); State.SpawnModuleDrop(spec.X + (i - 0.5f) * 1.1f, spec.Z, drops[i]);
} }
State.Terrain.StampCrater(spec.X, spec.Z, radius: 4.5f, depth: 1.1f); var specCraterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f };
State.Terrain.StampScorch(spec.X, spec.Z, radius: 5.4f); var specScorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f };
_stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f }); State.ApplyTerrainStamp(specCraterEv, recordInLedger: true);
_stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f }); State.ApplyTerrainStamp(specScorchEv, recordInLedger: true);
_stepEvents.Add(specCraterEv);
_stepEvents.Add(specScorchEv);
_stepEvents.Add(new SpectatorDestroyedEvent _stepEvents.Add(new SpectatorDestroyedEvent
{ {
SpectatorId = spec.Id, SpectatorId = spec.Id,
@ -3299,26 +3377,36 @@ namespace RustToDust.Ymir
{ {
if (craterRadius > 0f && craterDepth > 0f) if (craterRadius > 0f && craterDepth > 0f)
{ {
State.Terrain.StampCrater(x, z, radius: craterRadius, depth: craterDepth); var ev = new TerrainStampEvent
_stepEvents.Add(new TerrainStampEvent
{ {
Kind = (byte)TerrainStampKind.Crater, Kind = (byte)TerrainStampKind.Crater,
X = x, X = x,
Z = z, Z = z,
Radius = craterRadius, Radius = craterRadius,
Depth = craterDepth Depth = craterDepth
}); };
State.ApplyTerrainStamp(ev, recordInLedger: true);
_stepEvents.Add(ev);
} }
if (scorchRadius > 0f) if (scorchRadius > 0f)
{ {
State.Terrain.StampScorch(x, z, radius: scorchRadius); var ev = new TerrainStampEvent
_stepEvents.Add(new TerrainStampEvent
{ {
Kind = (byte)TerrainStampKind.Scorch, Kind = (byte)TerrainStampKind.Scorch,
X = x, X = x,
Z = z, Z = z,
Radius = scorchRadius Radius = scorchRadius
}); };
State.ApplyTerrainStamp(ev, recordInLedger: true);
_stepEvents.Add(ev);
}
}
void IOrdnanceTargetSink.EnsurePhysicsTilesAlongRay(Vector3 origin, Vector3 dir, float distance)
{
if (State.Terrain.IsHeightmapMode)
{
_tileSync.EnsureTilesAlongRay(_world, State.Terrain, origin.X, origin.Z, dir.X, dir.Z, distance);
} }
} }

View file

@ -0,0 +1,283 @@
using System;
using RustToDust.Core;
using Ymir.Box3D;
namespace RustToDust.Ymir
{
public sealed class Box3DPhysicsTileSync
{
public const ulong HeightfieldTileStableIdBase = 10_000;
public const ulong BuildingTileStableIdBase = 11_000;
public const ulong TreeTileStableIdBase = 12_000;
public const int MaxTiles = 256;
private readonly Box3DSoaBodyHandle[] _residentHandles = new Box3DSoaBodyHandle[MaxTiles];
private readonly bool[] _residentFlags = new bool[MaxTiles];
private readonly int[] _syncedStructuralVersions = new int[MaxTiles];
private float[]? _scratchHeights;
public int ResidentTileCount { get; private set; }
public bool TryGetResidentHandle(int tx, int tz, int tileGridCount, out Box3DSoaBodyHandle handle)
{
if ((uint)tx < (uint)tileGridCount && (uint)tz < (uint)tileGridCount)
{
int idx = tz * tileGridCount + tx;
if (_residentFlags[idx])
{
handle = _residentHandles[idx];
return true;
}
}
handle = default;
return false;
}
public void Reset()
{
Array.Clear(_residentHandles);
Array.Clear(_residentFlags);
Array.Clear(_syncedStructuralVersions);
ResidentTileCount = 0;
}
public bool EnsureTileResident(Box3DSoaWorld world, TerrainField terrain, int tx, int tz)
{
if (!terrain.IsHeightmapMode)
{
return false;
}
int grid = terrain.TileGridCount;
if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid)
{
return false;
}
int idx = tz * grid + tx;
int curVer = terrain.StructuralTileVersions[tx, tz];
if (_residentFlags[idx] && _syncedStructuralVersions[idx] == curVer)
{
return false;
}
int samplesPerTile = (terrain.HeightmapRes - 1) / grid;
int side = samplesPerTile + 1;
int sampleCount = side * side;
if (_scratchHeights is null || _scratchHeights.Length < sampleCount)
{
_scratchHeights = new float[sampleCount];
}
terrain.ExtractTilePhysicsHeights(tx, tz, _scratchHeights, out float minY, out float maxY);
if (_residentFlags[idx])
{
world.RemoveBody(_residentHandles[idx]);
ResidentTileCount--;
_residentFlags[idx] = false;
}
float originX = -terrain.MapHalfExtent + tx * terrain.MapTileSize;
float originZ = -terrain.MapHalfExtent + tz * terrain.MapTileSize;
ulong stableId = HeightfieldTileStableIdBase + (ulong)idx;
var handle = world.AddStaticHeightField(
stableId,
(originX, 0f, originZ),
_scratchHeights.AsSpan(0, sampleCount),
side,
side,
(terrain.HeightmapCellSize, 1.0f, terrain.HeightmapCellSize),
minY - 2f,
maxY + 2f,
friction: 0.15f,
restitution: 0.0f);
_residentHandles[idx] = handle;
_residentFlags[idx] = true;
_syncedStructuralVersions[idx] = curVer;
ResidentTileCount++;
return true;
}
public void EnsureTileRegion(Box3DSoaWorld world, TerrainField terrain, float worldX, float worldZ, int halfTileRadius)
{
if (!terrain.IsHeightmapMode)
{
return;
}
terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz);
int grid = terrain.TileGridCount;
int minTx = Math.Max(0, cx - halfTileRadius);
int maxTx = Math.Min(grid - 1, cx + halfTileRadius);
int minTz = Math.Max(0, cz - halfTileRadius);
int maxTz = Math.Min(grid - 1, cz + halfTileRadius);
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
EnsureTileResident(world, terrain, tx, tz);
}
}
}
public void EnsureTilesAlongRay(
Box3DSoaWorld world,
TerrainField terrain,
float ox, float oz,
float dx, float dz,
float maxDistance)
{
if (!terrain.IsHeightmapMode || maxDistance <= 0f)
{
return;
}
float half = terrain.MapHalfExtent;
float tileSize = terrain.MapTileSize;
int grid = terrain.TileGridCount;
float tMin = 0f;
float tMax = maxDistance;
if (!SlabClip(ox, dx, -half, half, ref tMin, ref tMax)) return;
if (!SlabClip(oz, dz, -half, half, ref tMin, ref tMax)) return;
float sx = ox + dx * tMin;
float sz = oz + dz * tMin;
terrain.MapWorldToTile(sx, sz, out int tx, out int tz);
float ex = ox + dx * tMax;
float ez = oz + dz * tMax;
terrain.MapWorldToTile(ex, ez, out int endTx, out int endTz);
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 ? tileSize / MathF.Abs(dx) : float.PositiveInfinity;
float tDeltaZ = stepZ != 0 ? tileSize / MathF.Abs(dz) : float.PositiveInfinity;
float nextBoundaryX = -half + (tx + (stepX > 0 ? 1 : 0)) * tileSize;
float nextBoundaryZ = -half + (tz + (stepZ > 0 ? 1 : 0)) * tileSize;
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;
int maxSteps = grid * 2 + 4;
for (int iter = 0; iter < maxSteps; iter++)
{
EnsureTileResident(world, terrain, tx, tz);
if (tx == endTx && tz == endTz)
{
break;
}
float curT;
if (tMaxX <= tMaxZ)
{
curT = tMaxX;
tMaxX += tDeltaX;
tx += stepX;
}
else
{
curT = tMaxZ;
tMaxZ += tDeltaZ;
tz += stepZ;
}
if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid || curT > tMax)
{
break;
}
}
}
public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4)
{
if (!terrain.IsHeightmapMode || maxTilesPerTick <= 0)
{
return 0;
}
int grid = terrain.TileGridCount;
int rebuilt = 0;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (!_residentFlags[idx])
{
continue;
}
if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx])
{
if (EnsureTileResident(world, terrain, tx, tz))
{
rebuilt++;
if (rebuilt >= maxTilesPerTick)
{
return rebuilt;
}
}
}
}
}
return rebuilt;
}
public void SyncWindow(Box3DSoaWorld world, TerrainField terrain, float centerX, float centerZ, int halfTileRadius = 1)
{
if (!terrain.IsHeightmapMode)
{
return;
}
terrain.MapWorldToTile(centerX, centerZ, out int cx, out int cz);
int grid = terrain.TileGridCount;
int minTx = Math.Max(0, cx - halfTileRadius);
int maxTx = Math.Min(grid - 1, cx + halfTileRadius);
int minTz = Math.Max(0, cz - halfTileRadius);
int maxTz = Math.Min(grid - 1, cz + halfTileRadius);
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (_residentFlags[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz))
{
world.RemoveBody(_residentHandles[idx]);
_residentHandles[idx] = default;
_residentFlags[idx] = false;
_syncedStructuralVersions[idx] = 0;
ResidentTileCount--;
}
}
}
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
EnsureTileResident(world, terrain, tx, tz);
}
}
}
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;
}
}
}

View file

@ -126,7 +126,7 @@ namespace RustToDust.Ymir
public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{ {
var hit = Inner.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); var hit = Inner.CastWorldRayClosest(origin, translation);
return new ClientRayHit( return new ClientRayHit(
hit.Hit, hit.Hit,
hit.StableId, hit.StableId,

View file

@ -103,6 +103,7 @@ namespace RustToDust.Ymir
bool isSpectatorShooter, bool isSpectatorShooter,
int shooterEntityId); int shooterEntityId);
void StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius); void StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius);
void EnsurePhysicsTilesAlongRay(Vector3 origin, Vector3 dir, float distance);
} }
public struct LiveOrdnanceInstance public struct LiveOrdnanceInstance
@ -763,6 +764,7 @@ namespace RustToDust.Ymir
for (int hop = 0; hop < 4 && remaining > 1e-4f; hop++) for (int hop = 0; hop < 4 && remaining > 1e-4f; hop++)
{ {
_sink.EnsurePhysicsTilesAlongRay(castOrigin, dir, remaining);
var rayHit = _sink.World.CastRayClosest( var rayHit = _sink.World.CastRayClosest(
(castOrigin.X, castOrigin.Y, castOrigin.Z), (castOrigin.X, castOrigin.Y, castOrigin.Z),
(dir.X * remaining, dir.Y * remaining, dir.Z * remaining)); (dir.X * remaining, dir.Y * remaining, dir.Z * remaining));
@ -1290,6 +1292,7 @@ namespace RustToDust.Ymir
for (int hop = 0; hop < 6 && remainingRange > 0.2f; hop++) for (int hop = 0; hop < 6 && remainingRange > 0.2f; hop++)
{ {
_sink.EnsurePhysicsTilesAlongRay(castOrigin, dir, remainingRange);
var rayHit = _sink.World.CastRayClosest( var rayHit = _sink.World.CastRayClosest(
(castOrigin.X, castOrigin.Y, castOrigin.Z), (castOrigin.X, castOrigin.Y, castOrigin.Z),
(dir.X * remainingRange, dir.Y * remainingRange, dir.Z * remainingRange)); (dir.X * remainingRange, dir.Y * remainingRange, dir.Z * remainingRange));

View file

@ -477,10 +477,10 @@ namespace RustToDust.Ymir
float rrX = x + right.X * w - fwd.X * l, rrZ = z + right.Z * w - fwd.Z * l; float rrX = x + right.X * w - fwd.X * l, rrZ = z + right.Z * w - fwd.Z * l;
float hCenter = terrain.SampleHeight(x, z); float hCenter = terrain.SampleHeight(x, z);
if (terrain.SampleNormal(flX, flZ).Ny < 0.72f || if (terrain.SampleNormal(flX, flZ).Ny < 0.58f ||
terrain.SampleNormal(frX, frZ).Ny < 0.72f || terrain.SampleNormal(frX, frZ).Ny < 0.58f ||
terrain.SampleNormal(rlX, rlZ).Ny < 0.72f || terrain.SampleNormal(rlX, rlZ).Ny < 0.58f ||
terrain.SampleNormal(rrX, rrZ).Ny < 0.72f) terrain.SampleNormal(rrX, rrZ).Ny < 0.58f)
{ {
planeCenterY = hCenter; planeCenterY = hCenter;
return centerNormal.Y >= 0.78f ? centerNormal : Vector3.UnitY; return centerNormal.Y >= 0.78f ? centerNormal : Vector3.UnitY;
@ -1007,6 +1007,27 @@ namespace RustToDust.Ymir
} }
} }
} }
else if (n == 4 && view.Size2[lane] > 2.4f && terrainNormal.Y >= 0.78f)
{
float fz = view.Size2[lane] * 0.98f;
float fw = view.Size0[lane] * 0.95f;
for (int ci = -1; ci <= 1; ci++)
{
float sx = fw * ci;
float cx = comPos.X + right.X * sx + fwd.X * fz;
float cz = comPos.Z + right.Z * sx + fwd.Z * fz;
if (WalkerState.SampleTerrainNormal(terrain, cx, cz).Y >= 0.58f)
{
float ch = terrain.SampleHeight(cx, cz);
Vector3 cornerRel = right * sx + fwd * fz - up * view.Size1[lane];
float neededGroundY = (ch + 0.22f * scale - cornerRel.Y) - rideHeight;
if (neededGroundY > effectiveGroundY)
{
effectiveGroundY = MathF.Min(comGroundY + 1.15f * scale, neededGroundY);
}
}
}
}
} }
float targetY = effectiveGroundY + rideHeight; float targetY = effectiveGroundY + rideHeight;
if (!activeMove && !ws.IsAirborne) if (!activeMove && !ws.IsAirborne)

View file

@ -797,6 +797,87 @@ namespace RustToDust.Tests
"Client must receive Exemplar walker snapshot even under dense 12 quad-walker contention"); "Client must receive Exemplar walker snapshot even under dense 12 quad-walker contention");
} }
[Fact]
public void Cut13a_OutOfPvsHistoricalCratersSyncViaPersistentScars_AndLiveCratersEnterWithin576mBubble()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
const float histX = 700f;
const float histZ = 700f;
float baseHistH = host.Session.State.Terrain.SampleHeight(histX, histZ);
// 1. Historical out-of-PVS crater stamped before Client A joins
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(histX, histZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f);
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
host.StepOnce(nowMs += 16);
float scarredHistH = host.Session.State.Terrain.SampleHeight(histX, histZ);
Assert.True(scarredHistH < baseHistH - 1.2f);
using var clientA = new RemoteArenaSession(ep, "Scout");
Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000));
// Out-of-PVS historical crater must be present immediately via PersistentScars
Assert.Equal(scarredHistH, clientA.ViewState.Terrain.SampleHeight(histX, histZ), precision: 3);
Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9);
// 2. Live crater stamped far outside 576m bubble (-700, 100 vs open-sky ~700, 100 = ~1400m apart)
int slotA = clientA.LocalContenderId;
var sion = host.Session.State.SionMap!;
float liveX = 700f, liveZ = 100f;
for (float x = 640f; x <= 760f; x += 8f)
{
if (!sion.IsInsideAnyBuildingXz(x, liveZ, padding: 10f))
{
liveX = x;
break;
}
}
float baseLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ);
host.Session.SetContenderPose(slotA, -700f, liveZ, 0f);
host.StepOnce(nowMs += 16);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(liveX, liveZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f);
for (int t = 0; t < 10; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork();
Thread.Sleep(1);
}
float hostLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ);
Assert.True(hostLiveH < baseLiveH - 1.2f);
Assert.Equal(baseLiveH, clientA.ViewState.Terrain.SampleHeight(liveX, liveZ), precision: 3);
// 3. Client A enters 576m local geometry bubble (liveX - 450m -> dist = 450m <= 576m)
host.Session.SetContenderPose(slotA, liveX - 450f, liveZ, 0f);
Assert.True(PumpUntil(
host,
new[] { clientA },
() => MathF.Abs(clientA.ViewState.Terrain.SampleHeight(liveX, liveZ) - hostLiveH) < 0.05f,
ref nowMs,
3000),
"Client must receive live TerrainStampEvent upon entering 576m bubble before reaching _predWorld 3x3 window");
// 4. Client A steps into (liveX, liveZ) tile -> _predWorld 3x3 window matches server Box3D crater depth 1:1
host.Session.SetContenderPose(slotA, liveX - 20f, liveZ, 0f);
for (int t = 0; t < 10; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.BeginRenderFrame(1.0 / 60.0, 1f);
Thread.Sleep(1);
}
Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9);
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hostHit = host.Session.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f));
var predHit = clientA.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f));
Assert.True(hostHit.Hit && predHit.Hit);
Assert.True(MathF.Abs(hostHit.Point.Y - predHit.Point.Y) < 0.05f,
$"Expected _predWorld crater impact Y ({predHit.Point.Y:F3}m) to match server ({hostHit.Point.Y:F3}m)");
}
private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) => private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) =>
CultNetRudpPacketCodec.Encode(new CultNetRudpPacket CultNetRudpPacketCodec.Encode(new CultNetRudpPacket
{ {

View file

@ -1,6 +1,9 @@
using System; using System;
using System.IO;
using System.Net;
using System.Numerics; using System.Numerics;
using RustToDust.Core; using RustToDust.Core;
using RustToDust.Net;
using RustToDust.Ymir; using RustToDust.Ymir;
using Xunit; using Xunit;
using Ymir.Box3D; using Ymir.Box3D;
@ -16,20 +19,24 @@ namespace RustToDust.Tests
var meta = sion.Metadata; var meta = sion.Metadata;
Assert.Equal(3072f, meta.SizeMeters); Assert.Equal(3072f, meta.SizeMeters);
Assert.Equal(6, meta.TileGrid); Assert.Equal(16, meta.TileGrid);
Assert.Equal(512f, meta.TileSizeMeters); Assert.Equal(192f, meta.TileSizeMeters);
Assert.Equal(1025, meta.GridRes); Assert.Equal(6145, meta.GridRes);
Assert.Equal(3.0f, meta.CellSizeMeters); Assert.Equal(0.5f, meta.CellSizeMeters);
Assert.Equal("heightmap_05m.u16z", meta.HeightmapFile);
Assert.False(string.IsNullOrWhiteSpace(meta.DemAssetHash));
Assert.Contains("swisstopo", meta.Attribution, StringComparison.OrdinalIgnoreCase); Assert.Contains("swisstopo", meta.Attribution, StringComparison.OrdinalIgnoreCase);
Assert.Equal(1025 * 1025, sion.Heights.Length); Assert.Equal(6145 * 6145, sion.BaseDem.Length);
Assert.Equal(2319, sion.Buildings.Count); Assert.Equal(2319, sion.Buildings.Count);
Assert.Equal(36, sion.CollisionMeshes.Count); Assert.Equal(36, sion.CollisionMeshes.Count);
var terrain = TerrainField.LoadHeightmap( var terrain = TerrainField.LoadSharedHeightmap(
meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY); meta.SizeMeters, meta.GridRes, meta.TileGrid,
sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale,
meta.MinY, meta.MaxY);
// Verify Basilique de Valere and valley buildings align cleanly with heightmap.f32 (0.00m coordinate drift) // Verify Basilique de Valere and valley buildings align cleanly with heightmap_05m.u16z (0.00m coordinate drift)
bool foundValere = false; bool foundValere = false;
int flatAlignChecked = 0; int flatAlignChecked = 0;
int closeAlignCount = 0; int closeAlignCount = 0;
@ -82,16 +89,19 @@ namespace RustToDust.Tests
{ {
var sion = SionMapLoader.Load(); var sion = SionMapLoader.Load();
var meta = sion.Metadata; var meta = sion.Metadata;
var terrain = TerrainField.LoadHeightmap( var terrain = TerrainField.LoadSharedHeightmap(
meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY); meta.SizeMeters, meta.GridRes, meta.TileGrid,
sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale,
meta.MinY, meta.MaxY);
Assert.True(terrain.IsHeightmapMode); Assert.True(terrain.IsHeightmapMode);
Assert.Equal(3072f, terrain.MapSize); Assert.Equal(3072f, terrain.MapSize);
Assert.Equal(1536f, terrain.MapHalfExtent); Assert.Equal(1536f, terrain.MapHalfExtent);
Assert.Equal(16, terrain.TileGridCount);
// Grid vertex exactness at (-1536, -1536) and (0, 0) // Grid vertex exactness at (-1536, -1536) and (0, 0)
Assert.Equal(sion.Heights[0], terrain.SampleHeight(-1536f, -1536f), precision: 4); Assert.Equal(sion.SampleBaseDemAtIndex(0), terrain.SampleHeight(-1536f, -1536f), precision: 4);
Assert.Equal(sion.Heights[512 * 1025 + 512], terrain.SampleHeight(0f, 0f), precision: 4); Assert.Equal(sion.SampleBaseDemAtIndex(3072 * 6145 + 3072), terrain.SampleHeight(0f, 0f), precision: 4);
// Plaza spawn area is flat; Valere hill rises > 100m // Plaza spawn area is flat; Valere hill rises > 100m
var (_, plazaNy, _) = terrain.SampleNormal(-60f, 360f); var (_, plazaNy, _) = terrain.SampleNormal(-60f, 360f);
@ -126,7 +136,7 @@ namespace RustToDust.Tests
Assert.Empty(state.ArenaCoverBoxes); Assert.Empty(state.ArenaCoverBoxes);
Assert.Equal(MatchState.SionInitialSafeRadius, state.Spectators.SafeRadius); Assert.Equal(MatchState.SionInitialSafeRadius, state.Spectators.SafeRadius);
// Verify StaticHeightField (1) + StaticMesh (36) exist in Ymir // Verify lazy tiled StaticHeightField (192m tiles) + StaticMesh (36) exist in Ymir
int hfCount = 0; int hfCount = 0;
int meshCount = 0; int meshCount = 0;
var view = session.World.View; var view = session.World.View;
@ -136,7 +146,8 @@ namespace RustToDust.Tests
if (kind == Box3DSoaKind.StaticHeightField) hfCount++; if (kind == Box3DSoaKind.StaticHeightField) hfCount++;
else if (kind == Box3DSoaKind.StaticMesh) meshCount++; else if (kind == Box3DSoaKind.StaticMesh) meshCount++;
} }
Assert.Equal(1, hfCount); Assert.InRange(hfCount, 1, 255);
Assert.Equal(hfCount, session.TileSync.ResidentTileCount);
Assert.Equal(36, meshCount); Assert.Equal(36, meshCount);
// Verify zero contenders, spectators, or drops spawned inside any building // Verify zero contenders, spectators, or drops spawned inside any building
@ -225,5 +236,147 @@ namespace RustToDust.Tests
float pDisp = MathF.Sqrt((player.X - pStartX) * (player.X - pStartX) + (player.Z - pStartZ) * (player.Z - pStartZ)); 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"); Assert.True(pDisp > 5f, $"Expected player displacement > 5m on Sion after 180 ticks, got {pDisp:F2}m");
} }
[Fact]
public void SionBox3DTile_CraterRebuildsLocalTileOnlyAndLeavesNeighborsIntact()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
// Tile (7, 7) spans [-192, 0) x [-192, 0); neighbor tile (8, 7) spans [0, 192) x [-192, 0).
// Pick an open-sky coordinate strictly inside tile (7, 7) away from any building footprint.
var sion = session.State.SionMap!;
float cx = -96f, cz = -96f;
bool foundSpot = false;
for (float z = -176f; z <= -16f && !foundSpot; z += 8f)
{
for (float x = -176f; x <= -16f; x += 8f)
{
if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f))
{
cx = x;
cz = z;
foundSpot = true;
break;
}
}
}
Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)");
session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 1);
Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetBefore));
Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborBefore));
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hitBefore = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f));
Assert.True(hitBefore.Hit);
Assert.Equal(Box3DPhysicsTileSync.HeightfieldTileStableIdBase + (ulong)(7 * 16 + 7), hitBefore.StableId);
// Stamp crater strictly inside tile (7, 7)
session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = cx,
Z = cz,
Radius = 6f,
Depth = 2.0f
});
int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4);
Assert.Equal(1, rebuilt);
Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetAfter));
Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborAfter));
Assert.NotEqual(handleTargetBefore, handleTargetAfter);
Assert.Equal(handleNeighborBefore, handleNeighborAfter);
var hitAfter = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f));
Assert.True(hitAfter.Hit);
Assert.True(hitAfter.Point.Y < hitBefore.Point.Y - 1.2f,
$"Expected Box3D raycast impact height to drop in crater (before={hitBefore.Point.Y:F3}, after={hitAfter.Point.Y:F3})");
}
[Fact]
public void ArenaScarLedgerStore_PersistsCratersAndRubbleAcrossResetAndRepairsToLayer0()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-scar-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string scarPath = Path.Combine(tempDir, "sion_scars_test.cultcache");
try
{
const float craterX = -120f;
const float craterZ = 180f;
const float rubbleX = 140f;
const float rubbleZ = 180f;
float baseCraterH;
float baseRubbleH;
float scarredCraterH;
float scarredRubbleH;
using (var host1 = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: scarPath, persistScars: true))
{
var state1 = host1.Session.State;
baseCraterH = state1.Terrain.SampleHeight(craterX, craterZ);
baseRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ);
state1.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
state1.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Rubble,
X = rubbleX,
Z = rubbleZ,
Radius = 6.0f,
Depth = 1.2f,
Yaw = 0.4f
});
scarredCraterH = state1.Terrain.SampleHeight(craterX, craterZ);
scarredRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ);
Assert.True(scarredCraterH < baseCraterH - 1.2f);
Assert.True(scarredRubbleH > baseRubbleH + 0.6f);
// ResetMatch preserves scars in RAM & flushes to CultCache
host1.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
Assert.Equal(scarredCraterH, host1.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(scarredRubbleH, host1.Session.State.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
}
Assert.True(File.Exists(scarPath), "Expected CultCache scar file on disk after host dispose");
using (var host2 = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 44, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: scarPath, persistScars: true))
{
var state2 = host2.Session.State;
Assert.Equal(scarredCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(scarredRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
// RepairArenaScars zeroes back to Layer 0
host2.RepairArenaScars();
Assert.Equal(baseCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(baseRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
Assert.Empty(state2.ScarLedger.Terrain);
}
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
} }
} }

View file

@ -13,7 +13,7 @@ namespace RustToDust.Tests
public void Generate_ProducesDeterministicNonFlatReliefWithinBounds() public void Generate_ProducesDeterministicNonFlatReliefWithinBounds()
{ {
Assert.Equal(1536f, TerrainField.ArenaSize); Assert.Equal(1536f, TerrainField.ArenaSize);
Assert.Equal(8, TerrainField.TileGridCount); Assert.Equal(8, TerrainField.DesertTileGridCount);
Assert.Equal(192f, TerrainField.TileSize); Assert.Equal(192f, TerrainField.TileSize);
Assert.Equal(-18f, TerrainField.MinWorldHeight); Assert.Equal(-18f, TerrainField.MinWorldHeight);
Assert.Equal(52f, TerrainField.MaxWorldHeight); Assert.Equal(52f, TerrainField.MaxWorldHeight);
@ -56,7 +56,6 @@ namespace RustToDust.Tests
public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles() public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles()
{ {
var terrain = TerrainField.Generate(42UL, Array.Empty<ArenaBoxSpec>()); var terrain = TerrainField.Generate(42UL, Array.Empty<ArenaBoxSpec>());
terrain.ClearDirtyMask();
// Tile (3, 3) spans X in [-192, 0), Z in [-192, 0). // Tile (3, 3) spans X in [-192, 0), Z in [-192, 0).
// Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else. // Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else.
@ -79,15 +78,15 @@ namespace RustToDust.Tests
$"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})"); $"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})");
// Only tile (3, 3) should have incremented from version 1 to 2 // Only tile (3, 3) should have incremented from version 1 to 2
for (int tz = 0; tz < TerrainField.TileGridCount; tz++) for (int tz = 0; tz < terrain.TileGridCount; tz++)
{ {
for (int tx = 0; tx < TerrainField.TileGridCount; tx++) for (int tx = 0; tx < terrain.TileGridCount; tx++)
{ {
int expected = (tx == 3 && tz == 3) ? 2 : 1; int expected = (tx == 3 && tz == 3) ? 2 : 1;
Assert.Equal(expected, terrain.TileVersions[tx, tz]); Assert.Equal(expected, terrain.StructuralTileVersions[tx, tz]);
Assert.Equal(expected, terrain.VisualTileVersions[tx, tz]);
} }
} }
Assert.Equal(1UL << (3 * TerrainField.TileGridCount + 3), terrain.DirtyTileMask);
} }
[Fact] [Fact]

View file

@ -328,7 +328,7 @@ $vCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "vehicles") -Des
$gCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "gear") -DestDir (Join-Path $stagedAssetsDir "gear") -IncludeExtensions @(".glb") $gCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "gear") -DestDir (Join-Path $stagedAssetsDir "gear") -IncludeExtensions @(".glb")
$dCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "decals") -DestDir (Join-Path $stagedAssetsDir "decals") -IncludeExtensions @(".png") $dCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "decals") -DestDir (Join-Path $stagedAssetsDir "decals") -IncludeExtensions @(".png")
$aCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "audio") -DestDir (Join-Path $stagedAssetsDir "audio") -IncludeExtensions @(".wav", ".md") $aCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "audio") -DestDir (Join-Path $stagedAssetsDir "audio") -IncludeExtensions @(".wav", ".md")
$mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".f32", ".png", ".bin", ".glb") $mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".u16z", ".png", ".bin", ".glb")
Write-Host "Staged runtime assets: vehicles=$vCount gear=$gCount decals=$dCount audio=$aCount sion=$mCount" Write-Host "Staged runtime assets: vehicles=$vCount gear=$gCount decals=$dCount audio=$aCount sion=$mCount"
# Step 4: Create ZIP and SHA256SUMS.txt # Step 4: Create ZIP and SHA256SUMS.txt

View file

@ -27,6 +27,7 @@ import struct
import urllib.parse import urllib.parse
import urllib.request import urllib.request
import zipfile import zipfile
import zlib
from collections import Counter, defaultdict from collections import Counter, defaultdict
from pathlib import Path from pathlib import Path
@ -54,12 +55,15 @@ import tifffile
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
ARENA_SIZE_M = 3072.0 ARENA_SIZE_M = 3072.0
HALF_EXTENT_M = 1536.0 HALF_EXTENT_M = 1536.0
GRID_RES = 1025 GRID_RES = 6145
CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 3.0m exact CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 0.5m exact
TILE_GRID = 6 TILE_GRID = 16
TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 512.0m exact TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 192.0m exact
BUILDING_TILE_GRID = 6
BUILDING_TILE_SIZE_M = ARENA_SIZE_M / BUILDING_TILE_GRID # 512.0m legacy until Cut 13b
SURFACE_TEX_RES = 2048 SURFACE_TEX_RES = 4096
SURFACE_MASK_RES = 2048
# Centered around Valere & Tourbillon twin citadels to frame: # Centered around Valere & Tourbillon twin citadels to frame:
# - Valere & Tourbillon fortress hills # - Valere & Tourbillon fortress hills
@ -77,8 +81,8 @@ WMS_BASE_URL = "https://wms.geo.admin.ch/"
SKIRT_DEPTH_M = 4.0 SKIRT_DEPTH_M = 4.0
MAX_LOD1_TRIS = 275_000 MAX_LOD1_TRIS = 275_000
MAX_TILES_GLB_BYTES = 28_000_000 MAX_TILES_GLB_BYTES = 28_000_000
MAX_SURFACE_PNG_BYTES = 3_000_000 MAX_SURFACE_PNG_BYTES = 14_000_000
MAX_TOTAL_ASSETS_BYTES = 40_000_000 MAX_TOTAL_ASSETS_BYTES = 85_000_000
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@ -266,7 +270,7 @@ def acquire_swisstopo_data(
if (ek, nk) not in needed_tiles: if (ek, nk) not in needed_tiles:
continue continue
for asset_name, asset in item.get("assets", {}).items(): for asset_name, asset in item.get("assets", {}).items():
if "_2_2056_5728.tif" in asset_name: if "_0.5_2056_5728.tif" in asset_name:
prev = best_alti.get((ek, nk)) prev = best_alti.get((ek, nk))
if prev is None or yr > prev[0]: if prev is None or yr > prev[0]:
best_alti[(ek, nk)] = (yr, item["id"], asset_name, asset["href"]) best_alti[(ek, nk)] = (yr, item["id"], asset_name, asset["href"])
@ -320,7 +324,7 @@ def acquire_swisstopo_data(
def sample_mosaic_grid( def sample_mosaic_grid(
mosaic: np.ndarray, e_origin: float, n_top: float, center_e: float, center_n: float, res: int mosaic: np.ndarray, e_origin: float, n_top: float, center_e: float, center_n: float, res: int
) -> np.ndarray: ) -> np.ndarray:
pixel_m = 2.0 pixel_m = 0.5
step_m = ARENA_SIZE_M / (res - 1) step_m = ARENA_SIZE_M / (res - 1)
xs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m xs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m
zs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m zs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m
@ -337,7 +341,7 @@ def build_heightmap(
) -> tuple[np.ndarray, np.ndarray, float, float, float]: ) -> tuple[np.ndarray, np.ndarray, float, float, float]:
ekms = sorted({k[0] for k in tif_paths}) ekms = sorted({k[0] for k in tif_paths})
nkms = sorted({k[1] for k in tif_paths}, reverse=True) # north-to-south rows nkms = sorted({k[1] for k in tif_paths}, reverse=True) # north-to-south rows
tile_px = 500 tile_px = 2000
mosaic = np.zeros((len(nkms) * tile_px, len(ekms) * tile_px), dtype=np.float32) mosaic = np.zeros((len(nkms) * tile_px, len(ekms) * tile_px), dtype=np.float32)
for ni, nk in enumerate(nkms): for ni, nk in enumerate(nkms):
@ -351,8 +355,8 @@ def build_heightmap(
n_top = (nkms[0] + 1) * 1000.0 n_top = (nkms[0] + 1) * 1000.0
# Grid coordinates in RustToDust: # Grid coordinates in RustToDust:
# row iz (0..1024): Z = -1536 + iz * 3.0 (North -> South), N = center_n - Z # row iz (0..6144): Z = -1536 + iz * 0.5 (North -> South), N = center_n - Z
# col ix (0..1024): X = -1536 + ix * 3.0 (West -> East), E = center_e + X # col ix (0..6144): X = -1536 + ix * 0.5 (West -> East), E = center_e + X
hm_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, GRID_RES) hm_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, GRID_RES)
surf_dem_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, SURFACE_TEX_RES) surf_dem_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, SURFACE_TEX_RES)
@ -362,6 +366,37 @@ def build_heightmap(
return hm_rel, surf_dem_asl, base_elev, float(hm_rel.min()), float(hm_rel.max()) return hm_rel, surf_dem_asl, base_elev, float(hm_rel.min()), float(hm_rel.max())
def export_heightmap_u16z(hm: np.ndarray, out_path: Path) -> tuple[float, float, str]:
"""
Export 0.5m quantized heightmap as heightmap_05m.u16z:
Header (24 bytes LE):
magic="RDHM", uint32 version=2, uint32 gridRes=6145,
float32 minY, float32 scale, uint32 rawByteCount
Payload:
zlib-compressed row-wise zig-zag int16 spatial prediction residuals of uint16[gridRes*gridRes].
"""
min_y = float(np.float32(hm.min()))
max_y = float(np.float32(hm.max()))
scale = float(np.float32(max(1e-6, (max_y - min_y) / 65535.0)))
q = np.clip(np.round((hm.astype(np.float64) - min_y) / scale), 0, 65535).astype(np.uint16)
pred = np.empty_like(q)
pred[0, 0] = 0
pred[1:, 0] = q[:-1, 0]
pred[:, 1:] = q[:, :-1]
diff = (q.astype(np.int32) - pred.astype(np.int32)).astype(np.int16)
d32 = diff.astype(np.int32)
zz = (((d32 << 1) ^ (d32 >> 15)) & 0xFFFF).astype(np.uint16)
raw_bytes = np.ascontiguousarray(zz, dtype="<u2").tobytes()
compressed = zlib.compress(raw_bytes, level=6)
header = struct.pack("<4sIIffI", b"RDHM", 2, int(hm.shape[0]), min_y, scale, len(raw_bytes))
payload = header + compressed
out_path.write_bytes(payload)
dem_hash = hashlib.sha256(payload).hexdigest()
return min_y, scale, dem_hash
def acquire_wms_masks( def acquire_wms_masks(
cache_dir: Path, e0: float, n0: float, e1: float, n1: float, res: int = SURFACE_TEX_RES cache_dir: Path, e0: float, n0: float, e1: float, n1: float, res: int = SURFACE_TEX_RES
) -> dict[str, np.ndarray]: ) -> dict[str, np.ndarray]:
@ -386,9 +421,18 @@ def acquire_wms_masks(
print(f" [WMS fetch] {layer} -> {dest.name}") print(f" [WMS fetch] {layer} -> {dest.name}")
req = urllib.request.Request(url, headers={"User-Agent": "RustToDust-SionBaker/1.0"}) req = urllib.request.Request(url, headers={"User-Agent": "RustToDust-SionBaker/1.0"})
tmp = dest.with_suffix(".png.part") tmp = dest.with_suffix(".png.part")
with urllib.request.urlopen(req, timeout=45) as resp: try:
tmp.write_bytes(resp.read()) with urllib.request.urlopen(req, timeout=45) as resp:
tmp.replace(dest) tmp.write_bytes(resp.read())
tmp.replace(dest)
except Exception:
if res > 2048:
fallback = acquire_wms_masks(cache_dir, e0, n0, e1, n1, 2048)
return {
k: zoom(v, (res / v.shape[0], res / v.shape[1], 1), order=1)
for k, v in fallback.items()
}
raise
out[key] = imagecodecs.png_decode(dest.read_bytes()) out[key] = imagecodecs.png_decode(dest.read_bytes())
return out return out
@ -452,13 +496,10 @@ def build_terrain_surface_texture(
fp_res_tris: list[np.ndarray], fp_res_tris: list[np.ndarray],
fp_ind_tris: list[np.ndarray], fp_ind_tris: list[np.ndarray],
fp_fort_tris: list[np.ndarray], fp_fort_tris: list[np.ndarray],
) -> bytes: ) -> tuple[bytes, bytes]:
""" """
Synthesize 2048x2048 RGB surface albedo PNG (< 3 MB) combining: Synthesize 4096x4096 RGB surface albedo PNG and 2048x2048 RGBA8 surface class mask PNG
- Grey alpine limestone cliffs (steep Valere / Tourbillon / hillside slopes) (R=rock_cliff, G=grass_vineyard, B=asphalt_gravel, A=water_channel).
- Valley meadows, terraced vineyards & alpine forest slopes
- Old Town stone plazas, industrial yards, rail ballast & road/bridge network
- Rhone river & canal glacial teal-blue water tint
""" """
res = dem_asl.shape[0] res = dem_asl.shape[0]
px_m = ARENA_SIZE_M / (res - 1) # 1.5m/px px_m = ARENA_SIZE_M / (res - 1) # 1.5m/px
@ -572,6 +613,7 @@ def build_terrain_surface_texture(
water_col = np.array([0.13, 0.27, 0.34], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.03 water_col = np.array([0.13, 0.27, 0.34], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.03
rgb = rgb * (1.0 - water_soft[..., None] * 0.96) + water_col * (water_soft[..., None] * 0.96) rgb = rgb * (1.0 - water_soft[..., None] * 0.96) + water_col * (water_soft[..., None] * 0.96)
road_total = np.zeros((res, res), dtype=np.float32)
# 6. Roads, highway A9 & bridges (drawn after water so bridges span the Rhone!) # 6. Roads, highway A9 & bridges (drawn after water so bridges span the Rhone!)
if wms_masks and "roads" in wms_masks: if wms_masks and "roads" in wms_masks:
r_rgba = wms_masks["roads"] r_rgba = wms_masks["roads"]
@ -586,11 +628,28 @@ def build_terrain_surface_texture(
highway_col = np.array([0.25, 0.25, 0.26], dtype=np.float32) highway_col = np.array([0.25, 0.25, 0.26], dtype=np.float32)
rgb = rgb * (1.0 - minor_soft[..., None] * 0.72) + street_col * (minor_soft[..., None] * 0.72) rgb = rgb * (1.0 - minor_soft[..., None] * 0.72) + street_col * (minor_soft[..., None] * 0.72)
rgb = rgb * (1.0 - major_soft[..., None] * 0.88) + highway_col * (major_soft[..., None] * 0.88) rgb = rgb * (1.0 - major_soft[..., None] * 0.88) + highway_col * (major_soft[..., None] * 0.88)
road_total = np.clip(np.maximum(minor_soft, major_soft), 0.0, 1.0)
# Darken slightly under exact building footprints for subtle ambient grounding # Darken slightly under exact building footprints for subtle ambient grounding
bldg_under = (mask_res | mask_ind | mask_fort) & (normal_y > 0.75) bldg_under = (mask_res | mask_ind | mask_fort) & (normal_y > 0.75)
rgb[bldg_under] *= 0.88 rgb[bldg_under] *= 0.88
# Build 2048x2048 RGBA8 surface class mask:
# R = rock_cliff, G = grass_vineyard, B = asphalt_gravel, A = water_channel
water_ch = gaussian_filter(water_mask.astype(np.float32), sigma=1.0) if np.any(water_mask) else np.zeros((res, res), dtype=np.float32)
rail_ch = gaussian_filter(binary_dilation(wms_masks["rail"][..., 3] > 50, iterations=4).astype(np.float32), sigma=1.2) if (wms_masks and "rail" in wms_masks) else np.zeros((res, res), dtype=np.float32)
asphalt_gravel = np.clip(np.maximum(road_total, np.maximum(rail_ch, np.maximum(res_soft, np.maximum(ind_soft, fort_soft)))), 0.0, 1.0)
rock_cliff = np.clip(cliff_t, 0.0, 1.0)
grass_vineyard = np.clip((1.0 - rock_cliff) * (1.0 - water_ch) * (1.0 - asphalt_gravel * 0.85), 0.0, 1.0)
mask_full = np.stack([rock_cliff, grass_vineyard, asphalt_gravel, np.clip(water_ch, 0.0, 1.0)], axis=-1)
step = max(1, res // SURFACE_MASK_RES)
if step > 1:
mask_ds = mask_full.reshape(SURFACE_MASK_RES, step, SURFACE_MASK_RES, step, 4).mean(axis=(1, 3))
else:
mask_ds = mask_full
mask_u8 = np.clip(np.round(mask_ds * 255.0), 0, 255).astype(np.uint8)
mask_png_bytes = imagecodecs.png_encode(mask_u8, level=9)
rgb_u8 = np.clip(np.round(rgb * 255.0), 0, 255).astype(np.uint8) rgb_u8 = np.clip(np.round(rgb * 255.0), 0, 255).astype(np.uint8)
png_bytes = imagecodecs.png_encode(rgb_u8, level=9) png_bytes = imagecodecs.png_encode(rgb_u8, level=9)
if len(png_bytes) >= MAX_SURFACE_PNG_BYTES: if len(png_bytes) >= MAX_SURFACE_PNG_BYTES:
@ -600,7 +659,7 @@ def build_terrain_surface_texture(
if len(png_bytes) >= MAX_SURFACE_PNG_BYTES: if len(png_bytes) >= MAX_SURFACE_PNG_BYTES:
rgb_u8 = (rgb_u8 & 0xFC) rgb_u8 = (rgb_u8 & 0xFC)
png_bytes = imagecodecs.png_encode(rgb_u8, level=9) png_bytes = imagecodecs.png_encode(rgb_u8, level=9)
return png_bytes return png_bytes, mask_png_bytes
def sample_heightmap(hm: np.ndarray, x: np.ndarray | float, z: np.ndarray | float) -> np.ndarray | float: def sample_heightmap(hm: np.ndarray, x: np.ndarray | float, z: np.ndarray | float) -> np.ndarray | float:
@ -1715,6 +1774,7 @@ def main() -> None:
parser.add_argument("--cache-dir", default=os.path.join(os.environ.get("TEMP", "/tmp"), "sion-cache")) parser.add_argument("--cache-dir", default=os.path.join(os.environ.get("TEMP", "/tmp"), "sion-cache"))
parser.add_argument("--center-e", type=float, default=DEFAULT_CENTER_E) parser.add_argument("--center-e", type=float, default=DEFAULT_CENTER_E)
parser.add_argument("--center-n", type=float, default=DEFAULT_CENTER_N) parser.add_argument("--center-n", type=float, default=DEFAULT_CENTER_N)
parser.add_argument("--terrain-only", action="store_true", help="Re-bake 0.5m DEM, surface, mask & metadata.json while preserving existing tiles/ & buildings_manifest.json")
args = parser.parse_args() args = parser.parse_args()
repo_root = Path(args.repo_root).resolve() repo_root = Path(args.repo_root).resolve()
@ -1725,21 +1785,23 @@ def main() -> None:
cache_dir = Path(args.cache_dir) cache_dir = Path(args.cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True) cache_dir.mkdir(parents=True, exist_ok=True)
# Cut obsolete single-monolith GLBs & any stale tile files before baking # Cut obsolete single-monolith GLBs & legacy float32 heightmap
for obsolete in ("sion_lod2.glb", "sion_lod1.glb"): for obsolete in ("sion_lod2.glb", "sion_lod1.glb", "heightmap.f32"):
obs_path = out_dir / obsolete obs_path = out_dir / obsolete
if obs_path.exists(): if obs_path.exists():
obs_path.unlink() obs_path.unlink()
print(f"[Sion Baker] Removed obsolete monolith {obs_path.name}") print(f"[Sion Baker] Removed obsolete {obs_path.name}")
for stale in tiles_dir.iterdir(): if not args.terrain_only:
if stale.is_file(): for stale in tiles_dir.iterdir():
stale.unlink() if stale.is_file():
stale.unlink()
cE, cN = args.center_e, args.center_n cE, cN = args.center_e, args.center_n
e0, n0, e1, n1 = cE - HALF_EXTENT_M, cN - HALF_EXTENT_M, cE + HALF_EXTENT_M, cN + HALF_EXTENT_M e0, n0, e1, n1 = cE - HALF_EXTENT_M, cN - HALF_EXTENT_M, cE + HALF_EXTENT_M, cN + HALF_EXTENT_M
print( print(
f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m ({TILE_GRID}x{TILE_GRID} tiles of {TILE_SIZE_M:.0f}m) " f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m (terrain {TILE_GRID}x{TILE_GRID} @ {TILE_SIZE_M:.0f}m, "
f"bldg {BUILDING_TILE_GRID}x{BUILDING_TILE_GRID} @ {BUILDING_TILE_SIZE_M:.0f}m) "
f"EPSG:2056 center=({cE:.1f}, {cN:.1f}) bbox=[{e0:.1f}..{e1:.1f}, {n0:.1f}..{n1:.1f}]" f"EPSG:2056 center=({cE:.1f}, {cN:.1f}) bbox=[{e0:.1f}..{e1:.1f}, {n0:.1f}..{n1:.1f}]"
) )
tif_paths, gdb_paths, stac_ids = acquire_swisstopo_data(cache_dir, e0, n0, e1, n1) tif_paths, gdb_paths, stac_ids = acquire_swisstopo_data(cache_dir, e0, n0, e1, n1)
@ -1750,15 +1812,105 @@ def main() -> None:
except Exception as exc: except Exception as exc:
print(f" [WMS warning] Falling back to DEM-only river/road synthesis ({exc})") print(f" [WMS warning] Falling back to DEM-only river/road synthesis ({exc})")
print(f"[Sion Baker] Stitching & resampling swissALTI3D to {GRID_RES}x{GRID_RES} float32...") print(f"[Sion Baker] Stitching & resampling swissALTI3D 0.5m to {GRID_RES}x{GRID_RES}...")
hm, surf_dem_asl, base_elev, min_y, max_y = build_heightmap(tif_paths, cE, cN) hm, surf_dem_asl, base_elev, min_y, max_y = build_heightmap(tif_paths, cE, cN)
hm_path = out_dir / "heightmap.f32" hm_path = out_dir / "heightmap_05m.u16z"
hm.astype("<f4").tofile(str(hm_path)) hm_min_y, hm_scale, dem_hash = export_heightmap_u16z(hm, hm_path)
print( print(
f" heightmap.f32: {hm.shape}, {hm_path.stat().st_size:,} bytes, " f" heightmap_05m.u16z: {hm.shape}, {hm_path.stat().st_size:,} bytes, "
f"baseElevationM={base_elev:.2f}m, Y=[{min_y:.2f}, {max_y:.2f}]m (relief={max_y - min_y:.2f}m)" f"baseElevationM={base_elev:.2f}m, Y=[{min_y:.2f}, {max_y:.2f}]m (scale={hm_scale:.6f}m/step, sha256={dem_hash[:12]}...)"
) )
if args.terrain_only:
meta_path = out_dir / "metadata.json"
existing_meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.exists() else {}
manifest_path = out_dir / "buildings_manifest.json"
manifest_data = json.loads(manifest_path.read_text(encoding="utf-8"))
fp_res_tris: list[np.ndarray] = []
fp_ind_tris: list[np.ndarray] = []
fp_fort_tris: list[np.ndarray] = []
for b in manifest_data.get("buildings", []):
cx, cz = float(b["center"][0]), float(b["center"][2])
hx, hz = float(b["size"][0]) * 0.5, float(b["size"][2]) * 0.5
gy = float(b.get("groundY", 0.0))
p0 = np.array([cx - hx, gy, cz - hz])
p1 = np.array([cx + hx, gy, cz - hz])
p2 = np.array([cx + hx, gy, cz + hz])
p3 = np.array([cx - hx, gy, cz + hz])
t1 = np.stack([p0, p1, p2], axis=0)
t2 = np.stack([p0, p2, p3], axis=0)
st = b.get("archStyle", "residential")
if st == "fortress":
fp_fort_tris.extend((t1, t2))
elif st == "industrial":
fp_ind_tris.extend((t1, t2))
else:
fp_res_tris.extend((t1, t2))
print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png + {SURFACE_MASK_RES}x{SURFACE_MASK_RES} terrain_surface_mask.png...")
surf_png, mask_png = build_terrain_surface_texture(
surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris
)
surf_path = out_dir / "terrain_surface.png"
surf_path.write_bytes(surf_png)
mask_path = out_dir / "terrain_surface_mask.png"
mask_path.write_bytes(mask_png)
print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)")
print(f" terrain_surface_mask.png: {len(mask_png):,} bytes ({len(mask_png)/1e6:.2f} MB)")
meta = {
"name": "Sion, Valais, Switzerland",
"attribution": "Federal Office of Topography swisstopo",
"sources": [
"ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)",
"ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)",
],
"stacItems": stac_ids,
"demAssetHash": dem_hash,
"crs": "EPSG:2056",
"originE": e0,
"originN": n0,
"centerE": cE,
"centerN": cN,
"baseElevationM": base_elev,
"minY": round(min_y, 3),
"maxY": round(max_y, 3),
"reliefM": round(max_y - min_y, 3),
"sizeMeters": ARENA_SIZE_M,
"tileGrid": TILE_GRID,
"tileSizeMeters": TILE_SIZE_M,
"buildingTileGrid": BUILDING_TILE_GRID,
"buildingTileSizeMeters": BUILDING_TILE_SIZE_M,
"gridRes": GRID_RES,
"cellSizeMeters": CELL_SIZE_M,
"heightmapFile": "heightmap_05m.u16z",
"heightmapFormat": "rdhm_v2_u16_zigzag_zlib",
"heightmapMinY": hm_min_y,
"heightmapScale": hm_scale,
"surfaceTexture": "terrain_surface.png",
"surfaceTextureSize": SURFACE_TEX_RES,
"surfaceTextureFormat": "png_rgb_north_to_south_west_to_east",
"surfaceMaskTexture": "terrain_surface_mask.png",
"surfaceMaskTextureSize": SURFACE_MASK_RES,
"surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water",
"collisionFormat": existing_meta.get("collisionFormat", {}),
"rowOrder": "north_to_south_z_neg_to_pos",
"colOrder": "west_to_east_x_neg_to_pos",
"coordinateTransform": {
"X": "E - centerE (East = +X)",
"Y": "Z_asl - baseElevationM (Up = +Y)",
"Z": "-(N - centerN) (North = -Z)",
},
"tileCount": existing_meta.get("tileCount", len(existing_meta.get("tiles", []))),
"tiles": existing_meta.get("tiles", []),
}
meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")
total_assets_bytes = sum(p.stat().st_size for p in out_dir.rglob("*") if p.is_file())
print(f"[Sion Baker] Terrain-only complete | Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< {MAX_TOTAL_ASSETS_BYTES/1e6:.0f} MB limit)")
if total_assets_bytes >= MAX_TOTAL_ASSETS_BYTES:
raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes >= {MAX_TOTAL_ASSETS_BYTES}")
return
# Read semantic layers across intersecting GDB tiles # Read semantic layers across intersecting GDB tiles
print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...") print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...")
reader = OgrReader() reader = OgrReader()
@ -1877,8 +2029,8 @@ def main() -> None:
bmax = all_rtd_pts.max(axis=0) bmax = all_rtd_pts.max(axis=0)
box_center = (bmin + bmax) * 0.5 box_center = (bmin + bmax) * 0.5
tx = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / TILE_SIZE_M)))) tx = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M))))
tz = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / TILE_SIZE_M)))) tz = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M))))
tkey = (tx, tz) tkey = (tx, tz)
tile_bldg_counts[tkey] += 1 tile_bldg_counts[tkey] += 1
@ -1942,16 +2094,19 @@ def main() -> None:
} }
) )
# Bake 2048x2048 terrain_surface.png albedo # Bake 4096x4096 terrain_surface.png albedo + 2048x2048 terrain_surface_mask.png
print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png...") print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png + {SURFACE_MASK_RES}x{SURFACE_MASK_RES} terrain_surface_mask.png...")
surf_png = build_terrain_surface_texture( surf_png, mask_png = build_terrain_surface_texture(
surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris
) )
surf_path = out_dir / "terrain_surface.png" surf_path = out_dir / "terrain_surface.png"
surf_path.write_bytes(surf_png) surf_path.write_bytes(surf_png)
mask_path = out_dir / "terrain_surface_mask.png"
mask_path.write_bytes(mask_png)
print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)") print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)")
print(f" terrain_surface_mask.png: {len(mask_png):,} bytes ({len(mask_png)/1e6:.2f} MB)")
if len(surf_png) >= MAX_SURFACE_PNG_BYTES: if len(surf_png) >= MAX_SURFACE_PNG_BYTES:
raise RuntimeError(f"terrain_surface.png exceeded 3 MB budget: {len(surf_png)} bytes") raise RuntimeError(f"terrain_surface.png exceeded budget: {len(surf_png)} bytes")
# Export per-tile LOD2 GLBs & RCOL v1 collision bins # Export per-tile LOD2 GLBs & RCOL v1 collision bins
non_empty_tiles = sorted(tile_bldg_counts.keys()) non_empty_tiles = sorted(tile_bldg_counts.keys())
@ -1971,8 +2126,8 @@ def main() -> None:
total_lod2_bytes += l2_bytes total_lod2_bytes += l2_bytes
total_col_tris += c_tris total_col_tris += c_tris
total_col_bytes += c_bytes total_col_bytes += c_bytes
tile_cx = -HALF_EXTENT_M + (tx + 0.5) * TILE_SIZE_M tile_cx = -HALF_EXTENT_M + (tx + 0.5) * BUILDING_TILE_SIZE_M
tile_cz = -HALF_EXTENT_M + (tz + 0.5) * TILE_SIZE_M tile_cz = -HALF_EXTENT_M + (tz + 0.5) * BUILDING_TILE_SIZE_M
tile_stats[tkey] = { tile_stats[tkey] = {
"tx": tx, "tx": tx,
"tz": tz, "tz": tz,
@ -2035,8 +2190,8 @@ def main() -> None:
"coordinateSystem": "rusttodust_arena_gltf", "coordinateSystem": "rusttodust_arena_gltf",
"attribution": "Federal Office of Topography swisstopo", "attribution": "Federal Office of Topography swisstopo",
"sizeMeters": ARENA_SIZE_M, "sizeMeters": ARENA_SIZE_M,
"tileGrid": TILE_GRID, "tileGrid": BUILDING_TILE_GRID,
"tileSizeMeters": TILE_SIZE_M, "tileSizeMeters": BUILDING_TILE_SIZE_M,
"count": len(manifest_entries), "count": len(manifest_entries),
"classes": dict(class_counts.most_common()), "classes": dict(class_counts.most_common()),
"buildings": manifest_entries, "buildings": manifest_entries,
@ -2048,10 +2203,11 @@ def main() -> None:
"name": "Sion, Valais, Switzerland", "name": "Sion, Valais, Switzerland",
"attribution": "Federal Office of Topography swisstopo", "attribution": "Federal Office of Topography swisstopo",
"sources": [ "sources": [
"ch.swisstopo.swissalti3d (2m DTM, Open Government Data)", "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)",
"ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)", "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)",
], ],
"stacItems": stac_ids, "stacItems": stac_ids,
"demAssetHash": dem_hash,
"crs": "EPSG:2056", "crs": "EPSG:2056",
"originE": e0, "originE": e0,
"originN": n0, "originN": n0,
@ -2064,12 +2220,20 @@ def main() -> None:
"sizeMeters": ARENA_SIZE_M, "sizeMeters": ARENA_SIZE_M,
"tileGrid": TILE_GRID, "tileGrid": TILE_GRID,
"tileSizeMeters": TILE_SIZE_M, "tileSizeMeters": TILE_SIZE_M,
"buildingTileGrid": BUILDING_TILE_GRID,
"buildingTileSizeMeters": BUILDING_TILE_SIZE_M,
"gridRes": GRID_RES, "gridRes": GRID_RES,
"cellSizeMeters": CELL_SIZE_M, "cellSizeMeters": CELL_SIZE_M,
"heightmapFormat": "float32_le_row_major", "heightmapFile": "heightmap_05m.u16z",
"heightmapFormat": "rdhm_v2_u16_zigzag_zlib",
"heightmapMinY": hm_min_y,
"heightmapScale": hm_scale,
"surfaceTexture": "terrain_surface.png", "surfaceTexture": "terrain_surface.png",
"surfaceTextureSize": SURFACE_TEX_RES, "surfaceTextureSize": SURFACE_TEX_RES,
"surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east",
"surfaceMaskTexture": "terrain_surface_mask.png",
"surfaceMaskTextureSize": SURFACE_MASK_RES,
"surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water",
"collisionFormat": { "collisionFormat": {
"magic": "RCOL", "magic": "RCOL",
"version": 1, "version": 1,