using System; using System.Collections.Generic; using Godot; using RustToDust.Core; namespace RustToDust.Client; /// /// Manages physically detached armor plates and sheared hardpoint gear as tumbling, /// terrain-bouncing debris pieces that settle and fade out cleanly after 8 seconds. /// public partial class DebrisSystem : Node3D { private const float Gravity = -20f; private const float DefaultLifetime = 8.0f; private const float FadeDuration = 2.0f; private const int MaxActiveDebris = 256; private sealed class DebrisPiece { public required Node3D Node; public required Vector3 Velocity; public required Vector3 AngularVelocity; public required List FadeMaterials; public required float[] BaseAlphas; public float Age; public float Lifetime; public bool Settled; } private readonly List _pieces = new(); private uint _rngState = 0x9E3779B9u; public int ActiveCount => _pieces.Count; public void ClearAll() { for (int i = 0; i < _pieces.Count; i++) { if (GodotObject.IsInstanceValid(_pieces[i].Node)) { _pieces[i].Node.QueueFree(); } } _pieces.Clear(); for (int i = GetChildCount() - 1; i >= 0; i--) { Node ch = GetChild(i); RemoveChild(ch); ch.QueueFree(); } } /// /// Reparents from its vehicle hierarchy at its exact world transform /// into and launches it with an outward blast impulse and tumble. /// public void SpawnDetachedPart( Node3D part, Vector3 blastOriginWorld, Vector3 inheritedVelocity, float impulseScale = 1.0f, bool applyScorch = true) { if (!GodotObject.IsInstanceValid(part)) { return; } // Evict oldest settled or oldest piece if we hit the cap so debris never leaks indefinitely while (_pieces.Count >= MaxActiveDebris) { RemoveAt(0); } Transform3D worldXform = part.IsInsideTree() ? part.GlobalTransform : part.Transform; Node? oldParent = part.GetParent(); oldParent?.RemoveChild(part); AddChild(part); if (part.IsInsideTree() && IsInsideTree()) { part.GlobalTransform = worldXform; } else { part.Transform = worldXform; } Vector3 outward = worldXform.Origin - blastOriginWorld; outward.Y = 0f; if (outward.LengthSquared() < 1e-4f) { float ang = NextFloat() * MathF.Tau; outward = new Vector3(MathF.Cos(ang), 0f, MathF.Sin(ang)); } else { outward = outward.Normalized(); } float horizSpeed = (4.2f + NextFloat() * 4.8f) * impulseScale; float upSpeed = (4.0f + NextFloat() * 4.5f) * impulseScale; Vector3 vel = inheritedVelocity * 0.45f + outward * horizSpeed + Vector3.Up * upSpeed; Vector3 angVel = new( (NextFloat() * 2f - 1f) * 7.5f, (NextFloat() * 2f - 1f) * 7.5f, (NextFloat() * 2f - 1f) * 7.5f); var fadeMats = new List(); PrepareInstanceMaterials(part, fadeMats, applyScorch); var baseAlphas = new float[fadeMats.Count]; for (int i = 0; i < fadeMats.Count; i++) { baseAlphas[i] = fadeMats[i].AlbedoColor.A; } _pieces.Add(new DebrisPiece { Node = part, Velocity = vel, AngularVelocity = angVel, FadeMaterials = fadeMats, BaseAlphas = baseAlphas, Age = 0f, Lifetime = DefaultLifetime, Settled = false }); } public void Step(float dt, TerrainField terrain) { if (dt <= 0f || !float.IsFinite(dt)) { return; } float stepDt = Math.Clamp(dt, 0f, 0.05f); for (int i = _pieces.Count - 1; i >= 0; i--) { DebrisPiece p = _pieces[i]; if (!GodotObject.IsInstanceValid(p.Node)) { _pieces.RemoveAt(i); continue; } p.Age += stepDt; if (p.Age >= p.Lifetime) { RemoveAt(i); continue; } if (!p.Settled) { p.Velocity += new Vector3(0f, Gravity * stepDt, 0f); Vector3 pos = p.Node.Position + p.Velocity * stepDt; Basis basis = p.Node.Basis; float spinLen = p.AngularVelocity.Length(); if (spinLen > 1e-4f) { basis = new Basis(p.AngularVelocity / spinLen, spinLen * stepDt) * basis; basis = basis.Orthonormalized(); } float floorY = terrain.SampleHeight(pos.X, pos.Z) + 0.10f; if (pos.Y <= floorY) { pos.Y = floorY; if (p.Velocity.Y < -1.4f) { p.Velocity = new Vector3( p.Velocity.X * 0.62f, -p.Velocity.Y * 0.32f, p.Velocity.Z * 0.62f); p.AngularVelocity *= 0.55f; } else { p.Velocity = Vector3.Zero; p.AngularVelocity = Vector3.Zero; p.Settled = true; } } p.Node.Position = pos; p.Node.Basis = basis; } // Smooth alpha fade during final 2 seconds float remaining = p.Lifetime - p.Age; if (remaining < FadeDuration) { float alphaFrac = Math.Clamp(remaining / FadeDuration, 0f, 1f); for (int m = 0; m < p.FadeMaterials.Count; m++) { StandardMaterial3D sm = p.FadeMaterials[m]; if (sm.Transparency == BaseMaterial3D.TransparencyEnum.Disabled) { sm.Transparency = BaseMaterial3D.TransparencyEnum.Alpha; } Color col = sm.AlbedoColor; col.A = p.BaseAlphas[m] * alphaFrac; sm.AlbedoColor = col; } } } } private void RemoveAt(int index) { DebrisPiece p = _pieces[index]; _pieces.RemoveAt(index); if (GodotObject.IsInstanceValid(p.Node)) { if (p.Node.GetParent() == this) { RemoveChild(p.Node); } p.Node.QueueFree(); } } private static void PrepareInstanceMaterials(Node cur, List outMats, bool applyScorch) { if (cur is MeshInstance3D mi && mi.Mesh is not null) { if (mi.MaterialOverride is StandardMaterial3D ov) { var copy = (StandardMaterial3D)ov.Duplicate(); if (applyScorch) { ApplyScorchTint(copy); } mi.MaterialOverride = copy; outMats.Add(copy); } else { int surfCount = mi.Mesh.GetSurfaceCount(); for (int s = 0; s < surfCount; s++) { Material? src = mi.GetActiveMaterial(s); StandardMaterial3D copy = src is StandardMaterial3D sm ? (StandardMaterial3D)sm.Duplicate() : new StandardMaterial3D { AlbedoColor = new Color(0.28f, 0.25f, 0.23f), Roughness = 0.78f, Metallic = 0.45f }; if (applyScorch) { ApplyScorchTint(copy); } mi.SetSurfaceOverrideMaterial(s, copy); outMats.Add(copy); } } } int count = cur.GetChildCount(); for (int i = 0; i < count; i++) { PrepareInstanceMaterials(cur.GetChild(i), outMats, applyScorch); } } private static void ApplyScorchTint(StandardMaterial3D mat) { Color c = mat.AlbedoColor; mat.AlbedoColor = new Color(c.R * 0.42f + 0.04f, c.G * 0.36f + 0.03f, c.B * 0.34f + 0.02f, c.A); mat.Roughness = MathF.Max(mat.Roughness, 0.78f); mat.EmissionEnabled = true; mat.Emission = new Color(0.95f, 0.32f, 0.06f); mat.EmissionEnergyMultiplier = 0.35f; } private float NextFloat() { uint x = _rngState; x ^= x << 13; x ^= x >> 17; x ^= x << 5; _rngState = x; return (x & 0x00FFFFFFu) / 16777216f; } }