using System; using System.Collections.Generic; using Godot; using RustToDust.Core; namespace RustToDust.Client; public enum VehicleVisualRole { Player, Rival, SpectatorTourist, SpectatorPatron, SpectatorExemplar, SalvageDrop } /// /// Lightweight Node3D rig hierarchy for a Brokkr vehicle/mech GLB, submitting all /// rigid limbs, detachable armor chunks, and mounted gear into /// (zero rendering MeshInstance3D children on rigs, zero per-hit material clones). /// 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; } public sealed class StaticPartBinding { public required Node3D Pivot; public required ArrayMesh Mesh; } public readonly record struct ModularWeaponPartBinding( ArrayMesh Mesh, Transform3D LocalToGearPivot, string Slot); private sealed class BoundHardpoint { public required HardpointSpec Spec; public required VehicleAssetCache.GlbAnchorInfo AnchorInfo; public required Node3D AnchorNode; public string? MountedModuleId; public Node3D? GearNode; public ArrayMesh? GearMesh; public VehicleAssetCache.GearTemplate? GearTemplate; public ModularWeaponPartBinding[]? ModularParts; public float ManufacturerRoleIndex; public Vector3 ModularMuzzleTipLocal; public Vector3 ModularReceiverCenterLocal; public float HeatGlow; } private sealed class CellPartBinding { public required Node3D Pivot; public required ArrayMesh Mesh; public bool Detached; public float Scorch; public float HeatGlow; } private readonly record struct GearVisualRecipe( string GearGlbId, Vector3 VariantScale, Color? PaintTint, Color? AccentTint); private static readonly Color TouristGold = Color.FromHtml("#e6b838"); private static readonly Color TouristIvory = Color.FromHtml("#f2ead8"); private readonly VehicleAssetCache _cache; private readonly VehicleAssetCache.VehicleTemplate _template; private readonly Dictionary _hardpoints = new(StringComparer.Ordinal); private readonly List _hardpointList = new(); private readonly List<(int X, int Y)> _activeCells = new(); 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 _staticParts = new(); private readonly List[,] _cellParts; private readonly List _allCellParts = new(); private readonly bool[,] _strippedCells; private readonly HashSet _shearedHardpoints = new(StringComparer.Ordinal); private readonly VehicleRigAnimator.RigState _rigState = new(); private readonly VehicleVisualRole _role; private readonly float _roleIndex; private readonly string _chassisId; private bool _isStaticLod; private bool _castShadows = true; private bool _hasAnyStrippedCell; private float _hullScorch; private float _hullHeatGlow; public static double PerfDamageHeatMs; public static int PerfMaterialDupCount; private VehicleVisualInstance( VehicleAssetCache cache, VehicleAssetCache.VehicleTemplate template, Node3D root, Node3D modelRoot, string chassisId, VehicleVisualRole role) { _cache = cache; _template = template; Root = root; ModelRoot = modelRoot; _chassisId = chassisId; _role = role; _roleIndex = role switch { VehicleVisualRole.Rival => 1f, VehicleVisualRole.SpectatorTourist => 2f, VehicleVisualRole.SpectatorPatron => 3f, VehicleVisualRole.SpectatorExemplar => 4f, VehicleVisualRole.SalvageDrop => 5f, _ => 0f }; 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 IReadOnlyList StaticParts => _staticParts; public int BoundHardpointCount => _hardpoints.Count; public bool IsStaticLod => _isStaticLod; public bool HasAnyStrippedCell => _hasAnyStrippedCell; public float RoleIndex => _roleIndex; public void SetLodState(bool useStaticLod, bool castShadows) { if (_role == VehicleVisualRole.SalvageDrop) { _isStaticLod = useStaticLod; _castShadows = castShadows; return; } if (_hasAnyStrippedCell) { useStaticLod = false; } 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; } _castShadows = castShadows; } 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 dropPivot = new Node3D { Name = $"Model_{pkg.Id}", Scale = modelScale, Position = modelPos }; root.AddChild(dropPivot); return new VehicleVisualInstance(cache, template, root, dropPivot, chassisId, role); } 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 instance = new VehicleVisualInstance(cache, template, root, modelRoot, chassisId, role); instance.BindAll(); return instance; } private void BindAll() { 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}'."); } var bh = new BoundHardpoint { Spec = hp, AnchorInfo = anchorInfo, AnchorNode = anchorNode }; _hardpoints[hp.Id] = bh; _hardpointList.Add(bh); } // Bind rigid static parts & detachable per-cell armor parts to their live Node3D pivots foreach (var sp in _template.StaticRigidParts) { if (ResolveRelative(ModelRoot, sp.PivotPath) is { } pivot) { _staticParts.Add(new StaticPartBinding { Pivot = pivot, Mesh = sp.Mesh }); } } int w = pkg.GridWidth; int h = pkg.GridHeight; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { if (spec.IsActive(x, y)) { _activeCells.Add((x, y)); } } } foreach (var dp in _template.DetachableRigidParts) { if (dp.CellX < 0 || dp.CellX >= w || dp.CellY < 0 || dp.CellY >= h) { continue; } if (ResolveRelative(ModelRoot, dp.PivotPath) is { } pivot) { var binding = new CellPartBinding { Pivot = pivot, Mesh = dp.Mesh }; _cellParts[dp.CellX, dp.CellY].Add(binding); _allCellParts.Add(binding); } } } 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; public bool TryGetMountedWeaponCentroidsInModel( string hardpointId, string frontPartName, string rearPartName, out Vector3 frontInModel, out Vector3 rearInModel) { frontInModel = Vector3.Zero; rearInModel = Vector3.Zero; if (!_hardpoints.TryGetValue(hardpointId, out var bh) || bh.GearNode is null || !GodotObject.IsInstanceValid(bh.GearNode)) { return false; } Transform3D gearToModel = ComputeRelativeTransform(bh.GearNode, ModelRoot); if (bh.ModularParts is not null) { frontInModel = gearToModel * bh.ModularMuzzleTipLocal; rearInModel = gearToModel * bh.ModularReceiverCenterLocal; return true; } if (bh.GearTemplate is null) { return false; } if (!bh.GearTemplate.PartCentroidsLocal.TryGetValue(frontPartName, out Vector3 fLocal) || !bh.GearTemplate.PartCentroidsLocal.TryGetValue(rearPartName, out Vector3 rLocal)) { return false; } frontInModel = gearToModel * fLocal; rearInModel = gearToModel * rLocal; return true; } public static void BuildModularWeaponAssembly( VehicleAssetCache cache, ModularWeaponAssembly assembly, out ModularWeaponPartBinding[] parts, out Vector3 muzzleTipLocal, out Vector3 receiverCenterLocal, out float minY) { var rxTpl = cache.GetOrLoadWeaponPart(assembly.ReceiverPartName); var brlTpl = cache.GetOrLoadWeaponPart(assembly.BarrelPartName); var fdTpl = cache.GetOrLoadWeaponPart(assembly.FeedPartName); var mzTpl = cache.GetOrLoadWeaponPart(assembly.MuzzlePartName); Transform3D rxXf = Transform3D.Identity; Transform3D brlXf = rxTpl.SocketsLocal.TryGetValue("barrel", out var bx) ? bx : new Transform3D(Basis.Identity, new Vector3(0f, 0.20f, 0.24f)); Transform3D fdXf = rxTpl.SocketsLocal.TryGetValue("feed", out var fx) ? fx : new Transform3D(Basis.Identity, new Vector3(0.14f, 0.20f, 0f)); Transform3D brlMuzzle = brlTpl.SocketsLocal.TryGetValue("muzzle", out var mx) ? mx : new Transform3D(Basis.Identity, new Vector3(0f, 0f, 0.55f)); Transform3D mzXf = brlXf * brlMuzzle; Transform3D mzTip = mzTpl.SocketsLocal.TryGetValue("muzzle_tip", out var tx) ? tx : new Transform3D(Basis.Identity, new Vector3(0f, 0f, 0.22f)); muzzleTipLocal = (mzXf * mzTip).Origin; receiverCenterLocal = new Vector3(0f, rxTpl.Size.Y * 0.5f, 0f); minY = rxTpl.MinY; parts = new[] { new ModularWeaponPartBinding(rxTpl.SingleSurfaceMesh, rxXf, "receiver"), new ModularWeaponPartBinding(brlTpl.SingleSurfaceMesh, brlXf, "barrel"), new ModularWeaponPartBinding(fdTpl.SingleSurfaceMesh, fdXf, "feed"), new ModularWeaponPartBinding(mzTpl.SingleSurfaceMesh, mzXf, "muzzle") }; } public static void ResolveDropGearVisual( VehicleAssetCache cache, ModuleSpec mod, out ArrayMesh mesh, out Vector3 scale, out float yOffset) { GearVisualRecipe recipe = ResolveGearRecipe(mod); var template = cache.GetOrLoadGear(recipe.GearGlbId); mesh = cache.GetOrBuildGearVariantMesh(mod.Id, recipe.GearGlbId, recipe.PaintTint, recipe.AccentTint); scale = recipe.VariantScale; yOffset = -template.MinY * recipe.VariantScale.Y; } /// /// Synchronizes exterior gear transform anchors on all hardpoints 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; } if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) { bh.GearNode.GetParent()?.RemoveChild(bh.GearNode); bh.GearNode.QueueFree(); } bh.GearNode = null; bh.GearMesh = null; bh.GearTemplate = null; bh.ModularParts = null; bh.ManufacturerRoleIndex = 0f; bh.HeatGlow = 0f; bh.MountedModuleId = desiredId; if (mounted is null) { continue; } if (mounted.Spec.Procedural is { } proc) { BuildModularWeaponAssembly( _cache, proc.Assembly, out var modParts, out Vector3 muzzleTipLocal, out Vector3 receiverCenterLocal, out float minY); Transform3D mountXf = ComputeHardpointMountTransform( bh.Spec, bh.AnchorInfo, Vector3.One * proc.Assembly.VisualScale, localModelForwardZ: 1f, minY); var gearNode = new Node3D { Name = $"Mounted_{mounted.Spec.Id}_{bh.Spec.Id}", Transform = mountXf }; bh.AnchorNode.AddChild(gearNode); bh.GearNode = gearNode; bh.ModularParts = modParts; bh.ManufacturerRoleIndex = 10f + (float)proc.Manufacturer; bh.ModularMuzzleTipLocal = muzzleTipLocal; bh.ModularReceiverCenterLocal = receiverCenterLocal; } else { Node3D gearNode = CreateGearPivotForHardpoint( mounted.Spec, bh.Spec, bh.AnchorInfo, out ArrayMesh gearMesh, out VehicleAssetCache.GearTemplate gearTemplate); bh.AnchorNode.AddChild(gearNode); bh.GearNode = gearNode; bh.GearMesh = gearMesh; bh.GearTemplate = gearTemplate; } } } /// /// Detaches exterior armor/shroud plates when Armor[x, y] <= 0.01f, /// shears mounted gear off non-operational hardpoints into , /// and updates per-part scorch/heat channels for . /// public void SyncDamageAndHeat(ChassisGrid grid, DebrisSystem debris, Vector3 vehicleVelocity) { long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; Vector3 blastOrigin = Root.IsInsideTree() ? Root.GlobalPosition : Root.Position; float scorchSum = 0f; float maxHeat = 0f; int cellCount = _activeCells.Count; // 1. Part-by-cell detachment & cell scorch/heat channels for (int c = 0; c < cellCount; c++) { var (x, y) = _activeCells[c]; float armor = grid.Armor[x, y]; float maxArmor = MathF.Max(1f, grid.MaxArmor[x, y]); float temp = grid.Temperature[x, y]; float dmgFrac = 1f - Math.Clamp(armor / maxArmor, 0f, 1f); float cellScorch = Math.Clamp((dmgFrac - 0.18f) / 0.82f, 0f, 1f); float cellHeat = Math.Clamp((temp - 65f) / 110f, 0f, 1f); scorchSum += cellScorch; if (cellHeat > maxHeat) maxHeat = cellHeat; var parts = _cellParts[x, y]; if (!_strippedCells[x, y] && armor <= 0.01f) { _strippedCells[x, y] = true; _hasAnyStrippedCell = true; for (int i = 0; i < parts.Count; i++) { var pb = parts[i]; if (!pb.Detached && GodotObject.IsInstanceValid(pb.Pivot)) { pb.Detached = true; Transform3D worldXf = pb.Pivot.IsInsideTree() ? pb.Pivot.GlobalTransform : ComputeWorldTransformFallback(pb.Pivot); debris.SpawnDetachedPart(pb.Mesh, worldXf, blastOrigin, vehicleVelocity, _roleIndex, impulseScale: 1.0f, applyScorch: true); } } continue; } for (int i = 0; i < parts.Count; i++) { var pb = parts[i]; if (!pb.Detached) { pb.Scorch = cellScorch; pb.HeatGlow = cellHeat; } } } _hullScorch = cellCount > 0 ? Math.Clamp((scorchSum / cellCount) * 0.85f, 0f, 0.85f) : 0f; _hullHeatGlow = maxHeat * 0.72f; // 2. Hardpoint shear & mounted gear heat glow for (int i = 0; i < _hardpointList.Count; i++) { var bh = _hardpointList[i]; if (!_shearedHardpoints.Contains(bh.Spec.Id) && !grid.IsHardpointOperational(bh.Spec)) { _shearedHardpoints.Add(bh.Spec.Id); _hasAnyStrippedCell = true; if (bh.GearNode is not null && GodotObject.IsInstanceValid(bh.GearNode)) { Transform3D worldXf = bh.GearNode.IsInsideTree() ? bh.GearNode.GlobalTransform : ComputeWorldTransformFallback(bh.GearNode); ModularWeaponPartBinding[]? modParts = bh.ModularParts; float mfgRole = bh.ManufacturerRoleIndex; ArrayMesh? gearMesh = bh.GearMesh; Node3D sheared = bh.GearNode; bh.GearNode = null; bh.GearMesh = null; bh.GearTemplate = null; bh.ModularParts = null; bh.ManufacturerRoleIndex = 0f; bh.MountedModuleId = null; bh.HeatGlow = 0f; sheared.GetParent()?.RemoveChild(sheared); sheared.QueueFree(); if (modParts is not null) { for (int p = 0; p < modParts.Length; p++) { debris.SpawnDetachedPart( modParts[p].Mesh, worldXf * modParts[p].LocalToGearPivot, blastOrigin, vehicleVelocity, mfgRole, impulseScale: 1.15f, applyScorch: true); } } else if (gearMesh is not null) { debris.SpawnDetachedPart(gearMesh, worldXf, blastOrigin, vehicleVelocity, _roleIndex, impulseScale: 1.15f, applyScorch: true); } } continue; } if (bh.GearNode is null) { continue; } MountedModule? mounted = grid.GetMountedOn(bh.Spec.Id); bh.HeatGlow = mounted is not null ? Math.Clamp((mounted.CurrentTemp - 65f) / 115f, 0f, 1f) : 0f; } if (t0 != 0) { PerfDamageHeatMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; } } public void SubmitToPool(MultiMeshPartPool pool) { if (!Root.Visible) { return; } Transform3D modelWorld = ModelRoot.IsInsideTree() ? ModelRoot.GlobalTransform : Root.Transform * ModelRoot.Transform; if (_role == VehicleVisualRole.SalvageDrop) { ArrayMesh dropMesh = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; pool.Submit(dropMesh, in modelWorld, new Color(0f, 0f, _roleIndex, 1f), _castShadows); return; } if (_isStaticLod) { pool.Submit(_template.SingleSurfaceLodFarMesh, in modelWorld, new Color(_hullScorch, _hullHeatGlow, _roleIndex, 1f), _castShadows); return; } for (int i = 0; i < _staticParts.Count; i++) { var sp = _staticParts[i]; if (!GodotObject.IsInstanceValid(sp.Pivot)) { continue; } Transform3D xf = ReferenceEquals(sp.Pivot, ModelRoot) ? modelWorld : (sp.Pivot.IsInsideTree() ? sp.Pivot.GlobalTransform : ComputeWorldTransformFallback(sp.Pivot)); pool.Submit(sp.Mesh, in xf, new Color(_hullScorch, _hullHeatGlow, _roleIndex, 1f), _castShadows); } for (int i = 0; i < _allCellParts.Count; i++) { var pb = _allCellParts[i]; if (pb.Detached || !GodotObject.IsInstanceValid(pb.Pivot)) { continue; } Transform3D xf = ReferenceEquals(pb.Pivot, ModelRoot) ? modelWorld : (pb.Pivot.IsInsideTree() ? pb.Pivot.GlobalTransform : ComputeWorldTransformFallback(pb.Pivot)); pool.Submit(pb.Mesh, in xf, new Color(pb.Scorch, pb.HeatGlow, _roleIndex, 1f), wantsShadow: false); } for (int i = 0; i < _hardpointList.Count; i++) { var bh = _hardpointList[i]; if (bh.GearNode is null || !GodotObject.IsInstanceValid(bh.GearNode)) { continue; } Transform3D xf = bh.GearNode.IsInsideTree() ? bh.GearNode.GlobalTransform : ComputeWorldTransformFallback(bh.GearNode); if (bh.ModularParts is { } modParts) { Color custom = new(0f, bh.HeatGlow, bh.ManufacturerRoleIndex, 1f); for (int p = 0; p < modParts.Length; p++) { Transform3D partXf = xf * modParts[p].LocalToGearPivot; pool.Submit(modParts[p].Mesh, in partXf, in custom, wantsShadow: false); } } else if (bh.GearMesh is not null) { pool.Submit(bh.GearMesh, in xf, new Color(0f, bh.HeatGlow, _roleIndex, 1f), wantsShadow: false); } } } /// /// Fast zero-allocation ray intersection against cached far-LOD triangles in space /// so POM impact decals sit flush on sculpted armor surfaces without per-hit GPU mesh readbacks. /// public bool TryRayHitAttachedPart( Vector3 rayOriginWorld, Vector3 rayDirWorld, out Node3D? hitPivot, out Transform3D decalLocalToPivot, float decalSize) { hitPivot = null; decalLocalToPivot = Transform3D.Identity; if (!Root.IsInsideTree() || !ModelRoot.IsInsideTree() || _template.FarRayTris.Length < 3) { return false; } Transform3D modelXf = ModelRoot.GlobalTransform; Transform3D inv = modelXf.AffineInverse(); Vector3 locOrig = inv * rayOriginWorld; Vector3 locDir = inv.Basis * rayDirWorld; float dirLen = locDir.Length(); if (dirLen < 1e-6f) { return false; } locDir /= dirLen; if (!RayIntersectsAabb(_template.FarRayAabb, locOrig, locDir)) { return false; } Vector3[] tris = _template.FarRayTris; float bestT = float.PositiveInfinity; Vector3 bestLocalN = Vector3.Back; for (int t = 0; t + 2 < tris.Length; t += 3) { Vector3 v0 = tris[t]; Vector3 v1 = tris[t + 1]; Vector3 v2 = tris[t + 2]; if (RayTriangle(locOrig, locDir, v0, v1, v2, out float hitT) && hitT < bestT) { Vector3 fn = (v1 - v0).Cross(v2 - v0); if (fn.LengthSquared() > 1e-10f) { fn = fn.Normalized(); if (fn.Dot(-locDir) < 0f) fn = -fn; bestT = hitT; bestLocalN = fn; } } } if (!float.IsFinite(bestT)) { return false; } Vector3 hitWorld = modelXf * (locOrig + locDir * bestT); Vector3 normalWorld = (modelXf.Basis.Inverse().Transposed() * bestLocalN).Normalized(); Vector3 upRef = MathF.Abs(normalWorld.Y) > 0.92f ? Vector3.Forward : Vector3.Up; Vector3 right = upRef.Cross(normalWorld).Normalized(); Vector3 up = normalWorld.Cross(right).Normalized(); Transform3D worldDecalXf = new(new Basis(right * decalSize, up * decalSize, normalWorld), hitWorld); hitPivot = ModelRoot; decalLocalToPivot = inv * worldDecalXf; return true; } private Node3D CreateGearPivotForHardpoint( ModuleSpec mod, HardpointSpec hp, VehicleAssetCache.GlbAnchorInfo anchorInfo, out ArrayMesh gearMesh, out VehicleAssetCache.GearTemplate gearTemplate) { GearVisualRecipe recipe = ResolveGearRecipe(mod); gearTemplate = _cache.GetOrLoadGear(recipe.GearGlbId); gearMesh = _cache.GetOrBuildGearVariantMesh(mod.Id, recipe.GearGlbId, recipe.PaintTint, recipe.AccentTint); Transform3D xf = ComputeHardpointMountTransform( hp, anchorInfo, recipe.VariantScale, gearTemplate.LocalModelForward.Z, gearTemplate.MinY); return new Node3D { Name = $"Mounted_{mod.Id}_{hp.Id}", Transform = xf }; } private static Transform3D ComputeHardpointMountTransform( HardpointSpec hp, VehicleAssetCache.GlbAnchorInfo anchorInfo, Vector3 variantScale, float localModelForwardZ, float minY) { 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) { 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 { 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; } } Vector3 rightX = upOut.Cross(desiredGearFwd); rightX = rightX.LengthSquared() < 1e-5f ? Vector3.Right : rightX.Normalized(); desiredGearFwd = rightX.Cross(upOut).Normalized(); var desiredModelBasis = new Basis(rightX, upOut, desiredGearFwd); if (localModelForwardZ < 0f) { desiredModelBasis *= new Basis(Vector3.Up, MathF.PI); } Basis localBasis = anchorModelBasis.Inverse() * desiredModelBasis; 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 = 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( variantScale.X * scaleX, variantScale.Y * scaleY, variantScale.Z * scaleZ); } Basis finalBasis = localBasis * Basis.FromScale(fitScale); float ySeat = -minY * fitScale.Y; Vector3 pos = (anchorModelBasis.Inverse() * upOut) * ySeat; return new Transform3D(finalBasis, pos); } 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), "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 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); } } private Transform3D ComputeWorldTransformFallback(Node3D node) { Transform3D xf = Transform3D.Identity; for (Node? cur = node; cur is Node3D n3d; cur = cur.GetParent()) { xf = n3d.Transform * xf; if (ReferenceEquals(cur, Root)) { break; } } return xf; } private static Transform3D ComputeRelativeTransform(Node3D node, Node3D ancestor) { Transform3D xf = Transform3D.Identity; for (Node? cur = node; cur is Node3D n3d && !ReferenceEquals(cur, ancestor); cur = cur.GetParent()) { xf = n3d.Transform * xf; } return xf; } /// /// Computes the highest rendered vertex Y in local space across active rigid parts /// and all currently mounted gear meshes. /// public float ComputeMountedMaxY() { float maxY = float.NegativeInfinity; if (_role == VehicleVisualRole.SalvageDrop) { ArrayMesh m = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; AccumulateMeshMinMaxY(m, ModelRoot.Transform, out _, out maxY); return float.IsFinite(maxY) ? maxY : ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; } for (int i = 0; i < _staticParts.Count; i++) { AccumulateMeshMinMaxY(_staticParts[i].Mesh, ComputeRelativeTransform(_staticParts[i].Pivot, Root), out _, out float pyMax); if (pyMax > maxY) maxY = pyMax; } for (int i = 0; i < _allCellParts.Count; i++) { var pb = _allCellParts[i]; if (!pb.Detached) { AccumulateMeshMinMaxY(pb.Mesh, ComputeRelativeTransform(pb.Pivot, Root), out _, out float cyMax); if (cyMax > maxY) maxY = cyMax; } } for (int i = 0; i < _hardpointList.Count; i++) { var bh = _hardpointList[i]; if (bh.GearNode is null || !GodotObject.IsInstanceValid(bh.GearNode)) { continue; } Transform3D gearRel = ComputeRelativeTransform(bh.GearNode, Root); if (bh.ModularParts is { } modParts) { for (int p = 0; p < modParts.Length; p++) { AccumulateMeshMinMaxY(modParts[p].Mesh, gearRel * modParts[p].LocalToGearPivot, out _, out float pyMax); if (pyMax > maxY) maxY = pyMax; } } else if (bh.GearMesh is not null) { AccumulateMeshMinMaxY(bh.GearMesh, gearRel, out _, out float gyMax); if (gyMax > maxY) maxY = gyMax; } } return float.IsFinite(maxY) ? maxY : ModelRoot.Position.Y + _template.MaxY * ModelRoot.Scale.Y; } /// /// Computes the lowest rendered vertex Y in world/parent space (or space if ). /// public float ComputeMinVertexY(float baseWorldY = 0f, bool relativeToModelRoot = false) { float minY = float.PositiveInfinity; Transform3D rootBase = relativeToModelRoot ? Transform3D.Identity : new Transform3D(Basis.Identity, new Vector3(0f, baseWorldY, 0f)) * Root.Transform; if (_role == VehicleVisualRole.SalvageDrop) { ArrayMesh m = _isStaticLod ? _template.SingleSurfaceLodFarMesh : _template.SingleSurfaceStaticMesh; Transform3D xf = relativeToModelRoot ? Transform3D.Identity : rootBase * ModelRoot.Transform; AccumulateMeshMinMaxY(m, xf, out minY, out _); return minY; } Node3D relTarget = relativeToModelRoot ? ModelRoot : Root; Transform3D baseXf = relativeToModelRoot ? Transform3D.Identity : rootBase; for (int i = 0; i < _staticParts.Count; i++) { Transform3D xf = baseXf * ComputeRelativeTransform(_staticParts[i].Pivot, relTarget); AccumulateMeshMinMaxY(_staticParts[i].Mesh, xf, out float pyMin, out _); if (pyMin < minY) minY = pyMin; } for (int i = 0; i < _allCellParts.Count; i++) { var pb = _allCellParts[i]; if (!pb.Detached) { Transform3D xf = baseXf * ComputeRelativeTransform(pb.Pivot, relTarget); AccumulateMeshMinMaxY(pb.Mesh, xf, out float cyMin, out _); if (cyMin < minY) minY = cyMin; } } return minY; } private static void AccumulateMeshMinMaxY(ArrayMesh mesh, Transform3D xform, out float minY, out float maxY) { minY = float.PositiveInfinity; maxY = float.NegativeInfinity; int surfCount = mesh.GetSurfaceCount(); 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) { continue; } Vector3[] verts = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array(); for (int v = 0; v < verts.Length; v++) { float wy = (xform * verts[v]).Y; if (wy < minY) minY = wy; if (wy > maxY) maxY = wy; } } } private static bool RayIntersectsAabb(Aabb aabb, Vector3 orig, Vector3 dir) { Vector3 min = aabb.Position; Vector3 max = aabb.End; float tmin = float.NegativeInfinity; float tmax = float.PositiveInfinity; for (int axis = 0; axis < 3; axis++) { float o = orig[axis]; float d = dir[axis]; if (MathF.Abs(d) < 1e-7f) { if (o < min[axis] || o > max[axis]) return false; } else { float inv = 1f / d; float t1 = (min[axis] - o) * inv; float t2 = (max[axis] - o) * inv; if (t1 > t2) (t1, t2) = (t2, t1); tmin = MathF.Max(tmin, t1); tmax = MathF.Min(tmax, t2); if (tmin > tmax) return false; } } return tmax >= 0f; } private static bool RayTriangle(Vector3 orig, Vector3 dir, Vector3 v0, Vector3 v1, Vector3 v2, out float t) { t = 0f; Vector3 e1 = v1 - v0; Vector3 e2 = v2 - v0; Vector3 pvec = dir.Cross(e2); float det = e1.Dot(pvec); if (MathF.Abs(det) < 1e-7f) return false; float invDet = 1f / det; Vector3 tvec = orig - v0; float u = tvec.Dot(pvec) * invDet; if (u < 0f || u > 1f) return false; Vector3 qvec = tvec.Cross(e1); float v = dir.Dot(qvec) * invDet; if (v < 0f || u + v > 1f) return false; t = e2.Dot(qvec) * invDet; return t > 0.01f; } }