using System; using System.Collections.Generic; using Godot; using RustToDust.Core; namespace RustToDust.Client; public enum VehicleVisualRole { Player, Rival, SpectatorTourist, SpectatorPatron, SpectatorExemplar, SalvageDrop } /// /// Live Godot 3D instance of a Brokkr vehicle/mech GLB, managing: /// - grounded model alignment (minY = 0 at physics chassis bottom -HalfHeight), /// - exterior hardpoint anchor bindings and snap-on modular gear GLBs, /// - joint pivot bindings with rest transforms and vehicle-space axes, /// - part-by-cell armor/shroud detachment and hardpoint gear shearing into , /// - per-cell scorch/damage darkening and thermal heat glow. /// public sealed class VehicleVisualInstance { public sealed class BoundJoint { public required string JointId; public required Node3D Node; public required Transform3D RestLocal; public required Vector3 AxisInParent; public required float MinRad; public required float MaxRad; } private sealed class BoundHardpoint { public required HardpointSpec Spec; public required VehicleAssetCache.GlbAnchorInfo AnchorInfo; public required Node3D AnchorNode; public string? MountedModuleId; public Node3D? GearNode; public readonly List GearHeatMaterials = new(); } private sealed class CellPartBinding { public required MeshInstance3D Node; public readonly List<(StandardMaterial3D Mat, Color BaseColor, float BaseRoughness)> Materials = new(); public bool Detached; public float LastTintScore = -1f; } private readonly record struct GearVisualRecipe( string GearGlbId, Vector3 VariantScale, Color? PaintTint, Color? AccentTint); private static readonly Color RivalArmorColor = Color.FromHtml("#5d4d42"); private static readonly Color RivalAccentColor = Color.FromHtml("#b64a32"); private static readonly Color TouristGold = Color.FromHtml("#e6b838"); private static readonly Color TouristIvory = Color.FromHtml("#f2ead8"); private static readonly Color PatronTeal = Color.FromHtml("#2d7a78"); private static readonly Color PatronBronze = Color.FromHtml("#a86c36"); private static readonly Color ExemplarObsidian = Color.FromHtml("#1b1b22"); private static readonly Color ExemplarCrimson = Color.FromHtml("#c92a2a"); private static readonly Color SalvageSteel = Color.FromHtml("#545b5c"); private static readonly Color SalvageCyan = Color.FromHtml("#44d9e8"); private readonly VehicleAssetCache _cache; private readonly VehicleAssetCache.VehicleTemplate _template; private readonly Dictionary _hardpoints = new(StringComparer.Ordinal); private readonly Dictionary _joints = new(StringComparer.Ordinal); private readonly Dictionary _namedNodes = new(StringComparer.Ordinal); private readonly Dictionary _restLocalByName = new(StringComparer.Ordinal); private readonly Dictionary _restModelByName = new(StringComparer.Ordinal); private readonly Dictionary _restModelByNode = new(); private readonly List[,] _cellParts; private readonly bool[,] _strippedCells; private readonly HashSet _shearedHardpoints = new(StringComparer.Ordinal); private readonly VehicleRigAnimator.RigState _rigState = new(); private readonly string _chassisId; private MeshInstance3D? _lodStaticMesh; private bool _isStaticLod; private bool _castShadows = true; private VehicleVisualInstance( VehicleAssetCache cache, VehicleAssetCache.VehicleTemplate template, Node3D root, Node3D modelRoot, string chassisId) { _cache = cache; _template = template; Root = root; ModelRoot = modelRoot; _chassisId = chassisId; int w = template.Package.GridWidth; int h = template.Package.GridHeight; _cellParts = new List[w, h]; _strippedCells = new bool[w, h]; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { _cellParts[x, y] = new List(); } } } public Node3D Root { get; } public Node3D ModelRoot { get; } public VehicleAssetCache.VehicleTemplate Template => _template; public VehiclePackage Package => _template.Package; public string ChassisId => _chassisId; public string ModelId => _template.Package.Id; public VehicleRigAnimator.RigState RigState => _rigState; public IReadOnlyDictionary Joints => _joints; public int BoundHardpointCount => _hardpoints.Count; public bool IsStaticLod => _isStaticLod; public void SetLodState(bool useStaticLod, bool castShadows) { if (_lodStaticMesh is null) { if (ModelRoot is MeshInstance3D dropMi) { if (_isStaticLod != useStaticLod) { _isStaticLod = useStaticLod; dropMi.Mesh = useStaticLod ? _template.BakedLodFarMesh : _template.BakedStaticMesh; } if (_castShadows != castShadows) { _castShadows = castShadows; dropMi.CastShadow = castShadows ? GeometryInstance3D.ShadowCastingSetting.On : GeometryInstance3D.ShadowCastingSetting.Off; } } return; } if (_isStaticLod != useStaticLod) { _isStaticLod = useStaticLod; ModelRoot.Visible = !useStaticLod; ModelRoot.PhysicsInterpolationMode = useStaticLod ? Node.PhysicsInterpolationModeEnum.Off : Node.PhysicsInterpolationModeEnum.Inherit; ModelRoot.ProcessMode = useStaticLod ? Node.ProcessModeEnum.Disabled : Node.ProcessModeEnum.Inherit; _lodStaticMesh.Visible = useStaticLod; } if (_castShadows != castShadows) { _castShadows = castShadows; _lodStaticMesh.CastShadow = castShadows ? GeometryInstance3D.ShadowCastingSetting.On : GeometryInstance3D.ShadowCastingSetting.Off; } } public static VehicleVisualInstance Create( VehicleAssetCache cache, string chassisId, VehicleVisualRole role, float visualScale = 1.0f, float? targetHalfHeight = null) { var template = cache.GetOrLoadVehicle(chassisId); var pkg = template.Package; float halfHeight = targetHalfHeight ?? (pkg.HalfHeight * visualScale); float effectiveScale = targetHalfHeight.HasValue && pkg.HalfHeight > 1e-4f ? visualScale * (targetHalfHeight.Value / pkg.HalfHeight) : visualScale; var root = new Node3D { Name = $"Actor_{chassisId}" }; Vector3 modelScale = new(effectiveScale, effectiveScale, effectiveScale); // Align glTF grounded minY=0 to physics chassis bottom (-halfHeight) Vector3 modelPos = new(0f, -halfHeight - template.MinY * effectiveScale, 0f); if (role == VehicleVisualRole.SalvageDrop) { var dropMesh = new MeshInstance3D { Name = $"Model_{pkg.Id}", Mesh = template.BakedStaticMesh, Scale = modelScale, Position = modelPos }; ApplyRoleTint(dropMesh, role); root.AddChild(dropMesh); return new VehicleVisualInstance(cache, template, root, dropMesh, chassisId); } if (template.SceneTemplate.Duplicate() is not Node3D modelRoot) { throw new InvalidOperationException($"Failed to duplicate GLB scene template for '{pkg.Id}'."); } modelRoot.Name = $"Model_{pkg.Id}"; modelRoot.Scale = modelScale; modelRoot.Position = modelPos; root.AddChild(modelRoot); var lodMesh = new MeshInstance3D { Name = $"LodStatic_{pkg.Id}", Mesh = template.BakedLodFarMesh, Scale = modelScale, Position = modelPos, Visible = false }; if (role != VehicleVisualRole.Player) { ApplyRoleTint(lodMesh, role); } root.AddChild(lodMesh); var instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId) { _lodStaticMesh = lodMesh }; instance.BindAll(role); return instance; } private void BindAll(VehicleVisualRole role) { var pkg = _template.Package; // Collect cumulative pure glTF model-space transforms (minY=0, unscaled) starting at ModelRoot = Identity var modelXforms = new Dictionary { [ModelRoot] = Transform3D.Identity }; int modelChildCount = ModelRoot.GetChildCount(); for (int i = 0; i < modelChildCount; i++) { CollectNodeTransforms(ModelRoot.GetChild(i), Transform3D.Identity, modelXforms); } // Bind named nodes for procedural/mechanism rigs foreach (var (origName, relPath) in _template.NodesByOriginalName) { Node3D? node = ResolveRelative(ModelRoot, relPath); if (node is not null) { _namedNodes[origName] = node; _restLocalByName[origName] = node.Transform; if (modelXforms.TryGetValue(node, out var mxf)) { _restModelByName[origName] = mxf; _restModelByNode[node] = mxf; } } } // Bind all joints from rtd.joint metadata foreach (var (jointId, jInfo) in _template.Joints) { Node3D? jNode = ResolveRelative(ModelRoot, jInfo.RelativePath); if (jNode is null) { throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing joint node '{jInfo.NodeName}' ({jointId})."); } Basis parentModelBasis = Basis.Identity; Node? parent = jNode.GetParent(); if (parent is not null && modelXforms.TryGetValue(parent, out var pxf)) { parentModelBasis = pxf.Basis.Orthonormalized(); } Vector3 axisInParent = parentModelBasis.Inverse() * jInfo.Axis; axisInParent = axisInParent.LengthSquared() > 1e-6f ? axisInParent.Normalized() : Vector3.Up; _joints[jointId] = new BoundJoint { JointId = jointId, Node = jNode, RestLocal = jNode.Transform, AxisInParent = axisInParent, MinRad = Mathf.DegToRad(jInfo.MinVal), MaxRad = Mathf.DegToRad(jInfo.MaxVal) }; } // Bind every ChassisSpec hardpoint to its exact exterior anchor Node3D ChassisSpec spec = pkg.ToChassisSpec(); var pkgHpById = new Dictionary(StringComparer.Ordinal); foreach (var rec in pkg.Hardpoints) { pkgHpById[rec.Id] = rec; } for (int i = 0; i < spec.Hardpoints.Length; i++) { HardpointSpec hp = spec.Hardpoints[i]; if (!pkgHpById.TryGetValue(hp.Id, out var rec) || !_template.Anchors.TryGetValue(rec.AnchorId, out var anchorInfo)) { throw new InvalidOperationException($"{pkg.Id}: missing AnchorId for hardpoint '{hp.Id}'."); } Node3D? anchorNode = ResolveRelative(ModelRoot, anchorInfo.RelativePath); if (anchorNode is null) { throw new InvalidOperationException($"{pkg.Id}: duplicated scene missing anchor node '{rec.AnchorId}'."); } _hardpoints[hp.Id] = new BoundHardpoint { Spec = hp, AnchorInfo = anchorInfo, AnchorNode = anchorNode }; } // Apply role palette tinting to painted hull meshes before binding per-cell damage clones if (role != VehicleVisualRole.Player) { ApplyRoleTint(ModelRoot, role); } // Bind detachable exterior armor/shroud parts to their (CellX, CellY) int w = pkg.GridWidth; int h = pkg.GridHeight; foreach (var dp in _template.DetachableParts) { if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h) { continue; } if (ResolveRelative(ModelRoot, dp.RelativePath) is MeshInstance3D mi) { _cellParts[dp.CellX, dp.CellY].Add(new CellPartBinding { Node = mi }); } } } public Node3D? GetNamedNode(string name) => _namedNodes.TryGetValue(name, out var n) && GodotObject.IsInstanceValid(n) ? n : null; public bool TryGetRestLocal(string name, out Transform3D xform) => _restLocalByName.TryGetValue(name, out xform); public bool TryGetRestModel(string name, out Transform3D xform) => _restModelByName.TryGetValue(name, out xform); public bool TryGetRestModel(Node3D node, out Transform3D xform) => _restModelByNode.TryGetValue(node, out xform); public Node3D? GetHardpointAnchorNode(string hardpointId) => _hardpoints.TryGetValue(hardpointId, out var bh) ? bh.AnchorNode : null; public Node3D? GetMountedGearNode(string hardpointId) => _hardpoints.TryGetValue(hardpointId, out var bh) && GodotObject.IsInstanceValid(bh.GearNode) ? bh.GearNode : null; public int CountDetachablePartsForCell(int x, int y) => x >= 0 && x < _template.Package.GridWidth && y >= 0 && y < _template.Package.GridHeight ? _cellParts[x, y].Count : 0; /// /// Synchronizes visible exterior gear GLBs on all hardpoint anchors with . /// public void SyncMountedGear(ChassisGrid grid) { foreach (var bh in _hardpoints.Values) { if (_shearedHardpoints.Contains(bh.Spec.Id) || !grid.IsHardpointOperational(bh.Spec)) { continue; } MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id); string? desiredId = mounted?.Spec.Id; if (string.Equals(bh.MountedModuleId, desiredId, StringComparison.Ordinal)) { continue; } // Clear old gear visual if unmounted or swapped if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) { bh.GearNode.GetParent()?.RemoveChild(bh.GearNode); bh.GearNode.QueueFree(); } bh.GearNode = null; bh.GearHeatMaterials.Clear(); bh.MountedModuleId = desiredId; if (mounted is null) { continue; } Node3D gearNode = InstantiateGearForHardpoint(mounted.Spec, bh.Spec, bh.AnchorInfo, bh.GearHeatMaterials); bh.AnchorNode.AddChild(gearNode); bh.GearNode = gearNode; } } /// /// Detaches exterior armor/shroud plates when Armor[x, y] <= 0.01f, /// shears mounted gear off non-operational hardpoints, and applies scorch/heat glow. /// public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity) { int w = Math.Min(grid.Spec.Width, _template.Package.GridWidth); int h = Math.Min(grid.Spec.Height, _template.Package.GridHeight); Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position; // 1. Part-by-cell detachment & cell scorch/heat tinting for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (!grid.Spec.IsActive(x, y)) { continue; } float armor = grid.Armor[x, y]; var parts = _cellParts[x, y]; if (!_strippedCells[x, y] && armor <= 0.01f) { _strippedCells[x, y] = true; for (int i = 0; i < parts.Count; i++) { var pb = parts[i]; if (!pb.Detached && GodotObject.IsInstanceValid(pb.Node)) { pb.Detached = true; debris.SpawnDetachedPart(pb.Node, blastOrigin, vehicleVelocity, impulseScale: 1.0f, applyScorch: true); } } continue; } if (parts.Count == 0) { continue; } float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f); float heatGlow = Math.Clamp((grid.Temperature[x, y] - 65f) / 110f, 0f, 1f); float tintScore = MathF.Round(dmgFrac * 20f) + MathF.Round(heatGlow * 20f) * 32f; if (dmgFrac < 0.25f && heatGlow < 0.05f) { continue; } for (int i = 0; i < parts.Count; i++) { var pb = parts[i]; if (pb.Detached || !GodotObject.IsInstanceValid(pb.Node)) { continue; } if (MathF.Abs(pb.LastTintScore - tintScore) < 0.5f) { continue; } pb.LastTintScore = tintScore; ApplyCellDamageAndHeat(pb, dmgFrac, heatGlow); } } } // 2. Hardpoint shear & mounted gear heat glow foreach (var bh in _hardpoints.Values) { if (!_shearedHardpoints.Contains(bh.Spec.Id) && !grid.IsHardpointOperational(bh.Spec)) { _shearedHardpoints.Add(bh.Spec.Id); if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) { Node3D sheared = bh.GearNode; bh.GearNode = null; bh.MountedModuleId = null; bh.GearHeatMaterials.Clear(); debris.SpawnDetachedPart(sheared, blastOrigin, vehicleVelocity, impulseScale: 1.15f, applyScorch: true); } continue; } if (bh.GearNode is null || bh.GearHeatMaterials.Count == 0) { continue; } MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id); if (mounted is null) { continue; } float heatFrac = Math.Clamp((mounted.CurrentTemp - 65f) / 115f, 0f, 1f); for (int m = 0; m < bh.GearHeatMaterials.Count; m++) { StandardMaterial3D gm = bh.GearHeatMaterials[m]; gm.EmissionEnabled = heatFrac > 0.02f; gm.Emission = new Color(1.0f, 0.34f, 0.08f); gm.EmissionEnergyMultiplier = heatFrac * 2.2f; } } } public static Node3D CreateStandaloneGearVisual(VehicleAssetCache cache, ModuleSpec mod) { var list = new List(); GearVisualRecipe recipe = ResolveGearRecipe(mod); var template = cache.GetOrLoadGear(recipe.GearGlbId); if (template.SceneTemplate.Duplicate() is not Node3D node) { return new Node3D { Name = $"Gear_{mod.Id}" }; } node.Name = $"GearDrop_{mod.Id}"; node.Scale = recipe.VariantScale; node.Position = new Vector3(0f, -template.MinY * recipe.VariantScale.Y, 0f); if (recipe.PaintTint.HasValue || recipe.AccentTint.HasValue) { ApplyGearVariantTint(node, recipe.PaintTint, recipe.AccentTint, list); } return node; } private Node3D InstantiateGearForHardpoint( ModuleSpec mod, HardpointSpec hp, VehicleAssetCache.GlbAnchorInfo anchorInfo, List heatMaterialsOut) { GearVisualRecipe recipe = ResolveGearRecipe(mod); VehicleAssetCache.GearTemplate gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId); if (gearTemplate.SceneTemplate.Duplicate() is not Node3D gearNode) { throw new InvalidOperationException($"Failed to duplicate gear GLB '{recipe.GearGlbId}'."); } gearNode.Name = $"Mounted_{mod.Id}_{hp.Id}"; // Compute outward socket normal & desired gear forward direction in vehicle/model space Basis anchorModelBasis = anchorInfo.ModelSpaceTransform.Basis.Orthonormalized(); Vector3 upOut = anchorModelBasis.Y.Normalized(); if (upOut.LengthSquared() < 1e-6f) upOut = Vector3.Up; Vector3 vehForward = new(0f, 0f, 1f); Vector3 desiredGearFwd; if (hp.Kind == HardpointKind.Weapon) { // Special guard for forward-facing chin mounts (e.g. manticore hp.weapon.chin): // drop the turret base under the chin (-Y) so the barrel points straight forward (+Z) instead of up into the nose. if (upOut.Z > 0.72f) { upOut = upOut.Y <= 0.1f ? new Vector3(0f, -1f, 0f) : new Vector3(0f, 1f, 0f); desiredGearFwd = vehForward; } else { Vector3 proj = vehForward - upOut * vehForward.Dot(upOut); desiredGearFwd = proj.LengthSquared() > 1e-4f ? proj.Normalized() : anchorModelBasis.Z.Normalized(); } } else { // Non-weapon modules (radiator / engine / armor): align neatly to hull tangent plane if (MathF.Abs(upOut.Z) > 0.78f) { Vector3 upProj = Vector3.Up - upOut * Vector3.Up.Dot(upOut); desiredGearFwd = upProj.LengthSquared() > 1e-4f ? upProj.Normalized() : Vector3.Up; } else { Vector3 proj = vehForward - upOut * vehForward.Dot(upOut); desiredGearFwd = proj.LengthSquared() > 1e-4f ? proj.Normalized() : Vector3.Up; } } // Right-handed basis: Y = upOut, Z = desiredGearFwd, X = Y x Z Vector3 rightX = upOut.Cross(desiredGearFwd); if (rightX.LengthSquared() < 1e-5f) { rightX = Vector3.Right; } else { rightX = rightX.Normalized(); } desiredGearFwd = rightX.Cross(upOut).Normalized(); var desiredModelBasis = new Basis(rightX, upOut, desiredGearFwd); // If the gear GLB's own forward points along -Z, rotate 180 deg around Y if (gearTemplate.LocalModelForward.Z < 0f) { desiredModelBasis *= new Basis(Vector3.Up, MathF.PI); } Basis localBasis = anchorModelBasis.Inverse() * desiredModelBasis; // Fit cleanly to the socket's physical rtd.size float sx = MathF.Max(0.25f, anchorInfo.Size.X); float sy = MathF.Max(0.25f, anchorInfo.Size.Y); Vector3 fitScale; if (hp.Kind == HardpointKind.Weapon) { float baseScale = Math.Clamp(MathF.Min(sx, sy) / 0.56f, 0.72f, 1.75f); fitScale = recipe.VariantScale * baseScale; } else { float scaleX = Math.Clamp(sx / 0.48f, 0.72f, 2.15f); float scaleZ = Math.Clamp(sy / 0.45f, 0.72f, 2.15f); float scaleY = Math.Clamp(0.5f * (scaleX + scaleZ), 0.72f, 1.85f); fitScale = new Vector3( recipe.VariantScale.X * scaleX, recipe.VariantScale.Y * scaleY, recipe.VariantScale.Z * scaleZ); } gearNode.Basis = localBasis * Basis.FromScale(fitScale); // Seat gear minY right on the anchor collar origin (with slight downward offset if chin flipped) float ySeat = -gearTemplate.MinY * fitScale.Y; gearNode.Position = (anchorModelBasis.Inverse() * upOut) * ySeat; ApplyGearVariantTint(gearNode, recipe.PaintTint, recipe.AccentTint, heatMaterialsOut); return gearNode; } private static GearVisualRecipe ResolveGearRecipe(ModuleSpec mod) { return mod.Id switch { "mg_762" => new("mg_762", Vector3.One, null, null), "autocannon" => new("autocannon", Vector3.One, null, null), "recoilless" => new("recoilless", Vector3.One, null, null), "copper_rad" => new("copper_rad", Vector3.One, null, null), "gilded_lance" => new("gilded_lance", Vector3.One, null, null), "gold_radiator" => new("gold_radiator", Vector3.One, null, null), // Clean tint/scale variants from the 6 real gear GLBs "flak" => new("autocannon", new Vector3(1.12f, 0.92f, 0.68f), Color.FromHtml("#5a4a3f"), Color.FromHtml("#d96c27")), "pd_flak" => new("mg_762", new Vector3(1.22f, 1.10f, 0.85f), Color.FromHtml("#3d4440"), Color.FromHtml("#e08a4a")), "touring_plasma" => new("gilded_lance", new Vector3(1.05f, 0.96f, 0.72f), TouristIvory, Color.FromHtml("#38c9d8")), "aegis_pd" => new("gilded_lance", new Vector3(0.95f, 0.92f, 0.56f), TouristGold, Color.FromHtml("#38c9d8")), "diesel_core" => new("copper_rad", new Vector3(0.92f, 1.15f, 1.05f), Color.FromHtml("#363a38"), Color.FromHtml("#b35a2b")), "turbo_core" => new("copper_rad", new Vector3(1.12f, 1.28f, 1.38f), Color.FromHtml("#2a2f32"), Color.FromHtml("#e07024")), "noble_core" => new("gold_radiator", new Vector3(1.10f, 1.32f, 1.38f), TouristGold, Color.FromHtml("#38c9d8")), "welded_plate" => new("copper_rad", new Vector3(1.30f, 0.34f, 0.95f), Color.FromHtml("#4e5740"), Color.FromHtml("#6a6f66")), "gilded_plate" => new("gold_radiator", new Vector3(1.30f, 0.34f, 0.95f), TouristIvory, TouristGold), _ => new(mod.IsImperial ? "gilded_lance" : "mg_762", Vector3.One, null, null) }; } private static void ApplyGearVariantTint( Node cur, Color? paintTint, Color? accentTint, List trackMaterials) { if (cur is MeshInstance3D mi && mi.Mesh is not null) { int surfCount = mi.Mesh.GetSurfaceCount(); for (int s = 0; s < surfCount; s++) { Material? src = mi.GetActiveMaterial(s); if (src is not StandardMaterial3D sm) { continue; } var copy = (StandardMaterial3D)sm.Duplicate(); string matName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); if (accentTint.HasValue && (matName.Contains("copper") || matName.Contains("signal") || matName.Contains("cyan") || matName.Contains("gold"))) { copy.AlbedoColor = accentTint.Value; } else if (paintTint.HasValue && (matName.Contains("olive") || matName.Contains("ivory") || matName.Contains("armor"))) { copy.AlbedoColor = paintTint.Value; } mi.SetSurfaceOverrideMaterial(s, copy); if (!matName.Contains("rubber") && !matName.Contains("glass")) { trackMaterials.Add(copy); } } } int count = cur.GetChildCount(); for (int i = 0; i < count; i++) { ApplyGearVariantTint(cur.GetChild(i), paintTint, accentTint, trackMaterials); } } private static void ApplyRoleTint(Node root, VehicleVisualRole role) { var (armorColor, accentColor) = role switch { VehicleVisualRole.Rival => (RivalArmorColor, RivalAccentColor), VehicleVisualRole.SpectatorTourist => (TouristGold, TouristIvory), VehicleVisualRole.SpectatorPatron => (PatronTeal, PatronBronze), VehicleVisualRole.SpectatorExemplar => (ExemplarObsidian, ExemplarCrimson), VehicleVisualRole.SalvageDrop => (SalvageSteel, SalvageCyan), _ => (RivalArmorColor, RivalAccentColor) }; var clonedCache = new Dictionary(); TintSubtreeRecursive(root, armorColor, accentColor, role, clonedCache); } private static void TintSubtreeRecursive( Node cur, Color armorColor, Color accentColor, VehicleVisualRole role, Dictionary clonedCache) { if (cur is MeshInstance3D mi && mi.Mesh is not null) { int surfCount = mi.Mesh.GetSurfaceCount(); for (int s = 0; s < surfCount; s++) { if (mi.GetActiveMaterial(s) is not StandardMaterial3D sm) { continue; } string mName = (sm.ResourceName ?? string.Empty).ToLowerInvariant(); bool isPrimaryPaint = mName.Contains("olive") || mName.Contains("khaki"); bool isAccentPaint = mName.Contains("signal") || mName.Contains("orange"); if (!isPrimaryPaint && !isAccentPaint) { continue; } if (!clonedCache.TryGetValue(sm, out var copy)) { copy = (StandardMaterial3D)sm.Duplicate(); copy.AlbedoColor = isPrimaryPaint ? armorColor : accentColor; if (role == VehicleVisualRole.SpectatorTourist && isPrimaryPaint) { copy.Metallic = 0.72f; copy.Roughness = 0.30f; } else if (role == VehicleVisualRole.SpectatorExemplar && isAccentPaint) { copy.EmissionEnabled = true; copy.Emission = ExemplarCrimson; copy.EmissionEnergyMultiplier = 0.65f; } clonedCache[sm] = copy; } mi.SetSurfaceOverrideMaterial(s, copy); } } int count = cur.GetChildCount(); for (int i = 0; i < count; i++) { TintSubtreeRecursive(cur.GetChild(i), armorColor, accentColor, role, clonedCache); } } private static void ApplyCellDamageAndHeat(CellPartBinding binding, float dmgFrac, float heatGlow) { if (binding.Materials.Count == 0 && binding.Node.Mesh is not null) { int surfCount = binding.Node.Mesh.GetSurfaceCount(); for (int s = 0; s < surfCount; s++) { Material? src = binding.Node.GetActiveMaterial(s); StandardMaterial3D copy = src is StandardMaterial3D sm ? (StandardMaterial3D)sm.Duplicate() : new StandardMaterial3D { AlbedoColor = new Color(0.32f, 0.34f, 0.30f), Roughness = 0.6f, Metallic = 0.35f }; binding.Node.SetSurfaceOverrideMaterial(s, copy); binding.Materials.Add((copy, copy.AlbedoColor, copy.Roughness)); } } float scorch = Math.Clamp((dmgFrac - 0.25f) / 0.75f, 0f, 1f) * 0.65f; for (int i = 0; i < binding.Materials.Count; i++) { var (mat, baseCol, baseRough) = binding.Materials[i]; mat.AlbedoColor = new Color( baseCol.R * (1f - scorch) + 0.05f * scorch, baseCol.G * (1f - scorch) + 0.035f * scorch, baseCol.B * (1f - scorch) + 0.03f * scorch, baseCol.A); mat.Roughness = MathF.Min(0.95f, baseRough + scorch * 0.35f); mat.EmissionEnabled = heatGlow > 0.05f; mat.Emission = new Color(1.0f, 0.32f, 0.08f); mat.EmissionEnergyMultiplier = heatGlow * 1.4f; } } private static Node3D? ResolveRelative(Node3D root, NodePath relPath) { if (relPath.IsEmpty) { return null; } return relPath.ToString() == "." ? root : root.GetNodeOrNull(relPath); } private static void CollectNodeTransforms(Node cur, Transform3D parentXf, Dictionary map) { Transform3D xf = cur is Node3D n3d ? parentXf * n3d.Transform : parentXf; map[cur] = xf; int count = cur.GetChildCount(); for (int i = 0; i < count; i++) { CollectNodeTransforms(cur.GetChild(i), xf, map); } } /// /// Computes the highest rendered vertex Y in local space across the hull /// and all currently mounted gear meshes. /// public float ComputeMountedMaxY() { float maxY = float.NegativeInfinity; AccumulateMaxYRecursive(ModelRoot, Transform3D.Identity, ref maxY, isRoot: true); if (!float.IsFinite(maxY)) { return ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; } return maxY; } private static void AccumulateMaxYRecursive(Node cur, Transform3D parentToRoot, ref float maxY, bool isRoot = false) { Transform3D toRoot = parentToRoot; if (cur is Node3D n3d) { if (!isRoot && !n3d.Visible) { return; } toRoot = parentToRoot * n3d.Transform; } if (cur is MeshInstance3D mi && mi.Mesh is { } mesh) { int surfCount = mesh.GetSurfaceCount(); bool foundVerts = false; for (int s = 0; s < surfCount; s++) { var arrays = mesh.SurfaceGetArrays(s); if (arrays.Count > (int)Mesh.ArrayType.Vertex && arrays[(int)Mesh.ArrayType.Vertex].VariantType == Variant.Type.PackedVector3Array) { Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); for (int v = 0; v < verts.Length; v++) { float wy = (toRoot * verts[v]).Y; if (wy > maxY) { maxY = wy; } } foundVerts = true; } } if (!foundVerts) { Aabb aabb = mesh.GetAabb(); for (int c = 0; c < 8; c++) { Vector3 corner = aabb.Position + new Vector3( (c & 1) != 0 ? aabb.Size.X : 0f, (c & 2) != 0 ? aabb.Size.Y : 0f, (c & 4) != 0 ? aabb.Size.Z : 0f); float wy = (toRoot * corner).Y; if (wy > maxY) { maxY = wy; } } } } int childCount = cur.GetChildCount(); for (int i = 0; i < childCount; i++) { AccumulateMaxYRecursive(cur.GetChild(i), toRoot, ref maxY); } } }