RustToDust/client/SionMapRenderer.cs

322 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using Godot;
using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Renders Sion, Switzerland legacy building tiles (swapping cleanly between LOD1 &lt;= 520m, LOD2 520..2200m,
/// and culled &gt; 2200m). Terrain rendering is unified in <see cref="TerrainRenderer"/>.
/// (This class is scheduled for deletion in Cut 13c when <c>WorldCityRenderer</c> lands.)
/// </summary>
public partial class SionMapRenderer : Node3D
{
public const float Lod1DistanceM = 400f;
public const float CullDistanceM = 1750f;
public const float ShadowDistanceM = 280f;
private sealed class BuildingTileEntry
{
public int Tx;
public int Tz;
public float CenterX;
public float CenterZ;
public required ArrayMesh Lod1Mesh;
public required ArrayMesh Lod2Mesh;
public required MeshInstance3D Instance;
}
private readonly List<BuildingTileEntry> _buildingTiles = new(36);
private readonly Dictionary<string, StandardMaterial3D> _sharedBuildingMaterials = new(StringComparer.Ordinal);
private string? _builtForDir;
public bool IsBuilt { get; private set; }
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)
{
if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase))
{
return;
}
ClearBuilt();
_builtForDir = sion.DirectoryPath;
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 BuildBuildingTiles(SionMapData sion)
{
var tiles = sion.Metadata.Tiles;
for (int i = 0; i < tiles.Count; i++)
{
var tm = tiles[i];
string lod1Path = Path.Combine(sion.DirectoryPath, tm.Lod1RelativePath.Replace('/', Path.DirectorySeparatorChar));
string lod2Path = Path.Combine(sion.DirectoryPath, tm.Lod2RelativePath.Replace('/', Path.DirectorySeparatorChar));
ArrayMesh lod1Mesh = LoadMergedTileGlb(lod1Path);
ArrayMesh lod2Mesh = LoadMergedTileGlb(lod2Path);
var mi = new MeshInstance3D
{
Name = $"SionBuildings_{tm.Tx}_{tm.Tz}",
Mesh = lod2Mesh,
CastShadow = GeometryInstance3D.ShadowCastingSetting.Off
};
AddChild(mi);
_buildingTiles.Add(new BuildingTileEntry
{
Tx = tm.Tx,
Tz = tm.Tz,
CenterX = tm.Center.X,
CenterZ = tm.Center.Z,
Lod1Mesh = lod1Mesh,
Lod2Mesh = lod2Mesh,
Instance = mi
});
}
}
private ArrayMesh LoadMergedTileGlb(string glbPath)
{
if (!File.Exists(glbPath))
{
throw new FileNotFoundException($"Missing Sion building GLB: {glbPath}", glbPath);
}
var doc = new GltfDocument();
var state = new GltfState();
Error err = doc.AppendFromFile(glbPath, state);
if (err != Error.Ok)
{
throw new InvalidOperationException($"GltfDocument failed to load '{glbPath}': {err}");
}
Node? root = doc.GenerateScene(state);
if (root is null)
{
throw new InvalidOperationException($"GltfDocument generated null scene for '{glbPath}'.");
}
try
{
var byMat = new Dictionary<string, (StandardMaterial3D Mat, List<Vector3> Pos, List<Vector3> Norm, List<int> Idx)>(StringComparer.Ordinal);
CollectMeshesRecursive(root, Transform3D.Identity, byMat);
var outMesh = new ArrayMesh();
foreach (var kv in byMat)
{
var entry = kv.Value;
if (entry.Pos.Count == 0 || entry.Idx.Count == 0)
{
continue;
}
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = entry.Pos.ToArray();
arrays[(int)Mesh.ArrayType.Normal] = entry.Norm.ToArray();
arrays[(int)Mesh.ArrayType.Index] = entry.Idx.ToArray();
int surfIdx = outMesh.GetSurfaceCount();
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
outMesh.SurfaceSetMaterial(surfIdx, entry.Mat);
}
return outMesh;
}
finally
{
root.Free();
}
}
private void CollectMeshesRecursive(
Node node,
Transform3D parentXf,
Dictionary<string, (StandardMaterial3D Mat, List<Vector3> Pos, List<Vector3> Norm, List<int> Idx)> byMat)
{
Transform3D xf = node is Node3D n3 ? parentXf * n3.Transform : parentXf;
if (node is MeshInstance3D mi && mi.Mesh is not null)
{
Basis normalBasis = xf.Basis.Inverse().Transposed();
int surfCount = mi.Mesh.GetSurfaceCount();
for (int s = 0; s < surfCount; s++)
{
var arr = mi.Mesh.SurfaceGetArrays(s);
if (arr.Count <= (int)Mesh.ArrayType.Vertex)
{
continue;
}
Vector3[] posArr = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
if (posArr.Length == 0)
{
continue;
}
Vector3[]? normArr = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array
? arr[(int)Mesh.ArrayType.Normal].AsVector3Array()
: null;
int[]? idxArr = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array
? arr[(int)Mesh.ArrayType.Index].AsInt32Array()
: null;
Material? srcMat = mi.Mesh.SurfaceGetMaterial(s);
(string matKey, StandardMaterial3D sharedMat) = GetOrShareBuildingMaterial(srcMat);
if (!byMat.TryGetValue(matKey, out var bucket))
{
bucket = (sharedMat, new List<Vector3>(posArr.Length), new List<Vector3>(posArr.Length), new List<int>(idxArr?.Length ?? posArr.Length));
byMat[matKey] = bucket;
}
int baseVert = bucket.Pos.Count;
for (int v = 0; v < posArr.Length; v++)
{
bucket.Pos.Add(xf * posArr[v]);
Vector3 n = normArr is not null && v < normArr.Length
? (normalBasis * normArr[v]).Normalized()
: Vector3.Up;
bucket.Norm.Add(n);
}
if (idxArr is not null && idxArr.Length > 0)
{
for (int k = 0; k < idxArr.Length; k++)
{
bucket.Idx.Add(baseVert + idxArr[k]);
}
}
else
{
for (int k = 0; k < posArr.Length; k++)
{
bucket.Idx.Add(baseVert + k);
}
}
}
}
for (int i = 0; i < node.GetChildCount(); i++)
{
CollectMeshesRecursive(node.GetChild(i), xf, byMat);
}
}
private (string Key, StandardMaterial3D Mat) GetOrShareBuildingMaterial(Material? srcMat)
{
if (srcMat is StandardMaterial3D std)
{
Color c = std.AlbedoColor;
string key = $"{std.ResourceName}|{c.R:F3},{c.G:F3},{c.B:F3},{c.A:F3}|{std.Roughness:F2}|{std.Metallic:F2}";
if (!_sharedBuildingMaterials.TryGetValue(key, out var cached))
{
cached = new StandardMaterial3D
{
AlbedoColor = c,
Roughness = std.Roughness,
Metallic = std.Metallic,
CullMode = BaseMaterial3D.CullModeEnum.Back
};
_sharedBuildingMaterials[key] = cached;
}
return (key, cached);
}
const string defaultKey = "__default_building";
if (!_sharedBuildingMaterials.TryGetValue(defaultKey, out var defMat))
{
defMat = new StandardMaterial3D
{
AlbedoColor = new Color(0.55f, 0.52f, 0.48f),
Roughness = 0.88f,
Metallic = 0.04f
};
_sharedBuildingMaterials[defaultKey] = defMat;
}
return (defaultKey, defMat);
}
private void ClearBuilt()
{
for (int i = 0; i < _buildingTiles.Count; i++)
{
_buildingTiles[i].Instance.QueueFree();
}
_buildingTiles.Clear();
_sharedBuildingMaterials.Clear();
_builtForDir = null;
IsBuilt = false;
ActiveLod1TileCount = 0;
ActiveLod2TileCount = 0;
CulledTileCount = 0;
}
}