2405 lines
92 KiB
C#
2405 lines
92 KiB
C#
using System;
|
|
using System.Buffers.Binary;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text.Json;
|
|
using Godot;
|
|
using RustToDust.Core;
|
|
|
|
namespace RustToDust.Client;
|
|
|
|
/// <summary>
|
|
/// Runtime GLB asset loader & template cache for all 15 Brokkr vehicles (resolved via
|
|
/// <see cref="VehiclePackage.ModelAsset"/> + <see cref="VehicleCatalogLoader.LocateVehiclesDirectory"/>)
|
|
/// and all 6 modular gear GLBs in <c>assets/gear/</c>.
|
|
/// Parses the glTF JSON chunk to map <c>rtd.id</c>, <c>rtd.kind</c>, <c>rtd.size</c>, and <c>rtd.joint</c>
|
|
/// deterministically to exact <see cref="NodePath"/>s inside the Godot scene tree generated by
|
|
/// <see cref="GltfDocument"/> + <see cref="GltfState"/>.
|
|
/// </summary>
|
|
public sealed class VehicleAssetCache : IDisposable
|
|
{
|
|
public sealed record GlbAnchorInfo(
|
|
string Id,
|
|
string Kind,
|
|
Vector3 Size,
|
|
NodePath RelativePath,
|
|
Transform3D ModelSpaceTransform);
|
|
|
|
public sealed record GlbJointInfo(
|
|
string JointId,
|
|
string NodeName,
|
|
Vector3 Axis,
|
|
float MinVal,
|
|
float MaxVal,
|
|
NodePath RelativePath);
|
|
|
|
public sealed record GlbPartNodeInfo(
|
|
string NodeName,
|
|
int CellX,
|
|
int CellY,
|
|
string Kind,
|
|
NodePath RelativePath,
|
|
bool HasProtectedDescendant);
|
|
|
|
public sealed record RigidPartTemplate(
|
|
NodePath PivotPath,
|
|
ArrayMesh Mesh,
|
|
int CellX,
|
|
int CellY,
|
|
string Kind);
|
|
|
|
public sealed class VehicleTemplate
|
|
{
|
|
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 ArrayMesh SingleSurfaceStaticMesh { get; init; }
|
|
public required ArrayMesh SingleSurfaceLodFarMesh { get; init; }
|
|
public required Vector3[] FarRayTris { get; init; }
|
|
public required Aabb FarRayAabb { get; init; }
|
|
public required float MinY { get; init; }
|
|
public required float MaxY { get; init; }
|
|
public required IReadOnlyDictionary<string, GlbAnchorInfo> Anchors { get; init; }
|
|
public required IReadOnlyDictionary<string, GlbJointInfo> Joints { get; init; }
|
|
public required IReadOnlyDictionary<string, NodePath> NodesByOriginalName { get; init; }
|
|
public required IReadOnlyList<GlbPartNodeInfo> DetachableParts { get; init; }
|
|
public required IReadOnlyList<RigidPartTemplate> StaticRigidParts { get; init; }
|
|
public required IReadOnlyList<RigidPartTemplate> DetachableRigidParts { get; init; }
|
|
public required IReadOnlyList<NodePath> MobilityNodePaths { get; init; }
|
|
}
|
|
|
|
public sealed class GearTemplate
|
|
{
|
|
public required string Id { get; init; }
|
|
public required string GlbPath { get; init; }
|
|
public required Node3D SceneTemplate { get; init; }
|
|
public required ArrayMesh BakedDropMesh { get; init; }
|
|
public required ArrayMesh SingleSurfaceMesh { get; init; }
|
|
public required Vector3 Size { get; init; }
|
|
public required float MinY { get; init; }
|
|
public required Vector3 LocalModelForward { get; init; }
|
|
public required IReadOnlyDictionary<string, Vector3> PartCentroidsLocal { get; init; }
|
|
}
|
|
|
|
public sealed class DropPodTemplate
|
|
{
|
|
public required string GlbPath { get; init; }
|
|
public required Node3D SceneTemplate { get; init; }
|
|
public required ArrayMesh CoreMesh { get; init; }
|
|
public required ArrayMesh PetalMesh { get; init; }
|
|
public required Transform3D[] PetalLocalTransforms { get; init; }
|
|
public required Vector3 Size { get; init; }
|
|
public required float MinY { get; init; }
|
|
public required float MaxY { get; init; }
|
|
}
|
|
|
|
public sealed class WeaponPartTemplate
|
|
{
|
|
public required string Id { get; init; }
|
|
public required string Slot { get; init; }
|
|
public required string GlbPath { get; init; }
|
|
public required Node3D SceneTemplate { get; init; }
|
|
public required ArrayMesh SingleSurfaceMesh { get; init; }
|
|
public required Vector3 Size { get; init; }
|
|
public required float MinY { get; init; }
|
|
public required IReadOnlyDictionary<string, Transform3D> SocketsLocal { get; init; }
|
|
}
|
|
|
|
public static readonly string[] ExpectedGearIds =
|
|
{
|
|
"mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator"
|
|
};
|
|
|
|
public static readonly string[] ExpectedWeaponPartIds =
|
|
{
|
|
"rx_salvage_frame", "rx_korrathi_cradle", "rx_auralian_prism", "rx_vex_pod_rack",
|
|
"brl_autocannon", "brl_sabot_rail", "brl_prism_lance", "brl_missile_tube",
|
|
"fd_belt_drum", "fd_rotary_loader", "fd_capacitor_bank", "fd_swarm_magazine",
|
|
"mz_slotted_brake", "mz_mirv_warhead", "mz_loiter_aero_fin", "mz_plasma_diffuser"
|
|
};
|
|
|
|
private readonly Dictionary<string, VehicleTemplate> _vehicles = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly Dictionary<string, GearTemplate> _gear = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly Dictionary<string, WeaponPartTemplate> _weaponParts = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly Dictionary<string, ArrayMesh> _gearVariantMeshes = new(StringComparer.OrdinalIgnoreCase);
|
|
private DropPodTemplate? _dropPod;
|
|
private readonly string _vehiclesDir;
|
|
private readonly string _gearDir;
|
|
private readonly string _weaponPartsDir;
|
|
private bool _disposed;
|
|
|
|
public VehicleAssetCache()
|
|
{
|
|
_vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
|
|
string assetsDir = Directory.GetParent(_vehiclesDir)?.FullName
|
|
?? throw new DirectoryNotFoundException($"Could not locate assets parent directory of '{_vehiclesDir}'.");
|
|
_gearDir = Path.Combine(assetsDir, "gear");
|
|
if (!Directory.Exists(_gearDir))
|
|
{
|
|
throw new DirectoryNotFoundException($"Could not locate gear directory '{_gearDir}'.");
|
|
}
|
|
_weaponPartsDir = Path.Combine(_gearDir, "parts");
|
|
}
|
|
|
|
public IReadOnlyDictionary<string, VehicleTemplate> Vehicles => _vehicles;
|
|
public IReadOnlyDictionary<string, GearTemplate> Gear => _gear;
|
|
public IReadOnlyDictionary<string, WeaponPartTemplate> WeaponParts => _weaponParts;
|
|
|
|
public void PreloadAll()
|
|
{
|
|
foreach (var pkg in Catalog.PackagesById.Values)
|
|
{
|
|
GetOrLoadVehicle(pkg.Id);
|
|
}
|
|
foreach (string gearId in ExpectedGearIds)
|
|
{
|
|
GetOrLoadGear(gearId);
|
|
}
|
|
foreach (string partId in ExpectedWeaponPartIds)
|
|
{
|
|
GetOrLoadWeaponPart(partId);
|
|
}
|
|
GetOrLoadDropPod();
|
|
}
|
|
|
|
public WeaponPartTemplate GetOrLoadWeaponPart(string partId)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
if (_weaponParts.TryGetValue(partId, out var cached))
|
|
{
|
|
return cached;
|
|
}
|
|
|
|
string glbPath = Path.Combine(_weaponPartsDir, $"{partId}.glb");
|
|
if (!File.Exists(glbPath))
|
|
{
|
|
throw new FileNotFoundException($"Missing modular weapon part GLB '{partId}': {glbPath}", glbPath);
|
|
}
|
|
|
|
var template = LoadWeaponPartTemplate(partId, glbPath);
|
|
_weaponParts[partId] = template;
|
|
return template;
|
|
}
|
|
|
|
public DropPodTemplate GetOrLoadDropPod()
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
if (_dropPod is not null)
|
|
{
|
|
return _dropPod;
|
|
}
|
|
|
|
string glbPath = Path.Combine(_vehiclesDir, "drop_pod", "drop_pod.glb");
|
|
if (!File.Exists(glbPath))
|
|
{
|
|
throw new FileNotFoundException($"Missing drop pod GLB: {glbPath}", glbPath);
|
|
}
|
|
|
|
_dropPod = LoadDropPodTemplate(glbPath);
|
|
return _dropPod;
|
|
}
|
|
|
|
public VehicleTemplate GetOrLoadVehicle(string vehicleId)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
string resolvedId = ResolveModelId(vehicleId);
|
|
if (_vehicles.TryGetValue(resolvedId, out var cached))
|
|
{
|
|
return cached;
|
|
}
|
|
|
|
var pkg = Catalog.TryGetPackage(resolvedId)
|
|
?? throw new KeyNotFoundException($"Unknown vehicle '{vehicleId}' in Catalog.PackagesById.");
|
|
|
|
string glbPath = Path.Combine(_vehiclesDir, pkg.Id, pkg.ModelAsset);
|
|
if (!File.Exists(glbPath))
|
|
{
|
|
throw new FileNotFoundException($"Missing vehicle GLB for '{pkg.Id}': {glbPath}", glbPath);
|
|
}
|
|
|
|
var template = LoadVehicleTemplate(pkg, glbPath);
|
|
_vehicles[pkg.Id] = template;
|
|
return template;
|
|
}
|
|
|
|
public static string ResolveModelId(string chassisId) =>
|
|
string.Equals(chassisId, "exemplar_frame", StringComparison.OrdinalIgnoreCase)
|
|
? "raptor"
|
|
: chassisId;
|
|
|
|
public GearTemplate GetOrLoadGear(string gearId)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
if (_gear.TryGetValue(gearId, out var cached))
|
|
{
|
|
return cached;
|
|
}
|
|
|
|
string glbPath = Path.Combine(_gearDir, $"{gearId}.glb");
|
|
if (!File.Exists(glbPath))
|
|
{
|
|
throw new FileNotFoundException($"Missing gear GLB '{gearId}': {glbPath}", glbPath);
|
|
}
|
|
|
|
var template = LoadGearTemplate(gearId, glbPath);
|
|
_gear[gearId] = template;
|
|
return template;
|
|
}
|
|
|
|
public ArrayMesh GetOrBuildGearVariantMesh(
|
|
string moduleId,
|
|
string gearGlbId,
|
|
Color? paintTint,
|
|
Color? accentTint)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
if (_gearVariantMeshes.TryGetValue(moduleId, out ArrayMesh? cached))
|
|
{
|
|
return cached;
|
|
}
|
|
|
|
GearTemplate tpl = GetOrLoadGear(gearGlbId);
|
|
ArrayMesh mesh = !paintTint.HasValue && !accentTint.HasValue
|
|
? tpl.SingleSurfaceMesh
|
|
: CollapseToSingleSurfaceMechPaintMesh(tpl.BakedDropMesh, paintTint, accentTint);
|
|
_gearVariantMeshes[moduleId] = mesh;
|
|
return mesh;
|
|
}
|
|
|
|
private static VehicleTemplate LoadVehicleTemplate(VehiclePackage pkg, string glbPath)
|
|
{
|
|
byte[] jsonBytes = ReadGlbJsonChunk(glbPath);
|
|
using var gltfJson = JsonDocument.Parse(jsonBytes);
|
|
JsonElement jsonRoot = gltfJson.RootElement;
|
|
|
|
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)
|
|
{
|
|
throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for '{glbPath}': {err}");
|
|
}
|
|
|
|
Node? generated = doc.GenerateScene(state);
|
|
if (generated is not Node3D sceneRoot)
|
|
{
|
|
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");
|
|
int nodeCount = Math.Min(gltfNodes.Count, jsonNodes.GetArrayLength());
|
|
|
|
var pathByGltfIndex = new NodePath[nodeCount];
|
|
var nodeByGltfIndex = new Node3D?[nodeCount];
|
|
var origNameByIndex = new string[nodeCount];
|
|
var nodesByOriginalName = new Dictionary<string, NodePath>(StringComparer.Ordinal);
|
|
var anchors = new Dictionary<string, GlbAnchorInfo>(StringComparer.Ordinal);
|
|
var joints = new Dictionary<string, GlbJointInfo>(StringComparer.Ordinal);
|
|
var protectedIndices = new HashSet<int>();
|
|
var parentByIndex = new Dictionary<int, int>();
|
|
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
JsonElement jn = jsonNodes[i];
|
|
if (jn.TryGetProperty("children", out var childrenEl) && childrenEl.ValueKind == JsonValueKind.Array)
|
|
{
|
|
foreach (var ch in childrenEl.EnumerateArray())
|
|
{
|
|
parentByIndex[ch.GetInt32()] = i;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Resolve every glTF node deterministically to its exact Godot Node3D via GltfNode.GetSceneNodePath(state)
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
GltfNode gn = gltfNodes[i];
|
|
JsonElement jn = jsonNodes[i];
|
|
string origName = !string.IsNullOrEmpty(gn.OriginalName)
|
|
? gn.OriginalName
|
|
: (jn.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{i}" : $"node_{i}");
|
|
origNameByIndex[i] = origName;
|
|
|
|
Node? resolved = ResolveSceneNode(sceneRoot, gn.GetSceneNodePath(state), origName);
|
|
if (resolved is Node3D n3d)
|
|
{
|
|
NodePath relPath = BuildRelativeNodePath(sceneRoot, n3d);
|
|
pathByGltfIndex[i] = relPath;
|
|
nodeByGltfIndex[i] = n3d;
|
|
nodesByOriginalName.TryAdd(origName, relPath);
|
|
}
|
|
else
|
|
{
|
|
pathByGltfIndex[i] = new NodePath();
|
|
}
|
|
}
|
|
|
|
// Compute model-space transforms once from sceneRoot
|
|
var modelTransforms = new Dictionary<Node, Transform3D>();
|
|
CollectModelTransforms(sceneRoot, Transform3D.Identity, modelTransforms);
|
|
|
|
// Extract rtd.* extras from glTF JSON chunk & mark protected structural/joint/hardpoint nodes
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
JsonElement jn = jsonNodes[i];
|
|
Node3D? node = nodeByGltfIndex[i];
|
|
if (node is null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
NodePath relPath = pathByGltfIndex[i];
|
|
if (!jn.TryGetProperty("extras", out JsonElement extras) || extras.ValueKind != JsonValueKind.Object)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (extras.TryGetProperty("rtd.id", out var rtdIdEl) && rtdIdEl.ValueKind == JsonValueKind.String)
|
|
{
|
|
string hpId = rtdIdEl.GetString()!;
|
|
string hpKind = extras.TryGetProperty("rtd.kind", out var kEl) && kEl.ValueKind == JsonValueKind.String
|
|
? kEl.GetString()!
|
|
: "weapon";
|
|
Vector3 hpSize = ReadVec3(extras, "rtd.size", new Vector3(0.5f, 0.5f, 0.1f));
|
|
Transform3D modelXform = modelTransforms.TryGetValue(node, out var xf) ? xf : Transform3D.Identity;
|
|
anchors[hpId] = new GlbAnchorInfo(hpId, hpKind, hpSize, relPath, modelXform);
|
|
MarkAncestorsProtected(i, parentByIndex, protectedIndices);
|
|
}
|
|
|
|
if (extras.TryGetProperty("rtd.joint", out var rtdJointEl) && rtdJointEl.ValueKind == JsonValueKind.String)
|
|
{
|
|
string jId = rtdJointEl.GetString()!;
|
|
Vector3 axis = ReadVec3(extras, "rtd.axis", Vector3.Up);
|
|
if (axis.LengthSquared() < 1e-6f) axis = Vector3.Up;
|
|
axis = axis.Normalized();
|
|
float minVal = extras.TryGetProperty("rtd.min", out var mnEl) ? mnEl.GetSingle() : -180f;
|
|
float maxVal = extras.TryGetProperty("rtd.max", out var mxEl) ? mxEl.GetSingle() : 180f;
|
|
joints[jId] = new GlbJointInfo(jId, origNameByIndex[i], axis, minVal, maxVal, relPath);
|
|
MarkAncestorsProtected(i, parentByIndex, protectedIndices);
|
|
}
|
|
}
|
|
|
|
// Also mark structural mechanism/skeleton/mobility nodes and their ancestors protected
|
|
var mobilityPaths = new List<NodePath>();
|
|
var mechNames = new HashSet<string>(StringComparer.Ordinal);
|
|
if (pkg.Mechanisms is not null)
|
|
{
|
|
foreach (var d in pkg.Mechanisms.Dofs) mechNames.Add(d.Name);
|
|
foreach (var r in pkg.Mechanisms.Rams)
|
|
{
|
|
mechNames.Add(r.Name);
|
|
mechNames.Add(r.BarrelBone);
|
|
mechNames.Add(r.RodBone);
|
|
}
|
|
foreach (var sc in pkg.Mechanisms.Scissors)
|
|
{
|
|
mechNames.Add(sc.Name);
|
|
mechNames.Add(sc.UpperBone);
|
|
mechNames.Add(sc.LowerBone);
|
|
}
|
|
}
|
|
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
string nm = origNameByIndex[i];
|
|
if (mechNames.Contains(nm) || IsStructuralNodeName(nm))
|
|
{
|
|
MarkAncestorsProtected(i, parentByIndex, protectedIndices);
|
|
}
|
|
}
|
|
|
|
foreach (var pc in pkg.PartCells)
|
|
{
|
|
if (string.Equals(pc.Kind, "mobility", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
if (nodesByOriginalName.TryGetValue(pc.NodeName, out var mobPath))
|
|
{
|
|
mobilityPaths.Add(mobPath);
|
|
}
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
if (string.Equals(origNameByIndex[i], pc.NodeName, StringComparison.Ordinal))
|
|
{
|
|
MarkAncestorsProtected(i, parentByIndex, protectedIndices);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Compute protected-descendant flag for each glTF node index
|
|
var hasProtectedDesc = new bool[nodeCount];
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
if (protectedIndices.Contains(i))
|
|
{
|
|
int cur = i;
|
|
while (parentByIndex.TryGetValue(cur, out int p))
|
|
{
|
|
hasProtectedDesc[p] = true;
|
|
cur = p;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Index detachable exterior armor/shroud (and safe leaf cladding) parts mapped to cells
|
|
var indexByName = new Dictionary<string, int>(StringComparer.Ordinal);
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
indexByName.TryAdd(origNameByIndex[i], i);
|
|
}
|
|
|
|
var detachableParts = new List<GlbPartNodeInfo>();
|
|
foreach (var pc in pkg.PartCells)
|
|
{
|
|
if (!indexByName.TryGetValue(pc.NodeName, out int idx))
|
|
{
|
|
continue;
|
|
}
|
|
Node3D? node = nodeByGltfIndex[idx];
|
|
if (node is not MeshInstance3D)
|
|
{
|
|
continue;
|
|
}
|
|
if (protectedIndices.Contains(idx) || hasProtectedDesc[idx])
|
|
{
|
|
continue;
|
|
}
|
|
if (!IsDetachablePartKind(pc.Kind, pc.NodeName, node.GetChildCount()))
|
|
{
|
|
continue;
|
|
}
|
|
detachableParts.Add(new GlbPartNodeInfo(
|
|
pc.NodeName,
|
|
pc.CellX,
|
|
pc.CellY,
|
|
pc.Kind,
|
|
pathByGltfIndex[idx],
|
|
hasProtectedDesc[idx]));
|
|
}
|
|
|
|
// Verify all VehiclePackage hardpoint AnchorIds & Joints resolved
|
|
foreach (var hp in pkg.Hardpoints)
|
|
{
|
|
if (!anchors.ContainsKey(hp.AnchorId))
|
|
{
|
|
sceneRoot.QueueFree();
|
|
throw new InvalidOperationException($"{pkg.Id}: failed to resolve hardpoint AnchorId '{hp.AnchorId}' in '{glbPath}'.");
|
|
}
|
|
}
|
|
foreach (var j in pkg.Joints)
|
|
{
|
|
if (!joints.ContainsKey(j.Id))
|
|
{
|
|
sceneRoot.QueueFree();
|
|
throw new InvalidOperationException($"{pkg.Id}: failed to resolve joint '{j.Id}' in '{glbPath}'.");
|
|
}
|
|
}
|
|
|
|
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, targetMinY: minY);
|
|
|
|
ArrayMesh singleSurfaceStatic = CollapseToSingleSurfaceMechPaintMesh(bakedStaticMesh);
|
|
ArrayMesh singleSurfaceLodFar = CollapseToSingleSurfaceMechPaintMesh(bakedLodFarMesh);
|
|
Vector3[] farRayTris = ExtractFlatTriangles(singleSurfaceLodFar);
|
|
Aabb farRayAabb = singleSurfaceLodFar.GetAabb().Grow(0.20f);
|
|
|
|
// D: Extract single-surface MechPaint rigid parts (static limbs + detachable armor chunks)
|
|
// and strip all MeshInstance3D nodes from SceneTemplate so live rigs have zero MeshInstance3D children!
|
|
ExtractRigidPartsAndStripMeshes(
|
|
sceneRoot,
|
|
protectedNodes,
|
|
mergedDetachableInfos,
|
|
out var staticRigidParts,
|
|
out var detachableRigidParts);
|
|
|
|
return new VehicleTemplate
|
|
{
|
|
Package = pkg,
|
|
GlbPath = glbPath,
|
|
SceneTemplate = sceneRoot,
|
|
BakedStaticMesh = bakedStaticMesh,
|
|
BakedLodFarMesh = bakedLodFarMesh,
|
|
SingleSurfaceStaticMesh = singleSurfaceStatic,
|
|
SingleSurfaceLodFarMesh = singleSurfaceLodFar,
|
|
FarRayTris = farRayTris,
|
|
FarRayAabb = farRayAabb,
|
|
MinY = minY,
|
|
MaxY = maxY,
|
|
Anchors = anchors,
|
|
Joints = joints,
|
|
NodesByOriginalName = survivingNames,
|
|
DetachableParts = mergedDetachableInfos,
|
|
StaticRigidParts = staticRigidParts,
|
|
DetachableRigidParts = detachableRigidParts,
|
|
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();
|
|
var state = new GltfState();
|
|
Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty);
|
|
if (err != Error.Ok)
|
|
{
|
|
throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for gear '{glbPath}': {err}");
|
|
}
|
|
|
|
Node? generated = doc.GenerateScene(state);
|
|
if (generated is not Node3D sceneRoot)
|
|
{
|
|
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);
|
|
var partCentroids = CollectGearPartCentroids(sceneRoot);
|
|
MergeGearSubMeshes(sceneRoot, gearId);
|
|
ArrayMesh bakedDropMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false);
|
|
ArrayMesh singleSurfaceMesh = CollapseToSingleSurfaceMechPaintMesh(bakedDropMesh);
|
|
Vector3 localFwd = new Vector3(0f, 0f, 1f);
|
|
|
|
return new GearTemplate
|
|
{
|
|
Id = gearId,
|
|
GlbPath = glbPath,
|
|
SceneTemplate = sceneRoot,
|
|
BakedDropMesh = bakedDropMesh,
|
|
SingleSurfaceMesh = singleSurfaceMesh,
|
|
Size = bMax - bMin,
|
|
MinY = bMin.Y,
|
|
LocalModelForward = localFwd,
|
|
PartCentroidsLocal = partCentroids
|
|
};
|
|
}
|
|
|
|
private static WeaponPartTemplate LoadWeaponPartTemplate(string partId, string glbPath)
|
|
{
|
|
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)
|
|
{
|
|
throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for weapon part '{glbPath}': {err}");
|
|
}
|
|
|
|
Node? generated = doc.GenerateScene(state);
|
|
if (generated is not Node3D sceneRoot)
|
|
{
|
|
generated?.QueueFree();
|
|
throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for weapon part '{glbPath}'.");
|
|
}
|
|
ClearOwnerRecursive(sceneRoot);
|
|
|
|
var modelTransforms = new Dictionary<Node, Transform3D>();
|
|
CollectModelTransforms(sceneRoot, Transform3D.Identity, modelTransforms);
|
|
|
|
string partSlot = "unknown";
|
|
var sockets = new Dictionary<string, Transform3D>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
byte[] jsonBytes = ReadGlbJsonChunk(glbPath);
|
|
using (var jsonDoc = JsonDocument.Parse(jsonBytes))
|
|
{
|
|
if (jsonDoc.RootElement.TryGetProperty("nodes", out JsonElement jsonNodes) &&
|
|
jsonNodes.ValueKind == JsonValueKind.Array)
|
|
{
|
|
var gltfNodes = state.Nodes;
|
|
int nodeCount = Math.Min(gltfNodes.Count, jsonNodes.GetArrayLength());
|
|
for (int i = 0; i < nodeCount; i++)
|
|
{
|
|
JsonElement jn = jsonNodes[i];
|
|
if (!jn.TryGetProperty("extras", out JsonElement extras) || extras.ValueKind != JsonValueKind.Object)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
GltfNode gn = gltfNodes[i];
|
|
string origName = !string.IsNullOrEmpty(gn.OriginalName)
|
|
? gn.OriginalName
|
|
: (jn.TryGetProperty("name", out var nm) ? nm.GetString() ?? $"node_{i}" : $"node_{i}");
|
|
Node? resolved = ResolveSceneNode(sceneRoot, gn.GetSceneNodePath(state), origName);
|
|
if (resolved is not Node3D n3d)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (extras.TryGetProperty("rtd.part_slot", out var slotEl) && slotEl.ValueKind == JsonValueKind.String)
|
|
{
|
|
partSlot = slotEl.GetString() ?? partSlot;
|
|
}
|
|
if (extras.TryGetProperty("rtd.socket", out var sockEl) && sockEl.ValueKind == JsonValueKind.String)
|
|
{
|
|
string? sockName = sockEl.GetString();
|
|
if (!string.IsNullOrWhiteSpace(sockName) && modelTransforms.TryGetValue(n3d, out Transform3D sockXf))
|
|
{
|
|
sockets[sockName] = sockXf;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
|
|
ArrayMesh bakedMesh = BuildBakedStaticMesh(sceneRoot, coarseMaterials: false);
|
|
ArrayMesh singleSurfaceMesh = CollapseToSingleSurfaceMechPaintMesh(bakedMesh);
|
|
|
|
return new WeaponPartTemplate
|
|
{
|
|
Id = partId,
|
|
Slot = partSlot,
|
|
GlbPath = glbPath,
|
|
SceneTemplate = sceneRoot,
|
|
SingleSurfaceMesh = singleSurfaceMesh,
|
|
Size = bMax - bMin,
|
|
MinY = bMin.Y,
|
|
SocketsLocal = sockets
|
|
};
|
|
}
|
|
|
|
private static DropPodTemplate LoadDropPodTemplate(string glbPath)
|
|
{
|
|
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)
|
|
{
|
|
throw new InvalidOperationException($"GltfDocument.AppendFromFile failed for drop_pod '{glbPath}': {err}");
|
|
}
|
|
|
|
Node? generated = doc.GenerateScene(state);
|
|
if (generated is not Node3D sceneRoot)
|
|
{
|
|
generated?.QueueFree();
|
|
throw new InvalidOperationException($"GltfDocument.GenerateScene did not return a Node3D for drop_pod '{glbPath}'.");
|
|
}
|
|
ClearOwnerRecursive(sceneRoot);
|
|
|
|
ComputeSceneMeshBounds(sceneRoot, out Vector3 bMin, out Vector3 bMax);
|
|
float yGroundShift = MathF.Abs(bMin.Y) > 1e-4f ? -bMin.Y : 0f;
|
|
Transform3D groundShift = new Transform3D(Basis.Identity, new Vector3(0f, yGroundShift, 0f));
|
|
|
|
var allMeshes = new List<MeshInstance3D>();
|
|
CollectAllMeshInstances(sceneRoot, allMeshes);
|
|
|
|
var coreSources = new List<(Mesh Mesh, Transform3D RelXf)>(allMeshes.Count);
|
|
var petalMeshes = new MeshInstance3D?[4];
|
|
var petalTransforms = new Transform3D[4];
|
|
|
|
for (int i = 0; i < allMeshes.Count; i++)
|
|
{
|
|
MeshInstance3D mi = allMeshes[i];
|
|
if (!CanMergeMeshInstance(mi) || mi.Mesh is null)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
string nodeName = mi.Name.ToString();
|
|
int petalIdx = -1;
|
|
if (nodeName.StartsWith("Petal_", StringComparison.OrdinalIgnoreCase) &&
|
|
int.TryParse(nodeName.AsSpan(6), out int parsedIdx) &&
|
|
parsedIdx is >= 0 and < 4)
|
|
{
|
|
petalIdx = parsedIdx;
|
|
}
|
|
|
|
if (petalIdx >= 0)
|
|
{
|
|
petalMeshes[petalIdx] = mi;
|
|
petalTransforms[petalIdx] = groundShift * ComputeRelativeTransform(sceneRoot, mi);
|
|
}
|
|
else
|
|
{
|
|
coreSources.Add((mi.Mesh, groundShift * ComputeRelativeTransform(sceneRoot, mi)));
|
|
}
|
|
}
|
|
|
|
for (int p = 0; p < 4; p++)
|
|
{
|
|
if (petalMeshes[p]?.Mesh is null)
|
|
{
|
|
sceneRoot.QueueFree();
|
|
throw new InvalidOperationException($"drop_pod GLB '{glbPath}' missing Petal_{p} mesh.");
|
|
}
|
|
}
|
|
|
|
ArrayMesh coreMesh = CollapseToSingleSurfaceMechPaintMesh(coreSources)
|
|
?? throw new InvalidOperationException($"drop_pod GLB '{glbPath}' produced empty CoreMesh.");
|
|
|
|
var petalSources = new List<(Mesh Mesh, Transform3D RelXf)>(1)
|
|
{
|
|
(petalMeshes[0]!.Mesh!, Transform3D.Identity)
|
|
};
|
|
ArrayMesh petalMesh = CollapseToSingleSurfaceMechPaintMesh(petalSources)
|
|
?? throw new InvalidOperationException($"drop_pod GLB '{glbPath}' produced empty PetalMesh.");
|
|
|
|
return new DropPodTemplate
|
|
{
|
|
GlbPath = glbPath,
|
|
SceneTemplate = sceneRoot,
|
|
CoreMesh = coreMesh,
|
|
PetalMesh = petalMesh,
|
|
PetalLocalTransforms = petalTransforms,
|
|
Size = bMax - bMin,
|
|
MinY = 0f,
|
|
MaxY = bMax.Y - bMin.Y
|
|
};
|
|
}
|
|
|
|
private static readonly HashSet<string> ExactStructuralNodeNames = new(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
"chassis", "hull", "pelvis", "core", "trunk", "waist", "waistlug", "torso.pose", "aim.turret", "hull.pose",
|
|
"legl.hipslew", "legr.hipslew", "legl.hip", "legr.hip", "legl.hipyaw", "legr.hipyaw",
|
|
"legl.cross", "legr.cross",
|
|
"legl.shin", "legr.shin", "legl.foot", "legr.foot", "footl", "footr",
|
|
"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.coxa", "legfr.coxa", "legbl.coxa", "legbr.coxa",
|
|
"legfl.s1", "legfr.s1", "legbl.s1", "legbr.s1",
|
|
"legfl.s2", "legfr.s2", "legbl.s2", "legbr.s2",
|
|
"footfl", "footfr", "footbl", "footbr",
|
|
"bone.hip_splay.fl", "bone.hip_splay.fr", "bone.hip_splay.rl", "bone.hip_splay.rr",
|
|
"thigh.fl", "thigh.fr", "thigh.rl", "thigh.rr",
|
|
"shin.fl", "shin.fr", "shin.rl", "shin.rr",
|
|
"ankle.fl", "ankle.fr", "ankle.rl", "ankle.rr",
|
|
"foot.fl", "foot.fr", "foot.rl", "foot.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++)
|
|
{
|
|
ClearOwnerRecursive(cur.GetChild(i));
|
|
}
|
|
}
|
|
|
|
private static bool IsDetachablePartKind(string kind, string nodeName, int childCount)
|
|
{
|
|
if (string.Equals(kind, "armor", StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(kind, "shroud", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return true;
|
|
}
|
|
if (!string.Equals(kind, "hull", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
string low = nodeName.ToLowerInvariant();
|
|
// Safe exterior cladding panels (e.g., buggy hood/side panels, skirt/tasset/cod plates, mech dress panels)
|
|
if (low.Contains("hood") || low.Contains("side.") || low.Contains("roof") ||
|
|
low.Contains("tasset") || low.Contains("cod") || low.Contains("cuisse") ||
|
|
low.Contains(".panels") || low.Contains(".dress.") || low.Contains("brow") ||
|
|
low.Contains("pauldron") || low.Contains("wing") && !low.Contains("stub_wing"))
|
|
{
|
|
return true;
|
|
}
|
|
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, and collapse PaintTag==0 surfaces on protected structural meshes
|
|
var mergedProtectedMeshes = new HashSet<MeshInstance3D>();
|
|
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;
|
|
mergedProtectedMeshes.Add(parentMi);
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (int i = 0; i < allMeshes.Count; i++)
|
|
{
|
|
MeshInstance3D mi = allMeshes[i];
|
|
if (GodotObject.IsInstanceValid(mi) &&
|
|
protectedNodes.Contains(mi) &&
|
|
!mergedProtectedMeshes.Contains(mi) &&
|
|
CanMergeMeshInstance(mi) &&
|
|
mi.Mesh is not null &&
|
|
mi.Mesh.GetSurfaceCount() > 1)
|
|
{
|
|
var single = new List<(MeshInstance3D, Transform3D)>(1) { (mi, Transform3D.Identity) };
|
|
ArrayMesh? collapsed = BuildMergedArrayMesh(single);
|
|
if (collapsed is not null && collapsed.GetSurfaceCount() < mi.Mesh.GetSurfaceCount())
|
|
{
|
|
mi.MaterialOverride = null;
|
|
mi.Mesh = collapsed;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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 Dictionary<string, Vector3> CollectGearPartCentroids(Node3D sceneRoot)
|
|
{
|
|
var result = new Dictionary<string, Vector3>(StringComparer.OrdinalIgnoreCase);
|
|
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) || mi.Mesh is null)
|
|
{
|
|
continue;
|
|
}
|
|
Transform3D toRoot = ComputeRelativeTransform(sceneRoot, mi);
|
|
Vector3 sum = Vector3.Zero;
|
|
int count = 0;
|
|
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 &&
|
|
arr[(int)Mesh.ArrayType.Vertex].VariantType == Variant.Type.PackedVector3Array)
|
|
{
|
|
Vector3[] verts = arr[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
|
for (int v = 0; v < verts.Length; v++)
|
|
{
|
|
sum += toRoot * verts[v];
|
|
count++;
|
|
}
|
|
}
|
|
}
|
|
if (count > 0)
|
|
{
|
|
result[mi.Name] = sum / count;
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
private static void ExtractRigidPartsAndStripMeshes(
|
|
Node3D sceneRoot,
|
|
HashSet<Node> protectedNodes,
|
|
List<GlbPartNodeInfo> detachableInfos,
|
|
out List<RigidPartTemplate> staticPartsOut,
|
|
out List<RigidPartTemplate> detachablePartsOut)
|
|
{
|
|
staticPartsOut = new List<RigidPartTemplate>();
|
|
detachablePartsOut = new List<RigidPartTemplate>();
|
|
|
|
var detachableSet = new Dictionary<MeshInstance3D, GlbPartNodeInfo>();
|
|
for (int i = 0; i < detachableInfos.Count; i++)
|
|
{
|
|
var dp = detachableInfos[i];
|
|
if (sceneRoot.GetNodeOrNull(dp.RelativePath) is MeshInstance3D dmi)
|
|
{
|
|
detachableSet[dmi] = dp;
|
|
}
|
|
}
|
|
|
|
// 1. Extract detachable per-cell armor chunks in their rigidParent's local space
|
|
foreach (var (mi, dp) in detachableSet)
|
|
{
|
|
if (!CanMergeMeshInstance(mi) || mi.Mesh is null)
|
|
{
|
|
continue;
|
|
}
|
|
Node3D rigidParent = protectedNodes.Contains(mi)
|
|
? mi
|
|
: FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
|
|
Transform3D relXf = ReferenceEquals(mi, rigidParent)
|
|
? Transform3D.Identity
|
|
: ComputeRelativeTransform(rigidParent, mi);
|
|
var single = new List<(Mesh Mesh, Transform3D RelXf)>(1) { (mi.Mesh, relXf) };
|
|
ArrayMesh? collapsed = CollapseToSingleSurfaceMechPaintMesh(single);
|
|
if (collapsed is not null)
|
|
{
|
|
detachablePartsOut.Add(new RigidPartTemplate(
|
|
BuildRelativeNodePath(sceneRoot, rigidParent),
|
|
collapsed,
|
|
dp.CellX,
|
|
dp.CellY,
|
|
dp.Kind));
|
|
}
|
|
}
|
|
|
|
// 2. Group remaining non-detachable rigid meshes by rigidParent and collapse each to 1 surface
|
|
var allMeshes = new List<MeshInstance3D>();
|
|
CollectAllMeshInstances(sceneRoot, allMeshes);
|
|
var staticByPivot = new Dictionary<Node3D, List<(Mesh Mesh, Transform3D RelXf)>>();
|
|
for (int i = 0; i < allMeshes.Count; i++)
|
|
{
|
|
MeshInstance3D mi = allMeshes[i];
|
|
if (detachableSet.ContainsKey(mi) || !CanMergeMeshInstance(mi) || mi.Mesh is null)
|
|
{
|
|
continue;
|
|
}
|
|
Node3D rigidParent = protectedNodes.Contains(mi)
|
|
? mi
|
|
: FindNearestProtectedParent(mi, sceneRoot, protectedNodes);
|
|
Transform3D relXf = ReferenceEquals(mi, rigidParent)
|
|
? Transform3D.Identity
|
|
: ComputeRelativeTransform(rigidParent, mi);
|
|
if (!staticByPivot.TryGetValue(rigidParent, out var list))
|
|
{
|
|
list = new List<(Mesh, Transform3D)>();
|
|
staticByPivot[rigidParent] = list;
|
|
}
|
|
list.Add((mi.Mesh, relXf));
|
|
}
|
|
|
|
foreach (var (rigidParent, items) in staticByPivot)
|
|
{
|
|
ArrayMesh? collapsed = CollapseToSingleSurfaceMechPaintMesh(items);
|
|
if (collapsed is not null)
|
|
{
|
|
staticPartsOut.Add(new RigidPartTemplate(
|
|
BuildRelativeNodePath(sceneRoot, rigidParent),
|
|
collapsed,
|
|
-1,
|
|
-1,
|
|
"static"));
|
|
}
|
|
}
|
|
|
|
// 3. Strip all MeshInstance3D nodes from sceneRoot:
|
|
// - Protected MeshInstance3Ds become plain Node3D pivots preserving Name, Transform, and children.
|
|
// - Non-protected MeshInstance3Ds are removed cleanly.
|
|
for (int i = 0; i < allMeshes.Count; i++)
|
|
{
|
|
MeshInstance3D mi = allMeshes[i];
|
|
if (!GodotObject.IsInstanceValid(mi) || ReferenceEquals(mi, sceneRoot))
|
|
{
|
|
continue;
|
|
}
|
|
if (protectedNodes.Contains(mi))
|
|
{
|
|
ReplaceMeshInstanceWithPivot(mi);
|
|
}
|
|
else
|
|
{
|
|
ReparentChildrenAndRemove(mi);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void ReplaceMeshInstanceWithPivot(MeshInstance3D mi)
|
|
{
|
|
Node? parent = mi.GetParent();
|
|
if (parent is null)
|
|
{
|
|
return;
|
|
}
|
|
int idx = mi.GetIndex();
|
|
var pivot = new Node3D
|
|
{
|
|
Name = mi.Name,
|
|
Transform = mi.Transform
|
|
};
|
|
parent.RemoveChild(mi);
|
|
parent.AddChild(pivot);
|
|
parent.MoveChild(pivot, idx);
|
|
while (mi.GetChildCount() > 0)
|
|
{
|
|
Node ch = mi.GetChild(0);
|
|
mi.RemoveChild(ch);
|
|
pivot.AddChild(ch);
|
|
}
|
|
mi.QueueFree();
|
|
}
|
|
|
|
private static Vector3[] ExtractFlatTriangles(ArrayMesh mesh)
|
|
{
|
|
var tris = new List<Vector3>();
|
|
int surfCount = mesh.GetSurfaceCount();
|
|
for (int s = 0; s < surfCount; s++)
|
|
{
|
|
var arr = mesh.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();
|
|
int[]? indices = arr.Count > (int)Mesh.ArrayType.Index && arr[(int)Mesh.ArrayType.Index].VariantType == Variant.Type.PackedInt32Array
|
|
? arr[(int)Mesh.ArrayType.Index].AsInt32Array()
|
|
: null;
|
|
int triCount = (indices is not null ? indices.Length : verts.Length) / 3;
|
|
for (int t = 0; t < triCount; t++)
|
|
{
|
|
int i0 = indices is not null ? indices[t * 3] : t * 3;
|
|
int i1 = indices is not null ? indices[t * 3 + 1] : t * 3 + 1;
|
|
int i2 = indices is not null ? indices[t * 3 + 2] : t * 3 + 2;
|
|
tris.Add(verts[i0]);
|
|
tris.Add(verts[i1]);
|
|
tris.Add(verts[i2]);
|
|
}
|
|
}
|
|
return tris.ToArray();
|
|
}
|
|
|
|
public static ArrayMesh CollapseToSingleSurfaceMechPaintMesh(
|
|
ArrayMesh src,
|
|
Color? gearPaintTint = null,
|
|
Color? gearAccentTint = null)
|
|
{
|
|
var list = new List<(Mesh Mesh, Transform3D RelXf)>(1) { (src, Transform3D.Identity) };
|
|
return CollapseToSingleSurfaceMechPaintMesh(list, gearPaintTint, gearAccentTint) ?? new ArrayMesh();
|
|
}
|
|
|
|
private static ArrayMesh? CollapseToSingleSurfaceMechPaintMesh(
|
|
List<(Mesh Mesh, Transform3D RelXf)> sources,
|
|
Color? gearPaintTint = null,
|
|
Color? gearAccentTint = null)
|
|
{
|
|
int totalVerts = 0;
|
|
int totalIndices = 0;
|
|
var chunks = new List<(Godot.Collections.Array Arrays, Transform3D RelXf, Vector3 LinearCol, int Band, float Rough, int VertCount, int IdxCount)>();
|
|
|
|
for (int i = 0; i < sources.Count; i++)
|
|
{
|
|
var (mesh, relXf) = sources[i];
|
|
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;
|
|
}
|
|
var arr = mesh.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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
if (idxCount < 3)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
ClassifyMaterialForMechPaint(mesh.SurfaceGetMaterial(s), gearPaintTint, gearAccentTint, out Vector3 linCol, out int band, out float rough);
|
|
chunks.Add((arr, relXf, linCol, band, rough, verts.Length, idxCount));
|
|
totalVerts += verts.Length;
|
|
totalIndices += idxCount;
|
|
}
|
|
}
|
|
|
|
if (totalVerts == 0 || totalIndices == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var outVerts = new Vector3[totalVerts];
|
|
var outNorms = new Vector3[totalVerts];
|
|
var outColors = new Color[totalVerts];
|
|
var outUvs = new Vector2[totalVerts];
|
|
var outUv2s = new Vector2[totalVerts];
|
|
var outIndices = new int[totalIndices];
|
|
|
|
int vOff = 0;
|
|
int iOff = 0;
|
|
for (int c = 0; c < chunks.Count; c++)
|
|
{
|
|
var (arr, relXf, linCol, band, rough, vCount, idxCount) = chunks[c];
|
|
Vector3[] srcV = 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[vOff + v] = relXf * srcV[v];
|
|
}
|
|
|
|
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];
|
|
outNorms[vOff + v] = n.LengthSquared() > 1e-10f ? n.Normalized() : Vector3.Up;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
for (int v = 0; v < vCount; v++) outNorms[vOff + v] = Vector3.Up;
|
|
}
|
|
|
|
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, vOff, vCount);
|
|
}
|
|
else
|
|
{
|
|
// Gear or unbaked submesh: neutral cavity AO, crisp edge highlight, steady rest height above mud line
|
|
var defaultCol = new Color(0.86f, 0.36f, 0.50f, 0.65f);
|
|
for (int v = 0; v < vCount; v++) outColors[vOff + v] = defaultCol;
|
|
}
|
|
|
|
var uv0 = new Vector2(linCol.X, linCol.Y);
|
|
var uv1 = new Vector2(linCol.Z, band * 2.0f + rough);
|
|
for (int v = 0; v < vCount; v++)
|
|
{
|
|
outUvs[vOff + v] = uv0;
|
|
outUv2s[vOff + v] = uv1;
|
|
}
|
|
|
|
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[iOff + k] = srcIdx[k] + vOff;
|
|
}
|
|
else
|
|
{
|
|
for (int k = 0; k < idxCount; k++) outIndices[iOff + k] = k + vOff;
|
|
}
|
|
}
|
|
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[iOff + k] = a + vOff;
|
|
outIndices[iOff + k + 1] = cIdx + vOff;
|
|
outIndices[iOff + k + 2] = bIdx + vOff;
|
|
}
|
|
}
|
|
|
|
vOff += vCount;
|
|
iOff += idxCount;
|
|
}
|
|
|
|
var surfArrays = new Godot.Collections.Array();
|
|
surfArrays.Resize((int)Mesh.ArrayType.Max);
|
|
surfArrays[(int)Mesh.ArrayType.Vertex] = outVerts;
|
|
surfArrays[(int)Mesh.ArrayType.Normal] = outNorms;
|
|
surfArrays[(int)Mesh.ArrayType.Color] = outColors;
|
|
surfArrays[(int)Mesh.ArrayType.TexUV] = outUvs;
|
|
surfArrays[(int)Mesh.ArrayType.TexUV2] = outUv2s;
|
|
surfArrays[(int)Mesh.ArrayType.Index] = outIndices;
|
|
|
|
var outMesh = new ArrayMesh();
|
|
outMesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surfArrays);
|
|
return outMesh;
|
|
}
|
|
|
|
private static void ClassifyMaterialForMechPaint(
|
|
Material? mat,
|
|
Color? gearPaintTint,
|
|
Color? gearAccentTint,
|
|
out Vector3 linearColor,
|
|
out int band,
|
|
out float roughness)
|
|
{
|
|
if (mat is not StandardMaterial3D sm)
|
|
{
|
|
linearColor = new Vector3(0.08f, 0.09f, 0.06f);
|
|
band = 3;
|
|
roughness = 0.58f;
|
|
return;
|
|
}
|
|
|
|
string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant();
|
|
roughness = Math.Clamp(sm.Roughness, 0.08f, 0.90f);
|
|
|
|
if (mName.Contains("mfg_primary"))
|
|
{
|
|
Color b = sm.AlbedoColor.SrgbToLinear();
|
|
linearColor = new Vector3(b.R, b.G, b.B);
|
|
band = 3;
|
|
roughness = 0.50f;
|
|
return;
|
|
}
|
|
|
|
if (mName.Contains("mfg_accent"))
|
|
{
|
|
Color b = sm.AlbedoColor.SrgbToLinear();
|
|
linearColor = new Vector3(b.R, b.G, b.B);
|
|
band = 4;
|
|
roughness = 0.38f;
|
|
return;
|
|
}
|
|
|
|
if (mName.Contains("mfg_glow"))
|
|
{
|
|
Color eCol = (sm.EmissionEnabled ? sm.Emission : sm.AlbedoColor).SrgbToLinear();
|
|
linearColor = new Vector3(eCol.R, eCol.G, eCol.B);
|
|
band = 5;
|
|
roughness = 0.22f;
|
|
return;
|
|
}
|
|
|
|
if (mName.Contains("lamp") || mName.Contains("glow") || mName.Contains("cyan") ||
|
|
mName.Contains("amber") || mName.Contains("optic_red"))
|
|
{
|
|
Color eCol = (sm.EmissionEnabled ? sm.Emission : sm.AlbedoColor).SrgbToLinear();
|
|
linearColor = new Vector3(eCol.R, eCol.G, eCol.B);
|
|
band = 5;
|
|
roughness = 0.22f;
|
|
return;
|
|
}
|
|
|
|
if (mName.Contains("olive") || mName.Contains("khaki") || mName.Contains("armour") || mName.Contains("armor"))
|
|
{
|
|
if (gearPaintTint.HasValue)
|
|
{
|
|
Color c = gearPaintTint.Value.SrgbToLinear();
|
|
linearColor = new Vector3(c.R, c.G, c.B);
|
|
band = 6;
|
|
roughness = 0.56f;
|
|
return;
|
|
}
|
|
Color b = sm.AlbedoColor.SrgbToLinear();
|
|
linearColor = new Vector3(b.R, b.G, b.B);
|
|
band = 3;
|
|
roughness = 0.58f;
|
|
return;
|
|
}
|
|
|
|
if (mName.Contains("ivory") && gearPaintTint.HasValue)
|
|
{
|
|
Color c = gearPaintTint.Value.SrgbToLinear();
|
|
linearColor = new Vector3(c.R, c.G, c.B);
|
|
band = 6;
|
|
roughness = 0.42f;
|
|
return;
|
|
}
|
|
|
|
if (mName.Contains("signal") || mName.Contains("orange") || mName.Contains("hazard"))
|
|
{
|
|
if (gearAccentTint.HasValue)
|
|
{
|
|
Color c = gearAccentTint.Value.SrgbToLinear();
|
|
linearColor = new Vector3(c.R, c.G, c.B);
|
|
band = 7;
|
|
roughness = 0.42f;
|
|
return;
|
|
}
|
|
Color b = sm.AlbedoColor.SrgbToLinear();
|
|
linearColor = new Vector3(b.R, b.G, b.B);
|
|
band = 4;
|
|
roughness = 0.44f;
|
|
return;
|
|
}
|
|
|
|
if (gearAccentTint.HasValue && (mName.Contains("copper") || mName.Contains("gold")))
|
|
{
|
|
Color c = gearAccentTint.Value.SrgbToLinear();
|
|
linearColor = new Vector3(c.R, c.G, c.B);
|
|
band = 7;
|
|
roughness = 0.36f;
|
|
return;
|
|
}
|
|
|
|
Color lin = sm.AlbedoColor.SrgbToLinear();
|
|
linearColor = new Vector3(lin.R, lin.G, lin.B);
|
|
band = sm.Metallic >= 0.70f ? 2 : (sm.Metallic >= 0.35f ? 1 : 0);
|
|
}
|
|
|
|
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 ? 2f : 32f;
|
|
float pbrScale = coarse ? 0f : 4f;
|
|
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)
|
|
{
|
|
Color[] srcC = arr[(int)Mesh.ArrayType.Color].AsColorArray();
|
|
Array.Copy(srcC, 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, float targetMinY)
|
|
{
|
|
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 hasColor = arr.Count > (int)Mesh.ArrayType.Color && arr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray;
|
|
Color[]? colors = hasColor ? arr[(int)Mesh.ArrayType.Color].AsColorArray() : 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 accumColor = colors is not null ? new List<Color>(verts.Length / 2 + 16) : null;
|
|
var counts = new List<int>(verts.Length / 2 + 16);
|
|
var cellMinY = new List<float>(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]);
|
|
if (accumColor is not null) accumColor.Add(colors![v]);
|
|
counts.Add(1);
|
|
cellMinY.Add(p.Y);
|
|
}
|
|
else
|
|
{
|
|
accumPos[ci] += p;
|
|
if (accumNorm is not null) accumNorm[ci] += norms![v];
|
|
if (accumColor is not null) accumColor[ci] += colors![v];
|
|
counts[ci]++;
|
|
if (p.Y < cellMinY[ci]) cellMinY[ci] = p.Y;
|
|
}
|
|
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;
|
|
Color[]? outColors = accumColor is not null ? new Color[accumPos.Count] : null;
|
|
for (int i = 0; i < accumPos.Count; i++)
|
|
{
|
|
Vector3 avg = accumPos[i] / counts[i];
|
|
// Preserve exact ground-contacting vertex minY so far LOD ChassisDrops never float or sink
|
|
float y = cellMinY[i] <= targetMinY + 0.08f ? cellMinY[i] : avg.Y;
|
|
if (y < targetMinY) y = targetMinY;
|
|
outVerts[i] = new Vector3(avg.X, y, avg.Z);
|
|
if (outNorms is not null)
|
|
{
|
|
Vector3 n = accumNorm![i];
|
|
outNorms[i] = n.LengthSquared() > 1e-8f ? n.Normalized() : Vector3.Up;
|
|
}
|
|
if (outColors is not null)
|
|
{
|
|
outColors[i] = accumColor![i] / counts[i];
|
|
}
|
|
}
|
|
|
|
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;
|
|
if (outColors is not null) newArr[(int)Mesh.ArrayType.Color] = outColors;
|
|
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;
|
|
while (true)
|
|
{
|
|
if (!protectedSet.Add(cur))
|
|
{
|
|
// Still continue up in case a parent wasn't marked yet, or break if parent already marked
|
|
}
|
|
if (!parentByIndex.TryGetValue(cur, out int parent))
|
|
{
|
|
break;
|
|
}
|
|
cur = parent;
|
|
}
|
|
}
|
|
|
|
private static Node? ResolveSceneNode(Node3D sceneRoot, NodePath scenePath, string originalName)
|
|
{
|
|
if (!scenePath.IsEmpty)
|
|
{
|
|
Node? direct = sceneRoot.GetNodeOrNull(scenePath);
|
|
if (direct is not null)
|
|
{
|
|
return direct;
|
|
}
|
|
|
|
string raw = scenePath.ToString();
|
|
if (raw == "." || raw == sceneRoot.Name)
|
|
{
|
|
return sceneRoot;
|
|
}
|
|
|
|
int slash = raw.IndexOf('/');
|
|
if (slash >= 0)
|
|
{
|
|
string sub = raw[(slash + 1)..];
|
|
Node? trimmed = sceneRoot.GetNodeOrNull(sub);
|
|
if (trimmed is not null)
|
|
{
|
|
return trimmed;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Fallback: sanitized name match
|
|
string sanitized = originalName.Replace('.', '_').Replace(':', '_').Replace('@', '_').Replace('/', '_');
|
|
return FindNodeRecursive(sceneRoot, originalName, sanitized);
|
|
}
|
|
|
|
private static Node? FindNodeRecursive(Node cur, string exactName, string sanitized)
|
|
{
|
|
string nm = cur.Name;
|
|
if (string.Equals(nm, exactName, StringComparison.Ordinal) ||
|
|
string.Equals(nm, sanitized, StringComparison.Ordinal))
|
|
{
|
|
return cur;
|
|
}
|
|
int count = cur.GetChildCount();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
Node? found = FindNodeRecursive(cur.GetChild(i), exactName, sanitized);
|
|
if (found is not null)
|
|
{
|
|
return found;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private static NodePath BuildRelativeNodePath(Node root, Node target)
|
|
{
|
|
if (ReferenceEquals(root, target))
|
|
{
|
|
return new NodePath(".");
|
|
}
|
|
|
|
var segments = new List<string>();
|
|
Node? cur = target;
|
|
while (cur is not null && !ReferenceEquals(cur, root))
|
|
{
|
|
segments.Add(cur.Name);
|
|
cur = cur.GetParent();
|
|
}
|
|
if (!ReferenceEquals(cur, root))
|
|
{
|
|
return new NodePath(".");
|
|
}
|
|
segments.Reverse();
|
|
return new NodePath(string.Join("/", segments));
|
|
}
|
|
|
|
private static void CollectModelTransforms(Node cur, Transform3D parentTransform, Dictionary<Node, Transform3D> map)
|
|
{
|
|
Transform3D world = cur is Node3D n3d ? parentTransform * n3d.Transform : parentTransform;
|
|
map[cur] = world;
|
|
int count = cur.GetChildCount();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
CollectModelTransforms(cur.GetChild(i), world, map);
|
|
}
|
|
}
|
|
|
|
private static void ComputeSceneMeshBoundsY(Node3D root, out float minY, out float maxY)
|
|
{
|
|
ComputeSceneMeshBounds(root, out Vector3 mn, out Vector3 mx);
|
|
minY = mn.Y;
|
|
maxY = mx.Y;
|
|
}
|
|
|
|
private static void ComputeSceneMeshBounds(Node3D root, out Vector3 boundsMin, out Vector3 boundsMax)
|
|
{
|
|
Vector3 mn = new(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
|
|
Vector3 mx = new(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
|
|
AccumulateBounds(root, Transform3D.Identity, ref mn, ref mx);
|
|
|
|
if (!float.IsFinite(mn.X))
|
|
{
|
|
mn = Vector3.Zero;
|
|
mx = Vector3.One;
|
|
}
|
|
boundsMin = mn;
|
|
boundsMax = mx;
|
|
}
|
|
|
|
private static void AccumulateBounds(Node cur, Transform3D parentXf, ref Vector3 mn, ref Vector3 mx)
|
|
{
|
|
Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf;
|
|
if (cur is MeshInstance3D mi && mi.Mesh is not null)
|
|
{
|
|
bool usedVertices = false;
|
|
int surfCount = mi.Mesh.GetSurfaceCount();
|
|
for (int s = 0; s < surfCount; s++)
|
|
{
|
|
var arrays = mi.Mesh.SurfaceGetArrays(s);
|
|
if (arrays.Count > (int)Mesh.ArrayType.Vertex)
|
|
{
|
|
Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
|
|
if (verts.Length > 0)
|
|
{
|
|
usedVertices = true;
|
|
for (int v = 0; v < verts.Length; v++)
|
|
{
|
|
Vector3 w = xf * verts[v];
|
|
mn = new Vector3(MathF.Min(mn.X, w.X), MathF.Min(mn.Y, w.Y), MathF.Min(mn.Z, w.Z));
|
|
mx = new Vector3(MathF.Max(mx.X, w.X), MathF.Max(mx.Y, w.Y), MathF.Max(mx.Z, w.Z));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!usedVertices)
|
|
{
|
|
Aabb aabb = mi.Mesh.GetAabb();
|
|
Vector3 p = aabb.Position;
|
|
Vector3 sz = aabb.Size;
|
|
for (int ix = 0; ix < 2; ix++)
|
|
{
|
|
for (int iy = 0; iy < 2; iy++)
|
|
{
|
|
for (int iz = 0; iz < 2; iz++)
|
|
{
|
|
Vector3 corner = new(p.X + ix * sz.X, p.Y + iy * sz.Y, p.Z + iz * sz.Z);
|
|
Vector3 w = xf * corner;
|
|
mn = new Vector3(MathF.Min(mn.X, w.X), MathF.Min(mn.Y, w.Y), MathF.Min(mn.Z, w.Z));
|
|
mx = new Vector3(MathF.Max(mx.X, w.X), MathF.Max(mx.Y, w.Y), MathF.Max(mx.Z, w.Z));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int count = cur.GetChildCount();
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
AccumulateBounds(cur.GetChild(i), xf, ref mn, ref mx);
|
|
}
|
|
}
|
|
|
|
private static byte[] ReadGlbJsonChunk(string glbPath)
|
|
{
|
|
byte[] data = File.ReadAllBytes(glbPath);
|
|
if (data.Length < 20)
|
|
{
|
|
throw new InvalidDataException($"{glbPath}: GLB smaller than 20-byte header.");
|
|
}
|
|
|
|
uint magic = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(0, 4));
|
|
uint version = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(4, 4));
|
|
if (magic != 0x46546C67 || version != 2)
|
|
{
|
|
throw new InvalidDataException($"{glbPath}: invalid GLB header magic=0x{magic:X8} version={version}.");
|
|
}
|
|
|
|
uint jsonLen = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12, 4));
|
|
uint jsonType = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(16, 4));
|
|
if (jsonType != 0x4E4F534A)
|
|
{
|
|
throw new InvalidDataException($"{glbPath}: first GLB chunk is not JSON (0x{jsonType:X8}).");
|
|
}
|
|
|
|
return data.AsSpan(20, (int)jsonLen).ToArray();
|
|
}
|
|
|
|
private static Vector3 ReadVec3(JsonElement obj, string propName, Vector3 fallback)
|
|
{
|
|
if (!obj.TryGetProperty(propName, out JsonElement arr) || arr.ValueKind != JsonValueKind.Array || arr.GetArrayLength() < 3)
|
|
{
|
|
return fallback;
|
|
}
|
|
return new Vector3(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle());
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
foreach (var v in _vehicles.Values)
|
|
{
|
|
if (GodotObject.IsInstanceValid(v.SceneTemplate))
|
|
{
|
|
v.SceneTemplate.QueueFree();
|
|
}
|
|
}
|
|
foreach (var g in _gear.Values)
|
|
{
|
|
if (GodotObject.IsInstanceValid(g.SceneTemplate))
|
|
{
|
|
g.SceneTemplate.QueueFree();
|
|
}
|
|
}
|
|
foreach (var wp in _weaponParts.Values)
|
|
{
|
|
if (GodotObject.IsInstanceValid(wp.SceneTemplate))
|
|
{
|
|
wp.SceneTemplate.QueueFree();
|
|
}
|
|
}
|
|
_vehicles.Clear();
|
|
_gear.Clear();
|
|
_weaponParts.Clear();
|
|
if (_dropPod is not null && GodotObject.IsInstanceValid(_dropPod.SceneTemplate))
|
|
{
|
|
_dropPod.SceneTemplate.QueueFree();
|
|
}
|
|
_dropPod = null;
|
|
}
|
|
}
|