Optimize arena rendering and simulation loop to 60 FPS
This commit is contained in:
parent
805c169794
commit
0f36eed3a0
12 changed files with 1810 additions and 231 deletions
|
|
@ -46,6 +46,8 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
public required VehiclePackage Package { get; init; }
|
||||
public required string GlbPath { get; init; }
|
||||
public required Node3D SceneTemplate { get; init; }
|
||||
public required ArrayMesh BakedStaticMesh { get; init; }
|
||||
public required ArrayMesh BakedLodFarMesh { get; init; }
|
||||
public required float MinY { get; init; }
|
||||
public required float MaxY { get; init; }
|
||||
public required IReadOnlyDictionary<string, GlbAnchorInfo> Anchors { get; init; }
|
||||
|
|
@ -170,6 +172,7 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
generated?.QueueFree();
|
||||
throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for '{glbPath}'.");
|
||||
}
|
||||
ClearOwnerRecursive(sceneRoot);
|
||||
|
||||
var gltfNodes = state.GetNodes();
|
||||
var jsonNodes = jsonRoot.GetProperty("nodes");
|
||||
|
|
@ -383,21 +386,89 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
|
||||
ComputeSceneMeshBoundsY(sceneRoot, out float minY, out float maxY);
|
||||
|
||||
// Build full set of protected structural/rig/joint/anchor/mobility Godot nodes
|
||||
var protectedNodes = new HashSet<Node> { sceneRoot };
|
||||
for (int i = 0; i < nodeCount; i++)
|
||||
{
|
||||
if ((protectedIndices.Contains(i) || hasProtectedDesc[i]) && nodeByGltfIndex[i] is { } pn)
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(pn, sceneRoot, protectedNodes);
|
||||
}
|
||||
}
|
||||
foreach (var a in anchors.Values)
|
||||
{
|
||||
if (sceneRoot.GetNodeOrNull(a.RelativePath) is { } an)
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(an, sceneRoot, protectedNodes);
|
||||
}
|
||||
}
|
||||
foreach (var j in joints.Values)
|
||||
{
|
||||
if (sceneRoot.GetNodeOrNull(j.RelativePath) is { } jn)
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(jn, sceneRoot, protectedNodes);
|
||||
}
|
||||
}
|
||||
foreach (var mp in mobilityPaths)
|
||||
{
|
||||
if (sceneRoot.GetNodeOrNull(mp) is { } mn)
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(mn, sceneRoot, protectedNodes);
|
||||
}
|
||||
}
|
||||
|
||||
// Map original detachable MeshInstance3Ds so we can merge them per (rigidParent, CellX, CellY)
|
||||
var detachableByNode = new Dictionary<MeshInstance3D, (int CellX, int CellY, string Kind)>();
|
||||
foreach (var dp in detachableParts)
|
||||
{
|
||||
if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D mi && !protectedNodes.Contains(mi))
|
||||
{
|
||||
detachableByNode.TryAdd(mi, (dp.CellX, dp.CellY, dp.Kind));
|
||||
}
|
||||
}
|
||||
|
||||
// A & B: Merge detachable armor per (rigidParent, CellX, CellY) and static meshes per rigidParent
|
||||
var mergedDetachableInfos = MergeVehicleSubMeshes(sceneRoot, protectedNodes, detachableByNode);
|
||||
|
||||
// Prune stale nodesByOriginalName entries that were collapsed into merged meshes
|
||||
var survivingNames = new Dictionary<string, NodePath>(StringComparer.Ordinal);
|
||||
foreach (var (origName, relPath) in nodesByOriginalName)
|
||||
{
|
||||
Node? resolved = relPath.ToString() == "." ? sceneRoot : sceneRoot.GetNodeOrNull(relPath);
|
||||
if (resolved is not null)
|
||||
{
|
||||
survivingNames[origName] = relPath;
|
||||
}
|
||||
}
|
||||
|
||||
// C: Build single-node BakedStaticMesh + decimated BakedLodFarMesh (>130m) per template
|
||||
ArrayMesh bakedStaticMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false);
|
||||
ArrayMesh bakedCoarseStatic = BuildBakedStaticMesh(sceneRoot, coarseMaterials: true);
|
||||
ArrayMesh bakedLodFarMesh = DecimateMeshGrid(bakedCoarseStatic, cellSize: 0.45f);
|
||||
|
||||
return new VehicleTemplate
|
||||
{
|
||||
Package = pkg,
|
||||
GlbPath = glbPath,
|
||||
SceneTemplate = sceneRoot,
|
||||
BakedStaticMesh = bakedStaticMesh,
|
||||
BakedLodFarMesh = bakedLodFarMesh,
|
||||
MinY = minY,
|
||||
MaxY = maxY,
|
||||
Anchors = anchors,
|
||||
Joints = joints,
|
||||
NodesByOriginalName = nodesByOriginalName,
|
||||
DetachableParts = detachableParts,
|
||||
NodesByOriginalName = survivingNames,
|
||||
DetachableParts = mergedDetachableInfos,
|
||||
MobilityNodePaths = mobilityPaths
|
||||
};
|
||||
}
|
||||
|
||||
private static readonly HashSet<string> PreservedGearPartNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"barrel_inner", "receiver", "muzzle_brake_L", "gun_housing",
|
||||
"sight_tube", "breech_band", "condenser_ring_2", "ivory_cowl"
|
||||
};
|
||||
|
||||
private static GearTemplate LoadGearTemplate(string gearId, string glbPath)
|
||||
{
|
||||
var doc = new GltfDocument();
|
||||
|
|
@ -414,8 +485,10 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
generated?.QueueFree();
|
||||
throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for gear '{glbPath}'.");
|
||||
}
|
||||
ClearOwnerRecursive(sceneRoot);
|
||||
|
||||
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
|
||||
MergeGearSubMeshes(sceneRoot, gearId);
|
||||
Vector3 localFwd = new Vector3(0f, 0f, 1f);
|
||||
|
||||
return new GearTemplate
|
||||
|
|
@ -429,33 +502,35 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
};
|
||||
}
|
||||
|
||||
private static bool IsStructuralNodeName(string name)
|
||||
private static readonly HashSet<string> ExactStructuralNodeNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
string low = name.ToLowerInvariant();
|
||||
if (low is "chassis" or "hull" or "pelvis" or "core" or "trunk" or "waist" or "torso.pose" or "aim.turret" or "hull.pose")
|
||||
"chassis", "hull", "pelvis", "core", "trunk", "waist", "torso.pose", "aim.turret", "hull.pose",
|
||||
"legl.hip", "legr.hip", "legl.shin", "legr.shin", "legl.foot", "legr.foot",
|
||||
"legl.upper", "legr.upper", "legl.lower", "legr.lower", "legl.ankle", "legr.ankle",
|
||||
"legl.thigh", "legr.thigh", "legl.cannon", "legr.cannon",
|
||||
"legl.oleo", "legr.oleo", "legl.oleofork", "legr.oleofork",
|
||||
"legl.torqueup", "legr.torqueup", "legl.torquelow", "legr.torquelow",
|
||||
"legl.lug", "legr.lug", "legl.ramluga0", "legl.ramluga1", "legr.ramluga0", "legr.ramluga1",
|
||||
"legl.recessram0", "legl.recessram1", "legr.recessram0", "legr.recessram1",
|
||||
"legfl.s1", "legfr.s1", "legbl.s1", "legbr.s1",
|
||||
"legfl.s2", "legfr.s2", "legbl.s2", "legbr.s2",
|
||||
"footfl", "footfr", "footbl", "footbr",
|
||||
"thigh.fl", "thigh.fr", "thigh.rl", "thigh.rr",
|
||||
"shin.fl", "shin.fr", "shin.rl", "shin.rr",
|
||||
"ankle.fl", "ankle.fr", "ankle.rl", "ankle.rr"
|
||||
};
|
||||
|
||||
private static bool IsStructuralNodeName(string name) =>
|
||||
ExactStructuralNodeNames.Contains(name);
|
||||
|
||||
private static void ClearOwnerRecursive(Node cur)
|
||||
{
|
||||
cur.Owner = null;
|
||||
int count = cur.GetChildCount();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
return true;
|
||||
ClearOwnerRecursive(cur.GetChild(i));
|
||||
}
|
||||
if (low.StartsWith("slot_frame.", StringComparison.Ordinal) ||
|
||||
low.StartsWith("hp.", StringComparison.Ordinal) ||
|
||||
low.StartsWith("joint.", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (low.StartsWith("leg", StringComparison.Ordinal) &&
|
||||
!low.Contains("shield") && !low.Contains("armor") && !low.Contains("plate") &&
|
||||
!low.Contains("greave") && !low.Contains("shroud") && !low.Contains("skirt") &&
|
||||
!low.Contains("cheek") && !low.Contains("collar"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return low.Contains("hip") && !low.Contains("cap") && !low.Contains("fender") && !low.Contains("flange") && !low.Contains("guard") && !low.Contains("shroud")
|
||||
|| low.Contains("thigh") && !low.Contains("shield") && !low.Contains("guard") && !low.Contains("shroud") && !low.Contains("lame") && !low.Contains("cuisse")
|
||||
|| low.Contains("shin") && !low.Contains("greave") && !low.Contains("guard") && !low.Contains("cheek") && !low.Contains("shroud")
|
||||
|| low.Contains("oleo") || low.Contains("torque") || low.Contains("recessram")
|
||||
|| low.StartsWith("arm", StringComparison.Ordinal) || low.StartsWith("shoulder", StringComparison.Ordinal)
|
||||
|| low.StartsWith("forearm", StringComparison.Ordinal) || low.StartsWith("elbow", StringComparison.Ordinal)
|
||||
|| low.StartsWith("tail.", StringComparison.Ordinal) || low.StartsWith("foot", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static bool IsDetachablePartKind(string kind, string nodeName, int childCount)
|
||||
|
|
@ -482,6 +557,764 @@ public sealed class VehicleAssetCache : IDisposable
|
|||
return childCount == 0 && (low.Contains("canopy") || low.Contains("hatch") || low.Contains("visor"));
|
||||
}
|
||||
|
||||
private static void MarkNodeAndAncestorsProtected(Node node, Node root, HashSet<Node> protectedNodes)
|
||||
{
|
||||
Node? cur = node;
|
||||
while (cur is not null)
|
||||
{
|
||||
protectedNodes.Add(cur);
|
||||
if (ReferenceEquals(cur, root))
|
||||
{
|
||||
break;
|
||||
}
|
||||
cur = cur.GetParent();
|
||||
}
|
||||
}
|
||||
|
||||
private static Node3D FindNearestProtectedParent(Node node, Node3D sceneRoot, HashSet<Node> protectedNodes)
|
||||
{
|
||||
Node? cur = node.GetParent();
|
||||
while (cur is not null)
|
||||
{
|
||||
if (cur is Node3D n3d && protectedNodes.Contains(cur))
|
||||
{
|
||||
return n3d;
|
||||
}
|
||||
if (ReferenceEquals(cur, sceneRoot))
|
||||
{
|
||||
break;
|
||||
}
|
||||
cur = cur.GetParent();
|
||||
}
|
||||
return sceneRoot;
|
||||
}
|
||||
|
||||
private static Transform3D ComputeRelativeTransform(Node3D ancestor, Node descendant)
|
||||
{
|
||||
Transform3D xf = Transform3D.Identity;
|
||||
Node? cur = descendant;
|
||||
while (cur is not null && !ReferenceEquals(cur, ancestor))
|
||||
{
|
||||
if (cur is Node3D n3d)
|
||||
{
|
||||
xf = n3d.Transform * xf;
|
||||
}
|
||||
cur = cur.GetParent();
|
||||
}
|
||||
return xf;
|
||||
}
|
||||
|
||||
private static bool CanMergeMeshInstance(MeshInstance3D mi)
|
||||
{
|
||||
if (mi.Mesh is null || mi.Mesh.GetSurfaceCount() == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (mi.Mesh is ArrayMesh am)
|
||||
{
|
||||
int surfCount = am.GetSurfaceCount();
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
if (am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void CollectAllMeshInstances(Node cur, List<MeshInstance3D> outList)
|
||||
{
|
||||
if (cur is MeshInstance3D mi)
|
||||
{
|
||||
outList.Add(mi);
|
||||
}
|
||||
int count = cur.GetChildCount();
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
CollectAllMeshInstances(cur.GetChild(i), outList);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReparentChildrenAndRemove(MeshInstance3D mi)
|
||||
{
|
||||
Node? parent = mi.GetParent();
|
||||
if (parent is not null)
|
||||
{
|
||||
for (int i = mi.GetChildCount() - 1; i >= 0; i--)
|
||||
{
|
||||
Node ch = mi.GetChild(i);
|
||||
mi.RemoveChild(ch);
|
||||
if (ch is Node3D ch3d)
|
||||
{
|
||||
ch3d.Transform = mi.Transform * ch3d.Transform;
|
||||
}
|
||||
parent.AddChild(ch);
|
||||
}
|
||||
parent.RemoveChild(mi);
|
||||
}
|
||||
mi.QueueFree();
|
||||
}
|
||||
|
||||
private static List<GlbPartNodeInfo> MergeVehicleSubMeshes(
|
||||
Node3D sceneRoot,
|
||||
HashSet<Node> protectedNodes,
|
||||
Dictionary<MeshInstance3D, (int CellX, int CellY, string Kind)> detachableByNode)
|
||||
{
|
||||
var allMeshes = new List<MeshInstance3D>();
|
||||
CollectAllMeshInstances(sceneRoot, allMeshes);
|
||||
|
||||
var detachableGroups = new Dictionary<(Node3D RigidParent, int CellX, int CellY), (string Kind, List<(MeshInstance3D Mi, Transform3D RelXf)> Items)>();
|
||||
var staticGroups = new Dictionary<Node3D, List<(MeshInstance3D Mi, Transform3D RelXf)>>();
|
||||
var detachResultNodes = new List<(MeshInstance3D Node, int CellX, int CellY, string Kind)>();
|
||||
|
||||
for (int i = 0; i < allMeshes.Count; i++)
|
||||
{
|
||||
MeshInstance3D mi = allMeshes[i];
|
||||
if (!CanMergeMeshInstance(mi))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (detachableByNode.TryGetValue(mi, out var detInfo))
|
||||
{
|
||||
Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
|
||||
Transform3D relXf = ComputeRelativeTransform(rigidParent, mi);
|
||||
var key = (rigidParent, detInfo.CellX, detInfo.CellY);
|
||||
if (!detachableGroups.TryGetValue(key, out var group))
|
||||
{
|
||||
group = (detInfo.Kind, new List<(MeshInstance3D, Transform3D)>());
|
||||
detachableGroups[key] = group;
|
||||
}
|
||||
group.Items.Add((mi, relXf));
|
||||
}
|
||||
else if (!protectedNodes.Contains(mi))
|
||||
{
|
||||
Node3D rigidParent = FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
|
||||
Transform3D relXf = ComputeRelativeTransform(rigidParent, mi);
|
||||
if (!staticGroups.TryGetValue(rigidParent, out var list))
|
||||
{
|
||||
list = new List<(MeshInstance3D, Transform3D)>();
|
||||
staticGroups[rigidParent] = list;
|
||||
}
|
||||
list.Add((mi, relXf));
|
||||
}
|
||||
}
|
||||
|
||||
// B. Merge detachable armor parts per (rigidParent, CellX, CellY)
|
||||
int detSeq = 0;
|
||||
foreach (var ((rigidParent, cellX, cellY), (kind, items)) in detachableGroups)
|
||||
{
|
||||
if (items.Count == 1 && ReferenceEquals(items[0].Mi.GetParent(), rigidParent))
|
||||
{
|
||||
// Already a single child directly under rigidParent — keep as-is
|
||||
detachResultNodes.Add((items[0].Mi, cellX, cellY, kind));
|
||||
continue;
|
||||
}
|
||||
|
||||
ArrayMesh? merged = BuildMergedArrayMesh(items);
|
||||
if (merged is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var chunkNode = new MeshInstance3D
|
||||
{
|
||||
Name = $"ArmorCell_{cellX}_{cellY}_{detSeq++}",
|
||||
Mesh = merged
|
||||
};
|
||||
rigidParent.AddChild(chunkNode);
|
||||
detachResultNodes.Add((chunkNode, cellX, cellY, kind));
|
||||
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
ReparentChildrenAndRemove(items[i].Mi);
|
||||
}
|
||||
}
|
||||
|
||||
// A. Merge static non-detachable sub-meshes per rigid articulated parent
|
||||
foreach (var (rigidParent, items) in staticGroups)
|
||||
{
|
||||
if (rigidParent is MeshInstance3D parentMi && CanMergeMeshInstance(parentMi))
|
||||
{
|
||||
var combined = new List<(MeshInstance3D, Transform3D)>(items.Count + 1)
|
||||
{
|
||||
(parentMi, Transform3D.Identity)
|
||||
};
|
||||
combined.AddRange(items);
|
||||
ArrayMesh? merged = BuildMergedArrayMesh(combined);
|
||||
if (merged is not null)
|
||||
{
|
||||
parentMi.MaterialOverride = null;
|
||||
parentMi.Mesh = merged;
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
ReparentChildrenAndRemove(items[i].Mi);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (items.Count > 1 || (items.Count == 1 && !ReferenceEquals(items[0].Mi.GetParent(), rigidParent)))
|
||||
{
|
||||
ArrayMesh? merged = BuildMergedArrayMesh(items);
|
||||
if (merged is not null)
|
||||
{
|
||||
var staticNode = new MeshInstance3D
|
||||
{
|
||||
Name = $"{rigidParent.Name}_StaticMerged",
|
||||
Mesh = merged
|
||||
};
|
||||
rigidParent.AddChild(staticNode);
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
ReparentChildrenAndRemove(items[i].Mi);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prune empty non-protected grouping nodes left behind
|
||||
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, protectedNodes);
|
||||
|
||||
var result = new List<GlbPartNodeInfo>(detachResultNodes.Count);
|
||||
for (int i = 0; i < detachResultNodes.Count; i++)
|
||||
{
|
||||
var (node, cellX, cellY, kind) = detachResultNodes[i];
|
||||
if (!GodotObject.IsInstanceValid(node) || !sceneRoot.IsAncestorOf(node))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
result.Add(new GlbPartNodeInfo(
|
||||
node.Name,
|
||||
cellX,
|
||||
cellY,
|
||||
kind,
|
||||
BuildRelativeNodePath(sceneRoot, node),
|
||||
HasProtectedDescendant: false));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void MergeGearSubMeshes(Node3D sceneRoot, string gearId)
|
||||
{
|
||||
var keptNodes = new HashSet<Node> { sceneRoot };
|
||||
var allMeshes = new List<MeshInstance3D>();
|
||||
CollectAllMeshInstances(sceneRoot, allMeshes);
|
||||
|
||||
for (int i = 0; i < allMeshes.Count; i++)
|
||||
{
|
||||
MeshInstance3D mi = allMeshes[i];
|
||||
if (PreservedGearPartNames.Contains(mi.Name))
|
||||
{
|
||||
MarkNodeAndAncestorsProtected(mi, sceneRoot, keptNodes);
|
||||
}
|
||||
}
|
||||
|
||||
var mergeList = new List<(MeshInstance3D Mi, Transform3D RelXf)>();
|
||||
for (int i = 0; i < allMeshes.Count; i++)
|
||||
{
|
||||
MeshInstance3D mi = allMeshes[i];
|
||||
if (!keptNodes.Contains(mi) && CanMergeMeshInstance(mi))
|
||||
{
|
||||
mergeList.Add((mi, ComputeRelativeTransform(sceneRoot, mi)));
|
||||
}
|
||||
}
|
||||
|
||||
if (mergeList.Count <= 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ArrayMesh? merged = BuildMergedArrayMesh(mergeList);
|
||||
if (merged is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var mergedNode = new MeshInstance3D
|
||||
{
|
||||
Name = $"{gearId}_StaticMerged",
|
||||
Mesh = merged
|
||||
};
|
||||
sceneRoot.AddChild(mergedNode);
|
||||
for (int i = 0; i < mergeList.Count; i++)
|
||||
{
|
||||
ReparentChildrenAndRemove(mergeList[i].Mi);
|
||||
}
|
||||
PruneEmptyNonProtectedNodes(sceneRoot, sceneRoot, keptNodes);
|
||||
}
|
||||
|
||||
private static ArrayMesh BuildBakedStaticMesh(Node3D sceneRoot, bool coarseMaterials = false)
|
||||
{
|
||||
var allMeshes = new List<MeshInstance3D>();
|
||||
CollectAllMeshInstances(sceneRoot, allMeshes);
|
||||
|
||||
var items = new List<(MeshInstance3D Mi, Transform3D RelXf)>(allMeshes.Count);
|
||||
for (int i = 0; i < allMeshes.Count; i++)
|
||||
{
|
||||
MeshInstance3D mi = allMeshes[i];
|
||||
if (CanMergeMeshInstance(mi))
|
||||
{
|
||||
items.Add((mi, ComputeRelativeTransform(sceneRoot, mi)));
|
||||
}
|
||||
}
|
||||
|
||||
return BuildMergedArrayMesh(items, coarseMaterials) ?? new ArrayMesh();
|
||||
}
|
||||
|
||||
private static void PruneEmptyNonProtectedNodes(Node cur, Node sceneRoot, HashSet<Node> protectedNodes)
|
||||
{
|
||||
for (int i = cur.GetChildCount() - 1; i >= 0; i--)
|
||||
{
|
||||
Node ch = cur.GetChild(i);
|
||||
PruneEmptyNonProtectedNodes(ch, sceneRoot, protectedNodes);
|
||||
if (!ReferenceEquals(ch, sceneRoot) &&
|
||||
!protectedNodes.Contains(ch) &&
|
||||
ch is not MeshInstance3D &&
|
||||
ch.GetChildCount() == 0)
|
||||
{
|
||||
cur.RemoveChild(ch);
|
||||
ch.QueueFree();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct StandardMatKey(
|
||||
int PaintTag,
|
||||
int R,
|
||||
int G,
|
||||
int B,
|
||||
int A,
|
||||
int Metallic,
|
||||
int Roughness,
|
||||
bool EmissionEnabled,
|
||||
int EmR,
|
||||
int EmG,
|
||||
int EmB,
|
||||
int EmEnergy,
|
||||
int Transparency,
|
||||
int CullMode);
|
||||
|
||||
private static bool TryGetMaterialValueKey(Material mat, bool coarse, out StandardMatKey key)
|
||||
{
|
||||
if (mat is StandardMaterial3D sm &&
|
||||
sm.AlbedoTexture is null &&
|
||||
sm.NormalTexture is null &&
|
||||
sm.RoughnessTexture is null &&
|
||||
sm.MetallicTexture is null &&
|
||||
sm.EmissionTexture is null)
|
||||
{
|
||||
string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant();
|
||||
int paintTag = (mName.Contains("olive") || mName.Contains("khaki")) ? 1
|
||||
: (mName.Contains("signal") || mName.Contains("orange")) ? 2
|
||||
: 0;
|
||||
float colorScale = coarse ? 6f : 255f;
|
||||
float pbrScale = coarse ? 2f : 100f;
|
||||
key = new StandardMatKey(
|
||||
paintTag,
|
||||
(int)MathF.Round(sm.AlbedoColor.R * colorScale),
|
||||
(int)MathF.Round(sm.AlbedoColor.G * colorScale),
|
||||
(int)MathF.Round(sm.AlbedoColor.B * colorScale),
|
||||
(int)MathF.Round(sm.AlbedoColor.A * 10f),
|
||||
(int)MathF.Round(sm.Metallic * pbrScale),
|
||||
(int)MathF.Round(sm.Roughness * pbrScale),
|
||||
sm.EmissionEnabled,
|
||||
(int)MathF.Round(sm.Emission.R * colorScale),
|
||||
(int)MathF.Round(sm.Emission.G * colorScale),
|
||||
(int)MathF.Round(sm.Emission.B * colorScale),
|
||||
(int)MathF.Round(sm.EmissionEnergyMultiplier * pbrScale),
|
||||
(int)sm.Transparency,
|
||||
(int)sm.CullMode);
|
||||
return true;
|
||||
}
|
||||
key = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
private sealed class MaterialSurfaceBucket
|
||||
{
|
||||
public required Material? Material;
|
||||
public readonly List<(Mesh Mesh, int SurfaceIdx, Transform3D RelXf)> Sources = new();
|
||||
}
|
||||
|
||||
private static ArrayMesh? BuildMergedArrayMesh(List<(MeshInstance3D Mi, Transform3D RelXf)> items, bool coarseMaterials = false)
|
||||
{
|
||||
if (items.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var buckets = new List<MaterialSurfaceBucket>();
|
||||
var bucketByMatId = new Dictionary<ulong, MaterialSurfaceBucket>();
|
||||
var bucketByMatVal = new Dictionary<StandardMatKey, MaterialSurfaceBucket>();
|
||||
MaterialSurfaceBucket? nullMatBucket = null;
|
||||
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
var (mi, relXf) = items[i];
|
||||
if (mi.Mesh is not { } mesh)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
int surfCount = mesh.GetSurfaceCount();
|
||||
var am = mesh as ArrayMesh;
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
if (am is not null && am.SurfaceGetPrimitiveType(s) != Mesh.PrimitiveType.Triangles)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Material? mat = mi.MaterialOverride ?? mi.GetActiveMaterial(s);
|
||||
MaterialSurfaceBucket bucket;
|
||||
if (mat is null)
|
||||
{
|
||||
nullMatBucket ??= new MaterialSurfaceBucket { Material = null };
|
||||
if (!buckets.Contains(nullMatBucket))
|
||||
{
|
||||
buckets.Add(nullMatBucket);
|
||||
}
|
||||
bucket = nullMatBucket;
|
||||
}
|
||||
else if (TryGetMaterialValueKey(mat, coarseMaterials, out var matKey))
|
||||
{
|
||||
if (!bucketByMatVal.TryGetValue(matKey, out bucket!))
|
||||
{
|
||||
bucket = new MaterialSurfaceBucket { Material = mat };
|
||||
bucketByMatVal[matKey] = bucket;
|
||||
buckets.Add(bucket);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ulong id = mat.GetInstanceId();
|
||||
if (!bucketByMatId.TryGetValue(id, out bucket!))
|
||||
{
|
||||
bucket = new MaterialSurfaceBucket { Material = mat };
|
||||
bucketByMatId[id] = bucket;
|
||||
buckets.Add(bucket);
|
||||
}
|
||||
}
|
||||
bucket.Sources.Add((mesh, s, relXf));
|
||||
}
|
||||
}
|
||||
|
||||
if (buckets.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var outMesh = new ArrayMesh();
|
||||
for (int b = 0; b < buckets.Count; b++)
|
||||
{
|
||||
var bucket = buckets[b];
|
||||
bool anyNormal = false;
|
||||
bool anyTangent = false;
|
||||
bool anyUv = false;
|
||||
bool anyUv2 = false;
|
||||
bool anyColor = false;
|
||||
int totalVerts = 0;
|
||||
int totalIndices = 0;
|
||||
|
||||
var cachedArrays = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, int VertCount, int IndexCount)>(bucket.Sources.Count);
|
||||
for (int s = 0; s < bucket.Sources.Count; s++)
|
||||
{
|
||||
var (mesh, surfIdx, relXf) = bucket.Sources[s];
|
||||
var arr = mesh.SurfaceGetArrays(surfIdx);
|
||||
if (arr.Count <= (int)Mesh.ArrayType.Vertex ||
|
||||
arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
||||
if (verts.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array) anyNormal = true;
|
||||
if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array) anyTangent = true;
|
||||
if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array) anyUv = true;
|
||||
if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array) anyUv2 = true;
|
||||
if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray) anyColor = true;
|
||||
|
||||
int idxCount = verts.Length;
|
||||
if (arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array)
|
||||
{
|
||||
idxCount = arr[(int)Mesh.ArrayType.Index].AsInt32Array().Length;
|
||||
}
|
||||
|
||||
totalVerts += verts.Length;
|
||||
totalIndices += idxCount;
|
||||
cachedArrays.Add((arr, relXf, verts.Length, idxCount));
|
||||
}
|
||||
|
||||
if (totalVerts == 0 || totalIndices == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var outVerts = new Vector3[totalVerts];
|
||||
Vector3[]? outNormals = anyNormal ? new Vector3[totalVerts] : null;
|
||||
float[]? outTangents = anyTangent ? new float[totalVerts * 4] : null;
|
||||
Vector2[]? outUvs = anyUv ? new Vector2[totalVerts] : null;
|
||||
Vector2[]? outUv2s = anyUv2 ? new Vector2[totalVerts] : null;
|
||||
Color[]? outColors = anyColor ? new Color[totalVerts] : null;
|
||||
var outIndices = new int[totalIndices];
|
||||
|
||||
int vOffset = 0;
|
||||
int iOffset = 0;
|
||||
for (int c = 0; c < cachedArrays.Count; c++)
|
||||
{
|
||||
var (arr, relXf, vCount, idxCount) = cachedArrays[c];
|
||||
Vector3[] srcVerts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
||||
bool flipWinding = relXf.Basis.Determinant() < 0f;
|
||||
Basis normBasis = relXf.Basis.Inverse().Transposed();
|
||||
|
||||
for (int v = 0; v < vCount; v++)
|
||||
{
|
||||
outVerts[vOffset + v] = relXf * srcVerts[v];
|
||||
}
|
||||
|
||||
if (outNormals is not null)
|
||||
{
|
||||
if (arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array)
|
||||
{
|
||||
Vector3[] srcN = arr[(int)Mesh.ArrayType.Normal].AsVector3Array();
|
||||
for (int v = 0; v < vCount; v++)
|
||||
{
|
||||
Vector3 n = normBasis * srcN[v];
|
||||
outNormals[vOffset + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int v = 0; v < vCount; v++) outNormals[vOffset + v] = Vector3.Up;
|
||||
}
|
||||
}
|
||||
|
||||
if (outTangents is not null)
|
||||
{
|
||||
if (arr.Count > (int)Mesh.ArrayType.Tangent && arr[(int)Mesh.ArrayType.Tangent].VariantType == Variant.Type.PackedFloat32Array)
|
||||
{
|
||||
float[] srcT = arr[(int)Mesh.ArrayType.Tangent].AsFloat32Array();
|
||||
for (int v = 0; v < vCount; v++)
|
||||
{
|
||||
int sBase = v * 4;
|
||||
int dBase = (vOffset + v) * 4;
|
||||
Vector3 t = relXf.Basis * new Vector3(srcT[sBase], srcT[sBase + 1], srcT[sBase + 2]);
|
||||
t = t.LengthSquared() > 1e-10f ? t.Normalized() : Vector3.Right;
|
||||
outTangents[dBase] = t.X;
|
||||
outTangents[dBase + 1] = t.Y;
|
||||
outTangents[dBase + 2] = t.Z;
|
||||
outTangents[dBase + 3] = flipWinding ? -srcT[sBase + 3] : srcT[sBase + 3];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int v = 0; v < vCount; v++)
|
||||
{
|
||||
int dBase = (vOffset + v) * 4;
|
||||
outTangents[dBase] = 1f;
|
||||
outTangents[dBase + 3] = 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (outUvs is not null)
|
||||
{
|
||||
if (arr.Count > (int)Mesh.ArrayType.TexUV && arr[(int)Mesh.ArrayType.TexUV].VariantType == Variant.Type.PackedVector2Array)
|
||||
{
|
||||
Array.Copy(arr[(int)Mesh.ArrayType.TexUV].AsVector2Array(), 0, outUvs, vOffset, vCount);
|
||||
}
|
||||
}
|
||||
|
||||
if (outUv2s is not null)
|
||||
{
|
||||
if (arr.Count > (int)Mesh.ArrayType.TexUV2 && arr[(int)Mesh.ArrayType.TexUV2].VariantType == Variant.Type.PackedVector2Array)
|
||||
{
|
||||
Array.Copy(arr[(int)Mesh.ArrayType.TexUV2].AsVector2Array(), 0, outUv2s, vOffset, vCount);
|
||||
}
|
||||
}
|
||||
|
||||
if (outColors is not null)
|
||||
{
|
||||
if (arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray)
|
||||
{
|
||||
Array.Copy(arr[(int)Mesh.ArrayType.Color].AsColorArray(), 0, outColors, vOffset, vCount);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int v = 0; v < vCount; v++) outColors[vOffset + v] = Colors.White;
|
||||
}
|
||||
}
|
||||
|
||||
bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array;
|
||||
int[]? srcIdx = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null;
|
||||
if (!flipWinding)
|
||||
{
|
||||
if (srcIdx is not null)
|
||||
{
|
||||
for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = srcIdx[k] + vOffset;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int k = 0; k < idxCount; k++) outIndices[iOffset + k] = k + vOffset;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int k = 0; k + 2 < idxCount; k += 3)
|
||||
{
|
||||
int a = srcIdx is not null ? srcIdx[k] : k;
|
||||
int bIdx = srcIdx is not null ? srcIdx[k + 1] : k + 1;
|
||||
int cIdx = srcIdx is not null ? srcIdx[k + 2] : k + 2;
|
||||
outIndices[iOffset + k] = a + vOffset;
|
||||
outIndices[iOffset + k + 1] = cIdx + vOffset;
|
||||
outIndices[iOffset + k + 2] = bIdx + vOffset;
|
||||
}
|
||||
}
|
||||
|
||||
vOffset += vCount;
|
||||
iOffset += idxCount;
|
||||
}
|
||||
|
||||
var surfArrays = new Godot.Collections.Array();
|
||||
surfArrays.Resize((int)Mesh.ArrayType.Max);
|
||||
surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts;
|
||||
if (outNormals is not null) surfArrays[(int)Mesh.ArrayType.Normal] = outNormals;
|
||||
if (outTangents is not null) surfArrays[(int)Mesh.ArrayType.Tangent] = outTangents;
|
||||
if (outUvs is not null) surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs;
|
||||
if (outUv2s is not null) surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s;
|
||||
if (outColors is not null) surfArrays[(int)Mesh.ArrayType.Color] = outColors;
|
||||
surfArrays[(int)Mesh.ArrayType.Index] = outIndices;
|
||||
|
||||
int newSurf = outMesh.GetSurfaceCount();
|
||||
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays);
|
||||
if (bucket.Material is not null)
|
||||
{
|
||||
outMesh.SurfaceSetMaterial(newSurf, bucket.Material);
|
||||
}
|
||||
}
|
||||
|
||||
return outMesh.GetSurfaceCount() > 0 ? outMesh : null;
|
||||
}
|
||||
|
||||
private static ArrayMesh DecimateMeshGrid(ArrayMesh src, float cellSize)
|
||||
{
|
||||
var outMesh = new ArrayMesh();
|
||||
float invCell = 1f / MathF.Max(0.02f, cellSize);
|
||||
int surfCount = src.GetSurfaceCount();
|
||||
|
||||
for (int s = 0; s < surfCount; s++)
|
||||
{
|
||||
var arr = src.SurfaceGetArrays(s);
|
||||
if (arr.Count <= (int)Mesh.ArrayType.Vertex ||
|
||||
arr[(int)Mesh.ArrayType.Vertex].VariantType != Variant.Type.PackedVector3Array)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
||||
if (verts.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
bool hasNorm = arr.Count > (int)Mesh.ArrayType.Normal && arr[(int)Mesh.ArrayType.Normal].VariantType == Variant.Type.PackedVector3Array;
|
||||
Vector3[]? norms = hasNorm ? arr[(int)Mesh.ArrayType.Normal].AsVector3Array() : null;
|
||||
|
||||
bool hasIdx = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array;
|
||||
int[]? indices = hasIdx ? arr[(int)Mesh.ArrayType.Index].AsInt32Array() : null;
|
||||
int triVertCount = indices is not null ? indices.Length : verts.Length;
|
||||
|
||||
var cellToNewIdx = new Dictionary<(int, int, int), int>(verts.Length / 2 + 16);
|
||||
var vertToCellIdx = new int[verts.Length];
|
||||
var accumPos = new List<Vector3>(verts.Length / 2 + 16);
|
||||
var accumNorm = norms is not null ? new List<Vector3>(verts.Length / 2 + 16) : null;
|
||||
var counts = new List<int>(verts.Length / 2 + 16);
|
||||
|
||||
for (int v = 0; v < verts.Length; v++)
|
||||
{
|
||||
Vector3 p = verts[v];
|
||||
var key = (
|
||||
(int)MathF.Floor(p.X * invCell),
|
||||
(int)MathF.Floor(p.Y * invCell),
|
||||
(int)MathF.Floor(p.Z * invCell));
|
||||
|
||||
if (!cellToNewIdx.TryGetValue(key, out int ci))
|
||||
{
|
||||
ci = accumPos.Count;
|
||||
cellToNewIdx[key] = ci;
|
||||
accumPos.Add(p);
|
||||
if (accumNorm is not null) accumNorm.Add(norms![v]);
|
||||
counts.Add(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
accumPos[ci] += p;
|
||||
if (accumNorm is not null) accumNorm[ci] += norms![v];
|
||||
counts[ci]++;
|
||||
}
|
||||
vertToCellIdx[v] = ci;
|
||||
}
|
||||
|
||||
var outIndices = new List<int>(triVertCount / 2 + 12);
|
||||
for (int k = 0; k + 2 < triVertCount; k += 3)
|
||||
{
|
||||
int i0 = indices is not null ? indices[k] : k;
|
||||
int i1 = indices is not null ? indices[k + 1] : k + 1;
|
||||
int i2 = indices is not null ? indices[k + 2] : k + 2;
|
||||
int c0 = vertToCellIdx[i0];
|
||||
int c1 = vertToCellIdx[i1];
|
||||
int c2 = vertToCellIdx[i2];
|
||||
if (c0 != c1 && c1 != c2 && c0 != c2)
|
||||
{
|
||||
outIndices.Add(c0);
|
||||
outIndices.Add(c1);
|
||||
outIndices.Add(c2);
|
||||
}
|
||||
}
|
||||
|
||||
if (outIndices.Count == 0)
|
||||
{
|
||||
// Keep original tiny surface intact if grid collapsed all triangles
|
||||
int fallbackSurf = outMesh.GetSurfaceCount();
|
||||
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arr);
|
||||
Material? fMat = src.SurfaceGetMaterial(s);
|
||||
if (fMat is not null) outMesh.SurfaceSetMaterial(fallbackSurf, fMat);
|
||||
continue;
|
||||
}
|
||||
|
||||
var outVerts = new Vector3[accumPos.Count];
|
||||
Vector3[]? outNorms = accumNorm is not null ? new Vector3[accumPos.Count] : null;
|
||||
for (int i = 0; i < accumPos.Count; i++)
|
||||
{
|
||||
outVerts[i] = accumPos[i] / counts[i];
|
||||
if (outNorms is not null)
|
||||
{
|
||||
Vector3 n = accumNorm![i];
|
||||
outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up;
|
||||
}
|
||||
}
|
||||
|
||||
var newArr = new Godot.Collections.Array();
|
||||
newArr.Resize((int)Mesh.ArrayType.Max);
|
||||
newArr[(int)Mesh.ArrayType.Vertex] = outVerts;
|
||||
if (outNorms is not null) newArr[(int)Mesh.ArrayType.Normal] = outNorms;
|
||||
newArr[(int)Mesh.ArrayType.Index] = outIndices.ToArray();
|
||||
|
||||
int newSurf = outMesh.GetSurfaceCount();
|
||||
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, newArr);
|
||||
Material? mat = src.SurfaceGetMaterial(s);
|
||||
if (mat is not null)
|
||||
{
|
||||
outMesh.SurfaceSetMaterial(newSurf, mat);
|
||||
}
|
||||
}
|
||||
|
||||
return outMesh.GetSurfaceCount() > 0 ? outMesh : src;
|
||||
}
|
||||
|
||||
private static void MarkAncestorsProtected(int idx, Dictionary<int, int> parentByIndex, HashSet<int> protectedSet)
|
||||
{
|
||||
int cur = idx;
|
||||
|
|
|
|||
Loading…
Reference in a new issue