RustToDust/client/SionMapRenderer.cs

559 lines
20 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Renders the 3072m x 3072m Sion, Switzerland arena:
/// - 6x6 (512m) seam-free chunked terrain ArrayMeshes from heightmap.f32 textured with terrain_surface.png + micro-grain shader.
/// - 36 spatial building tiles swapping cleanly between LOD1 (&lt;= 650m), LOD2 (650m..2200m), and culled (&gt; 2200m),
/// with shadow casting restricted to &lt;= 450m and shared PBR materials across all tiles.
/// </summary>
public partial class SionMapRenderer : Node3D
{
public const float Lod1DistanceM = 520f;
public const float CullDistanceM = 2200f;
public const float ShadowDistanceM = 220f;
private const int ChunkGridVerts = 129; // 128 quads per 512m chunk (4m spacing)
private sealed class BuildingTileEntry
{
public int Tx;
public int Tz;
public float CenterX;
public float CenterZ;
public required ArrayMesh Lod1Mesh;
public required ArrayMesh Lod2Mesh;
public required MeshInstance3D Instance;
}
private 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 Dictionary<string, StandardMaterial3D> _sharedBuildingMaterials = new(StringComparer.Ordinal);
private string? _builtForDir;
private ShaderMaterial? _terrainMat;
private ImageTexture? _surfaceTex;
private Color[]? _groundTintGrid;
private float _groundTintSizeM;
public bool IsBuilt { get; private set; }
public int TerrainChunkCount => _terrainChunks.Count;
public int BuildingTileCount => _buildingTiles.Count;
public int ActiveLod1TileCount { get; private set; }
public int ActiveLod2TileCount { get; private set; }
public int CulledTileCount { get; private set; }
public void EnsureBuilt(SionMapData sion, TerrainField terrain)
{
if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase))
{
return;
}
ClearBuilt();
_builtForDir = sion.DirectoryPath;
BuildTerrainMaterial(sion);
BuildTerrainChunks(sion, terrain);
BuildBuildingTiles(sion);
IsBuilt = true;
}
public void UpdateLod(Vector3 camPos)
{
if (!IsBuilt)
{
return;
}
const float lod1Sq = Lod1DistanceM * Lod1DistanceM;
const float cullSq = CullDistanceM * CullDistanceM;
const float shadowSq = ShadowDistanceM * ShadowDistanceM;
int lod1Count = 0;
int lod2Count = 0;
int culledCount = 0;
for (int i = 0; i < _buildingTiles.Count; i++)
{
var t = _buildingTiles[i];
float dx = t.CenterX - camPos.X;
float dz = t.CenterZ - camPos.Z;
float d2 = dx * dx + dz * dz;
if (d2 > cullSq)
{
if (t.Instance.Visible)
{
t.Instance.Visible = false;
}
culledCount++;
continue;
}
if (!t.Instance.Visible)
{
t.Instance.Visible = true;
}
ArrayMesh desired = d2 <= lod1Sq ? t.Lod1Mesh : t.Lod2Mesh;
if (!ReferenceEquals(t.Instance.Mesh, desired))
{
t.Instance.Mesh = desired;
}
if (d2 <= lod1Sq) lod1Count++;
else lod2Count++;
var desiredShadow = d2 <= shadowSq
? GeometryInstance3D.ShadowCastingSetting.On
: GeometryInstance3D.ShadowCastingSetting.Off;
if (t.Instance.CastShadow != desiredShadow)
{
t.Instance.CastShadow = desiredShadow;
}
}
ActiveLod1TileCount = lod1Count;
ActiveLod2TileCount = lod2Count;
CulledTileCount = culledCount;
}
private void BuildTerrainMaterial(SionMapData sion)
{
string surfPath = Path.Combine(sion.DirectoryPath, sion.Metadata.SurfaceTexture);
if (!File.Exists(surfPath))
{
throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath);
}
var img = Image.LoadFromFile(surfPath);
if (img is null || img.IsEmpty())
{
throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}");
}
// 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 + vec3(macro + grit * near_fade), vec3(0.0), vec3(1.0));
ALBEDO = col;
ROUGHNESS = mix(0.88, 0.96, slope);
METALLIC = 0.03;
}
"""
};
_terrainMat = new ShaderMaterial { Shader = shader };
_terrainMat.SetShaderParameter("surface_tex", _surfaceTex);
}
private void BuildTerrainChunks(SionMapData sion, TerrainField terrain)
{
int grid = sion.Metadata.TileGrid;
float sizeM = sion.Metadata.SizeMeters;
float tileSize = sion.Metadata.TileSizeMeters;
float half = sizeM * 0.5f;
int n = ChunkGridVerts;
float step = tileSize / (n - 1);
// Precompute shared index buffer for every 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)
{
var tiles = sion.Metadata.Tiles;
for (int i = 0; i < tiles.Count; i++)
{
var tm = tiles[i];
string lod1Path = Path.Combine(sion.DirectoryPath, tm.Lod1RelativePath.Replace('/', Path.DirectorySeparatorChar));
string lod2Path = Path.Combine(sion.DirectoryPath, tm.Lod2RelativePath.Replace('/', Path.DirectorySeparatorChar));
ArrayMesh lod1Mesh = LoadMergedTileGlb(lod1Path);
ArrayMesh lod2Mesh = LoadMergedTileGlb(lod2Path);
var mi = new MeshInstance3D
{
Name = $"SionBuildings_{tm.Tx}_{tm.Tz}",
Mesh = lod2Mesh,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
AddChild(mi);
_buildingTiles.Add(new BuildingTileEntry
{
Tx = tm.Tx,
Tz = tm.Tz,
CenterX = tm.Center.X,
CenterZ = tm.Center.Z,
Lod1Mesh = lod1Mesh,
Lod2Mesh = lod2Mesh,
Instance = mi
});
}
}
private ArrayMesh LoadMergedTileGlb(string glbPath)
{
if (!File.Exists(glbPath))
{
throw new FileNotFoundException($"Missing Sion building GLB: {glbPath}", glbPath);
}
var doc = new GltfDocument();
var state = new GltfState();
Error err = doc.AppendFromFile(glbPath, state);
if (err != Error.Ok)
{
throw new InvalidOperationException($"GltfDocument failed to load '{glbPath}': {err}");
}
Node? root = doc.GenerateScene(state);
if (root is null)
{
throw new InvalidOperationException($"GltfDocument generated null scene for '{glbPath}'.");
}
try
{
var byMat = new Dictionary<string, (StandardMaterial3D Mat, List<Vector3> Pos, List<Vector3> Norm, List<int> Idx)>(StringComparer.Ordinal);
CollectMeshesRecursive(root, Transform3D.Identity, byMat);
var outMesh = new ArrayMesh();
foreach (var kv in byMat)
{
var entry = kv.Value;
if (entry.Pos.Count == 0 || entry.Idx.Count == 0)
{
continue;
}
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = entry.Pos.ToArray();
arrays[(int)Mesh.ArrayType.Normal] = entry.Norm.ToArray();
arrays[(int)Mesh.ArrayType.Index] = entry.Idx.ToArray();
int surfIdx = outMesh.GetSurfaceCount();
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
outMesh.SurfaceSetMaterial(surfIdx, entry.Mat);
}
return outMesh;
}
finally
{
root.Free();
}
}
private void CollectMeshesRecursive(
Node node,
Transform3D parentXf,
Dictionary<string, (StandardMaterial3D Mat, List<Vector3> Pos, List<Vector3> Norm, List<int> Idx)> byMat)
{
Transform3D xf = node is Node3D n3 ? parentXf * n3.Transform : parentXf;
if (node is MeshInstance3D mi && mi.Mesh is not null)
{
Basis normalBasis = xf.Basis.Inverse().Transposed();
int surfCount = mi.Mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arr = mi.Mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Vertex)
{
continue;
}
Vector3[] posArr = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
if (posArr.Length == 0)
{
continue;
}
Vector3[]? normArr = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array
? arr[(int)Mesh.ArrayType.Normal].AsVector3Array()
: null;
int[]? idxArr = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array
? arr[(int)Mesh.ArrayType.Index].AsInt32Array()
: null;
Material? srcMat = mi.Mesh.SurfaceGetMaterial(s);
(string matKey, StandardMaterial3D sharedMat) = GetOrShareBuildingMaterial(srcMat);
if (!byMat.TryGetValue(matKey, out var bucket))
{
bucket = (sharedMat, new List<Vector3>(posArr.Length), new List<Vector3>(posArr.Length), new List<int>(idxArr?.Length ?? posArr.Length));
byMat[matKey] = bucket;
}
int baseVert = bucket.Pos.Count;
for (int v = 0; v < posArr.Length; v++)
{
bucket.Pos.Add(xf * posArr[v]);
Vector3 n = normArr is not null && v < normArr.Length
? (normalBasis * normArr[v]).Normalized()
: Vector3.Up;
bucket.Norm.Add(n);
}
if (idxArr is not null && idxArr.Length > 0)
{
for (int k = 0; k < idxArr.Length; k++)
{
bucket.Idx.Add(baseVert + idxArr[k]);
}
}
else
{
for (int k = 0; k < posArr.Length; k++)
{
bucket.Idx.Add(baseVert + k);
}
}
}
}
for (int i = 0; i < node.GetChildCount(); i++)
{
CollectMeshesRecursive(node.GetChild(i), xf, byMat);
}
}
private (string Key, StandardMaterial3D Mat) GetOrShareBuildingMaterial(Material? srcMat)
{
if (srcMat is StandardMaterial3D std)
{
Color c = std.AlbedoColor;
string key = $"{std.ResourceName}|{c.R:F3},{c.G:F3},{c.B:F3},{c.A:F3}|{std.Roughness:F2}|{std.Metallic:F2}";
if (!_sharedBuildingMaterials.TryGetValue(key, out var cached))
{
cached = new StandardMaterial3D
{
AlbedoColor = c,
Roughness = std.Roughness,
Metallic = std.Metallic,
CullMode = BaseMaterial3D.CullModeEnum.Back
};
_sharedBuildingMaterials[key] = cached;
}
return (key, cached);
}
const string defaultKey = "__default_building";
if (!_sharedBuildingMaterials.TryGetValue(defaultKey, out var defMat))
{
defMat = new StandardMaterial3D
{
AlbedoColor = new Color(0.55f, 0.52f, 0.48f),
Roughness = 0.88f,
Metallic = 0.04f
};
_sharedBuildingMaterials[defaultKey] = defMat;
}
return (defaultKey, defMat);
}
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()
{
for (int i = 0; i < _terrainChunks.Count; i++)
{
_terrainChunks[i].QueueFree();
}
_terrainChunks.Clear();
for (int i = 0; i < _buildingTiles.Count; i++)
{
_buildingTiles[i].Instance.QueueFree();
}
_buildingTiles.Clear();
_sharedBuildingMaterials.Clear();
_terrainMat = null;
_surfaceTex = null;
_groundTintGrid = null;
_groundTintSizeM = 0f;
_builtForDir = null;
IsBuilt = false;
ActiveLod1TileCount = 0;
ActiveLod2TileCount = 0;
CulledTileCount = 0;
}
}