using System; using System.Collections.Generic; using Godot; using RustToDust.Core; using RustToDust.Ymir; namespace RustToDust.Client; /// /// Client-side kinematic mirror of active projectiles, loitering drones, /// proximity mines, and thermal pools driven strictly by [Union(13)] /// (identical behavior in Solo and RemoteClient multiplayer, zero per-projectile s, /// zero material clones). /// public sealed class ClientOrdnanceMirror { public const int PoolCapacity = OrdnanceRuntime.PoolCapacity; public readonly record struct TransientVfxSpec( bool IsSphere, Vector3 Position, Vector3 Velocity, Basis Rotation, Vector3 StartScale, Vector3 EndScale, Color ColorStart, Color ColorEnd, float Lifetime); private struct MirroredSlot { public bool Active; public int OrdnanceId; public int ParentOrdnanceId; public ProceduralWeaponKey? WeaponKey; public byte NodeDefIndex; public OrdnanceNodeDef? Def; public OrdnanceVisualShape VisualShape; public Color Color; public float ManufacturerRoleIndex; public Vector3 Pos; public Vector3 Vel; public Vector3 AnchorPos; public int TargetEntityId; public bool TargetIsSpectator; public float Age; public float StageAge; public float OrbitAngle; public float TrailTimer; public float EmberTimer; public bool Armed; } private readonly MirroredSlot[] _slots = new MirroredSlot[PoolCapacity]; private readonly Dictionary _slotById = new(PoolCapacity); private int _activeCount; public int ActiveCount => _activeCount; public void Clear() { Array.Clear(_slots, 0, _slots.Length); _slotById.Clear(); _activeCount = 0; } public bool TryGetMirroredPose(int ordnanceId, out Vector3 pos, out OrdnanceVisualShape shape) { if (_slotById.TryGetValue(ordnanceId, out int idx) && _slots[idx].Active) { pos = _slots[idx].Pos; shape = _slots[idx].VisualShape; return true; } pos = Vector3.Zero; shape = OrdnanceVisualShape.None; return false; } public void ConsumeEvents( IReadOnlyList events, VehicleAssetCache cache, DebrisSystem debris, ParticlePool particles, bool hasCam, Vector3 camPos, Action emitTransient) { for (int i = 0; i < events.Count; i++) { if (events[i] is MatchResetEvent) { Clear(); continue; } if (events[i] is not OrdnanceNodeEvent ev) { continue; } var kind = (OrdnanceEventKind)ev.Kind; Vector3 pos = new(ev.PosX, ev.PosY, ev.PosZ); Vector3 vel = new(ev.VelX, ev.VelY, ev.VelZ); Color col = DecodeColorRgba(ev.ColorRgba); OrdnanceNodeDef? def = ResolveNodeDef(ev.WeaponKey, ev.NodeDefIndex); var shape = (OrdnanceVisualShape)ev.VisualShape; if (shape == OrdnanceVisualShape.None && def is not null) { shape = def.VisualShape; } switch (kind) { case OrdnanceEventKind.Spawned: UpsertSlot(ev, pos, vel, col, def, shape); break; case OrdnanceEventKind.StageTransition: { bool wasSabot = false; if (ev.ParentOrdnanceId != 0 && _slotById.TryGetValue(ev.ParentOrdnanceId, out int parentIdx) && _slots[parentIdx].Active) { wasSabot = _slots[parentIdx].VisualShape == OrdnanceVisualShape.SabotCarrier; RemoveAtSlot(parentIdx); } UpsertSlot(ev, pos, vel, col, def, shape); if (wasSabot) { float roleIdx = ev.WeaponKey is { } wk ? 10f + Math.Clamp((int)wk.Manufacturer, 0, 4) : 11f; var petalTpl = cache.GetOrLoadWeaponPart("mz_slotted_brake"); Vector3 dir = vel.LengthSquared() > 1e-3f ? vel.Normalized() : Vector3.Forward; Vector3 right = dir.Cross(Vector3.Up); if (right.LengthSquared() < 1e-4f) right = Vector3.Right; right = right.Normalized(); for (int side = -1; side <= 1; side += 2) { Vector3 pPos = pos + right * (side * 0.28f); Transform3D petalXf = new(Basis.FromScale(Vector3.One * 0.65f), pPos); debris.SpawnDetachedPart( petalTpl.SingleSurfaceMesh, petalXf, pos - right * (side * 0.45f), vel * 0.35f, roleIdx, impulseScale: 0.75f, applyScorch: true, lifetime: 2.2f); } particles.EmitOrdnanceBurst(pos, col, sparkCount: 4, radiusScale: 0.65f, camPos, hasCam); } else if (def?.Motion == OrdnanceMotion.LoiterOrbit) { emitTransient(new TransientVfxSpec( IsSphere: false, Position: pos, Velocity: Vector3.Zero, Rotation: Basis.Identity, StartScale: new Vector3(0.6f, 1.0f, 0.6f), EndScale: new Vector3(3.6f, 0.5f, 3.6f), ColorStart: (col * 2.4f) with { A = 0.85f }, ColorEnd: col with { A = 0f }, Lifetime: 0.30f)); } break; } case OrdnanceEventKind.Split: RemoveById(ev.OrdnanceId); particles.EmitOrdnanceBurst(pos, col, sparkCount: 6, radiusScale: 1.05f, camPos, hasCam); emitTransient(new TransientVfxSpec( IsSphere: false, Position: pos, Velocity: Vector3.Zero, Rotation: Basis.Identity, StartScale: new Vector3(0.7f, 1.0f, 0.7f), EndScale: new Vector3(5.2f, 0.5f, 5.2f), ColorStart: (col * 2.8f) with { A = 0.92f }, ColorEnd: col with { A = 0f }, Lifetime: 0.28f)); break; case OrdnanceEventKind.Detonated: { RemoveById(ev.OrdnanceId); float splashR = def is not null && def.SplashRadius > 0.5f ? def.SplashRadius : 4.2f; particles.EmitOrdnanceBurst(pos, col, sparkCount: 6, radiusScale: Math.Clamp(splashR / 4.5f, 0.7f, 1.6f), camPos, hasCam); emitTransient(new TransientVfxSpec( IsSphere: true, Position: pos + Vector3.Up * 0.2f, Velocity: Vector3.Up * 1.2f, Rotation: Basis.Identity, StartScale: Vector3.One * 0.55f, EndScale: Vector3.One * Math.Clamp(splashR * 0.75f, 1.8f, 4.8f), ColorStart: new Color(col.R * 3.2f, col.G * 3.2f, col.B * 3.2f, 0.92f), ColorEnd: new Color(col.R * 0.8f, col.G * 0.3f, col.B * 0.2f, 0f), Lifetime: 0.26f)); emitTransient(new TransientVfxSpec( IsSphere: false, Position: pos + Vector3.Up * 0.16f, Velocity: Vector3.Zero, Rotation: Basis.Identity, StartScale: new Vector3(0.7f, 1f, 0.7f), EndScale: new Vector3(Math.Clamp(splashR * 1.35f, 2.8f, 8.5f), 0.4f, Math.Clamp(splashR * 1.35f, 2.8f, 8.5f)), ColorStart: new Color(col.R * 2.9f, col.G * 2.9f, col.B * 2.9f, 0.90f), ColorEnd: col with { A = 0f }, Lifetime: 0.30f)); break; } case OrdnanceEventKind.Intercepted: RemoveById(ev.OrdnanceId); particles.EmitOrdnanceBurst(pos, new Color(1.0f, 0.75f, 0.28f), sparkCount: 5, radiusScale: 0.7f, camPos, hasCam); break; case OrdnanceEventKind.Expired: RemoveById(ev.OrdnanceId); break; } } } public void StepAndSubmit( float dt, IClientArenaSession session, VehicleAssetCache cache, MultiMeshPartPool partPool, ParticlePool particles, TerrainField terrain, bool hasCam, Vector3 camPos, Action submitActiveRing, Action submitActiveSphere) { if (_activeCount == 0) { return; } float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; var state = session.ViewState; var sabotMesh = cache.GetOrLoadWeaponPart("brl_sabot_rail").SingleSurfaceMesh; var rocketMesh = cache.GetOrLoadWeaponPart("mz_mirv_warhead").SingleSurfaceMesh; var droneMesh = cache.GetOrLoadWeaponPart("mz_loiter_aero_fin").SingleSurfaceMesh; var brakeMesh = cache.GetOrLoadWeaponPart("mz_slotted_brake").SingleSurfaceMesh; for (int i = 0; i < PoolCapacity; i++) { if (!_slots[i].Active) { continue; } ref MirroredSlot s = ref _slots[i]; var def = s.Def; float maxLife = def is not null && def.MaxLifetime > 0f ? def.MaxLifetime : 30f; if (stepDt > 0f) { s.Age += stepDt; s.StageAge += stepDt; if (s.Age > maxLife + 2.5f) { RemoveAtSlot(i); continue; } if (def is not null && !s.Armed && s.StageAge >= def.ArmDelay) { s.Armed = true; } AdvanceSlotKinematics(ref s, def, state, terrain, stepDt); } if (hasCam && s.Pos.DistanceSquaredTo(camPos) > 340f * 340f) { continue; } bool isThermalPool = (def?.IsThermalPool == true) || s.VisualShape == OrdnanceVisualShape.Pool; if (isThermalPool) { float radius = def is not null && def.WhileAlive is { RadialRadius: > 0.5f } ? def.WhileAlive.RadialRadius : (def is not null && def.SplashRadius > 0.5f ? def.SplashRadius : 5.5f); float pulse = 0.88f + 0.14f * MathF.Sin(s.StageAge * 7.5f + s.OrdnanceId); float groundY = terrain.SampleHeight(s.Pos.X, s.Pos.Z); Vector3 poolPos = new(s.Pos.X, MathF.Max(s.Pos.Y, groundY + 0.14f), s.Pos.Z); Transform3D ringXf = new(Basis.FromScale(new Vector3(radius * 2f * pulse, 0.35f, radius * 2f * pulse)), poolPos); submitActiveRing(ringXf, new Color(s.Color.R * 2.6f, s.Color.G * 2.6f, s.Color.B * 2.6f, 0.78f)); Transform3D discXf = new(Basis.FromScale(new Vector3(radius * 1.4f * pulse, 0.14f, radius * 1.4f * pulse)), poolPos - new Vector3(0f, 0.04f, 0f)); submitActiveSphere(discXf, new Color(s.Color.R * 2.1f, s.Color.G * 2.1f, s.Color.B * 2.1f, 0.42f)); if (stepDt > 0f) { s.EmberTimer += stepDt; if (s.EmberTimer >= 0.11f) { s.EmberTimer = 0f; particles.EmitThermalPoolEmber(poolPos, radius, s.Color, camPos, hasCam); } } continue; } if (s.VisualShape == OrdnanceVisualShape.Mine || def?.Motion == OrdnanceMotion.StationaryMine) { float groundY = terrain.SampleHeight(s.Pos.X, s.Pos.Z); Vector3 minePos = new(s.Pos.X, MathF.Max(s.Pos.Y, groundY + 0.10f), s.Pos.Z); Basis upright = new Basis(Vector3.Right, -MathF.PI * 0.5f) * Basis.FromScale(Vector3.One * 1.05f); Transform3D mineXf = new(upright, minePos); float blink = s.Armed ? (0.45f + 0.55f * MathF.Max(0f, MathF.Sin(s.StageAge * 9.5f + s.OrdnanceId))) : 0f; partPool.Submit(rocketMesh, in mineXf, new Color(0f, blink * 0.6f, s.ManufacturerRoleIndex, 1f), wantsShadow: false); if (s.Armed) { float proxR = def is not null && def.ProximityRadius > 0.5f ? def.ProximityRadius : 6.0f; float ringPulse = 0.92f + 0.08f * MathF.Sin(s.StageAge * 6f); Transform3D warnXf = new(Basis.FromScale(new Vector3(proxR * 0.55f * ringPulse, 0.18f, proxR * 0.55f * ringPulse)), minePos + new Vector3(0f, 0.08f, 0f)); submitActiveRing(warnXf, new Color(s.Color.R * 2.2f, s.Color.G * 2.2f, s.Color.B * 2.2f, 0.25f + 0.35f * blink)); } continue; } if (s.VisualShape == OrdnanceVisualShape.Drone || def?.Motion == OrdnanceMotion.LoiterOrbit) { Vector3 dir = s.Vel.LengthSquared() > 1e-3f ? s.Vel.Normalized() : Vector3.Forward; Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; Basis orient = Basis.LookingAt(-dir, up); if (def?.Motion == OrdnanceMotion.LoiterOrbit) { orient *= new Basis(Vector3.Forward, 0.32f); } Transform3D droneXf = new(orient * Basis.FromScale(Vector3.One * 2.4f), s.Pos); partPool.Submit(droneMesh, in droneXf, new Color(0f, 0.35f, s.ManufacturerRoleIndex, 1f), wantsShadow: false); if (def?.Motion == OrdnanceMotion.LoiterOrbit) { float scanPulse = 0.85f + 0.15f * MathF.Sin(s.StageAge * 8f); Transform3D haloXf = new(Basis.FromScale(new Vector3(2.4f * scanPulse, 0.25f, 2.4f * scanPulse)), s.Pos - new Vector3(0f, 0.45f, 0f)); submitActiveRing(haloXf, new Color(s.Color.R * 2.5f, s.Color.G * 2.5f, s.Color.B * 2.5f, 0.58f)); } if (stepDt > 0f) { s.TrailTimer += stepDt; if (s.TrailTimer >= 0.055f) { s.TrailTimer = 0f; particles.EmitOrdnanceTrail(s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit, camPos, hasCam); } } continue; } // Rocket, SabotCarrier, or Bolt projectile in flight { Vector3 dir = s.Vel.LengthSquared() > 1e-3f ? s.Vel.Normalized() : Vector3.Forward; Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; Basis orient = Basis.LookingAt(-dir, up); ArrayMesh projMesh = s.VisualShape switch { OrdnanceVisualShape.SabotCarrier => sabotMesh, OrdnanceVisualShape.Rocket => rocketMesh, _ => brakeMesh }; float projScale = s.VisualShape switch { OrdnanceVisualShape.SabotCarrier => 1.15f, OrdnanceVisualShape.Rocket => 1.55f, _ => 1.0f }; Transform3D projXf = new(orient * Basis.FromScale(Vector3.One * projScale), s.Pos); bool isRocket = s.VisualShape == OrdnanceVisualShape.Rocket || def?.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile; partPool.Submit(projMesh, in projXf, new Color(0f, isRocket ? 0.65f : 0.25f, s.ManufacturerRoleIndex, 1f), wantsShadow: false); if (isRocket) { Transform3D thrusterXf = new(Basis.FromScale(Vector3.One * 0.42f), s.Pos - dir * 0.22f); submitActiveSphere(thrusterXf, new Color(s.Color.R * 3.2f, s.Color.G * 3.2f, s.Color.B * 3.2f, 0.90f)); } if (stepDt > 0f) { s.TrailTimer += stepDt; if (s.TrailTimer >= (isRocket ? 0.035f : 0.055f)) { s.TrailTimer = 0f; particles.EmitOrdnanceTrail(s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket, camPos, hasCam); } } } } } private static void AdvanceSlotKinematics( ref MirroredSlot s, OrdnanceNodeDef? def, MatchState state, TerrainField terrain, float dt) { OrdnanceMotion motion = def?.Motion ?? OrdnanceMotion.Ballistic; switch (motion) { case OrdnanceMotion.Ballistic: s.Vel.Y -= 19.6f * (def?.GravityScale ?? 1f) * dt; s.Pos += s.Vel * dt; break; case OrdnanceMotion.RocketBoosted: { float burnTime = def?.BurnTime ?? 1.4f; if (s.StageAge <= burnTime && (def?.ThrustAccel ?? 0f) > 0f) { Vector3 dir = s.Vel.LengthSquared() > 1e-4f ? s.Vel.Normalized() : Vector3.Forward; float speed = s.Vel.Length(); float maxSpd = def!.MaxSpeed > 0f ? def.MaxSpeed : 360f; float nextSpd = MathF.Min(maxSpd, speed + def.ThrustAccel * dt); s.Vel = dir * nextSpd; } else { s.Vel.Y -= 19.6f * (def?.GravityScale ?? 0.25f) * dt; } s.Pos += s.Vel * dt; break; } case OrdnanceMotion.HomingMissile: { if (s.TargetEntityId >= 0) { Vector3 targetPt = Vector3.Zero; bool hasTarget = false; if (!s.TargetIsSpectator && s.TargetEntityId < state.Contenders.Count) { var tc = state.Contenders[s.TargetEntityId]; if (tc.IsGroundedActive) { targetPt = new Vector3(tc.X, tc.Y + tc.Grid.Spec.HalfHeight * 0.35f, tc.Z); hasTarget = true; } } else if (s.TargetIsSpectator) { for (int k = 0; k < state.Spectators.Spectators.Count; k++) { var sp = state.Spectators.Spectators[k]; if (sp.Id == s.TargetEntityId && sp.Alive) { targetPt = new Vector3(sp.X, sp.Y + sp.Grid.Spec.HalfHeight * 0.35f, sp.Z); hasTarget = true; break; } } } if (hasTarget && (targetPt - s.Pos).LengthSquared() > 1e-3f) { Vector3 desiredDir = (targetPt - s.Pos).Normalized(); Vector3 curDir = s.Vel.LengthSquared() > 1e-4f ? s.Vel.Normalized() : desiredDir; float maxTurn = (def?.TurnRateRad ?? 4.5f) * dt; float dot = Math.Clamp(curDir.Dot(desiredDir), -1f, 1f); float angle = MathF.Acos(dot); Vector3 newDir = angle <= maxTurn || angle < 1e-4f ? desiredDir : curDir.Lerp(desiredDir, maxTurn / angle).Normalized(); float spd = s.Vel.Length(); float maxSpd = def is not null && def.MaxSpeed > 0f ? def.MaxSpeed : MathF.Max(spd, 115f); spd = MathF.Min(maxSpd, spd + (def?.ThrustAccel ?? 90f) * dt); s.Vel = newDir * spd; } } s.Pos += s.Vel * dt; break; } case OrdnanceMotion.LoiterOrbit: { float orbitSpeed = def?.LoiterOrbitSpeedRad ?? 1.45f; float radius = def?.LoiterOrbitRadius ?? 15f; float agl = def?.LoiterAltitudeAgl ?? 35f; s.OrbitAngle += orbitSpeed * dt; float ox = s.AnchorPos.X + MathF.Cos(s.OrbitAngle) * radius; float oz = s.AnchorPos.Z + MathF.Sin(s.OrbitAngle) * radius; float oy = terrain.SampleHeight(ox, oz) + agl; Vector3 nextPos = new(ox, oy, oz); s.Vel = (nextPos - s.Pos) / MathF.Max(1e-4f, dt); s.Pos = nextPos; break; } case OrdnanceMotion.StationaryMine: break; } } private void UpsertSlot( OrdnanceNodeEvent ev, Vector3 pos, Vector3 vel, Color col, OrdnanceNodeDef? def, OrdnanceVisualShape shape) { if (_slotById.TryGetValue(ev.OrdnanceId, out int existing)) { ref var slot = ref _slots[existing]; slot.Pos = pos; slot.Vel = vel; slot.AnchorPos = pos; slot.TargetEntityId = ev.TargetEntityId; slot.TargetIsSpectator = ev.TargetIsSpectator; slot.Def = def; slot.VisualShape = shape; slot.Color = col; return; } int freeIdx = -1; for (int i = 0; i < PoolCapacity; i++) { if (!_slots[i].Active) { freeIdx = i; break; } } if (freeIdx < 0) { // Evict oldest slot to stay strictly bounded under PoolCapacity float maxAge = -1f; int oldest = 0; for (int i = 0; i < PoolCapacity; i++) { if (_slots[i].Age > maxAge) { maxAge = _slots[i].Age; oldest = i; } } RemoveAtSlot(oldest); freeIdx = oldest; } float mfgRole = ev.WeaponKey is { } wk ? 10f + Math.Clamp((int)wk.Manufacturer, 0, 4) : 5f; _slots[freeIdx] = new MirroredSlot { Active = true, OrdnanceId = ev.OrdnanceId, ParentOrdnanceId = ev.ParentOrdnanceId, WeaponKey = ev.WeaponKey, NodeDefIndex = ev.NodeDefIndex, Def = def, VisualShape = shape, Color = col, ManufacturerRoleIndex = mfgRole, Pos = pos, Vel = vel, AnchorPos = pos, TargetEntityId = ev.TargetEntityId, TargetIsSpectator = ev.TargetIsSpectator, Age = 0f, StageAge = 0f, OrbitAngle = 0f, TrailTimer = 0f, EmberTimer = 0f, Armed = def is null || def.ArmDelay <= 0f }; _slotById[ev.OrdnanceId] = freeIdx; _activeCount++; } private void RemoveById(int ordnanceId) { if (_slotById.TryGetValue(ordnanceId, out int idx)) { RemoveAtSlot(idx); } } private void RemoveAtSlot(int idx) { if (!_slots[idx].Active) { return; } _slotById.Remove(_slots[idx].OrdnanceId); _slots[idx] = default; _activeCount = Math.Max(0, _activeCount - 1); } private static OrdnanceNodeDef? ResolveNodeDef(ProceduralWeaponKey? key, byte nodeDefIndex) { if (!key.HasValue) { return null; } var spec = ProceduralWeaponGenerator.Generate(key.Value); if (nodeDefIndex < spec.FlattenedNodes.Length) { return spec.FlattenedNodes[nodeDefIndex]; } return spec.RootNode; } private static Color DecodeColorRgba(uint rgba) { if (rgba == 0) { return new Color(1.0f, 0.72f, 0.28f, 1.0f); } float r = ((rgba >> 24) & 0xFF) / 255f; float g = ((rgba >> 16) & 0xFF) / 255f; float b = ((rgba >> 8) & 0xFF) / 255f; return new Color(r, g, b, 1.0f); } }