698 lines
27 KiB
C#
698 lines
27 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text.Json;
|
|
using Godot;
|
|
using RustToDust.Core;
|
|
|
|
namespace RustToDust.Client;
|
|
|
|
/// <summary>
|
|
/// GPU-instanced MultiMesh + 6x6 octahedral impostor renderer for real Sion trees
|
|
/// baked via vendored cosmo_tree_gen (MIT) with hierarchical COLOR.rgba wind weights
|
|
/// bound to global <c>rtd_flow_field</c>.
|
|
/// </summary>
|
|
public partial class FoliageRenderer : Node3D
|
|
{
|
|
public const float Lod0MaxDistanceM = 28f;
|
|
public const float Lod1MaxDistanceM = 76f;
|
|
public const float Lod2MaxDistanceM = 230f;
|
|
public const float ImpostorMaxDistanceM = 1450f;
|
|
public const float StumpMaxDistanceM = 230f;
|
|
private const float RebuildMoveThresholdSq = 8.0f * 8.0f;
|
|
private const float RebuildTurnCosThreshold = 0.866f; // ~30 degrees
|
|
private const float FrustumCullMinDistSq = 48.0f * 48.0f;
|
|
private const float FrustumRearConeCosSq = 0.35f * 0.35f; // cull rear ~139 deg cone behind camera
|
|
|
|
private sealed class TreeArchetype
|
|
{
|
|
public int SpeciesId;
|
|
public int Variant;
|
|
public string Slug = string.Empty;
|
|
public float CanonicalHeightM;
|
|
public float ImpostorScale;
|
|
public float ImpostorOffsetY;
|
|
public int ImpostorFrames = 6;
|
|
public ArrayMesh Lod0 = null!;
|
|
public ArrayMesh Lod1 = null!;
|
|
public ArrayMesh Lod2 = null!;
|
|
public ArrayMesh SnappedStump = null!;
|
|
public ArrayMesh CharredSkeleton = null!;
|
|
public QuadMesh ImpostorQuad = null!;
|
|
|
|
public BucketState BucketLod0 = null!;
|
|
public BucketState? BucketLod1;
|
|
public BucketState? BucketLod2;
|
|
public BucketState? BucketImpostor;
|
|
public BucketState? BucketStump;
|
|
public BucketState? BucketCharred;
|
|
public int CanonicalArchIdx;
|
|
}
|
|
|
|
private sealed class BucketState
|
|
{
|
|
public MultiMesh MultiMesh = null!;
|
|
public MultiMeshInstance3D Instance = null!;
|
|
public readonly List<int> Indices = new(128);
|
|
}
|
|
|
|
private struct PrecomputedTree
|
|
{
|
|
public int ArchetypeIdx;
|
|
public Transform3D WorldXform;
|
|
public Transform3D WorldXformCanon;
|
|
public Vector3 Position;
|
|
public Color CustomDataBase; // (0, phase, height, 1)
|
|
}
|
|
|
|
private readonly List<TreeArchetype> _archetypes = new(17);
|
|
private readonly int[,] _archetypeLookup = new int[10, 2];
|
|
private readonly Dictionary<string, Texture2D> _textureCache = new(StringComparer.OrdinalIgnoreCase);
|
|
private Shader _leavesShader = null!;
|
|
private Shader _barkShader = null!;
|
|
private Shader _impostorShader = null!;
|
|
|
|
private SionTreeCatalog? _boundCatalog;
|
|
private PrecomputedTree[] _precomputed = Array.Empty<PrecomputedTree>();
|
|
private int _lastRenderVersion = -1;
|
|
private Vector3 _lastCamPos = new(float.NaN, float.NaN, float.NaN);
|
|
private Vector2 _lastCamFwdXz = new(0f, 1f);
|
|
private bool _lastCamConeActive;
|
|
private bool _assetsLoaded;
|
|
private bool _assetsLoadAttempted;
|
|
|
|
public bool IsBuilt => _assetsLoaded && _boundCatalog is not null;
|
|
public int ArchetypeCount => _archetypes.Count;
|
|
public int TotalTreeCount => _boundCatalog?.Count ?? 0;
|
|
public int VisibleLod0Count { get; private set; }
|
|
public int VisibleLod1Count { get; private set; }
|
|
public int VisibleLod2Count { get; private set; }
|
|
public int VisibleImpostorCount { get; private set; }
|
|
public int VisibleStumpCount { get; private set; }
|
|
public int VisibleCharredCount { get; private set; }
|
|
|
|
public override void _Ready()
|
|
{
|
|
for (int s = 0; s < 10; s++)
|
|
{
|
|
for (int v = 0; v < 2; v++)
|
|
{
|
|
_archetypeLookup[s, v] = -1;
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Invalidate()
|
|
{
|
|
_lastRenderVersion = -1;
|
|
_lastCamPos = new Vector3(float.NaN, float.NaN, float.NaN);
|
|
_lastCamFwdXz = new Vector2(0f, 1f);
|
|
_lastCamConeActive = false;
|
|
}
|
|
|
|
public bool VerifyAllLodsHaveVertexColor(out string error)
|
|
{
|
|
foreach (var arch in _archetypes)
|
|
{
|
|
ArrayMesh[] lods = { arch.Lod0, arch.Lod1, arch.Lod2 };
|
|
for (int l = 0; l < lods.Length; l++)
|
|
{
|
|
var mesh = lods[l];
|
|
if (mesh is null || mesh.GetSurfaceCount() == 0)
|
|
{
|
|
error = $"{arch.Slug} LOD{l} missing mesh surfaces";
|
|
return false;
|
|
}
|
|
for (int s = 0; s < mesh.GetSurfaceCount(); s++)
|
|
{
|
|
var arr = mesh.SurfaceGetArrays(s);
|
|
if (arr.Count <= (int)Mesh.ArrayType.Color ||
|
|
arr[(int)Mesh.ArrayType.Color].VariantType != Variant.Type.PackedColorArray)
|
|
{
|
|
error = $"{arch.Slug} LOD{l} surface {s} missing ARRAY_COLOR";
|
|
return false;
|
|
}
|
|
var colors = arr[(int)Mesh.ArrayType.Color].AsColorArray();
|
|
bool hasFlexGrad = false;
|
|
for (int k = 0; k < colors.Length; k++)
|
|
{
|
|
if (colors[k].G > 0.05f)
|
|
{
|
|
hasFlexGrad = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!hasFlexGrad)
|
|
{
|
|
error = $"{arch.Slug} LOD{l} surface {s} has zero wind flex gradient in COLOR.G";
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
error = string.Empty;
|
|
return _archetypes.Count == 17;
|
|
}
|
|
|
|
public void Sync(MatchState state, Vector3 camPos)
|
|
{
|
|
if (state.MapKind != ArenaMapKind.Sion || state.SionMap is null || state.SionMap.Trees.Count == 0)
|
|
{
|
|
Visible = false;
|
|
return;
|
|
}
|
|
SyncInternal(state.SionMap, state.SionTrees, camPos);
|
|
}
|
|
|
|
public void SyncBackdrop(SionMapData sionMap, Vector3 camPos)
|
|
{
|
|
if (sionMap.Trees.Count == 0)
|
|
{
|
|
Visible = false;
|
|
return;
|
|
}
|
|
SyncInternal(sionMap, null, camPos);
|
|
}
|
|
|
|
private void SyncInternal(SionMapData sionMap, SionTreeDestructionState? destruction, Vector3 camPos)
|
|
{
|
|
Visible = true;
|
|
EnsureAssetsLoaded(sionMap.DirectoryPath);
|
|
if (!_assetsLoaded)
|
|
{
|
|
return;
|
|
}
|
|
|
|
var catalog = sionMap.Trees;
|
|
if (!ReferenceEquals(_boundCatalog, catalog))
|
|
{
|
|
BindCatalog(catalog);
|
|
}
|
|
|
|
int curVer = destruction?.RenderVersion ?? 0;
|
|
Vector2 camFwdXz = new(0f, 1f);
|
|
bool useCamCone = false;
|
|
var cam = GetViewport()?.GetCamera3D();
|
|
if (cam is not null)
|
|
{
|
|
Vector3 fwd = -cam.GlobalTransform.Basis.Z;
|
|
if (MathF.Abs(fwd.Y) <= 0.50f)
|
|
{
|
|
float lenSq = fwd.X * fwd.X + fwd.Z * fwd.Z;
|
|
if (lenSq > 1e-4f)
|
|
{
|
|
float inv = 1f / MathF.Sqrt(lenSq);
|
|
camFwdXz = new Vector2(fwd.X * inv, fwd.Z * inv);
|
|
useCamCone = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
bool movedFar = !_lastCamPos.IsFinite() || _lastCamPos.DistanceSquaredTo(camPos) >= RebuildMoveThresholdSq;
|
|
bool coneToggled = useCamCone != _lastCamConeActive;
|
|
bool turnedFar = useCamCone && (_lastCamFwdXz.X * camFwdXz.X + _lastCamFwdXz.Y * camFwdXz.Y) < RebuildTurnCosThreshold;
|
|
if (!movedFar && !coneToggled && !turnedFar && curVer == _lastRenderVersion)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_lastCamPos = camPos;
|
|
_lastCamConeActive = useCamCone;
|
|
if (useCamCone)
|
|
{
|
|
_lastCamFwdXz = camFwdXz;
|
|
}
|
|
_lastRenderVersion = curVer;
|
|
RebuildBuckets(destruction, camPos, useCamCone ? camFwdXz : null);
|
|
}
|
|
|
|
private void EnsureAssetsLoaded(string sionDir)
|
|
{
|
|
if (_assetsLoadAttempted)
|
|
{
|
|
return;
|
|
}
|
|
_assetsLoadAttempted = true;
|
|
|
|
string treesDir = Path.Combine(sionDir, "trees");
|
|
string catalogPath = Path.Combine(treesDir, "trees_catalog.json");
|
|
if (!File.Exists(catalogPath))
|
|
{
|
|
GD.PrintErr($"FoliageRenderer: missing tree catalog at '{catalogPath}'.");
|
|
return;
|
|
}
|
|
|
|
_leavesShader = GD.Load<Shader>("res://tree_leaves.gdshader")
|
|
?? throw new InvalidOperationException("Missing res://tree_leaves.gdshader");
|
|
_barkShader = GD.Load<Shader>("res://tree_bark.gdshader")
|
|
?? throw new InvalidOperationException("Missing res://tree_bark.gdshader");
|
|
_impostorShader = GD.Load<Shader>("res://tree_impostor.gdshader")
|
|
?? throw new InvalidOperationException("Missing res://tree_impostor.gdshader");
|
|
|
|
using var stream = File.OpenRead(catalogPath);
|
|
using var doc = JsonDocument.Parse(stream);
|
|
var arr = doc.RootElement.GetProperty("archetypes");
|
|
|
|
foreach (var item in arr.EnumerateArray())
|
|
{
|
|
int speciesId = item.GetProperty("speciesId").GetInt32();
|
|
int variant = item.GetProperty("variant").GetInt32();
|
|
string slug = item.GetProperty("slug").GetString() ?? "";
|
|
string glbRel = item.GetProperty("glb").GetString() ?? "";
|
|
string leafRel = item.GetProperty("leafTexture").GetString() ?? "";
|
|
string barkRel = item.GetProperty("barkTexture").GetString() ?? "";
|
|
string impAlbRel = item.GetProperty("impostorAlbedo").GetString() ?? "";
|
|
string impNrmRel = item.GetProperty("impostorNormal").GetString() ?? "";
|
|
float canonH = item.GetProperty("canonicalHeightM").GetSingle();
|
|
float impScale = item.GetProperty("impostorScale").GetSingle();
|
|
float impOffsetY = item.GetProperty("impostorOffsetY").GetSingle();
|
|
int impFrames = item.GetProperty("impostorFrames").GetInt32();
|
|
Color barkTint = ReadColor3(item.GetProperty("barkTint"));
|
|
Color leafTint = ReadColor3(item.GetProperty("leafTint"));
|
|
|
|
var meshes = LoadArchetypeMeshes(Path.Combine(treesDir, glbRel));
|
|
if (meshes is null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
Texture2D barkTex = LoadTextureCached(Path.Combine(treesDir, barkRel));
|
|
Texture2D leafTex = LoadTextureCached(Path.Combine(treesDir, leafRel));
|
|
|
|
var barkMat = new ShaderMaterial { Shader = _barkShader };
|
|
barkMat.SetShaderParameter("albedo", barkTint);
|
|
barkMat.SetShaderParameter("albedo_texture", barkTex);
|
|
|
|
var leafMat = new ShaderMaterial { Shader = _leavesShader };
|
|
leafMat.SetShaderParameter("albedo", leafTint);
|
|
leafMat.SetShaderParameter("albedo_texture", leafTex);
|
|
|
|
ApplyTreeMaterials(meshes.Value.Lod0, barkMat, leafMat);
|
|
ApplyTreeMaterials(meshes.Value.Lod1, barkMat, leafMat);
|
|
ApplyTreeMaterials(meshes.Value.Lod2, barkMat, leafMat);
|
|
ApplyTreeMaterials(meshes.Value.SnappedStump, barkMat, leafMat);
|
|
ApplyTreeMaterials(meshes.Value.CharredSkeleton, barkMat, leafMat);
|
|
|
|
var impMat = new ShaderMaterial { Shader = _impostorShader };
|
|
string impAlbPath = Path.Combine(treesDir, impAlbRel);
|
|
string impNrmPath = Path.Combine(treesDir, impNrmRel);
|
|
if (File.Exists(impAlbPath) && File.Exists(impNrmPath))
|
|
{
|
|
impMat.SetShaderParameter("albedo_texture", LoadTextureCached(impAlbPath));
|
|
impMat.SetShaderParameter("normal_texture", LoadTextureCached(impNrmPath));
|
|
}
|
|
impMat.SetShaderParameter("impostor_frames", new Vector2(impFrames, impFrames));
|
|
impMat.SetShaderParameter("scale", impScale);
|
|
impMat.SetShaderParameter("position_offset", new Vector3(0f, impOffsetY, 0f));
|
|
|
|
var impQuad = new QuadMesh { Size = Vector2.One, Material = impMat };
|
|
|
|
var arch = new TreeArchetype
|
|
{
|
|
SpeciesId = speciesId,
|
|
Variant = variant,
|
|
Slug = slug,
|
|
CanonicalHeightM = MathF.Max(1f, canonH),
|
|
ImpostorScale = impScale,
|
|
ImpostorOffsetY = impOffsetY,
|
|
ImpostorFrames = impFrames,
|
|
Lod0 = meshes.Value.Lod0,
|
|
Lod1 = meshes.Value.Lod1,
|
|
Lod2 = meshes.Value.Lod2,
|
|
SnappedStump = meshes.Value.SnappedStump,
|
|
CharredSkeleton = meshes.Value.CharredSkeleton,
|
|
ImpostorQuad = impQuad
|
|
};
|
|
|
|
arch.BucketLod0 = CreateBucket($"{slug}_LOD0", arch.Lod0, castShadows: true, visibilityEndM: Lod0MaxDistanceM + 8f);
|
|
if (variant == 0)
|
|
{
|
|
arch.BucketLod1 = CreateBucket($"{slug}_LOD1", arch.Lod1, castShadows: true, visibilityEndM: Lod1MaxDistanceM + 10f);
|
|
arch.BucketLod2 = CreateBucket($"{slug}_LOD2", arch.Lod2, castShadows: false, visibilityEndM: Lod2MaxDistanceM + 12f);
|
|
arch.BucketImpostor = CreateBucket($"{slug}_Impostor", arch.ImpostorQuad, castShadows: false, visibilityEndM: ImpostorMaxDistanceM + 20f);
|
|
arch.BucketStump = CreateBucket($"{slug}_Stump", arch.SnappedStump, castShadows: false, visibilityEndM: StumpMaxDistanceM + 10f);
|
|
arch.BucketCharred = CreateBucket($"{slug}_Charred", arch.CharredSkeleton, castShadows: true, visibilityEndM: Lod2MaxDistanceM + 12f);
|
|
}
|
|
|
|
int idx = _archetypes.Count;
|
|
_archetypes.Add(arch);
|
|
if ((uint)speciesId < 10 && (uint)variant < 2)
|
|
{
|
|
_archetypeLookup[speciesId, variant] = idx;
|
|
}
|
|
}
|
|
|
|
for (int a = 0; a < _archetypes.Count; a++)
|
|
{
|
|
var arch = _archetypes[a];
|
|
int canon = _archetypeLookup[Math.Clamp(arch.SpeciesId, 0, 9), 0];
|
|
arch.CanonicalArchIdx = canon >= 0 ? canon : a;
|
|
}
|
|
|
|
_assetsLoaded = _archetypes.Count > 0;
|
|
}
|
|
|
|
private BucketState CreateBucket(string name, Mesh mesh, bool castShadows, float visibilityEndM)
|
|
{
|
|
var mm = new MultiMesh
|
|
{
|
|
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
|
|
UseColors = false,
|
|
UseCustomData = true,
|
|
Mesh = mesh,
|
|
InstanceCount = 0,
|
|
VisibleInstanceCount = 0
|
|
};
|
|
var mmi = new MultiMeshInstance3D
|
|
{
|
|
Name = name,
|
|
Multimesh = mm,
|
|
CastShadow = castShadows
|
|
? GeometryInstance3D.ShadowCastingSetting.On
|
|
: GeometryInstance3D.ShadowCastingSetting.Off,
|
|
VisibilityRangeEnd = visibilityEndM,
|
|
VisibilityRangeFadeMode = GeometryInstance3D.VisibilityRangeFadeModeEnum.Disabled,
|
|
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
|
|
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
|
|
Visible = false
|
|
};
|
|
AddChild(mmi);
|
|
return new BucketState { MultiMesh = mm, Instance = mmi };
|
|
}
|
|
|
|
private void BindCatalog(SionTreeCatalog catalog)
|
|
{
|
|
_boundCatalog = catalog;
|
|
var trees = catalog.Trees;
|
|
_precomputed = new PrecomputedTree[trees.Count];
|
|
|
|
for (int i = 0; i < trees.Count; i++)
|
|
{
|
|
var t = trees[i];
|
|
int sp = Math.Clamp((int)t.Species, 0, 9);
|
|
int vr = Math.Clamp((int)t.Variant, 0, 1);
|
|
int archIdx = _archetypeLookup[sp, vr];
|
|
if (archIdx < 0)
|
|
{
|
|
archIdx = _archetypeLookup[sp, 0];
|
|
}
|
|
if (archIdx < 0)
|
|
{
|
|
archIdx = 0;
|
|
}
|
|
|
|
var arch = _archetypes[archIdx];
|
|
var canonArch = _archetypes[arch.CanonicalArchIdx];
|
|
Basis yawBasis = Basis.FromEuler(new Vector3(0f, t.Yaw, 0f));
|
|
float scaleY = Math.Clamp(t.HeightM / arch.CanonicalHeightM, 0.35f, 2.2f);
|
|
float canonScaleY = Math.Clamp(t.HeightM / canonArch.CanonicalHeightM, 0.35f, 2.2f);
|
|
Basis rot = yawBasis.Scaled(new Vector3(scaleY, scaleY, scaleY));
|
|
Basis canonRot = ReferenceEquals(arch, canonArch)
|
|
? rot
|
|
: yawBasis.Scaled(new Vector3(canonScaleY, canonScaleY, canonScaleY));
|
|
Vector3 pos = new(t.X, t.Y, t.Z);
|
|
float phase = ((t.TreeId * 0x9E3779B9u) & 0xFFFFu) / 65536f;
|
|
|
|
_precomputed[i] = new PrecomputedTree
|
|
{
|
|
ArchetypeIdx = archIdx,
|
|
WorldXform = new Transform3D(rot, pos),
|
|
WorldXformCanon = new Transform3D(canonRot, pos),
|
|
Position = pos,
|
|
CustomDataBase = new Color(0f, phase, t.HeightM, 1f)
|
|
};
|
|
}
|
|
|
|
Invalidate();
|
|
}
|
|
|
|
private void RebuildBuckets(SionTreeDestructionState? destruction, Vector3 camPos, Vector2? camFwdXz)
|
|
{
|
|
for (int a = 0; a < _archetypes.Count; a++)
|
|
{
|
|
var arch = _archetypes[a];
|
|
arch.BucketLod0.Indices.Clear();
|
|
arch.BucketLod1?.Indices.Clear();
|
|
arch.BucketLod2?.Indices.Clear();
|
|
arch.BucketImpostor?.Indices.Clear();
|
|
arch.BucketStump?.Indices.Clear();
|
|
arch.BucketCharred?.Indices.Clear();
|
|
}
|
|
|
|
const float lod0Sq = Lod0MaxDistanceM * Lod0MaxDistanceM;
|
|
const float lod1Sq = Lod1MaxDistanceM * Lod1MaxDistanceM;
|
|
const float lod2Sq = Lod2MaxDistanceM * Lod2MaxDistanceM;
|
|
const float impSq = ImpostorMaxDistanceM * ImpostorMaxDistanceM;
|
|
const float stumpSq = StumpMaxDistanceM * StumpMaxDistanceM;
|
|
bool cullCone = camFwdXz.HasValue;
|
|
Vector2 fwd = camFwdXz ?? default;
|
|
|
|
for (int i = 0; i < _precomputed.Length; i++)
|
|
{
|
|
ref readonly var pt = ref _precomputed[i];
|
|
float dx = pt.Position.X - camPos.X;
|
|
float dz = pt.Position.Z - camPos.Z;
|
|
float dSq = dx * dx + dz * dz;
|
|
if (dSq > impSq)
|
|
{
|
|
continue;
|
|
}
|
|
if (cullCone && dSq > FrustumCullMinDistSq)
|
|
{
|
|
float dot = dx * fwd.X + dz * fwd.Y;
|
|
if (dot < 0f && dot * dot > FrustumRearConeCosSq * dSq)
|
|
{
|
|
continue;
|
|
}
|
|
}
|
|
|
|
SionTreeState st = destruction is not null
|
|
? destruction.GetState((ushort)i)
|
|
: SionTreeState.Intact;
|
|
|
|
var arch = _archetypes[pt.ArchetypeIdx];
|
|
var canonArch = _archetypes[arch.CanonicalArchIdx];
|
|
if (st == SionTreeState.Snapped)
|
|
{
|
|
if (dSq <= stumpSq && canonArch.BucketStump is not null)
|
|
{
|
|
canonArch.BucketStump.Indices.Add(i);
|
|
}
|
|
}
|
|
else if (st == SionTreeState.Charred)
|
|
{
|
|
if (dSq <= lod2Sq && canonArch.BucketCharred is not null)
|
|
{
|
|
canonArch.BucketCharred.Indices.Add(i);
|
|
}
|
|
else if (canonArch.BucketImpostor is not null)
|
|
{
|
|
canonArch.BucketImpostor.Indices.Add(i);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (dSq <= lod0Sq)
|
|
{
|
|
arch.BucketLod0.Indices.Add(i);
|
|
}
|
|
else if (dSq <= lod1Sq && canonArch.BucketLod1 is not null)
|
|
{
|
|
canonArch.BucketLod1.Indices.Add(i);
|
|
}
|
|
else if (dSq <= lod2Sq && canonArch.BucketLod2 is not null)
|
|
{
|
|
canonArch.BucketLod2.Indices.Add(i);
|
|
}
|
|
else if (canonArch.BucketImpostor is not null)
|
|
{
|
|
canonArch.BucketImpostor.Indices.Add(i);
|
|
}
|
|
}
|
|
}
|
|
|
|
int c0 = 0, c1 = 0, c2 = 0, cImp = 0, cStump = 0, cChar = 0;
|
|
for (int a = 0; a < _archetypes.Count; a++)
|
|
{
|
|
var arch = _archetypes[a];
|
|
c0 += CommitBucket(arch.BucketLod0, destruction, forceCharred: false, useCanonXform: false);
|
|
if (arch.BucketLod1 is not null) c1 += CommitBucket(arch.BucketLod1, destruction, forceCharred: false, useCanonXform: true);
|
|
if (arch.BucketLod2 is not null) c2 += CommitBucket(arch.BucketLod2, destruction, forceCharred: false, useCanonXform: true);
|
|
if (arch.BucketImpostor is not null) cImp += CommitBucket(arch.BucketImpostor, destruction, forceCharred: false, useCanonXform: true);
|
|
if (arch.BucketStump is not null) cStump += CommitBucket(arch.BucketStump, destruction, forceCharred: false, useCanonXform: true);
|
|
if (arch.BucketCharred is not null) cChar += CommitBucket(arch.BucketCharred, destruction, forceCharred: true, useCanonXform: true);
|
|
}
|
|
|
|
VisibleLod0Count = c0;
|
|
VisibleLod1Count = c1;
|
|
VisibleLod2Count = c2;
|
|
VisibleImpostorCount = cImp;
|
|
VisibleStumpCount = cStump;
|
|
VisibleCharredCount = cChar;
|
|
}
|
|
|
|
private int CommitBucket(BucketState bucket, SionTreeDestructionState? destruction, bool forceCharred, bool useCanonXform)
|
|
{
|
|
int count = bucket.Indices.Count;
|
|
if (count == 0)
|
|
{
|
|
bucket.MultiMesh.VisibleInstanceCount = 0;
|
|
bucket.Instance.Visible = false;
|
|
return 0;
|
|
}
|
|
|
|
if (bucket.MultiMesh.InstanceCount < count)
|
|
{
|
|
int cap = Math.Max(16, (int)BitOperationsRoundUp((uint)count));
|
|
bucket.MultiMesh.InstanceCount = cap;
|
|
}
|
|
bucket.MultiMesh.VisibleInstanceCount = count;
|
|
bucket.Instance.Visible = true;
|
|
|
|
float minX = float.PositiveInfinity, minY = float.PositiveInfinity, minZ = float.PositiveInfinity;
|
|
float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity, maxZ = float.NegativeInfinity;
|
|
|
|
for (int k = 0; k < count; k++)
|
|
{
|
|
int treeIdx = bucket.Indices[k];
|
|
ref readonly var pt = ref _precomputed[treeIdx];
|
|
bucket.MultiMesh.SetInstanceTransform(k, useCanonXform ? pt.WorldXformCanon : pt.WorldXform);
|
|
|
|
Vector3 p = pt.Position;
|
|
if (p.X < minX) minX = p.X;
|
|
if (p.Y < minY) minY = p.Y;
|
|
if (p.Z < minZ) minZ = p.Z;
|
|
if (p.X > maxX) maxX = p.X;
|
|
if (p.Y > maxY) maxY = p.Y;
|
|
if (p.Z > maxZ) maxZ = p.Z;
|
|
|
|
float isChar = forceCharred || (destruction is not null && destruction.GetState((ushort)treeIdx) == SionTreeState.Charred)
|
|
? 1f
|
|
: 0f;
|
|
Color c = pt.CustomDataBase;
|
|
c.R = isChar;
|
|
bucket.MultiMesh.SetInstanceCustomData(k, c);
|
|
}
|
|
|
|
var tightAabb = new Aabb(
|
|
new Vector3(minX - 14f, minY - 2f, minZ - 14f),
|
|
new Vector3((maxX - minX) + 28f, (maxY - minY) + 42f, (maxZ - minZ) + 28f));
|
|
bucket.MultiMesh.CustomAabb = tightAabb;
|
|
bucket.Instance.CustomAabb = tightAabb;
|
|
|
|
return count;
|
|
}
|
|
|
|
private static uint BitOperationsRoundUp(uint v)
|
|
{
|
|
v--;
|
|
v |= v >> 1;
|
|
v |= v >> 2;
|
|
v |= v >> 4;
|
|
v |= v >> 8;
|
|
v |= v >> 16;
|
|
return v + 1;
|
|
}
|
|
|
|
private Texture2D LoadTextureCached(string absPath)
|
|
{
|
|
if (_textureCache.TryGetValue(absPath, out var tex))
|
|
{
|
|
return tex;
|
|
}
|
|
var img = Image.LoadFromFile(absPath);
|
|
if (img is null)
|
|
{
|
|
throw new InvalidOperationException($"FoliageRenderer: failed to load texture '{absPath}'.");
|
|
}
|
|
img.GenerateMipmaps();
|
|
var itex = ImageTexture.CreateFromImage(img);
|
|
_textureCache[absPath] = itex;
|
|
return itex;
|
|
}
|
|
|
|
private static Color ReadColor3(JsonElement arr) =>
|
|
new(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle(), 1f);
|
|
|
|
private static void ApplyTreeMaterials(ArrayMesh mesh, ShaderMaterial barkMat, ShaderMaterial leafMat)
|
|
{
|
|
for (int s = 0; s < mesh.GetSurfaceCount(); s++)
|
|
{
|
|
string sName = mesh.SurfaceGetName(s) ?? string.Empty;
|
|
if (sName.Contains("foliage", StringComparison.OrdinalIgnoreCase) || s == 1)
|
|
{
|
|
mesh.SurfaceSetMaterial(s, leafMat);
|
|
}
|
|
else
|
|
{
|
|
mesh.SurfaceSetMaterial(s, barkMat);
|
|
}
|
|
}
|
|
}
|
|
|
|
private readonly record struct ArchetypeMeshes(
|
|
ArrayMesh Lod0,
|
|
ArrayMesh Lod1,
|
|
ArrayMesh Lod2,
|
|
ArrayMesh SnappedStump,
|
|
ArrayMesh CharredSkeleton);
|
|
|
|
private static ArchetypeMeshes? LoadArchetypeMeshes(string glbPath)
|
|
{
|
|
if (!File.Exists(glbPath))
|
|
{
|
|
GD.PrintErr($"FoliageRenderer: missing GLB '{glbPath}'.");
|
|
return null;
|
|
}
|
|
|
|
var doc = new GltfDocument();
|
|
var state = new GltfState();
|
|
Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty);
|
|
if (err != Error.Ok)
|
|
{
|
|
GD.PrintErr($"FoliageRenderer: GltfDocument failed on '{glbPath}': {err}");
|
|
return null;
|
|
}
|
|
|
|
Node? root = doc.GenerateScene(state);
|
|
if (root is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
ArrayMesh? lod0 = null, lod1 = null, lod2 = null, stump = null, charred = null;
|
|
var stack = new Stack<Node>();
|
|
stack.Push(root);
|
|
while (stack.Count > 0)
|
|
{
|
|
Node n = stack.Pop();
|
|
if (n is MeshInstance3D mi && mi.Mesh is ArrayMesh am)
|
|
{
|
|
string name = mi.Name.ToString();
|
|
if (name.Contains("Intact_LOD0", StringComparison.OrdinalIgnoreCase)) lod0 = am;
|
|
else if (name.Contains("Intact_LOD1", StringComparison.OrdinalIgnoreCase)) lod1 = am;
|
|
else if (name.Contains("Intact_LOD2", StringComparison.OrdinalIgnoreCase)) lod2 = am;
|
|
else if (name.Contains("SnappedStump", StringComparison.OrdinalIgnoreCase)) stump = am;
|
|
else if (name.Contains("CharredSkeleton", StringComparison.OrdinalIgnoreCase)) charred = am;
|
|
}
|
|
for (int i = 0; i < n.GetChildCount(); i++)
|
|
{
|
|
stack.Push(n.GetChild(i));
|
|
}
|
|
}
|
|
|
|
if (lod0 is null || lod1 is null || lod2 is null || stump is null || charred is null)
|
|
{
|
|
GD.PrintErr($"FoliageRenderer: incomplete meshes in '{glbPath}'.");
|
|
return null;
|
|
}
|
|
return new ArchetypeMeshes(lod0, lod1, lod2, stump, charred);
|
|
}
|
|
finally
|
|
{
|
|
root.Free();
|
|
}
|
|
}
|
|
}
|