RustToDust/client/TerrainRenderer.cs

1272 lines
45 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Unified Layer-0 + live GPU brush compute terrain renderer for both Desert (8x8) and Sion (16x16).
/// Replaces permanent SubViewports and CanvasItem brush shaders with one compute shader
/// (<c>terrain_tile_bake.glsl</c>) writing sparse 388x388 <see cref="Texture2Drd"/> delta slots
/// in an LRU pool (max 96 active scarred tiles; untouched tiles bind a 1x1 neutral fallback),
/// rendered via 3 exact-ratio shared PlaneMeshes (192/48/12) with zero T-junction edge morphing.
/// </summary>
public partial class TerrainRenderer : Node3D
{
public const int DeltaTexSize = 388;
public const float InnerTexelSpan = 384.0f;
public const float GutterStartIndex = 2.0f;
public const float GutterCenterOffset = 2.5f;
public const int MaxGpuScarTiles = 96;
public const int MaxDirtyRebakesPerSync = 4;
private const int BrushStrideBytes = 48;
private const int PushConstantBytes = 48;
private const int MaxSsboBrushes = 8192;
private const int GroundTintGridSize = 128;
private static readonly Color DesertAlbedoClear = new(0.69f, 0.50f, 0.31f, 1.0f);
private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f);
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct GpuBrush
{
public Vector4 PosRot;
public Vector4 RadDelta;
public Vector4 MatColor;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct TileBakePush
{
public Vector4 TileOriginAndSpan;
public Vector4 BaseColorAndGutter;
public uint BrushStart;
public uint BrushCount;
public uint TexSize;
public uint IsSion;
}
private sealed class TileNode
{
public int Tx;
public int Tz;
public float OriginX;
public float OriginZ;
public MeshInstance3D SurfaceMesh = null!;
public ShaderMaterial SurfaceMat = null!;
public int BakedStructuralVersion = -1;
public int BakedVisualVersion = -1;
public int LruSlotIndex = -1;
public float TileQuads = 192f;
public float SentTileQuads = -1f;
public Vector4 SentNeighborQuads = new(-1f, -1f, -1f, -1f);
}
private sealed class LruSlot
{
public int SlotIndex;
public Rid DeltaHeightRid;
public Rid DeltaAlbedoRid;
public Rid UniformSetRid;
public Texture2Drd DeltaHeightTex = null!;
public Texture2Drd DeltaAlbedoTex = null!;
public int AssignedTileIndex = -1;
public ulong LastUsedSeq;
public bool IsRdAllocated;
}
private sealed class PendingBakeJob
{
public int SlotIndex;
public float TileOriginX;
public float TileOriginZ;
public float TileSize;
public bool IsSion;
public GpuBrush[] Brushes = Array.Empty<GpuBrush>();
}
private TileNode[,]? _tiles;
private int _gridCount;
private float _tileSize = TerrainField.TileSize;
private float _mapSize = TerrainField.ArenaSize;
private readonly LruSlot[] _lruPool = new LruSlot[MaxGpuScarTiles];
private ulong _lruClock;
private PlaneMesh _nearPlaneMesh = null!;
private PlaneMesh _midPlaneMesh = null!;
private PlaneMesh _farPlaneMesh = null!;
private Shader _surfaceShader = null!;
private ImageTexture _neutralDeltaHeightTex = null!;
private ImageTexture _neutralDeltaAlbedoTex = null!;
private ImageTexture _zeroDem1x1Tex = null!;
private ImageTexture _whiteSurface1x1Tex = null!;
private ImageTexture _zeroMask1x1Tex = null!;
private Texture2Drd? _sionDemTexRd;
private Rid _sionDemRid;
private byte[]? _pendingSionDemUpload;
private int _pendingSionDemRes;
private ImageTexture? _sionSurfaceTex;
private ImageTexture? _sionMaskTex;
private Color[]? _groundTintGrid;
private float _groundTintSizeM;
private string? _loadedSionDir;
private float _sionDemMinY;
private float _sionDemScaleSpan;
private TerrainField? _lastTerrain;
private SionMapData? _lastSionMap;
private Vector3 _lastCamPos;
private int _rebakeCursor;
private readonly List<(int Idx, float DistSq)> _scarCandidateScratch = new(256);
private readonly List<(int Slot, float DistSq)> _lodResidentScratch = new(MaxGpuScarTiles);
// Render-thread compute state
private readonly object _jobLock = new();
private readonly List<PendingBakeJob> _pendingJobs = new();
private readonly byte[] _ssboStagingBytes = new byte[MaxSsboBrushes * BrushStrideBytes];
private readonly byte[] _pushBytes = new byte[PushConstantBytes];
private volatile bool _hasQueuedRdFlush;
private bool _rdInitialized;
private bool _rdFailed;
private Rid _bakeShaderRid;
private Rid _bakePipeRid;
private Rid _brushSsboRid;
// Synchronous test readback state (main thread calls ForceSync + readback via CallOnRenderThread)
private Rid _readbackTargetRid;
private byte[]? _readbackResult;
public int BakedTileCount { get; private set; }
public int DirtyRebakes { get; private set; }
public int ActiveGpuScarSlots
{
get
{
int count = 0;
for (int i = 0; i < _lruPool.Length; i++)
{
if (_lruPool[i] is not null && _lruPool[i].AssignedTileIndex >= 0)
{
count++;
}
}
return count;
}
}
public static double PerfBakeTileMs;
public static int PerfBakeTileCalls;
public override void _Ready()
{
var neutralHImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah);
neutralHImg.SetPixel(0, 0, new Color(0f, 0.88f, 0f, 0f));
_neutralDeltaHeightTex = ImageTexture.CreateFromImage(neutralHImg);
var neutralAImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8);
neutralAImg.SetPixel(0, 0, new Color(DesertAlbedoClear.R, DesertAlbedoClear.G, DesertAlbedoClear.B, 1.0f));
_neutralDeltaAlbedoTex = ImageTexture.CreateFromImage(neutralAImg);
var zeroDemImg = Image.CreateEmpty(1, 1, false, Image.Format.Rh);
zeroDemImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 1f));
_zeroDem1x1Tex = ImageTexture.CreateFromImage(zeroDemImg);
var surf1x1Img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8);
surf1x1Img.SetPixel(0, 0, Colors.White);
_whiteSurface1x1Tex = ImageTexture.CreateFromImage(surf1x1Img);
var mask1x1Img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8);
mask1x1Img.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f));
_zeroMask1x1Tex = ImageTexture.CreateFromImage(mask1x1Img);
_surfaceShader = GD.Load<Shader>("res://terrain_surface.gdshader")
?? throw new InvalidOperationException("Failed to load res://terrain_surface.gdshader");
for (int i = 0; i < MaxGpuScarTiles; i++)
{
_lruPool[i] = new LruSlot
{
SlotIndex = i,
DeltaHeightTex = new Texture2Drd(),
DeltaAlbedoTex = new Texture2Drd()
};
}
}
public override void _ExitTree()
{
base._ExitTree();
if (RenderingServer.GetRenderingDevice() is not null)
{
RenderingServer.CallOnRenderThread(Callable.From(DisposeRdResourcesOnRenderThread));
RenderingServer.ForceSync();
}
}
public void InvalidateAll()
{
if (_tiles is not null)
{
for (int tz = 0; tz < _gridCount; tz++)
{
for (int tx = 0; tx < _gridCount; tx++)
{
var t = _tiles[tx, tz];
if (t is null) continue;
t.BakedStructuralVersion = -1;
t.BakedVisualVersion = -1;
ReleaseTileSlot(t);
}
}
}
for (int i = 0; i < _lruPool.Length; i++)
{
if (_lruPool[i] is not null)
{
_lruPool[i].AssignedTileIndex = -1;
_lruPool[i].LastUsedSeq = 0;
}
}
BakedTileCount = 0;
DirtyRebakes = 0;
_rebakeCursor = 0;
_lastTerrain = null;
}
public void Sync(TerrainField terrain, SionMapData? sionMap = null)
{
bool mapChanged = !ReferenceEquals(_lastTerrain, terrain) || !ReferenceEquals(_lastSionMap, sionMap);
if (mapChanged)
{
InvalidateAll();
EnsureGridAllocated(terrain, sionMap);
_lastTerrain = terrain;
_lastSionMap = sionMap;
}
if (_tiles is null)
{
return;
}
int grid = terrain.TileGridCount;
int totalTiles = grid * grid;
bool isSion = sionMap is not null;
float halfTile = _tileSize * 0.5f;
Span<bool> wantSlot = stackalloc bool[totalTiles];
if (!isSion)
{
wantSlot.Fill(true);
}
else
{
_scarCandidateScratch.Clear();
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
if (terrain.GetTileBrushIndices(tx, tz).Count > 0)
{
var tile = _tiles[tx, tz];
float dx = (tile.OriginX + halfTile) - _lastCamPos.X;
float dz = (tile.OriginZ + halfTile) - _lastCamPos.Z;
_scarCandidateScratch.Add((tz * grid + tx, dx * dx + dz * dz));
}
}
}
if (_scarCandidateScratch.Count <= MaxGpuScarTiles)
{
for (int i = 0; i < _scarCandidateScratch.Count; i++)
{
wantSlot[_scarCandidateScratch[i].Idx] = true;
}
}
else
{
_scarCandidateScratch.Sort((a, b) => a.DistSq.CompareTo(b.DistSq));
for (int i = 0; i < MaxGpuScarTiles; i++)
{
wantSlot[_scarCandidateScratch[i].Idx] = true;
}
}
}
// 0. Release LRU slots on tiles outside the active top-96 scarred set (graceful Layer-0 DEM fallback)
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (!wantSlot[idx])
{
var tile = _tiles[tx, tz];
if (tile.LruSlotIndex >= 0)
{
ReleaseTileSlot(tile);
tile.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex);
tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex);
}
}
}
}
// 1. Structural dirty tiles, uninitialized tiles, and newly promoted top-96 tiles bake immediately (never throttled)
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
var tile = _tiles[tx, tz];
int structVer = terrain.StructuralTileVersions[tx, tz];
int visVer = terrain.VisualTileVersions[tx, tz];
bool isUninit = tile.BakedVisualVersion < 0;
if (!wantSlot[idx])
{
if (isUninit)
{
BakedTileCount++;
}
tile.BakedStructuralVersion = structVer;
tile.BakedVisualVersion = visVer;
continue;
}
bool isStructDirty = tile.BakedStructuralVersion != structVer;
bool needsSlotReacquire = tile.LruSlotIndex < 0;
if (isUninit || isStructDirty || needsSlotReacquire)
{
EnqueueTileBake(tx, tz, tile, terrain, isSion);
if (isUninit)
{
BakedTileCount++;
}
else
{
DirtyRebakes++;
}
tile.BakedStructuralVersion = structVer;
tile.BakedVisualVersion = visVer;
}
}
}
// 2. Remaining passive visual dirty tiles (Tracks / Scorch) inside top-96 throttled to <= MaxDirtyRebakesPerSync (4)
int rebakedThisSync = 0;
int startCursor = _rebakeCursor;
for (int step = 0; step < totalTiles; step++)
{
int idx = (startCursor + step) % totalTiles;
if (!wantSlot[idx])
{
continue;
}
int tx = idx % grid;
int tz = idx / grid;
var tile = _tiles[tx, tz];
int visVer = terrain.VisualTileVersions[tx, tz];
if (tile.BakedVisualVersion != visVer)
{
if (rebakedThisSync < MaxDirtyRebakesPerSync)
{
EnqueueTileBake(tx, tz, tile, terrain, isSion);
DirtyRebakes++;
tile.BakedStructuralVersion = terrain.StructuralTileVersions[tx, tz];
tile.BakedVisualVersion = visVer;
rebakedThisSync++;
_rebakeCursor = (idx + 1) % totalTiles;
}
else
{
break;
}
}
}
DispatchPendingJobsIfNeeded();
}
public int CountPendingDirtyVisualTiles(TerrainField terrain)
{
if (_tiles is null || !ReferenceEquals(_lastTerrain, terrain))
{
return 0;
}
int count = 0;
int grid = terrain.TileGridCount;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
if (_tiles[tx, tz].BakedVisualVersion != terrain.VisualTileVersions[tx, tz])
{
count++;
}
}
}
return count;
}
public void UpdateTileLod(Vector3 camPos)
{
_lastCamPos = camPos;
if (_tiles is null)
{
return;
}
const float nearRadiusSq = 220f * 220f;
const float midRadiusSq = 780f * 780f;
const float shadowRadiusSq = 360f * 360f;
float halfTile = _tileSize * 0.5f;
_lodResidentScratch.Clear();
for (int tz = 0; tz < _gridCount; tz++)
{
for (int tx = 0; tx < _gridCount; tx++)
{
var tile = _tiles[tx, tz];
float cx = tile.OriginX + halfTile;
float cz = tile.OriginZ + halfTile;
float dx = cx - camPos.X;
float dz = cz - camPos.Z;
float d2 = dx * dx + dz * dz;
if (tile.LruSlotIndex >= 0)
{
_lodResidentScratch.Add((tile.LruSlotIndex, d2));
}
PlaneMesh desiredMesh;
float quads;
if (d2 <= nearRadiusSq)
{
desiredMesh = _nearPlaneMesh;
quads = 192f;
}
else if (d2 <= midRadiusSq)
{
desiredMesh = _midPlaneMesh;
quads = 48f;
}
else
{
desiredMesh = _farPlaneMesh;
quads = 12f;
}
tile.TileQuads = quads;
if (!ReferenceEquals(tile.SurfaceMesh.Mesh, desiredMesh))
{
tile.SurfaceMesh.Mesh = desiredMesh;
}
var desiredShadow = d2 <= shadowRadiusSq
? GeometryInstance3D.ShadowCastingSetting.On
: GeometryInstance3D.ShadowCastingSetting.Off;
if (tile.SurfaceMesh.CastShadow != desiredShadow)
{
tile.SurfaceMesh.CastShadow = desiredShadow;
}
}
}
for (int tz = 0; tz < _gridCount; tz++)
{
for (int tx = 0; tx < _gridCount; tx++)
{
var tile = _tiles[tx, tz];
float qSelf = tile.TileQuads;
float qLeft = tx > 0 ? _tiles[tx - 1, tz].TileQuads : qSelf;
float qRight = tx < _gridCount - 1 ? _tiles[tx + 1, tz].TileQuads : qSelf;
float qTop = tz > 0 ? _tiles[tx, tz - 1].TileQuads : qSelf;
float qBottom = tz < _gridCount - 1 ? _tiles[tx, tz + 1].TileQuads : qSelf;
var nq = new Vector4(qLeft, qRight, qTop, qBottom);
if (tile.SentTileQuads != qSelf)
{
tile.SurfaceMat.SetShaderParameter("tile_quads", qSelf);
tile.SentTileQuads = qSelf;
}
if (tile.SentNeighborQuads != nq)
{
tile.SurfaceMat.SetShaderParameter("neighbor_quads", nq);
tile.SentNeighborQuads = nq;
}
}
}
if (_lodResidentScratch.Count > 0)
{
_lodResidentScratch.Sort((a, b) => b.DistSq.CompareTo(a.DistSq));
for (int i = 0; i < _lodResidentScratch.Count; i++)
{
_lruPool[_lodResidentScratch[i].Slot].LastUsedSeq = ++_lruClock;
}
}
}
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);
}
public bool TryGetHeightImageFormat(out Image.Format format)
{
format = Image.Format.Max;
if (RenderingServer.GetRenderingDevice() is null || _rdFailed)
{
return false;
}
format = Image.Format.Rgbah;
return true;
}
public bool TrySampleBakedHeight(float wx, float wz, out float bakedHeight)
{
bakedHeight = 0f;
if (_lastTerrain is not { } terrain || _tiles is null)
{
return false;
}
if (RenderingServer.GetRenderingDevice() is null || _rdFailed)
{
return false;
}
if (_hasQueuedRdFlush)
{
RenderingServer.ForceSync();
}
float half = terrain.MapHalfExtent;
float cx = Math.Clamp(wx, -half, half);
float cz = Math.Clamp(wz, -half, half);
terrain.MapWorldToTile(cx, cz, out int tx, out int tz);
var tile = _tiles[tx, tz];
float baseH = terrain.SampleBaseHeight(cx, cz);
if (tile.LruSlotIndex < 0)
{
bakedHeight = Math.Clamp(baseH, terrain.MapMinHeight, terrain.MapMaxHeight);
return true;
}
var slot = _lruPool[tile.LruSlotIndex];
if (!slot.IsRdAllocated || !slot.DeltaHeightRid.IsValid)
{
return false;
}
_readbackTargetRid = slot.DeltaHeightRid;
_readbackResult = null;
RenderingServer.CallOnRenderThread(Callable.From(ReadbackTextureOnRenderThread));
RenderingServer.ForceSync();
byte[]? raw = _readbackResult;
if (raw is null || raw.Length < DeltaTexSize * DeltaTexSize * 8)
{
return false;
}
float pixelsPerMeter = InnerTexelSpan / _tileSize;
float px = GutterCenterOffset + (cx - tile.OriginX) * pixelsPerMeter;
float py = GutterCenterOffset + (cz - tile.OriginZ) * pixelsPerMeter;
float fx = Math.Clamp(px - 0.5f, 0f, DeltaTexSize - 1.0001f);
float fy = Math.Clamp(py - 0.5f, 0f, DeltaTexSize - 1.0001f);
int x0 = (int)MathF.Floor(fx);
int y0 = (int)MathF.Floor(fy);
int x1 = Math.Min(x0 + 1, DeltaTexSize - 1);
int y1 = Math.Min(y0 + 1, DeltaTexSize - 1);
float txFrac = fx - x0;
float tyFrac = fy - y0;
float ReadHalfR(int x, int y)
{
int byteOff = (y * DeltaTexSize + x) * 8;
return (float)BitConverter.ToHalf(raw, byteOff);
}
float h00 = ReadHalfR(x0, y0);
float h10 = ReadHalfR(x1, y0);
float h01 = ReadHalfR(x0, y1);
float h11 = ReadHalfR(x1, y1);
float deltaH = (h00 * (1f - txFrac) + h10 * txFrac) * (1f - tyFrac) +
(h01 * (1f - txFrac) + h11 * txFrac) * tyFrac;
bakedHeight = Math.Clamp(baseH + deltaH, terrain.MapMinHeight, terrain.MapMaxHeight);
return true;
}
private void EnsureGridAllocated(TerrainField terrain, SionMapData? sionMap)
{
bool needsRebuild = _tiles is null ||
_gridCount != terrain.TileGridCount ||
MathF.Abs(_tileSize - terrain.MapTileSize) > 0.01f;
if (sionMap is not null)
{
EnsureSionLayer0Resources(sionMap);
}
if (needsRebuild)
{
if (_tiles is not null)
{
for (int tz = 0; tz < _gridCount; tz++)
{
for (int tx = 0; tx < _gridCount; tx++)
{
var old = _tiles[tx, tz];
if (old?.SurfaceMesh is not null && IsInstanceValid(old.SurfaceMesh))
{
old.SurfaceMesh.QueueFree();
}
}
}
}
_gridCount = terrain.TileGridCount;
_tileSize = terrain.MapTileSize;
_mapSize = terrain.MapSize;
_nearPlaneMesh = new PlaneMesh
{
Size = new Vector2(_tileSize, _tileSize),
SubdivideWidth = 191,
SubdivideDepth = 191
};
_midPlaneMesh = new PlaneMesh
{
Size = new Vector2(_tileSize, _tileSize),
SubdivideWidth = 47,
SubdivideDepth = 47
};
_farPlaneMesh = new PlaneMesh
{
Size = new Vector2(_tileSize, _tileSize),
SubdivideWidth = 11,
SubdivideDepth = 11
};
_tiles = new TileNode[_gridCount, _gridCount];
for (int tz = 0; tz < _gridCount; tz++)
{
for (int tx = 0; tx < _gridCount; tx++)
{
float originX = -terrain.MapHalfExtent + tx * _tileSize;
float originZ = -terrain.MapHalfExtent + tz * _tileSize;
var mat = new ShaderMaterial { Shader = _surfaceShader };
var mi = new MeshInstance3D
{
Name = $"Tile_{tx}_{tz}_Mesh",
Mesh = _nearPlaneMesh,
MaterialOverride = mat,
Position = new Vector3(originX + _tileSize * 0.5f, 0f, originZ + _tileSize * 0.5f)
};
AddChild(mi);
_tiles[tx, tz] = new TileNode
{
Tx = tx,
Tz = tz,
OriginX = originX,
OriginZ = originZ,
SurfaceMesh = mi,
SurfaceMat = mat
};
}
}
}
bool isSion = sionMap is not null;
float minY = terrain.MapMinHeight;
float maxY = terrain.MapMaxHeight;
float span = MathF.Max(1f, maxY - minY);
for (int tz = 0; tz < _gridCount; tz++)
{
for (int tx = 0; tx < _gridCount; tx++)
{
var tile = _tiles![tx, tz];
var mat = tile.SurfaceMat;
mat.SetShaderParameter("base_dem_tex", isSion && _sionDemTexRd is not null ? _sionDemTexRd : _zeroDem1x1Tex);
mat.SetShaderParameter("base_surface_tex", isSion && _sionSurfaceTex is not null ? _sionSurfaceTex : _whiteSurface1x1Tex);
mat.SetShaderParameter("base_mask_tex", isSion && _sionMaskTex is not null ? _sionMaskTex : _zeroMask1x1Tex);
mat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex);
mat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex);
mat.SetShaderParameter("dem_min_y", isSion ? _sionDemMinY : 0f);
mat.SetShaderParameter("dem_scale_span", isSion ? _sionDemScaleSpan : 0f);
mat.SetShaderParameter("dem_grid_res", isSion ? (float)sionMap!.Metadata.GridRes : 1f);
mat.SetShaderParameter("height_min", minY);
mat.SetShaderParameter("height_max", maxY);
mat.SetShaderParameter("map_size", _mapSize);
mat.SetShaderParameter("tile_origin_x", tile.OriginX);
mat.SetShaderParameter("tile_origin_z", tile.OriginZ);
mat.SetShaderParameter("tile_size", _tileSize);
mat.SetShaderParameter("inner_span", InnerTexelSpan);
mat.SetShaderParameter("tex_size", (float)DeltaTexSize);
mat.SetShaderParameter("gutter_center", GutterCenterOffset);
mat.SetShaderParameter("is_sion", isSion ? 1f : 0f);
tile.SurfaceMesh.CustomAabb = new Aabb(
new Vector3(-_tileSize * 0.5f, minY - 2f, -_tileSize * 0.5f),
new Vector3(_tileSize, span + 4f, _tileSize));
}
}
}
private void EnsureSionLayer0Resources(SionMapData sionMap)
{
if (string.Equals(_loadedSionDir, sionMap.DirectoryPath, StringComparison.OrdinalIgnoreCase))
{
return;
}
_loadedSionDir = sionMap.DirectoryPath;
_sionDemMinY = sionMap.BaseDemMinY;
_sionDemScaleSpan = 65535.0f * sionMap.BaseDemScale;
string surfPath = Path.Combine(sionMap.DirectoryPath, sionMap.Metadata.SurfaceTexture);
if (!File.Exists(surfPath))
{
throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath);
}
var surfImg = Image.LoadFromFile(surfPath)
?? throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}");
var tintImg = (Image)surfImg.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 = sionMap.Metadata.SizeMeters;
surfImg.GenerateMipmaps();
_sionSurfaceTex = ImageTexture.CreateFromImage(surfImg);
string maskName = string.IsNullOrWhiteSpace(sionMap.Metadata.SurfaceMaskTexture)
? "terrain_surface_mask.png"
: sionMap.Metadata.SurfaceMaskTexture;
string maskPath = Path.Combine(sionMap.DirectoryPath, maskName);
if (File.Exists(maskPath))
{
var maskImg = Image.LoadFromFile(maskPath);
if (maskImg is not null && !maskImg.IsEmpty())
{
maskImg.GenerateMipmaps();
_sionMaskTex = ImageTexture.CreateFromImage(maskImg);
}
}
if (RenderingServer.GetRenderingDevice() is not null)
{
_sionDemTexRd ??= new Texture2Drd();
byte[] demBytes = new byte[sionMap.BaseDem.Length * 2];
Buffer.BlockCopy(sionMap.BaseDem, 0, demBytes, 0, demBytes.Length);
_pendingSionDemUpload = demBytes;
_pendingSionDemRes = sionMap.Metadata.GridRes;
RenderingServer.CallOnRenderThread(Callable.From(UploadSionDemOnRenderThread));
}
}
private void EnqueueTileBake(int tx, int tz, TileNode tile, TerrainField terrain, bool isSion)
{
long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0;
IReadOnlyList<int> indices = terrain.GetTileBrushIndices(tx, tz);
if (indices.Count == 0 && isSion)
{
// Untouched Sion tile: release LRU slot and bind shared 1x1 neutral delta texture
ReleaseTileSlot(tile);
tile.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex);
tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex);
return;
}
int tileIdx = tz * _gridCount + tx;
LruSlot slot = AcquireLruSlot(tileIdx, tile);
tile.SurfaceMat.SetShaderParameter("delta_height_tex", slot.DeltaHeightTex);
tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", slot.DeltaAlbedoTex);
if (RenderingServer.GetRenderingDevice() is not null && !_rdFailed)
{
var brushes = terrain.Brushes;
var gpuList = new List<GpuBrush>(indices.Count);
for (int i = 0; i < indices.Count; i++)
{
var b = brushes[indices[i]];
if (b.RadiusX <= 0.05f || b.RadiusZ <= 0.05f)
{
continue;
}
float invRx = 1f / MathF.Max(0.1f, b.RadiusX);
float invRz = 1f / MathF.Max(0.1f, b.RadiusZ);
float maxR = MathF.Max(0.1f, MathF.Max(b.RadiusX, b.RadiusZ));
gpuList.Add(new GpuBrush
{
PosRot = new Vector4(b.X, b.Z, MathF.Cos(b.RotationRad), MathF.Sin(b.RotationRad)),
RadDelta = new Vector4(invRx, invRz, b.HeightDelta, maxR * maxR),
MatColor = new Vector4(b.AlbedoR, b.AlbedoG, b.AlbedoB, (float)(int)b.Kind)
});
}
lock (_jobLock)
{
_pendingJobs.Add(new PendingBakeJob
{
SlotIndex = slot.SlotIndex,
TileOriginX = tile.OriginX,
TileOriginZ = tile.OriginZ,
TileSize = _tileSize,
IsSion = isSion,
Brushes = gpuList.ToArray()
});
}
}
if (t0 != 0)
{
PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency;
PerfBakeTileCalls++;
}
}
private LruSlot AcquireLruSlot(int tileIdx, TileNode tile)
{
_lruClock++;
if (tile.LruSlotIndex >= 0)
{
var cur = _lruPool[tile.LruSlotIndex];
if (cur.AssignedTileIndex == tileIdx)
{
cur.LastUsedSeq = _lruClock;
return cur;
}
}
int bestIdx = -1;
ulong bestAge = ulong.MaxValue;
for (int i = 0; i < MaxGpuScarTiles; i++)
{
if (_lruPool[i].AssignedTileIndex < 0)
{
bestIdx = i;
break;
}
if (_lruPool[i].LastUsedSeq < bestAge)
{
bestAge = _lruPool[i].LastUsedSeq;
bestIdx = i;
}
}
var chosen = _lruPool[bestIdx];
if (chosen.AssignedTileIndex >= 0 && _tiles is not null)
{
int prevTileIdx = chosen.AssignedTileIndex;
int prevTx = prevTileIdx % _gridCount;
int prevTz = prevTileIdx / _gridCount;
if ((uint)prevTx < (uint)_gridCount && (uint)prevTz < (uint)_gridCount)
{
var evicted = _tiles[prevTx, prevTz];
if (evicted.LruSlotIndex == bestIdx)
{
evicted.LruSlotIndex = -1;
evicted.BakedVisualVersion = -1;
evicted.BakedStructuralVersion = -1;
evicted.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex);
evicted.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex);
}
}
}
chosen.AssignedTileIndex = tileIdx;
chosen.LastUsedSeq = _lruClock;
tile.LruSlotIndex = bestIdx;
return chosen;
}
private void ReleaseTileSlot(TileNode tile)
{
if (tile.LruSlotIndex >= 0)
{
var slot = _lruPool[tile.LruSlotIndex];
if (slot.AssignedTileIndex == tile.Tz * _gridCount + tile.Tx)
{
slot.AssignedTileIndex = -1;
}
tile.LruSlotIndex = -1;
}
}
private void DispatchPendingJobsIfNeeded()
{
if (RenderingServer.GetRenderingDevice() is null || _rdFailed)
{
lock (_jobLock)
{
_pendingJobs.Clear();
}
return;
}
bool any;
lock (_jobLock)
{
any = _pendingJobs.Count > 0;
}
if (any)
{
_hasQueuedRdFlush = true;
RenderingServer.CallOnRenderThread(Callable.From(FlushPendingGpuBakesOnRenderThread));
}
}
private void UploadSionDemOnRenderThread()
{
RenderingDevice? rd = RenderingServer.GetRenderingDevice();
byte[]? demBytes = _pendingSionDemUpload;
int res = _pendingSionDemRes;
_pendingSionDemUpload = null;
if (rd is null || demBytes is null || res <= 1)
{
return;
}
if (_sionDemRid.IsValid)
{
if (_sionDemTexRd is not null)
{
_sionDemTexRd.TextureRdRid = new Rid();
}
rd.FreeRid(_sionDemRid);
_sionDemRid = new Rid();
}
var fmt = new RDTextureFormat
{
TextureType = RenderingDevice.TextureType.Type2D,
Format = RenderingDevice.DataFormat.R16Unorm,
Width = (uint)res,
Height = (uint)res,
Depth = 1,
Mipmaps = 1,
ArrayLayers = 1,
Samples = RenderingDevice.TextureSamples.Samples1,
UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.CanUpdateBit
};
var dataArr = new Godot.Collections.Array<byte[]> { demBytes };
_sionDemRid = rd.TextureCreate(fmt, new RDTextureView(), dataArr);
if (_sionDemTexRd is not null && _sionDemRid.IsValid)
{
_sionDemTexRd.TextureRdRid = _sionDemRid;
}
}
private bool EnsureComputePipelineOnRenderThread(RenderingDevice rd)
{
if (_rdInitialized)
{
return true;
}
if (_rdFailed)
{
return false;
}
string source = Godot.FileAccess.GetFileAsString("res://terrain_tile_bake.glsl");
if (string.IsNullOrWhiteSpace(source))
{
GD.PrintErr("TerrainRenderer: missing compute shader res://terrain_tile_bake.glsl");
_rdFailed = true;
return false;
}
using var rdSrc = new RDShaderSource
{
Language = RenderingDevice.ShaderLanguage.Glsl,
SourceCompute = source
};
using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true);
if (!string.IsNullOrEmpty(spirv.CompileErrorCompute))
{
GD.PrintErr($"TerrainRenderer: SPIR-V compile error in terrain_tile_bake.glsl: {spirv.CompileErrorCompute}");
_rdFailed = true;
return false;
}
_bakeShaderRid = rd.ShaderCreateFromSpirV(spirv, "terrain_tile_bake");
_bakePipeRid = rd.ComputePipelineCreate(_bakeShaderRid);
if (!_bakeShaderRid.IsValid || !_bakePipeRid.IsValid)
{
GD.PrintErr("TerrainRenderer: failed to create compute pipeline");
_rdFailed = true;
return false;
}
_brushSsboRid = rd.StorageBufferCreate(MaxSsboBrushes * BrushStrideBytes, new byte[MaxSsboBrushes * BrushStrideBytes]);
_rdInitialized = true;
return true;
}
private void EnsureSlotRdAllocatedOnRenderThread(RenderingDevice rd, LruSlot slot)
{
if (slot.IsRdAllocated)
{
return;
}
var hFmt = new RDTextureFormat
{
TextureType = RenderingDevice.TextureType.Type2D,
Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat,
Width = DeltaTexSize,
Height = DeltaTexSize,
Depth = 1,
Mipmaps = 1,
ArrayLayers = 1,
Samples = RenderingDevice.TextureSamples.Samples1,
UsageBits = RenderingDevice.TextureUsageBits.SamplingBit |
RenderingDevice.TextureUsageBits.StorageBit |
RenderingDevice.TextureUsageBits.CanCopyFromBit
};
slot.DeltaHeightRid = rd.TextureCreate(hFmt, new RDTextureView());
var aFmt = new RDTextureFormat
{
TextureType = RenderingDevice.TextureType.Type2D,
Format = RenderingDevice.DataFormat.R8G8B8A8Unorm,
Width = DeltaTexSize,
Height = DeltaTexSize,
Depth = 1,
Mipmaps = 1,
ArrayLayers = 1,
Samples = RenderingDevice.TextureSamples.Samples1,
UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit
};
slot.DeltaAlbedoRid = rd.TextureCreate(aFmt, new RDTextureView());
var uniforms = new Godot.Collections.Array<RDUniform>
{
new RDUniform
{
UniformType = RenderingDevice.UniformType.Image,
Binding = 0,
_Ids = new Godot.Collections.Array<Rid> { slot.DeltaHeightRid }
},
new RDUniform
{
UniformType = RenderingDevice.UniformType.Image,
Binding = 1,
_Ids = new Godot.Collections.Array<Rid> { slot.DeltaAlbedoRid }
},
new RDUniform
{
UniformType = RenderingDevice.UniformType.StorageBuffer,
Binding = 2,
_Ids = new Godot.Collections.Array<Rid> { _brushSsboRid }
}
};
slot.UniformSetRid = rd.UniformSetCreate(uniforms, _bakeShaderRid, 0);
slot.DeltaHeightTex.TextureRdRid = slot.DeltaHeightRid;
slot.DeltaAlbedoTex.TextureRdRid = slot.DeltaAlbedoRid;
slot.IsRdAllocated = true;
}
private void FlushPendingGpuBakesOnRenderThread()
{
PendingBakeJob[] jobs;
lock (_jobLock)
{
if (_pendingJobs.Count == 0)
{
_hasQueuedRdFlush = false;
return;
}
jobs = _pendingJobs.ToArray();
_pendingJobs.Clear();
}
RenderingDevice? rd = RenderingServer.GetRenderingDevice();
if (rd is null || !EnsureComputePipelineOnRenderThread(rd))
{
_hasQueuedRdFlush = false;
return;
}
long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0;
int totalBrushes = 0;
var brushStarts = new uint[jobs.Length];
for (int j = 0; j < jobs.Length; j++)
{
int count = jobs[j].Brushes.Length;
if (totalBrushes + count > MaxSsboBrushes)
{
count = Math.Max(0, MaxSsboBrushes - totalBrushes);
}
brushStarts[j] = (uint)totalBrushes;
for (int b = 0; b < count; b++)
{
int byteOff = (totalBrushes + b) * BrushStrideBytes;
MemoryMarshal.Write(_ssboStagingBytes.AsSpan(byteOff, BrushStrideBytes), in jobs[j].Brushes[b]);
}
totalBrushes += count;
}
if (totalBrushes > 0)
{
rd.BufferUpdate(_brushSsboRid, 0, (uint)(totalBrushes * BrushStrideBytes), _ssboStagingBytes);
}
for (int j = 0; j < jobs.Length; j++)
{
EnsureSlotRdAllocatedOnRenderThread(rd, _lruPool[jobs[j].SlotIndex]);
}
uint groups = (uint)((DeltaTexSize + 7) / 8);
long cl = rd.ComputeListBegin();
rd.ComputeListBindComputePipeline(cl, _bakePipeRid);
for (int j = 0; j < jobs.Length; j++)
{
var job = jobs[j];
var slot = _lruPool[job.SlotIndex];
uint bCount = (uint)Math.Min(job.Brushes.Length, MaxSsboBrushes - (int)brushStarts[j]);
var push = new TileBakePush
{
TileOriginAndSpan = new Vector4(job.TileOriginX, job.TileOriginZ, job.TileSize, InnerTexelSpan),
BaseColorAndGutter = job.IsSion
? new Vector4(0f, 0f, 0f, GutterStartIndex)
: new Vector4(DesertAlbedoClear.R, DesertAlbedoClear.G, DesertAlbedoClear.B, GutterStartIndex),
BrushStart = brushStarts[j],
BrushCount = bCount,
TexSize = DeltaTexSize,
IsSion = job.IsSion ? 1u : 0u
};
MemoryMarshal.Write(_pushBytes, in push);
rd.ComputeListBindUniformSet(cl, slot.UniformSetRid, 0);
rd.ComputeListSetPushConstant(cl, _pushBytes, PushConstantBytes);
rd.ComputeListDispatch(cl, groups, groups, 1);
}
rd.ComputeListEnd();
_hasQueuedRdFlush = false;
if (t0 != 0)
{
PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency;
}
}
private void ReadbackTextureOnRenderThread()
{
RenderingDevice? rd = RenderingServer.GetRenderingDevice();
if (rd is null || !_readbackTargetRid.IsValid)
{
_readbackResult = null;
return;
}
_readbackResult = rd.TextureGetData(_readbackTargetRid, 0);
}
private void DisposeRdResourcesOnRenderThread()
{
RenderingDevice? rd = RenderingServer.GetRenderingDevice();
if (rd is null)
{
return;
}
for (int i = 0; i < _lruPool.Length; i++)
{
var slot = _lruPool[i];
if (slot is null || !slot.IsRdAllocated)
{
continue;
}
slot.DeltaHeightTex.TextureRdRid = new Rid();
slot.DeltaAlbedoTex.TextureRdRid = new Rid();
if (slot.UniformSetRid.IsValid) rd.FreeRid(slot.UniformSetRid);
if (slot.DeltaHeightRid.IsValid) rd.FreeRid(slot.DeltaHeightRid);
if (slot.DeltaAlbedoRid.IsValid) rd.FreeRid(slot.DeltaAlbedoRid);
slot.UniformSetRid = new Rid();
slot.DeltaHeightRid = new Rid();
slot.DeltaAlbedoRid = new Rid();
slot.IsRdAllocated = false;
}
if (_sionDemTexRd is not null)
{
_sionDemTexRd.TextureRdRid = new Rid();
}
if (_sionDemRid.IsValid)
{
rd.FreeRid(_sionDemRid);
_sionDemRid = new Rid();
}
if (_brushSsboRid.IsValid)
{
rd.FreeRid(_brushSsboRid);
_brushSsboRid = new Rid();
}
if (_bakePipeRid.IsValid)
{
rd.FreeRid(_bakePipeRid);
_bakePipeRid = new Rid();
}
if (_bakeShaderRid.IsValid)
{
rd.FreeRid(_bakeShaderRid);
_bakeShaderRid = new Rid();
}
_rdInitialized = false;
}
}