diff --git a/assets/vehicles/drop_pod/drop_pod.glb b/assets/vehicles/drop_pod/drop_pod.glb new file mode 100644 index 0000000..8bec65a Binary files /dev/null and b/assets/vehicles/drop_pod/drop_pod.glb differ diff --git a/client/ArenaAudioSystem.cs b/client/ArenaAudioSystem.cs index 50e7b74..9801bf1 100644 --- a/client/ArenaAudioSystem.cs +++ b/client/ArenaAudioSystem.cs @@ -485,6 +485,10 @@ public partial class ArenaAudioSystem : Node3D case ContenderLoadoutEvent loadout: HandleLoadoutChanged(session, state, loadout, localId, listenerPos); break; + + case DropPodEvent dpe: + HandleDropPodEvent(dpe, localId, listenerPos); + break; } } @@ -708,14 +712,98 @@ public partial class ArenaAudioSystem : Node3D } } + private void HandleDropPodEvent(DropPodEvent dpe, int localId, Vector3 listenerPos) + { + var kind = (DropPodEventKind)dpe.Kind; + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + bool isLocal = dpe.ContenderId == localId; + + switch (kind) + { + case DropPodEventKind.WaveAnnounced: + if (dpe.WaveIndex > 0 || dpe.RespawnsClosed) + { + PlayUi("ui_drop_wave", volumeDb: -3.5f, pitchScale: dpe.RespawnsClosed ? 0.85f : 1.0f); + } + break; + + case DropPodEventKind.PodLaunched: + if (isLocal) + { + PlayUi("pod_petal_pop", volumeDb: -7.5f, pitchScale: 0.72f); + } + break; + + case DropPodEventKind.PodRetroBurnStart: + PlayOneShot3D( + "impact_explosion", + pos, + listenerPos, + isLocal ? PriorityLocalAction : PriorityNearCombat, + volumeDb: isLocal ? -3.0f : -6.5f, + pitchScale: 0.68f, + isLocalSource: isLocal, + sourceEntityId: dpe.PodId); + break; + + case DropPodEventKind.PodTouchdownBlowPetals: + RecordExplosionPoint(dpe.X, dpe.Z); + int prio = isLocal ? PriorityLocalAction : PriorityLocalImpactOrKill; + PlayOneShot3D( + "pod_slam", + pos, + listenerPos, + prio, + volumeDb: isLocal ? -0.5f : -4.0f, + pitchScale: NextPitchJitter(0.94f, 1.06f), + isLocalSource: isLocal, + sourceEntityId: dpe.PodId); + PlayOneShot3D( + "pod_petal_pop", + pos, + listenerPos, + prio, + volumeDb: isLocal ? -1.5f : -5.5f, + pitchScale: NextPitchJitter(0.95f, 1.05f), + isLocalSource: isLocal, + sourceEntityId: dpe.PodId); + break; + } + } + private void UpdateLoopSlots(IClientArenaSession session, Vector3 listenerPos, float alpha) { var state = session.ViewState; int localId = session.LocalContenderId; - // Slot 0: Local player continuous engine / rotor / mech servo loop + // Slot 0: Local player continuous engine / rotor / mech servo / drop-pod retro loop var local = session.LocalContender; - if (local.Alive) + if (local.IsInDropPod) + { + var (pPos, _, _) = session.GetInterpolatedContenderPose(localId, alpha); + Vector3 pos = new(pPos.X, pPos.Y, pPos.Z); + OrbitalPod? localPod = null; + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == localId) + { + localPod = pods[i]; + break; + } + } + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + AssignLoopSlot( + 0, + isContender: true, + localId, + "pod_retro_burn", + pos, + distSq: 0f, + volumeDb: burning ? -1.5f : -13.5f, + pitchScale: burning ? 0.96f : 1.42f); + } + else if (local.IsGroundedActive) { var (pPos, _, pVel) = session.GetInterpolatedContenderPose(localId, alpha); Vector3 pos = new(pPos.X, pPos.Y, pPos.Z); @@ -728,7 +816,7 @@ public partial class ArenaAudioSystem : Node3D SilenceLoopSlot(0); } - // Slots 1..4: nearest 4 live rivals/spectators within 160m (with 12m hysteresis) + // Slots 1..4: nearest 4 live rivals/spectators/burning-pods within 160m (with 12m hysteresis) _loopCandidates.Clear(); float maxDistSq = MaxLoopDistance * MaxLoopDistance; @@ -736,7 +824,7 @@ public partial class ArenaAudioSystem : Node3D for (int i = 0; i < contenders.Count; i++) { var c = contenders[i]; - if (c.Id == localId || !c.Alive || !session.IsContenderVisible(c.Id)) continue; + if (c.Id == localId || !c.IsGroundedActive || !session.IsContenderVisible(c.Id)) continue; var (cPos, _, cVel) = session.GetInterpolatedContenderPose(c.Id, alpha); Vector3 pos = new(cPos.X, cPos.Y, cPos.Z); float distSq = pos.DistanceSquaredTo(listenerPos); @@ -773,6 +861,24 @@ public partial class ArenaAudioSystem : Node3D _loopCandidates.Add(new LoopCandidate(false, s.Id, clipKey, pos, scoreDistSq, volDb - 4.0f, pitch)); } + var activePods = session.ActivePods; + for (int i = 0; i < activePods.Count; i++) + { + var pod = activePods[i]; + if (pod.Phase != OrbitalPodPhase.RetroBurn || (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == localId)) + { + continue; + } + Vector3 pos = new(pod.X, pod.Y, pod.Z); + float distSq = pos.DistanceSquaredTo(listenerPos); + if (distSq > maxDistSq) continue; + int candId = 100000 + pod.PodId; + float scoreDistSq = IsHeldInRemoteLoopSlots(false, candId) + ? MathF.Max(0f, distSq - LoopHysteresisMeters * LoopHysteresisMeters) + : distSq; + _loopCandidates.Add(new LoopCandidate(false, candId, "pod_retro_burn", pos, scoreDistSq, -4.5f, 1.0f)); + } + _loopCandidates.Sort((a, b) => a.DistSq.CompareTo(b.DistSq)); int assigned = Math.Min(LoopVoiceCount - 1, _loopCandidates.Count); for (int i = 0; i < assigned; i++) diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index 0d07947..ee25ef6 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -101,6 +101,9 @@ public partial class ArenaRenderer : Node3D private readonly Dictionary<(bool IsContender, int Id), float> _tireDustNextTime = new(); private readonly Dictionary<(bool IsContender, int Id), float> _thermalVentNextTime = new(); private readonly Dictionary<(bool IsContender, int Id), float> _damageSmokeNextTime = new(); + private readonly Dictionary _podStreakNextTime = new(); + private readonly Dictionary _podRetroNextTime = new(); + private long _lastPodEventId; private float _vfxClock; private readonly Dictionary _contenderVisuals = new(); @@ -344,6 +347,7 @@ public partial class ArenaRenderer : Node3D SyncContenders(session, dt, alpha, hasCam, camPos); SyncSpectators(session, elapsedSeconds, dt, alpha, hasCam, camPos); SyncGroundDrops(state, elapsedSeconds, hasCam, camPos); + SyncOrbitalPods(session, alpha, hasCam, camPos); _debris.Step(dt, state.Terrain); _debris.SubmitToPool(_partPool); _partPool.EndFrame(); @@ -377,6 +381,7 @@ public partial class ArenaRenderer : Node3D } EmitContinuousActorParticles(session, hasCam, camPos, sampleGroundTint); + ConsumeDropPodEvents(session, events, camPos, hasCam); UpdateExplosiveRingsAndCores(events, stepDt); _particles.AdvanceAndCommit(stepDt); } @@ -472,6 +477,9 @@ public partial class ArenaRenderer : Node3D _tireDustNextTime.Clear(); _thermalVentNextTime.Clear(); _damageSmokeNextTime.Clear(); + _podStreakNextTime.Clear(); + _podRetroNextTime.Clear(); + _lastPodEventId = 0; _vfxClock = 0f; _activeBeamCount = 0; if (_vfxBeamMm is not null) @@ -558,11 +566,11 @@ public partial class ArenaRenderer : Node3D for (int i = 0; i < contenders.Count; i++) { var c = contenders[i]; - if (!c.Alive || !session.IsContenderVisible(c.Id)) + if (!c.IsGroundedActive || !session.IsContenderVisible(c.Id)) { if (_contenderVisuals.TryGetValue(c.Id, out var hiddenVis)) { - if (!c.Alive) + if (!c.IsGroundedActive) { hiddenVis.Visual.SyncDamageAndHeat(c.Grid, _debris, Vector3.Zero); } @@ -1005,6 +1013,201 @@ public partial class ArenaRenderer : Node3D _dropPillarMmi.Visible = pillarCount > 0; } + private void SyncOrbitalPods(IClientArenaSession session, float alpha, bool hasCam, Vector3 camPos) + { + var pods = session.ActivePods; + if (pods.Count == 0) + { + return; + } + + var podTpl = _assetCache.GetOrLoadDropPod(); + int localId = session.LocalContenderId; + + for (int i = 0; i < pods.Count; i++) + { + var pod = pods[i]; + if (pod.Phase == OrbitalPodPhase.Popped) + { + continue; + } + + Vector3 pos = new Vector3( + Mathf.Lerp(pod.PrevX, pod.X, alpha), + Mathf.Lerp(pod.PrevY, pod.Y, alpha), + Mathf.Lerp(pod.PrevZ, pod.Z, alpha)); + + var qPrev = new Quaternion(pod.PrevRotX, pod.PrevRotY, pod.PrevRotZ, pod.PrevRotW).Normalized(); + var qCurr = new Quaternion(pod.CurrRotX, pod.CurrRotY, pod.CurrRotZ, pod.CurrRotW).Normalized(); + Quaternion q = qPrev.Slerp(qCurr, alpha); + + Transform3D podXf = BuildPodTransform(pos, q, pod.VelX, pod.VelZ, pod.PodKind); + float roleIdx = ResolvePodRoleIndex(pod.PodKind, pod.ContenderId, localId, pod.WaveIndex, pod.Module?.IsImperial == true); + float heat = pod.Phase == OrbitalPodPhase.RetroBurn + ? 0.28f + : Math.Clamp(pod.HeatGlow * 0.16f, 0f, 0.18f); + float scorch = Math.Clamp(pod.Scorch * 0.7f, 0f, 0.55f); + Color custom = new(scorch, heat, roleIdx, 1f); + + bool wantsShadow = !hasCam || pos.DistanceSquaredTo(camPos) <= 65f * 65f; + _partPool.Submit(podTpl.CoreMesh, in podXf, in custom, wantsShadow); + + for (int p = 0; p < 4; p++) + { + Transform3D petalXf = podXf * podTpl.PetalLocalTransforms[p]; + _partPool.Submit(podTpl.PetalMesh, in petalXf, in custom, wantsShadow: false); + } + } + } + + private static Transform3D BuildPodTransform( + Vector3 pos, + Quaternion baseRot, + float velX, + float velZ, + OrbitalPodKind podKind) + { + Basis basis = new(baseRot); + float horizSpeed = MathF.Sqrt(velX * velX + velZ * velZ); + if (horizSpeed > 0.5f) + { + Vector3 horizDir = new Vector3(velX / horizSpeed, 0f, velZ / horizSpeed); + Vector3 tiltAxis = Vector3.Up.Cross(horizDir); + if (tiltAxis.LengthSquared() > 1e-4f) + { + float tiltRad = Math.Clamp(horizSpeed * 0.0085f, 0f, Mathf.DegToRad(14f)); + basis = new Basis(tiltAxis.Normalized(), tiltRad) * basis; + } + } + float scale = podKind == OrbitalPodKind.Contender ? 1.0f : 0.72f; + if (MathF.Abs(scale - 1.0f) > 1e-3f) + { + basis *= Basis.FromScale(Vector3.One * scale); + } + return new Transform3D(basis, pos); + } + + private static float ResolvePodRoleIndex( + OrbitalPodKind podKind, + int contenderId, + int localId, + int waveIndex, + bool isImperialGear) + { + if (podKind == OrbitalPodKind.Contender) + { + return contenderId == localId ? 0f : 1f; + } + return (waveIndex > 0 || isImperialGear) ? 2f : 5f; + } + + private void ConsumeDropPodEvents( + IClientArenaSession session, + IReadOnlyList events, + Vector3 camPos, + bool hasCam) + { + var state = session.ViewState; + int localId = session.LocalContenderId; + VehicleAssetCache.DropPodTemplate? podTpl = null; + + for (int i = 0; i < events.Count; i++) + { + if (events[i] is not DropPodEvent dpe) + { + continue; + } + if (dpe.EventId <= _lastPodEventId) + { + continue; + } + _lastPodEventId = dpe.EventId; + + if ((DropPodEventKind)dpe.Kind != DropPodEventKind.PodTouchdownBlowPetals) + { + continue; + } + + bool isContender = dpe.PodKind == (byte)OrbitalPodKind.Contender; + bool isLocal = isContender && dpe.ContenderId == localId; + if (isContender && !isLocal && !session.IsContenderVisible(dpe.ContenderId)) + { + continue; + } + + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + if (!isLocal && hasCam && pos.DistanceSquaredTo(camPos) > 420f * 420f) + { + continue; + } + + Vector3 normal = new(dpe.NormalX, dpe.NormalY, dpe.NormalZ); + if (normal.LengthSquared() < 1e-4f) normal = Vector3.Up; + normal = normal.Normalized(); + + podTpl ??= _assetCache.GetOrLoadDropPod(); + float yaw = isContender && dpe.ContenderId >= 0 && dpe.ContenderId < state.Contenders.Count + ? state.Contenders[dpe.ContenderId].Yaw + : (dpe.PodId * 1.17f); + Quaternion q = Quaternion.FromEuler(new Vector3(0f, yaw, 0f)); + Transform3D podXf = BuildPodTransform(pos, q, 0f, 0f, (OrbitalPodKind)dpe.PodKind); + + bool isImperial = dpe.WaveIndex > 0 + || (dpe.ModuleId is not null && Catalog.ModulesById.TryGetValue(dpe.ModuleId, out var ms) && ms.IsImperial); + float roleIdx = ResolvePodRoleIndex((OrbitalPodKind)dpe.PodKind, dpe.ContenderId, localId, dpe.WaveIndex, isImperial); + + Vector3 blastOrigin = pos + normal * (isContender ? 1.4f : 1.0f); + float impulseScale = isContender ? 2.15f : 1.65f; + float petalLife = isContender ? 8.0f : 4.5f; + + for (int p = 0; p < 4; p++) + { + Transform3D petalXf = podXf * podTpl.PetalLocalTransforms[p]; + _debris.SpawnDetachedPart( + podTpl.PetalMesh, + petalXf, + blastOrigin, + Vector3.Zero, + roleIdx, + impulseScale: impulseScale, + applyScorch: true, + lifetime: petalLife); + } + + // Touchdown retro shockwave ring + brief detonation core + Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 right = upRef.Cross(normal).Normalized(); + Vector3 fwd = normal.Cross(right).Normalized(); + Basis ringBasis = new(right, normal, fwd); + AddTransient(new TransientVfx + { + Shape = VfxShape.Ring, + Position = pos + normal * 0.22f, + Velocity = Vector3.Zero, + BaseRotation = ringBasis, + StartScale = new Vector3(1.4f, 1.0f, 1.4f), + EndScale = new Vector3(isContender ? 11.5f : 6.8f, 0.5f, isContender ? 11.5f : 6.8f), + ColorStart = new Color(3.4f, 1.85f, 0.55f, 0.94f), + ColorEnd = new Color(1.1f, 0.45f, 0.16f, 0.0f), + Age = 0f, + Lifetime = isContender ? 0.42f : 0.30f + }); + AddTransient(new TransientVfx + { + Shape = VfxShape.Sphere, + Position = pos + normal * 0.65f, + Velocity = normal * 1.8f, + BaseRotation = Basis.Identity, + StartScale = Vector3.One * (isContender ? 1.2f : 0.7f), + EndScale = Vector3.One * (isContender ? 4.4f : 2.6f), + ColorStart = new Color(3.8f, 2.2f, 0.65f, 0.90f), + ColorEnd = new Color(0.85f, 0.25f, 0.06f, 0.0f), + Age = 0f, + Lifetime = isContender ? 0.28f : 0.20f + }); + } + } + private void SyncTracerBeams(MatchState state) { int beamIdx = 0; @@ -1184,7 +1387,7 @@ public partial class ArenaRenderer : Node3D for (int i = 0; i < contenders.Count; i++) { var c = contenders[i]; - if (!c.Alive || !session.IsContenderVisible(c.Id)) + if (!c.IsGroundedActive || !session.IsContenderVisible(c.Id)) { continue; } @@ -1289,6 +1492,46 @@ public partial class ArenaRenderer : Node3D } } } + + var pods = session.ActivePods; + int localId = session.LocalContenderId; + for (int i = 0; i < pods.Count; i++) + { + var pod = pods[i]; + if (pod.Phase == OrbitalPodPhase.Popped) + { + continue; + } + bool isContender = pod.PodKind == OrbitalPodKind.Contender; + bool isLocal = isContender && pod.ContenderId == localId; + Vector3 podPos = new(pod.X, pod.Y, pod.Z); + if (pod.Phase == OrbitalPodPhase.RetroBurn) + { + float nextBurn = _podRetroNextTime.GetValueOrDefault(pod.PodId); + if (_vfxClock >= nextBurn) + { + _podRetroNextTime[pod.PodId] = _vfxClock + (isLocal ? 0.045f : 0.065f); + _particles.EmitPodRetroBurn( + podPos, + pod.LastAgl, + sampleGroundTint(pod.X, pod.Z), + isContender, + isLocal, + camPos, + hasCam); + } + } + else if (pod.HeatGlow > 0.12f) + { + float nextStreak = _podStreakNextTime.GetValueOrDefault(pod.PodId); + if (_vfxClock >= nextStreak) + { + _podStreakNextTime[pod.PodId] = _vfxClock + 0.085f; + Vector3 podVel = new(pod.VelX, pod.VelY, pod.VelZ); + _particles.EmitPodReentryStreak(podPos, podVel, pod.HeatGlow, isContender, camPos, hasCam); + } + } + } } private static Vector3 ResolveHotAnchorWorld(VehicleVisualInstance? vis, ChassisGrid grid, Vector3 fallbackPos, float halfHeight) diff --git a/client/CameraJuiceState.cs b/client/CameraJuiceState.cs index 822ed81..87accae 100644 --- a/client/CameraJuiceState.cs +++ b/client/CameraJuiceState.cs @@ -146,6 +146,47 @@ public sealed class CameraJuiceState case SpectatorDestroyedEvent sdet: ApplyDeathTrauma(isContender: false, sdet.SpectatorId, localPos, resolveActor); break; + + case DropPodEvent dpe: + { + var kind = (DropPodEventKind)dpe.Kind; + if (dpe.ContenderId == localContenderId) + { + if (kind == DropPodEventKind.PodRetroBurnStart) + { + AddTrauma(0.18f); + } + else if (kind == DropPodEventKind.PodTouchdownBlowPetals) + { + AddTrauma(0.36f); + } + } + else if (kind == DropPodEventKind.PodTouchdownBlowPetals) + { + float dx = dpe.X - localPos.X; + float dy = dpe.Y - localPos.Y; + float dz = dpe.Z - localPos.Z; + float distSq = dx * dx + dy * dy + dz * dz; + if (distSq < 48f * 48f) + { + float falloff = 1f - MathF.Sqrt(distSq) / 48f; + AddTrauma(0.18f * falloff); + } + } + break; + } + } + } + } + + public void ApplyOrbitalBurnRumble(float burnIntensity) + { + if (float.IsFinite(burnIntensity) && burnIntensity > 0f) + { + float target = Math.Clamp(burnIntensity, 0f, 1f) * 0.20f; + if (Trauma < target) + { + Trauma = target; } } } diff --git a/client/DebrisSystem.cs b/client/DebrisSystem.cs index 72e4b8f..7171288 100644 --- a/client/DebrisSystem.cs +++ b/client/DebrisSystem.cs @@ -15,7 +15,7 @@ public partial class DebrisSystem : Node3D private const float Gravity = -20f; private const float DefaultLifetime = 4.5f; private const float FadeDuration = 1.2f; - private const int MaxActiveDebris = 96; + private const int MaxActiveDebris = 256; private sealed class DebrisPiece { @@ -65,7 +65,8 @@ public partial class DebrisSystem : Node3D Vector3 inheritedVelocity, float roleIndex, float impulseScale = 1.0f, - bool applyScorch = true) + bool applyScorch = true, + float lifetime = DefaultLifetime) { if (mesh is null || mesh.GetSurfaceCount() == 0) { @@ -117,7 +118,7 @@ public partial class DebrisSystem : Node3D Scorch = applyScorch ? 0.85f : 0.15f, HeatGlow = applyScorch ? 0.45f : 0f, Age = 0f, - Lifetime = DefaultLifetime, + Lifetime = lifetime > 0.2f ? lifetime : DefaultLifetime, Settled = false }); } diff --git a/client/Hud.cs b/client/Hud.cs index 37e5585..2851627 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -45,6 +45,7 @@ public partial class Hud : CanvasLayer private Label _statsLabel = null!; private Label _safeLabel = null!; private Label _detectionLabel = null!; + private Label _waveLabel = null!; private Label _netStatusLabel = null!; private Label _promptLabel = null!; private Label _controlsHint = null!; @@ -304,32 +305,63 @@ public partial class Hud : CanvasLayer var net = session.ConnectionStatus; // Top-Left Status - _chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant(); - bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; - _planeBadge.Text = isCoronal ? "CORONAL" : "DORSAL"; - _planeBadge.Modulate = isCoronal ? CyanCol : OliveCol; - - _coreHpBar.MaxValue = Math.Max(1f, player.Grid.MaxCoreHp); - _coreHpBar.Value = Math.Max(0f, player.Grid.CoreHp); - _coreHpLabel.Text = $"CORE {player.Grid.CoreHp:F0} / {player.Grid.MaxCoreHp:F0}"; + OrbitalPod? localPod = null; + if (player.IsInDropPod) + { + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == player.Id) + { + localPod = pods[i]; + break; + } + } + } int aliveCount = 0; for (int i = 0; i < state.Contenders.Count; i++) { if (state.Contenders[i].Alive) aliveCount++; } - if (player.Grid.Spec.IsVtol) + + if (player.IsInDropPod) { - float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z)); - _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALT {agl:F1}m | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; - _controlsHint.Text = "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net"; + float agl = localPod is not null + ? MathF.Max(0f, localPod.LastAgl) + : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); + float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + _chassisHeader.Text = "ORBITAL DROP POD"; + _planeBadge.Text = burning ? "RETRO BURN" : "FREEFALL"; + _planeBadge.Modulate = burning ? OrangeCol : CyanCol; + _statsLabel.Text = $"ALT {agl:F0}m | VEL {velDown:F0} m/s | ALIVE {aliveCount} / {state.Contenders.Count}"; + _controlsHint.Text = "WASD Steer Pod | Mouse Look | Retro-Burn Auto | Wheel Zoom"; } else { - _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; - _controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net | Wheel Zoom"; + _chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant(); + bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; + _planeBadge.Text = isCoronal ? "CORONAL" : "DORSAL"; + _planeBadge.Modulate = isCoronal ? CyanCol : OliveCol; + + if (player.Grid.Spec.IsVtol) + { + float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z)); + _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALT {agl:F1}m | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; + _controlsHint.Text = "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net"; + } + else + { + _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; + _controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net | Wheel Zoom"; + } } + _coreHpBar.MaxValue = Math.Max(1f, player.Grid.MaxCoreHp); + _coreHpBar.Value = Math.Max(0f, player.Grid.CoreHp); + _coreHpLabel.Text = $"CORE {player.Grid.CoreHp:F0} / {player.Grid.MaxCoreHp:F0}"; + _radarTitle.Text = state.MapKind == ArenaMapKind.Sion ? "SION 3KM • RADAR" : "DESERT RING • RADAR"; @@ -365,6 +397,24 @@ public partial class Hud : CanvasLayer _detectionLabel.Modulate = OliveCol; } + var wave = session.DropWaveState; + if (wave.RespawnCutoffReached) + { + _waveLabel.Text = "FINAL RING — RESPAWNS CLOSED"; + _waveLabel.Modulate = RedCol; + } + else if (wave.NextWaveAtSec is float nextWaveAt) + { + float eta = MathF.Max(0f, nextWaveAt - state.Time); + _waveLabel.Text = $"PATRON WAVE {wave.NextWaveIndex} IN {eta:F0}s • RESP {player.RespawnsRemaining}"; + _waveLabel.Modulate = eta <= 10f ? GoldCol : CyanCol; + } + else + { + _waveLabel.Text = $"WAVE {wave.CurrentWaveIndex} ACTIVE • RESP {player.RespawnsRemaining}"; + _waveLabel.Modulate = OliveCol; + } + if (net.Mode == NetworkMode.Solo) { _netStatusLabel.Visible = false; @@ -394,11 +444,24 @@ public partial class Hud : CanvasLayer SyncNetworkPanel(net); } - _promptLabel.Text = BuildInteractionPrompt(state, player); - _promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text); + if (player.IsInDropPod) + { + float agl = localPod is not null + ? MathF.Max(0f, localPod.LastAgl) + : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); + float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); + _promptLabel.Text = $"ORBITAL INSERTION — ALT {agl:F0}m | VEL {velDown:F0}m/s | [WASD] STEER" + + (localPod?.Phase == OrbitalPodPhase.RetroBurn ? " [RETRO BURN]" : ""); + _promptLabel.Visible = true; + } + else + { + _promptLabel.Text = BuildInteractionPrompt(state, player); + _promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text); + } - // Crosshair + Heat Arc + Directional Incoming Hit Arcs - _crosshair.SetState(state, player, _getCameraYaw()); + // Crosshair + Heat Arc / Orbital Altimeter + Directional Incoming Hit Arcs + _crosshair.SetState(state, player, _getCameraYaw(), localPod); _crosshair.QueueRedraw(); // Radar (heading-up with camera yaw) @@ -417,7 +480,7 @@ public partial class Hud : CanvasLayer // Broadcast Chyron SyncBroadcastChyron(state.Broadcast); - // Outcome + // Outcome / WaitingForRespawnWave Banner var outcome = session.LocalOutcome; if (outcome == ClientMatchOutcome.Victory) { @@ -439,6 +502,14 @@ public partial class Hud : CanvasLayer _outcomeLabel.Text = $"{title}\n{sub}"; _outcomeLabel.Modulate = RedCol; } + else if (player.WaitingForRespawn) + { + _outcomeBanner.Visible = true; + _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", CyanCol); + float eta = wave.NextWaveAtSec is float nxt ? MathF.Max(0f, nxt - state.Time) : 0f; + _outcomeLabel.Text = $"AWAITING PATRON WAVE {wave.NextWaveIndex}\nRESPAWN IN {eta:F1}s (RESP: {player.RespawnsRemaining} LEFT)"; + _outcomeLabel.Modulate = CyanCol; + } else { _outcomeBanner.Visible = false; @@ -529,6 +600,11 @@ public partial class Hud : CanvasLayer _detectionLabel.AddThemeFontSizeOverride("font_size", 13); vbox.AddChild(_detectionLabel); + _waveLabel = new Label { Text = "WAVE 0" }; + _waveLabel.AddThemeFontSizeOverride("font_size", 12); + _waveLabel.AddThemeColorOverride("font_color", CyanCol); + vbox.AddChild(_waveLabel); + _netStatusLabel = new Label { Text = "", Visible = false }; _netStatusLabel.AddThemeFontSizeOverride("font_size", 12); vbox.AddChild(_netStatusLabel); @@ -1163,6 +1239,7 @@ public partial class Hud : CanvasLayer } private ContenderState? _player; + private OrbitalPod? _localPod; private float _cameraYaw; private MatchState? _lastState; private readonly List _incomingArcs = new(); @@ -1170,7 +1247,7 @@ public partial class Hud : CanvasLayer private float _hitMarkerRemaining; private float _hitMarkerDuration; - public void SetState(MatchState state, ContenderState player, float cameraYaw) + public void SetState(MatchState state, ContenderState player, float cameraYaw, OrbitalPod? localPod = null) { if (!ReferenceEquals(_lastState, state)) { @@ -1179,6 +1256,7 @@ public partial class Hud : CanvasLayer } _player = player; + _localPod = localPod; _cameraYaw = cameraYaw; } @@ -1337,6 +1415,47 @@ public partial class Hud : CanvasLayer return; } + if (_player.IsInDropPod) + { + float agl = _localPod is not null ? MathF.Max(0f, _localPod.LastAgl) : 0f; + float vel = _localPod is not null ? MathF.Max(0f, -_localPod.VelY) : 0f; + bool burning = _localPod?.Phase == OrbitalPodPhase.RetroBurn; + Color bracketCol = burning ? OrangeCol : CyanCol; + + float altFrac = Math.Clamp(agl / 410f, 0f, 1f); + const float barX = 72f; + const float barH = 76f; + Vector2 topL = center + new Vector2(-barX, -barH * 0.5f); + Vector2 topR = center + new Vector2(barX, -barH * 0.5f); + DrawLine(topL, topL + new Vector2(0f, barH), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f), 2.0f); + DrawLine(topR, topR + new Vector2(0f, barH), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f), 2.0f); + + float fillH = barH * altFrac; + DrawLine(topL + new Vector2(0f, barH - fillH), topL + new Vector2(0f, barH), bracketCol, 3.0f); + DrawLine(topR + new Vector2(0f, barH - fillH), topR + new Vector2(0f, barH), bracketCol, 3.0f); + + DrawString( + ThemeDB.FallbackFont, + center + new Vector2(-46f, 54f), + $"ALT {agl:F0}m | {vel:F0}m/s", + HorizontalAlignment.Left, + -1, + 11, + bracketCol); + if (burning) + { + DrawString( + ThemeDB.FallbackFont, + center + new Vector2(-46f, -52f), + "RETRO BURN ACTIVE", + HorizontalAlignment.Left, + -1, + 11, + OrangeCol); + } + return; + } + // Thermal heat-arc indicator around crosshair float heatRatio = 0f; bool overPlateau = false; @@ -1505,6 +1624,42 @@ public partial class Hud : CanvasLayer } } + // Active descending Orbital Pods (cyan/gold diamonds for gear, chevrons for contenders) + var pods = _session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + var pod = pods[i]; + if (pod.Phase == OrbitalPodPhase.Popped) continue; + var pp = ClampToRadarDisc(center, MathF.Max(4f, radius - 5f), WorldToRadar(center, scale, pod.X, pod.Z, _cameraYaw)); + if (pod.PodKind == OrbitalPodKind.Contender) + { + bool isLocalPod = pod.ContenderId == localId; + Color pCol = isLocalPod ? OliveCol : OrangeCol; + float sz = isLocalPod ? 5.5f : 3.6f; + var pts = new[] + { + pp + new Vector2(0f, -sz), + pp + new Vector2(-sz * 0.8f, sz * 0.7f), + pp + new Vector2(sz * 0.8f, sz * 0.7f) + }; + DrawColoredPolygon(pts, pCol); + } + else + { + bool isImp = pod.WaveIndex > 0 || pod.Module?.IsImperial == true; + Color gCol = isImp ? GoldCol : CyanCol; + const float d = 3.2f; + var pts = new[] + { + pp + new Vector2(0f, -d), + pp + new Vector2(d, 0f), + pp + new Vector2(0f, d), + pp + new Vector2(-d, 0f) + }; + DrawColoredPolygon(pts, gCol); + } + } + // Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory; hidden Exemplars vanish!) var contenderContacts = _session.LocalContenderContacts; var spectatorContacts = _session.LocalSpectatorContacts; @@ -1577,7 +1732,7 @@ public partial class Hud : CanvasLayer for (int i = 0; i < state.Contenders.Count; i++) { var c = state.Contenders[i]; - if (!c.Alive) continue; + if (!c.IsGroundedActive) continue; if (c.Id == localId) { diff --git a/client/Main.cs b/client/Main.cs index 2535db5..fcdbeb2 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -47,6 +47,9 @@ public partial class Main : Node3D private float _cameraZoom = 1.0f; private float _smoothedShoulderY; private string? _lastCamChassisId; + private float _orbitalPodCamBlend; + private ContenderLifecycle _prevLocalLifecycle = ContenderLifecycle.Active; + private MeshInstance3D _dropReticleMesh = null!; private Vector3 _baseCamPos; private Vector3 _baseLookDir = Vector3.Forward; private bool _hasBaseCamPose; @@ -89,6 +92,7 @@ public partial class Main : Node3D public Hud Hud => _hud; public ArenaMapKind MapKind => _mapKind; public ArenaMapKind? InitialMapKindOverride { get; set; } + public bool InitialSkipDropOverride { get; set; } public string? Failure { get; private set; } public int Seed => _seed; public float CameraYaw => _cameraYaw; @@ -108,6 +112,7 @@ public partial class Main : Node3D _arena = new ArenaRenderer { Name = "Arena" }; AddChild(_arena); + _arena.AssetCache.PreloadAll(); _audio = new ArenaAudioSystem { Name = "ArenaAudio" }; AddChild(_audio); @@ -128,6 +133,24 @@ public partial class Main : Node3D _hud.NetworkPanelToggled += _ => SyncMouseMode(); AddChild(_hud); + var reticleMat = new StandardMaterial3D + { + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha, + AlbedoColor = new Color(0.27f, 0.85f, 0.91f, 0.82f), + NoDepthTest = false, + CullMode = BaseMaterial3D.CullModeEnum.Disabled + }; + _dropReticleMesh = new MeshInstance3D + { + Name = "DropLandingReticle", + Mesh = new TorusMesh { InnerRadius = 2.5f, OuterRadius = 3.05f, Rings = 28, RingSegments = 8 }, + MaterialOverride = reticleMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + Visible = false + }; + AddChild(_dropReticleMesh); + string? cliConnect = GetCliArg("--connect"); string? cliHost = GetCliArg("--host", allowBareFlag: true); string? cliName = GetCliArg("--name"); @@ -190,6 +213,9 @@ public partial class Main : Node3D _perfTargetFrames = autoExitFrames; } + bool perfCombat = _perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1"; + bool skipInitialDrop = InitialSkipDropOverride || perfCombat; + if (!string.IsNullOrWhiteSpace(connectTarget)) { StartRemoteSession(connectTarget, _callsign); @@ -200,10 +226,10 @@ public partial class Main : Node3D } else { - Reset(_seed, _mapKind); + Reset(_seed, _mapKind, skipInitialDrop); } - if (_perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1" && _session is not null) + if (perfCombat && _session is not null) { SetupPerfCombatScenario(_session); } @@ -280,7 +306,7 @@ public partial class Main : Node3D _boundViewState = null; } - public void Reset(int seed, ArenaMapKind? mapKind = null) + public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false) { _seed = seed; if (mapKind.HasValue) @@ -297,7 +323,7 @@ public partial class Main : Node3D try { - _session = new LocalArenaSession(seed, _mapKind, _callsign); + _session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop); BindSessionPresentation(resetCamera: true); } catch (Exception ex) @@ -407,7 +433,17 @@ public partial class Main : Node3D { var p = _session.LocalContender; _cameraYaw = p.Yaw; - _cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f); + _prevLocalLifecycle = p.Lifecycle; + if (p.IsInDropPod) + { + _cameraPitch = Mathf.DegToRad(36f); + _orbitalPodCamBlend = 1.0f; + } + else + { + _cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f); + _orbitalPodCamBlend = 0f; + } _cameraZoom = 1.0f; _lastCamChassisId = null; _hasBaseCamPose = false; @@ -835,9 +871,30 @@ public partial class Main : Node3D _arena.ConsumeEvents(_session, _frameEvents, _frameFootsteps, dt, SampleCurrentMapGroundTint); var local = _session.LocalContender; + if (local.Lifecycle == ContenderLifecycle.Deploying && _prevLocalLifecycle != ContenderLifecycle.Deploying) + { + _cameraPitch = Mathf.DegToRad(36f); + _orbitalPodCamBlend = 1.0f; + } + _prevLocalLifecycle = local.Lifecycle; + var localPos = new System.Numerics.Vector3(local.X, local.Y, local.Z); _camJuice.ConsumeEvents(_frameEvents, _session.LocalContenderId, localPos, _session); _camJuice.ConsumeFootsteps(_frameFootsteps, _session.LocalContenderId); + if (local.IsInDropPod) + { + var pods = _session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + if (pods[i].PodKind == OrbitalPodKind.Contender && + pods[i].ContenderId == _session.LocalContenderId && + pods[i].Phase == OrbitalPodPhase.RetroBurn) + { + _camJuice.ApplyOrbitalBurnRumble(1.0f); + break; + } + } + } _camJuice.Update(dt, local.Speed, local.Grid.Spec.IsVtol); } @@ -989,8 +1046,13 @@ public partial class Main : Node3D private PlayerInput GatherPlayerInput() { - var (aimX, aimY, aimZ) = ComputeCenterScreenAim(); - if (_hud.IsUiTextInputFocused) + var local = Session.LocalContender; + bool inPod = local.IsInDropPod; + var (aimX, aimY, aimZ) = inPod + ? (local.X + MathF.Sin(_cameraYaw) * 120f, local.Y - 40f, local.Z + MathF.Cos(_cameraYaw) * 120f) + : ComputeCenterScreenAim(); + + if (_hud.IsUiTextInputFocused || local.WaitingForRespawn) { return new PlayerInput( Throttle: 0f, @@ -1012,15 +1074,18 @@ public partial class Main : Node3D if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f; if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f; - bool isVtol = Session.LocalContender.Grid.Spec.IsVtol; + bool isVtol = !inPod && local.Grid.Spec.IsVtol; float verticalThrottle = 0f; - if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f; - if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f; + if (!inPod) + { + if (Input.IsKeyPressed(Key.Space)) verticalThrottle += 1f; + if (Input.IsKeyPressed(Key.C) || Input.IsKeyPressed(Key.Ctrl)) verticalThrottle -= 1f; + } - bool brake = isVtol ? Input.IsKeyPressed(Key.Shift) : Input.IsKeyPressed(Key.Space); + bool brake = !inPod && (isVtol ? Input.IsKeyPressed(Key.Shift) : Input.IsKeyPressed(Key.Space)); bool pointerOnHud = Input.MouseMode != Input.MouseModeEnum.Captured && (_hud.NetworkPanelOpen || _hud.IsPointerOverInteractiveHud(GetViewport().GetMousePosition())); - bool fire = !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left); + bool fire = !inPod && !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left); return new PlayerInput( Throttle: throttle, @@ -1028,7 +1093,7 @@ public partial class Main : Node3D AimWorldX: aimX, AimWorldZ: aimZ, Fire: fire, - InteractPickup: _interactQueued, + InteractPickup: !inPod && _interactQueued, Brake: brake, AimWorldY: aimY, VerticalThrottle: verticalThrottle); @@ -1151,60 +1216,140 @@ public partial class Main : Node3D var spec = p.Grid.Spec; var (posInterp, _, _) = Session.GetInterpolatedContenderPose(p.Id, alpha); - float rightOffset = MathF.Max(1.6f, spec.HalfWidth * 1.15f + 0.8f); - float heightOffset = spec.HalfHeight * 1.45f + 1.4f; - float boundingR = MathF.Max(spec.HalfWidth, MathF.Max(spec.HalfHeight * 0.72f, spec.HalfLength * 0.90f)); - float backDist = Math.Clamp(boundingR * 2.15f + 4.2f, 7.2f, 19.5f) * _cameraZoom; - float targetShoulderY = (posInterp.Y - spec.HalfHeight) + heightOffset; + Vector3 camRight = new(-MathF.Cos(_cameraYaw), 0f, MathF.Sin(_cameraYaw)); + Vector3 camFwdHoriz = new(MathF.Sin(_cameraYaw), 0f, MathF.Cos(_cameraYaw)); - if (_lastCamChassisId != spec.Id || dt >= 1f) + Vector3 camPos; + Vector3 lookDir; + + if (p.WaitingForRespawn) { - _smoothedShoulderY = targetShoulderY; - _lastCamChassisId = spec.Id; + _dropReticleMesh.Visible = false; + float orbitRadius = MathF.Min(Session.ViewState.Spectators.SafeRadius * 0.45f, 165f); + float orbitAngle = _elapsedSeconds * 0.14f + _cameraYaw; + float ox = MathF.Cos(orbitAngle) * orbitRadius; + float oz = MathF.Sin(orbitAngle) * orbitRadius; + float oy = Session.ViewState.Terrain.SampleHeight(ox, oz) + 75f; + camPos = new Vector3(ox, MathF.Max(oy, 110f), oz); + float centerY = Session.ViewState.Terrain.SampleHeight(0f, 0f) + 12f; + lookDir = (new Vector3(0f, centerY, 0f) - camPos).Normalized(); + } + else if (p.IsInDropPod) + { + // Live landing ring reticle directly under the descending pod + float surfY = Session.ViewState.Terrain.SampleHeight(posInterp.X, posInterp.Z); + var (nx, ny, nz) = Session.ViewState.Terrain.SampleNormal(posInterp.X, posInterp.Z); + if (_mapKind == ArenaMapKind.Sion && Session.ViewState.SionMap is { } sm && + sm.TryGetBuildingAt(posInterp.X, posInterp.Z, 1.6f, out var bldg)) + { + if (bldg.RoofY > surfY && posInterp.Y >= bldg.RoofY - 1.0f) + { + surfY = bldg.RoofY; + nx = 0f; ny = 1f; nz = 0f; + } + } + Vector3 surfNorm = new Vector3(nx, ny, nz).Normalized(); + if (surfNorm.LengthSquared() < 1e-4f) surfNorm = Vector3.Up; + Vector3 upRef = MathF.Abs(surfNorm.Y) > 0.92f ? Vector3.Forward : Vector3.Up; + Vector3 rRight = upRef.Cross(surfNorm).Normalized(); + Vector3 rFwd = surfNorm.Cross(rRight).Normalized(); + float pulse = 1.0f + 0.08f * MathF.Sin(_elapsedSeconds * 7.5f); + _dropReticleMesh.Visible = true; + _dropReticleMesh.GlobalTransform = new Transform3D( + new Basis(rRight, surfNorm, rFwd) * Basis.FromScale(new Vector3(pulse, 1f, pulse)), + new Vector3(posInterp.X, surfY + 0.35f, posInterp.Z)); + + _orbitalPodCamBlend = 1.0f; + float backDist = 23.0f * _cameraZoom; + Vector3 pivot = new(posInterp.X, posInterp.Y + 3.2f, posInterp.Z); + lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized(); + + float effectiveRight = 2.6f; + if (CastStaticCameraRay(pivot, camRight, effectiveRight, out float rightHitDist)) + { + effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist)); + } + Vector3 shoulderPos = pivot + camRight * effectiveRight; + + float effectiveBack = backDist; + if (CastStaticCameraRay(shoulderPos, -lookDir, backDist, out float backHitDist)) + { + effectiveBack = MathF.Min(effectiveBack, SafeCameraPullbackDist(backHitDist)); + } + camPos = shoulderPos - lookDir * effectiveBack; + float minTerrainY = Session.ViewState.Terrain.SampleHeight(camPos.X, camPos.Z) + 2.2f; + if (camPos.Y < minTerrainY) camPos.Y = minTerrainY; + _smoothedShoulderY = pivot.Y; } else { - float yBlend = 1f - MathF.Exp(-dt * 24f); - _smoothedShoulderY = Mathf.Lerp(_smoothedShoulderY, targetShoulderY, yBlend); - } - - var pivot = new Vector3(posInterp.X, _smoothedShoulderY, posInterp.Z); - var camRight = new Vector3(-MathF.Cos(_cameraYaw), 0f, MathF.Sin(_cameraYaw)); - var camFwdHoriz = new Vector3(MathF.Sin(_cameraYaw), 0f, MathF.Cos(_cameraYaw)); - var lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized(); - - // Segment 1: sweep terrain + static Box3D (StableId < ContenderStableIdBase) from pivot along camRight * rightOffset - float effectiveRight = rightOffset; - if (CastStaticCameraRay(pivot, camRight, rightOffset, out float rightHitDist)) - { - effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist)); - } - Vector3 shoulderPos = pivot + camRight * effectiveRight; - - // Segment 2: sweep terrain + static Box3D from shoulderPos along -lookDir * backDist - float effectiveBack = backDist; - if (CastStaticCameraRay(shoulderPos, -lookDir, backDist, out float backHitDist)) - { - effectiveBack = MathF.Min(effectiveBack, SafeCameraPullbackDist(backHitDist)); - } - - Vector3 camPos = shoulderPos - lookDir * effectiveBack; - - float minTerrainY = Session.ViewState.Terrain.SampleHeight(camPos.X, camPos.Z) + 1.2f; - if (camPos.Y < minTerrainY) - { - camPos.Y = minTerrainY; - } - - // Segment 3: verify direct pivot -> camPos LOS against static terrain/buildings so stepped wings cannot occlude player - Vector3 pivotToCam = camPos - pivot; - float pivotToCamDist = pivotToCam.Length(); - if (pivotToCamDist > 0.05f) - { - Vector3 pivotToCamDir = pivotToCam / pivotToCamDist; - if (CastStaticCameraRay(pivot, pivotToCamDir, pivotToCamDist, out float wingHitDist)) + _dropReticleMesh.Visible = false; + if (_orbitalPodCamBlend > 0.001f && dt > 0f && dt < 0.5f) { - camPos = pivot + pivotToCamDir * SafeCameraPullbackDist(wingHitDist); + float targetPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(8f) : Mathf.DegToRad(12f); + _cameraPitch = Mathf.Lerp(_cameraPitch, targetPitch, 1f - MathF.Exp(-dt * 4.0f)); + _orbitalPodCamBlend *= MathF.Exp(-dt * 4.5f); + if (_orbitalPodCamBlend < 0.005f) _orbitalPodCamBlend = 0f; + } + + float rightOffset = MathF.Max(1.6f, spec.HalfWidth * 1.15f + 0.8f); + float heightOffset = spec.HalfHeight * 1.45f + 1.4f; + float boundingR = MathF.Max(spec.HalfWidth, MathF.Max(spec.HalfHeight * 0.72f, spec.HalfLength * 0.90f)); + float backDist = Math.Clamp(boundingR * 2.15f + 4.2f, 7.2f, 19.5f) * _cameraZoom; + if (_orbitalPodCamBlend > 0f) + { + backDist = Mathf.Lerp(backDist, 22.0f * _cameraZoom, _orbitalPodCamBlend); + heightOffset = Mathf.Lerp(heightOffset, heightOffset + 2.2f, _orbitalPodCamBlend); + } + float targetShoulderY = (posInterp.Y - spec.HalfHeight) + heightOffset; + + if (_lastCamChassisId != spec.Id || dt >= 1f) + { + _smoothedShoulderY = targetShoulderY; + _lastCamChassisId = spec.Id; + } + else + { + float yBlend = 1f - MathF.Exp(-dt * 24f); + _smoothedShoulderY = Mathf.Lerp(_smoothedShoulderY, targetShoulderY, yBlend); + } + + var pivot = new Vector3(posInterp.X, _smoothedShoulderY, posInterp.Z); + lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized(); + + // Segment 1: sweep terrain + static Box3D (StableId < ContenderStableIdBase) from pivot along camRight * rightOffset + float effectiveRight = rightOffset; + if (CastStaticCameraRay(pivot, camRight, rightOffset, out float rightHitDist)) + { + effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist)); + } + Vector3 shoulderPos = pivot + camRight * effectiveRight; + + // Segment 2: sweep terrain + static Box3D from shoulderPos along -lookDir * backDist + float effectiveBack = backDist; + if (CastStaticCameraRay(shoulderPos, -lookDir, backDist, out float backHitDist)) + { + effectiveBack = MathF.Min(effectiveBack, SafeCameraPullbackDist(backHitDist)); + } + + camPos = shoulderPos - lookDir * effectiveBack; + + float minTerrainY = Session.ViewState.Terrain.SampleHeight(camPos.X, camPos.Z) + 1.2f; + if (camPos.Y < minTerrainY) + { + camPos.Y = minTerrainY; + } + + // Segment 3: verify direct pivot -> camPos LOS against static terrain/buildings so stepped wings cannot occlude player + Vector3 pivotToCam = camPos - pivot; + float pivotToCamDist = pivotToCam.Length(); + if (pivotToCamDist > 0.05f) + { + Vector3 pivotToCamDir = pivotToCam / pivotToCamDist; + if (CastStaticCameraRay(pivot, pivotToCamDir, pivotToCamDist, out float wingHitDist)) + { + camPos = pivot + pivotToCamDir * SafeCameraPullbackDist(wingHitDist); + } } } diff --git a/client/ParticlePool.cs b/client/ParticlePool.cs index 50157a6..bd59c0d 100644 --- a/client/ParticlePool.cs +++ b/client/ParticlePool.cs @@ -255,6 +255,28 @@ public partial class ParticlePool : Node3D } break; } + + case DropPodEvent dpe: + if ((DropPodEventKind)dpe.Kind == DropPodEventKind.PodTouchdownBlowPetals) + { + bool isLocal = dpe.ContenderId == session.LocalContenderId; + bool isContender = dpe.PodKind == (byte)OrbitalPodKind.Contender; + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + Vector3 nrm = new(dpe.NormalX, dpe.NormalY, dpe.NormalZ); + if (nrm.LengthSquared() < 1e-4f) nrm = Vector3.Up; + nrm = nrm.Normalized(); + EmitPodTouchdownBurst(pos, nrm, sampleGroundTint(pos.X, pos.Z), isContender, isLocal, camPos, hasCam); + } + else if ((DropPodEventKind)dpe.Kind == DropPodEventKind.PodRetroBurnStart) + { + bool isLocal = dpe.ContenderId == session.LocalContenderId; + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + if (isLocal || !hasCam || pos.DistanceSquaredTo(camPos) <= 220f * 220f) + { + SpawnFlashLight(pos - new Vector3(0f, 0.8f, 0f), new Color(1.0f, 0.62f, 0.22f), 4.5f, 15f, 0.14f, priority: isLocal ? 9 : 4); + } + } + break; } } } @@ -920,6 +942,190 @@ public partial class ParticlePool : Node3D } } + public void EmitPodReentryStreak(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && podPos.DistanceSquaredTo(camPos) > 650f * 650f) + { + return; + } + + float scale = isContender ? 1.25f : 0.85f; + Vector3 upTrail = (-podVel.Normalized()) * (3.5f + NextFloat() * 3.0f); + SpawnParticle(new ParticleSlot + { + Active = true, + Mode = ModeSteamFire, + Position = podPos + new Vector3(NextSigned() * 0.55f, 0.6f, NextSigned() * 0.55f), + Velocity = upTrail + new Vector3(NextSigned() * 1.1f, 1.8f, NextSigned() * 1.1f), + Gravity = -1.5f, + Drag = 2.2f, + StartSize = 0.85f * scale, + EndSize = 0.28f * scale, + AspectY = 2.0f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = NextSigned() * 2.5f, + Emissive = 2.4f + heatGlow * 1.4f, + ColorStart = new Color(1.0f, 0.64f, 0.20f, 0.88f), + ColorEnd = new Color(0.75f, 0.22f, 0.06f, 0.0f), + Lifetime = 0.20f + NextFloat() * 0.10f + }); + } + + public void EmitPodRetroBurn( + Vector3 podBasePos, + float agl, + Color groundTint, + bool isContender, + bool isLocal, + Vector3 camPos, + bool hasCam) + { + EnsureInitialized(); + float distSq = hasCam ? podBasePos.DistanceSquaredTo(camPos) : 0f; + if (hasCam && distSq > 480f * 480f) + { + return; + } + + float scale = isContender ? 1.20f : 0.85f; + // Downward fiery retro plume + for (int i = 0; i < 2; i++) + { + SpawnParticle(new ParticleSlot + { + Active = true, + Mode = ModeSteamFire, + Position = podBasePos + new Vector3(NextSigned() * 0.65f, 0.05f, NextSigned() * 0.65f), + Velocity = new Vector3(NextSigned() * 2.2f, -(14f + NextFloat() * 9f), NextSigned() * 2.2f), + Gravity = -2.0f, + Drag = 2.4f, + StartSize = 0.72f * scale, + EndSize = 1.65f * scale, + AspectY = 1.45f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = NextSigned() * 3.0f, + Emissive = 3.1f, + ColorStart = new Color(1.0f, 0.72f, 0.26f, 0.94f), + ColorEnd = new Color(0.85f, 0.24f, 0.05f, 0.0f), + Lifetime = 0.16f + NextFloat() * 0.08f + }); + } + + // Hot retro ember spark + if (NextFloat() < 0.7f) + { + SpawnParticle(new ParticleSlot + { + Active = true, + Mode = ModeSparkStreak, + Position = podBasePos + new Vector3(NextSigned() * 0.7f, 0.1f, NextSigned() * 0.7f), + Velocity = new Vector3(NextSigned() * 6.5f, -(9f + NextFloat() * 6f), NextSigned() * 6.5f), + Gravity = 6.0f, + Drag = 1.2f, + StartSize = 0.26f, + EndSize = 0.10f, + AspectY = 1.6f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = 0f, + Emissive = 3.2f, + ColorStart = new Color(1.0f, 0.78f, 0.30f, 0.96f), + ColorEnd = new Color(0.95f, 0.28f, 0.06f, 0.0f), + Lifetime = 0.18f + NextFloat() * 0.08f + }); + } + + // Ground dust wash when < 55m AGL + if (agl < 55f && (!hasCam || distSq <= 240f * 240f)) + { + float washT = Math.Clamp(1f - agl / 55f, 0.15f, 1f); + Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.25f, 0f); + Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.56f * washT); + Color dustEnd = new(groundTint.R * 0.9f, groundTint.G * 0.9f, groundTint.B * 0.9f, 0.0f); + int dustCount = isContender ? 2 : 1; + for (int d = 0; d < dustCount; d++) + { + float ang = NextFloat() * MathF.Tau; + float spd = (6.5f + NextFloat() * 7.0f) * washT * scale; + SpawnParticle(new ParticleSlot + { + Active = true, + Mode = ModeDustSmoke, + Position = groundPos + new Vector3(MathF.Cos(ang) * 0.9f, 0f, MathF.Sin(ang) * 0.9f), + Velocity = new Vector3(MathF.Cos(ang) * spd, 1.2f + NextFloat() * 1.4f, MathF.Sin(ang) * spd), + Gravity = 0.35f, + Drag = 2.6f, + StartSize = 0.85f * scale, + EndSize = 2.35f * scale, + AspectY = 1.0f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = NextSigned() * 1.8f, + Emissive = 0f, + ColorStart = dustStart, + ColorEnd = dustEnd, + Lifetime = 0.42f + NextFloat() * 0.18f + }); + } + } + + if (isLocal || !hasCam || distSq <= 95f * 95f) + { + SpawnFlashLight(podBasePos - new Vector3(0f, 0.6f, 0f), new Color(1.0f, 0.60f, 0.18f), 3.8f, 14f, 0.09f, priority: isLocal ? 8 : 3); + } + } + + public void EmitPodTouchdownBurst( + Vector3 pos, + Vector3 normal, + Color groundTint, + bool isContender, + bool isLocal, + Vector3 camPos, + bool hasCam) + { + EnsureInitialized(); + float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; + if (!isLocal && hasCam && distSq > 360f * 360f) + { + return; + } + + float scale = isContender ? 1.35f : 0.95f; + int dustCount = isContender ? 7 : 4; + Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.68f); + Color dustEnd = new(groundTint.R * 0.88f, groundTint.G * 0.88f, groundTint.B * 0.88f, 0.0f); + for (int i = 0; i < dustCount; i++) + { + float ang = (i / (float)dustCount) * MathF.Tau + NextFloat() * 0.4f; + float spd = (7.5f + NextFloat() * 6.5f) * scale; + SpawnParticle(new ParticleSlot + { + Active = true, + Mode = ModeDustSmoke, + Position = pos + normal * 0.35f + new Vector3(MathF.Cos(ang) * 1.1f, 0f, MathF.Sin(ang) * 1.1f), + Velocity = new Vector3(MathF.Cos(ang) * spd, 1.8f + NextFloat() * 2.2f, MathF.Sin(ang) * spd), + Gravity = 0.45f, + Drag = 2.2f, + StartSize = 0.95f * scale, + EndSize = 2.55f * scale, + AspectY = 1.0f, + Rotation = NextFloat() * MathF.Tau, + AngularVel = NextSigned() * 1.6f, + Emissive = 0f, + ColorStart = dustStart, + ColorEnd = dustEnd, + Lifetime = 0.55f + NextFloat() * 0.25f + }); + } + + SpawnSparkBurst(pos + normal * 0.5f, normal, isContender ? 8 : 4, new Color(1.0f, 0.68f, 0.20f, 0.98f), 16f * scale); + + if (isLocal || !hasCam || distSq <= 140f * 140f) + { + SpawnFlashLight(pos + normal * 1.2f, new Color(1.0f, 0.58f, 0.16f), 5.8f, 18f, 0.18f, priority: isLocal ? 10 : 6); + } + } + private void EmitImpactDustPlume(Vector3 pos, Vector3 normal, Color groundTint, int count, float size) { Color c0 = new(groundTint.R, groundTint.G, groundTint.B, 0.60f); diff --git a/client/PomDecalPool.cs b/client/PomDecalPool.cs index d97bc85..c7472d5 100644 --- a/client/PomDecalPool.cs +++ b/client/PomDecalPool.cs @@ -142,6 +142,29 @@ public partial class PomDecalPool : Node3D case HitImpactEvent hit: StampHit(in hit, state, getVisual); break; + case DropPodEvent dpe: + if ((DropPodEventKind)dpe.Kind == DropPodEventKind.PodTouchdownBlowPetals) + { + bool isContender = dpe.PodKind == (byte)OrbitalPodKind.Contender; + Vector3 pos = new(dpe.X, dpe.Y, dpe.Z); + Vector3 nrm = new(dpe.NormalX, dpe.NormalY, dpe.NormalZ); + if (nrm.LengthSquared() < 1e-4f) nrm = Vector3.Up; + nrm = nrm.Normalized(); + Transform3D xf = BuildSurfaceTransform(pos + nrm * 0.05f, nrm, isContender ? 6.2f : 3.8f, dpe.PodId * 1.13f); + AllocateSlot(new DecalSlot + { + Active = true, + Age = 0f, + Lifetime = isContender ? 34f : 24f, + TileIndex = 15f, + InitialHeat = 1.0f, + BaseOpacity = 0.98f, + DepthScale = 0.095f, + WorldXform = xf, + DetachedFadeRemaining = -1f + }); + } + break; } } diff --git a/client/VehicleAssetCache.cs b/client/VehicleAssetCache.cs index 346e3ac..64741a2 100644 --- a/client/VehicleAssetCache.cs +++ b/client/VehicleAssetCache.cs @@ -83,6 +83,18 @@ public sealed class VehicleAssetCache : IDisposable public required IReadOnlyDictionary 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 static readonly string[] ExpectedGearIds = { "mg_762", "autocannon", "recoilless", "copper_rad", "gilded_lance", "gold_radiator" @@ -91,6 +103,7 @@ public sealed class VehicleAssetCache : IDisposable private readonly Dictionary _vehicles = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _gear = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _gearVariantMeshes = new(StringComparer.OrdinalIgnoreCase); + private DropPodTemplate? _dropPod; private readonly string _vehiclesDir; private readonly string _gearDir; private bool _disposed; @@ -120,6 +133,25 @@ public sealed class VehicleAssetCache : IDisposable { GetOrLoadGear(gearId); } + GetOrLoadDropPod(); + } + + 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) @@ -565,6 +597,95 @@ public sealed class VehicleAssetCache : IDisposable }; } + 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(); + 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 ExactStructuralNodeNames = new(StringComparer.OrdinalIgnoreCase) { "chassis", "hull", "pelvis", "core", "trunk", "waist", "waistlug", "torso.pose", "aim.turret", "hull.pose", @@ -2110,5 +2231,10 @@ public sealed class VehicleAssetCache : IDisposable } _vehicles.Clear(); _gear.Clear(); + if (_dropPod is not null && GodotObject.IsInstanceValid(_dropPod.SceneTemplate)) + { + _dropPod.SceneTemplate.QueueFree(); + } + _dropPod = null; } } diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index 0f04ab2..bf6bd97 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -39,6 +39,7 @@ public partial class Smoke : Node { _main = GD.Load("res://Main.tscn").Instantiate
(); _main.InitialMapKindOverride = ArenaMapKind.Desert; + _main.InitialSkipDropOverride = true; AddChild(_main); if (_main.Failure is { } failure) @@ -275,6 +276,7 @@ public partial class Smoke : Node await MaybeCapturePreviewAsync(isHeadless); await VerifyMaxLoadPaladinGarageAsync(); await VerifySionMapAsync(); + await VerifyOrbitalDropSequenceAsync(); } private async Task VerifyHudAndShadersAsync(bool isHeadless) @@ -1447,7 +1449,8 @@ public partial class Smoke : Node var audio = _main.Audio; audio.EnsureInitialized(); Check(audio.Bank.HavenClipCount == 25, $"Expected 25 curated Haven clips in ProceduralAudioBank, got {audio.Bank.HavenClipCount}"); - Check(audio.Bank.ProceduralClipCount == 18, $"Expected 18 procedural clips in ProceduralAudioBank, got {audio.Bank.ProceduralClipCount}"); + Check(audio.Bank.ProceduralClipCount == RustToDust.Core.Audio.PcmSynth.CueRegistry.Count, + $"Expected {RustToDust.Core.Audio.PcmSynth.CueRegistry.Count} procedural clips in ProceduralAudioBank, got {audio.Bank.ProceduralClipCount}"); audio.ClearAll(); audio.ResetStatsForTest(); @@ -1812,7 +1815,7 @@ public partial class Smoke : Node private async Task VerifySionMapAsync() { - _main.Reset(42, ArenaMapKind.Sion); + _main.Reset(42, ArenaMapKind.Sion, skipInitialDrop: true); Check(_main.Failure is null, $"Sion Reset failed: {_main.Failure}"); if (_main.Failure is not null) { @@ -1882,6 +1885,127 @@ public partial class Smoke : Node GD.Print($"SMOKE INFO: Sion verified (chunks={_main.SionMap.TerrainChunkCount}, tiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))"); } + private async Task VerifyOrbitalDropSequenceAsync() + { + var podTpl = _main.Arena.AssetCache.GetOrLoadDropPod(); + Check(podTpl.CoreMesh.GetSurfaceCount() == 1, $"Expected single-surface DropPod CoreMesh, got {podTpl.CoreMesh.GetSurfaceCount()}"); + Check(podTpl.PetalMesh.GetSurfaceCount() == 1, $"Expected single-surface DropPod PetalMesh, got {podTpl.PetalMesh.GetSurfaceCount()}"); + Check(podTpl.PetalLocalTransforms.Length == 4, $"Expected 4 DropPod petal transforms, got {podTpl.PetalLocalTransforms.Length}"); + Check(podTpl.Size.Y >= 4.0f && podTpl.Size.Y <= 5.2f, $"Unexpected DropPod height {podTpl.Size.Y:F2}m"); + + // Verify COLOR_0 weathering exists on both CoreMesh and PetalMesh + var coreArr = podTpl.CoreMesh.SurfaceGetArrays(0); + var petalArr = podTpl.PetalMesh.SurfaceGetArrays(0); + Check(coreArr.Count > (int)Mesh.ArrayType.Color && coreArr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray, + "DropPod CoreMesh missing COLOR_0 weathering array"); + Check(petalArr.Count > (int)Mesh.ArrayType.Color && petalArr[(int)Mesh.ArrayType.Color].VariantType == Variant.Type.PackedColorArray, + "DropPod PetalMesh missing COLOR_0 weathering array"); + + int bucketsBefore = _main.Arena.PartPool.BucketCount; + _main.Reset(42, ArenaMapKind.Sion, skipInitialDrop: false); + Check(_main.Failure is null, $"Sion Orbital Reset failed: {_main.Failure}"); + if (_main.Failure is not null) + { + return; + } + + _main.SetPhysicsProcess(false); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var session = _main.Session; + var player = session.LocalContender; + Check(player.Lifecycle == ContenderLifecycle.Deploying && player.IsInDropPod, + $"Expected player to start Deploying in DropPod, got {player.Lifecycle}"); + Check(!player.IsGroundedActive, "Expected player IsGroundedActive == false while inside DropPod"); + Check(session.ActivePods.Count >= 50, $"Expected >= 50 Wave 0 active pods (40 gear + 12 contenders), got {session.ActivePods.Count}"); + var pVisDeploying = _main.Arena.GetContenderVisual(player.Id); + Check(pVisDeploying is null || !pVisDeploying.Root.Visible, "Expected ground vehicle visual hidden while inside DropPod"); + + _main.Arena.Sync(session, 0.1f, 1f / 60f, 1f); + int bucketsDuringDrop = _main.Arena.PartPool.BucketCount; + Check(bucketsDuringDrop <= bucketsBefore + 2, + $"Expected DropPod to add <= 2 MultiMeshPartPool buckets (Core + Petal), delta={bucketsDuringDrop - bucketsBefore}"); + + bool sawRetroBurn = false; + bool sawGearEarlyTouchdown = false; + int touchdownTick = -1; + int debrisAtTouchdown = 0; + + _main.SetScriptedInput(new PlayerInput( + Throttle: 1f, + Steer: 0f, + AimWorldX: player.X, + AimWorldZ: player.Z + 120f, + Fire: false, + InteractPickup: false, + Brake: false)); + + for (int tick = 0; tick < 620; tick++) + { + var tickInp = _main.Session.LocalContender.IsInDropPod + ? new PlayerInput(1f, 0f, player.X, player.Z + 120f, false, false, false) + : new PlayerInput(1f, 0f, player.X, player.Z + 60f, false, false, false); + + session.SubmitLocalInput(in tickInp, isPhysicsTick: true); + _main.Arena.Sync(session, (tick + 1) / 60f, 1f / 60f, 1f); + + var evs = new List(32); + session.DrainSimEvents(evs); + _main.Arena.ConsumeEvents(session, evs, Array.Empty(), 1f / 60f, _main.SampleCurrentMapGroundTint); + _main.CameraJuice.ConsumeEvents(evs, session.LocalContenderId, new System.Numerics.Vector3(player.X, player.Y, player.Z), session); + _main.Audio.UpdateFrame(session, evs, Array.Empty(), _main.Camera.GlobalPosition, 1f / 60f, 1f); + _main.Hud.Sync(session); + + if (tick == 270) // t = 4.5s: gear pods should have landed while player is still falling + { + sawGearEarlyTouchdown = session.ViewState.GroundDrops.Count >= 35 && player.IsInDropPod; + } + + if (player.IsInDropPod) + { + foreach (var pod in session.ActivePods) + { + if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == player.Id && pod.Phase == OrbitalPodPhase.RetroBurn) + { + sawRetroBurn = true; + break; + } + } + } + else if (touchdownTick < 0 && player.IsGroundedActive) + { + touchdownTick = tick; + debrisAtTouchdown = _main.Arena.Debris.ActiveCount; + break; + } + } + + Check(sawGearEarlyTouchdown, $"Expected >= 35 Wave 0 gear drops on ground at t=4.5s while player still in pod (drops={session.ViewState.GroundDrops.Count}, inPod={player.IsInDropPod})"); + Check(sawRetroBurn, "Expected local player pod to enter RetroBurn phase"); + Check(touchdownTick > 240 && touchdownTick < 620, $"Expected player pod touchdown in (240, 620) ticks, got {touchdownTick}"); + Check(debrisAtTouchdown >= 4, $"Expected >= 4 blown-off petals in DebrisSystem on touchdown, got {debrisAtTouchdown}"); + Check(VehicleVisualInstance.PerfMaterialDupCount == 0, $"Expected 0 material duplicates during orbital drop, got {VehicleVisualInstance.PerfMaterialDupCount}"); + + var pVisLanded = _main.Arena.GetContenderVisual(player.Id); + Check(pVisLanded is not null && pVisLanded.Root.Visible, "Expected player ground chassis visual visible immediately on touchdown"); + + // Verify post-touchdown ground driving works cleanly + float landX = player.X; + float landZ = player.Z; + for (int t = 0; t < 30; t++) + { + var driveInp = new PlayerInput(1f, 0f, player.X, player.Z + 60f, false, false, false); + session.SubmitLocalInput(in driveInp, isPhysicsTick: true); + } + float postDisp = MathF.Sqrt((player.X - landX) * (player.X - landX) + (player.Z - landZ) * (player.Z - landZ)); + Check(postDisp > 1.5f, $"Expected post-touchdown driving displacement > 1.5m over 30 ticks, got {postDisp:F2}m"); + + _main.SetScriptedInput(null); + _main.SetPhysicsProcess(true); + + GD.Print($"SMOKE INFO: Cut 6b OrbitalDrop verified (touchdownTick={touchdownTick}, debris={debrisAtTouchdown}, postDisp={postDisp:F2}m, bucketsDelta={bucketsDuringDrop - bucketsBefore}, matDups={VehicleVisualInstance.PerfMaterialDupCount})"); + } + private static int CountPremulViolations(Image img, float tolerance) { int count = 0; diff --git a/src/RustToDust.Core/Audio/PcmSynth.cs b/src/RustToDust.Core/Audio/PcmSynth.cs index 282662e..5ecd11d 100644 --- a/src/RustToDust.Core/Audio/PcmSynth.cs +++ b/src/RustToDust.Core/Audio/PcmSynth.cs @@ -24,7 +24,11 @@ namespace RustToDust.Core.Audio UiHitKill, UiOverheatAlarm, UiPickupModule, - UiPickupImperial + UiPickupImperial, + PodRetroBurnLoop, + PodSlamImpact, + PodPetalBlow, + UiDropWaveKlaxon } public sealed record PcmClipData( @@ -154,7 +158,11 @@ namespace RustToDust.Core.Audio (ProceduralCueId.UiHitKill, "ui_hit_kill"), (ProceduralCueId.UiOverheatAlarm, "ui_overheat_alarm"), (ProceduralCueId.UiPickupModule, "ui_pickup_module"), - (ProceduralCueId.UiPickupImperial, "ui_pickup_imperial") + (ProceduralCueId.UiPickupImperial, "ui_pickup_imperial"), + (ProceduralCueId.PodRetroBurnLoop, "pod_retro_burn"), + (ProceduralCueId.PodSlamImpact, "pod_slam"), + (ProceduralCueId.PodPetalBlow, "pod_petal_pop"), + (ProceduralCueId.UiDropWaveKlaxon, "ui_drop_wave") }; public static IReadOnlyList<(ProceduralCueId Cue, string Key)> CueRegistry => AllCues; @@ -405,6 +413,26 @@ namespace RustToDust.Core.Audio isLoop = false; buf = GenUiPickupImperial(); break; + case ProceduralCueId.PodRetroBurnLoop: + key = "pod_retro_burn"; + isLoop = true; + buf = GenPodRetroBurnLoop(); + break; + case ProceduralCueId.PodSlamImpact: + key = "pod_slam"; + isLoop = false; + buf = GenPodSlamImpact(); + break; + case ProceduralCueId.PodPetalBlow: + key = "pod_petal_pop"; + isLoop = false; + buf = GenPodPetalBlow(); + break; + case ProceduralCueId.UiDropWaveKlaxon: + key = "ui_drop_wave"; + isLoop = false; + buf = GenUiDropWaveKlaxon(); + break; default: throw new ArgumentOutOfRangeException(nameof(cue), cue, null); } @@ -775,6 +803,90 @@ namespace RustToDust.Core.Audio return s; } + private static float[] GenPodRetroBurnLoop() + { + int n = SampleRate; + float[] rumbleNoise = GeneratePeriodicFilteredNoise(n, 0xA17C9311u, lpAlpha: 0.08f); + float[] jetRoar = GeneratePeriodicFilteredNoise(n, 0x55E2B409u, lpAlpha: 0.12f); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float pulse = 1f + 0.14f * MathF.Sin(MathF.Tau * 19f * t); + float sub = 0.34f * MathF.Sin(MathF.Tau * 46f * t) + 0.22f * MathF.Sin(MathF.Tau * 73f * t); + float turbine = 0.10f * MathF.Sin(MathF.Tau * 184f * t); + s[i] = (sub + turbine + rumbleNoise[i] * 1.85f + jetRoar[i] * 1.35f) * pulse; + } + NormalizePeak(s, 0.84f); + return s; + } + + private static float[] GenPodSlamImpact() + { + int n = (int)(0.62f * SampleRate); + var s = new float[n]; + uint rng = 0x3D18A275u; + float lp = 0f; + float phase = 0f; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float freq = 26f + 98f * MathF.Exp(-t * 28f); + phase += MathF.Tau * freq / SampleRate; + float sub = MathF.Sin(phase) * MathF.Exp(-t * 6.8f); + float white = NextSignedNoise(ref rng); + lp = lp * 0.84f + white * 0.16f; + float crunch = (white * 0.25f + lp * 1.4f) * MathF.Exp(-t * 9.5f); + float bell = (MathF.Sin(MathF.Tau * 210f * t) + 0.45f * MathF.Sin(MathF.Tau * 335f * t)) * MathF.Exp(-t * 14f); + float attack = MathF.Min(1f, t / 0.002f); + float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f; + s[i] = (sub * 0.85f + crunch * 0.55f + bell * 0.26f) * attack * fadeOut; + } + NormalizePeak(s, 0.88f); + return s; + } + + private static float[] GenPodPetalBlow() + { + int n = (int)(0.42f * SampleRate); + var s = new float[n]; + uint rng = 0x71B4C20Eu; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float boltSnap = MathF.Sin(MathF.Tau * (940f - 520f * MathF.Min(1f, t * 14f)) * t) * MathF.Exp(-t * 36f); + float clang = (MathF.Sin(MathF.Tau * 412f * t) + 0.6f * MathF.Sin(MathF.Tau * 685f * t)) * MathF.Exp(-t * 16f); + float hiss = NextSignedNoise(ref rng) * MathF.Exp(-t * 12f); + float attack = MathF.Min(1f, t / 0.0015f); + float fadeOut = u > 0.82f ? (1f - (u - 0.82f) / 0.18f) : 1f; + s[i] = (boltSnap * 0.55f + clang * 0.45f + hiss * 0.48f) * attack * fadeOut; + } + NormalizePeak(s, 0.84f); + return s; + } + + private static float[] GenUiDropWaveKlaxon() + { + int n = (int)(0.54f * SampleRate); + var s = new float[n]; + for (int i = 0; i < n; i++) + { + float t = i / (float)SampleRate; + float u = i / (float)(n - 1); + float e1 = MathF.Min(1f, t / 0.006f) * MathF.Exp(-t * 8.5f); + float t2 = t - 0.18f; + float e2 = t2 >= 0f ? MathF.Min(1f, t2 / 0.006f) * MathF.Exp(-t2 * 7.5f) : 0f; + float horn1 = MathF.Sin(MathF.Tau * 392f * t) + 0.42f * MathF.Sin(MathF.Tau * 588f * t); + float horn2 = t2 >= 0f ? (MathF.Sin(MathF.Tau * 523.25f * t2) + 0.42f * MathF.Sin(MathF.Tau * 784.88f * t2)) : 0f; + float fadeOut = u > 0.86f ? (1f - (u - 0.86f) / 0.14f) : 1f; + s[i] = (horn1 * e1 * 0.48f + horn2 * e2 * 0.54f) * fadeOut; + } + NormalizePeak(s, 0.82f); + return s; + } + private static float[] GeneratePeriodicFilteredNoise(int n, uint seed, float lpAlpha) { int fade = Math.Min(2048, n / 4); diff --git a/src/RustToDust.Core/OrbitalDropSystem.cs b/src/RustToDust.Core/OrbitalDropSystem.cs index 4158cc9..f904ed3 100644 --- a/src/RustToDust.Core/OrbitalDropSystem.cs +++ b/src/RustToDust.Core/OrbitalDropSystem.cs @@ -312,10 +312,10 @@ namespace RustToDust.Core ? MathF.Max(terrainNext, sampleNext.SurfaceY) : terrainNext; - // 3. Closing speed & burn trigger (accounts for both terrain slope and surface step) + // 3. Closing speed & burn trigger (use continuous terrain slope so vertical building edges never spike vClose to ~800 m/s) float vDown = MathF.Max(0f, -pod.VelY); - float surfaceRiseRate = MathF.Max(0f, (surfaceNext - surfaceNow) / dt); - float vClose = vDown + surfaceRiseRate; + float slopeRiseRate = MathF.Max(0f, (terrainNext - terrainNow) / dt); + float vClose = vDown + slopeRiseRate; float hBurn = MathF.Max( 8.0f, MathF.Max(0f, vClose * vClose - vTouch * vTouch) / (2f * aNetNom) + preset.SafetyMarginM); diff --git a/tools/vehicles/build_drop_pod.py b/tools/vehicles/build_drop_pod.py new file mode 100644 index 0000000..58bac25 --- /dev/null +++ b/tools/vehicles/build_drop_pod.py @@ -0,0 +1,407 @@ +"""Build the Brokkr-powered Imperial Orbital Drop Pod GLB into assets/vehicles/drop_pod/drop_pod.glb.""" +from __future__ import annotations + +import math +import sys +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import vehicle_common as vc # noqa: E402 + + +def _add_prism_wedge( + bm: bmesh.types.BMesh, + x0_bot: float, + x1_bot: float, + x0_top: float, + x1_top: float, + hw_bot: float, + hw_top: float, + z0: float, + z1: float, + mat_idx: int, + taper_edge: float = 0.14, +) -> None: + """Create a tapered trapezoidal armored hull plate oriented with outward face along +X.""" + # Inner face (4 corners), outer face beveled slightly narrower for crisp chamfers + v_in_bl = bm.verts.new((x0_bot, -hw_bot, z0)) + v_in_br = bm.verts.new((x0_bot, hw_bot, z0)) + v_in_tr = bm.verts.new((x0_top, hw_top, z1)) + v_in_tl = bm.verts.new((x0_top, -hw_top, z1)) + + hw_ob = max(0.05, hw_bot - taper_edge) + hw_ot = max(0.05, hw_top - taper_edge) + v_out_bl = bm.verts.new((x1_bot, -hw_ob, z0 + 0.05)) + v_out_br = bm.verts.new((x1_bot, hw_ob, z0 + 0.05)) + v_out_tr = bm.verts.new((x1_top, hw_ot, z1 - 0.05)) + v_out_tl = bm.verts.new((x1_top, -hw_ot, z1 - 0.05)) + + quads = [ + (v_out_bl, v_out_br, v_out_tr, v_out_tl), # outer (+X) + (v_in_br, v_in_bl, v_in_tl, v_in_tr), # inner (-X) + (v_in_bl, v_out_bl, v_out_tl, v_in_tl), # -Y flank + (v_out_br, v_in_br, v_in_tr, v_out_tr), # +Y flank + (v_in_bl, v_in_br, v_out_br, v_out_bl), # bottom (-Z) + (v_out_tl, v_out_tr, v_in_tr, v_in_tl), # top (+Z) + ] + for q in quads: + f = bm.faces.new(q) + f.material_index = mat_idx + + +def _add_local_box( + bm: bmesh.types.BMesh, + center: tuple[float, float, float], + size: tuple[float, float, float], + rot_deg: tuple[float, float, float], + mat_idx: int, +) -> None: + rot_m = ( + Matrix.Rotation(math.radians(rot_deg[2]), 4, "Z") + @ Matrix.Rotation(math.radians(rot_deg[1]), 4, "Y") + @ Matrix.Rotation(math.radians(rot_deg[0]), 4, "X") + ) + mat = Matrix.Translation(center) @ rot_m @ Matrix.Diagonal((size[0], size[1], size[2], 1.0)) + ret = bmesh.ops.create_cube(bm, size=1.0, matrix=mat) + verts_set = set(ret["verts"]) + for f in bm.faces: + if all(v in verts_set for v in f.verts): + f.material_index = mat_idx + + +def _build_petal_mesh(name: str, mats: dict[str, bpy.types.Material]) -> tuple[bpy.types.Mesh, Vector]: + """Build a single armored blow-off hull petal with local origin at its exact geometric centroid. + + Authored in local radial coordinates where +X is outward, Y is tangential width, Z is vertical. + Returns (mesh, world_centroid_offset_in_radial_XZ). + """ + mat_order = ("olive_armor", "signal_orange", "gunmetal", "socket_bay") + bm = bmesh.new() + + # World-space radial placement before centroid centering: + # Pod petal spans Z = 0.56..3.32m, leaning inward from r ~ 1.32m (bottom) to 0.94m (top). + z0, z1 = 0.56, 3.32 + x0_b, x1_b = 1.04, 1.34 + x0_t, x1_t = 0.72, 0.96 + hw_b, hw_t = 0.54, 0.37 + + # 0: Main armored outer shell (olive_armor) + _add_prism_wedge(bm, x0_b, x1_b, x0_t, x1_t, hw_b, hw_t, z0, z1, mat_idx=0, taper_edge=0.11) + + # 3: Recessed dark inner liner plate (socket_bay) + _add_prism_wedge(bm, x0_b - 0.04, x0_b + 0.01, x0_t - 0.04, x0_t + 0.01, hw_b - 0.09, hw_t - 0.07, z0 + 0.14, z1 - 0.14, mat_idx=3, taper_edge=0.02) + + # Mid-slope angle for surface-aligned ribs and chevron plates + dx = x1_t - x1_b + dz = z1 - z0 + pitch_deg = math.degrees(math.atan2(-dx, dz)) # tilt inward toward +Z + + # 0: Heavy vertical central blast rib (olive_armor) + mid_x = 0.5 * (x1_b + x1_t) + 0.04 + mid_z = 0.5 * (z0 + z1) + _add_local_box(bm, (mid_x, 0.0, mid_z), (0.14, 0.22, 2.24), (0.0, pitch_deg, 0.0), mat_idx=0) + + # 1: Imperial accent chevron / hazard stripe band near upper third (signal_orange) + stripe_z = 2.48 + t_s = (stripe_z - z0) / dz + stripe_x = x1_b + dx * t_s + 0.025 + _add_local_box(bm, (stripe_x, 0.0, stripe_z), (0.08, 0.54, 0.22), (0.0, pitch_deg, 0.0), mat_idx=1) + _add_local_box(bm, (x1_b + dx * 0.22 + 0.025, 0.0, 1.15), (0.07, 0.68, 0.14), (0.0, pitch_deg, 0.0), mat_idx=1) + + # 2: Explosive bolt hinge lugs at base & top clamp collar (gunmetal) + for side in (-1.0, 1.0): + _add_local_box(bm, (x1_b - 0.04, side * 0.34, z0 + 0.16), (0.14, 0.12, 0.20), (0.0, pitch_deg, 0.0), mat_idx=2) + _add_local_box(bm, (x1_t - 0.03, side * 0.22, z1 - 0.15), (0.12, 0.10, 0.18), (0.0, pitch_deg, 0.0), mat_idx=2) + + # Bevel crisp armor edges slightly + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + bmesh.ops.bevel( + bm, + geom=list(bm.edges), + offset=0.015, + segments=1, + affect="EDGES", + clamp_overlap=True, + ) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces) + + # Compute exact AABB centroid of the petal and shift all vertices so local origin == centroid! + coords = np.array([v.co[:] for v in bm.verts], dtype=np.float64) + c_min = coords.min(axis=0) + c_max = coords.max(axis=0) + centroid = Vector(((c_min[0] + c_max[0]) * 0.5, (c_min[1] + c_max[1]) * 0.5, (c_min[2] + c_max[2]) * 0.5)) + bmesh.ops.translate(bm, verts=bm.verts, vec=-centroid) + + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + + for m_name in mat_order: + mesh.materials.append(mats[m_name]) + + sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") + sharp.data.foreach_set("value", np.ones(len(mesh.polygons), dtype=bool)) + mesh.update() + return mesh, centroid + + +def build_drop_pod() -> Path: + vc.reset_scene() + mats = vc.ensure_materials() + + root = vc.make_empty("DropPodRoot") + body_empty = vc.make_empty("CoreBody", parent=root) + + # 1. Heavy Octagonal Ablative Heatshield Base (Z = 0.00 .. 0.62, width ~2.80m) + shield_prof = [ + [0.00, 0.00], + [1.12, 0.00], + [1.36, 0.14], + [1.40, 0.34], + [1.24, 0.56], + [0.98, 0.64], + [0.00, 0.64], + ] + vc.make_lathe_part( + "HeatshieldBase", + shield_prof, + segments=8, + loop=False, + smooth=False, + mat_name="gunmetal", + parent=body_empty, + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.015, + ) + + # Armored lower skirt bumper ring + skirt_prof = [ + [1.33, 0.22], + [1.43, 0.25], + [1.42, 0.42], + [1.28, 0.50], + ] + vc.make_lathe_part( + "HeatshieldSkirt", + skirt_prof, + segments=8, + loop=True, + smooth=False, + mat_name="olive_armor", + parent=body_empty, + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.012, + ) + + # Central ventral retro-exhaust port + vc.make_tube_part( + "RetroNozzle", + 0.34, + 0.46, + 0.18, + segments=12, + inner0=0.22, + inner1=0.32, + smooth=False, + mat_name="copper_rad", + parent=body_empty, + location=(0.0, 0.0, 0.01), + ) + + # 2. Inner Armored Pressure Core (Gunmetal + dark bulkhead ribs inside the 4 petals) + core_prof = [ + [0.86, 0.58], + [0.84, 1.45], + [0.78, 2.55], + [0.72, 3.35], + [0.82, 3.55], + [0.00, 3.55], + ] + vc.make_lathe_part( + "PressureVessel", + core_prof, + segments=8, + loop=False, + smooth=False, + mat_name="gunmetal", + parent=body_empty, + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.012, + ) + for ring_z, ring_r in ((1.20, 0.87), (2.05, 0.83), (2.90, 0.77)): + vc.make_tube_part( + f"BulkheadRing_{ring_z:.1f}", + ring_r, + ring_r, + 0.16, + segments=8, + smooth=False, + mat_name="socket_bay", + parent=body_empty, + location=(0.0, 0.0, ring_z), + rotation_deg=(0.0, 0.0, 22.5), + ) + + # 3. Four Structural Spine Buttresses + Retro-Thruster Pods at 0, 90, 180, 270 deg + nozzle_prof = [ + [0.14, 0.00], + [0.24, 0.00], + [0.19, 0.16], + [0.13, 0.34], + [0.17, 0.42], + [0.08, 0.42], + [0.11, 0.14], + ] + for i in range(4): + ang_deg = i * 90.0 + ang = math.radians(ang_deg) + ca, sa = math.cos(ang), math.sin(ang) + + # Vertical structural spine rib between petals + vc.make_box( + f"SpineButtress_{i}", + (0.40, 0.28, 2.86), + "gunmetal", + parent=body_empty, + location=(0.94 * ca, 0.94 * sa, 1.98), + rotation_deg=(0.0, 10.5, ang_deg), + bevel=0.014, + ) + vc.make_box( + f"SpineStripe_{i}", + (0.10, 0.22, 0.56), + "signal_orange", + parent=body_empty, + location=(1.04 * ca, 1.04 * sa, 2.42), + rotation_deg=(0.0, 10.5, ang_deg), + bevel=0.006, + ) + + # Retro-thruster housing & flared copper bell nozzle + vc.make_box( + f"ThrusterPod_{i}", + (0.46, 0.40, 0.72), + "olive_armor", + parent=body_empty, + location=(1.18 * ca, 1.18 * sa, 0.68), + rotation_deg=(0.0, -14.0, ang_deg), + bevel=0.014, + ) + vc.make_lathe_part( + f"RetroNozzle_{i}", + nozzle_prof, + segments=12, + loop=True, + smooth=False, + mat_name="copper_rad", + parent=body_empty, + location=(1.26 * ca, 1.26 * sa, 0.12), + rotation_deg=(0.0, -14.0, ang_deg), + ) + + # 4. Upper Drogue Collar, Airbrake Fins & Ballistic Crown (Z = 3.34 .. 4.60) + crown_prof = [ + [0.00, 3.34], + [0.98, 3.34], + [1.04, 3.55], + [0.88, 3.92], + [0.64, 4.30], + [0.44, 4.54], + [0.24, 4.60], + [0.00, 4.60], + ] + vc.make_lathe_part( + "DrogueCrown", + crown_prof, + segments=8, + loop=False, + smooth=False, + mat_name="olive_armor", + parent=body_empty, + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.015, + ) + vc.make_tube_part( + "DrogueCapRim", + 0.48, + 0.34, + 0.28, + segments=8, + smooth=False, + mat_name="gunmetal", + parent=body_empty, + location=(0.0, 0.0, 4.32), + rotation_deg=(0.0, 0.0, 22.5), + bevel=0.010, + ) + vc.make_tube_part( + "DrogueChuteWell", + 0.24, + 0.24, + 0.10, + segments=12, + smooth=False, + mat_name="socket_bay", + parent=body_empty, + location=(0.0, 0.0, 4.52), + ) + + for i in range(4): + ang_deg = i * 90.0 + ang = math.radians(ang_deg) + ca, sa = math.cos(ang), math.sin(ang) + vc.make_box( + f"AeroFin_{i}", + (0.44, 0.12, 0.62), + "gunmetal", + parent=body_empty, + location=(0.94 * ca, 0.94 * sa, 3.96), + rotation_deg=(0.0, 22.0, ang_deg), + bevel=0.010, + ) + vc.make_box( + f"CrownChevron_{i}", + (0.14, 0.34, 0.16), + "signal_orange", + parent=body_empty, + location=(0.86 * ca, 0.86 * sa, 3.82), + rotation_deg=(0.0, 24.0, ang_deg), + bevel=0.006, + ) + vc.make_box( + f"BeaconNode_{i}", + (0.08, 0.12, 0.08), + "cyan_coil", + parent=body_empty, + location=(0.56 * ca, 0.56 * sa, 4.36), + rotation_deg=(0.0, 0.0, ang_deg), + bevel=0.004, + ) + + # 5. Four Distinct Armored Petals (Petal_0..3) at 45, 135, 225, 315 deg + # Each petal has its own mesh datablock with origin at its EXACT geometric centroid! + for i in range(4): + ang_deg = 45.0 + i * 90.0 + ang = math.radians(ang_deg) + petal_mesh, centroid_local = _build_petal_mesh(f"PetalMesh_{i}", mats) + p_obj = bpy.data.objects.new(f"Petal_{i}", petal_mesh) + world_loc = ( + centroid_local.x * math.cos(ang) - centroid_local.y * math.sin(ang), + centroid_local.x * math.sin(ang) + centroid_local.y * math.cos(ang), + centroid_local.z, + ) + vc._link_object(p_obj, parent=root, location=world_loc, rotation_deg=(0.0, 0.0, ang_deg)) + + glb_path = vc.ASSETS_VEHICLES_DIR / "drop_pod" / "drop_pod.glb" + tris, bounds = vc.export_vehicle_glb(glb_path, root=root) + print(f"[drop_pod] tris={tris} bounds={bounds} glb={glb_path}") + return glb_path + + +if __name__ == "__main__": + build_drop_pod() diff --git a/tools/vehicles/verify_glbs.py b/tools/vehicles/verify_glbs.py index 1dd0301..fcf8d18 100644 --- a/tools/vehicles/verify_glbs.py +++ b/tools/vehicles/verify_glbs.py @@ -462,9 +462,71 @@ def validate_gear(gid: str) -> dict[str, Any]: } +def validate_drop_pod() -> dict[str, Any]: + glb_path = VEHICLES_DIR / "drop_pod" / "drop_pod.glb" + if not glb_path.is_file(): + raise AssertionError(f"Missing drop_pod GLB: {glb_path}") + gltf, bin_blob = parse_glb(glb_path) + tri_total, g_min, g_max = compute_glb_stats(gltf, bin_blob) + if tri_total < 400 or tri_total > 12000: + raise AssertionError(f"drop_pod: unexpected tri count {tri_total}") + if abs(float(g_min[1])) > 0.02: + raise AssertionError(f"drop_pod: not grounded at minY=0 (got {g_min[1]:.4f})") + + size = g_max - g_min + if size[1] < 4.0 or size[1] > 5.2 or size[0] < 2.2 or size[0] > 3.4: + raise AssertionError(f"drop_pod: unexpected dimensions {size}") + + nodes = gltf.get("nodes", []) + meshes = gltf.get("meshes", []) + accessors = gltf.get("accessors", []) + buffer_views = gltf.get("bufferViews", []) + node_names = {n.get("name", ""): n for n in nodes} + + for req in ("DropPodRoot", "CoreBody", "RetroNozzle"): + if req not in node_names: + raise AssertionError(f"drop_pod: missing required node {req!r}") + + petal_centroids = [] + for i in range(4): + pname = f"Petal_{i}" + if pname not in node_names or "mesh" not in node_names[pname]: + raise AssertionError(f"drop_pod: missing mesh node {pname!r}") + p_mesh = meshes[node_names[pname]["mesh"]] + p_min = np.array([math.inf, math.inf, math.inf], dtype=np.float64) + p_max = np.array([-math.inf, -math.inf, -math.inf], dtype=np.float64) + for prim in p_mesh.get("primitives", []): + attrs = prim.get("attributes", {}) + if "COLOR_0" not in attrs: + raise AssertionError(f"drop_pod: {pname} primitive missing COLOR_0 weathering") + pts = _read_accessor(accessors, buffer_views, bin_blob, attrs["POSITION"]) + p_min = np.minimum(p_min, pts.min(axis=0)) + p_max = np.maximum(p_max, pts.max(axis=0)) + local_center = (p_min + p_max) * 0.5 + offset = float(np.linalg.norm(local_center)) + if offset > 0.03: + raise AssertionError(f"drop_pod: {pname} local origin not at centroid (offset={offset:.4f}m)") + petal_centroids.append(round(offset, 5)) + + for m_idx, mesh in enumerate(meshes): + for prim in mesh.get("primitives", []): + if "COLOR_0" not in prim.get("attributes", {}): + raise AssertionError(f"drop_pod: mesh[{m_idx}] missing COLOR_0 weathering") + + return { + "id": "drop_pod", + "tris": tri_total, + "bytes": glb_path.stat().st_size, + "minY": round(float(g_min[1]), 4), + "size": [round(float(v), 3) for v in size], + "petalOffsets": petal_centroids, + } + + def main() -> int: v_reports = [validate_vehicle(v) for v in EXPECTED_VEHICLES] g_reports = [validate_gear(g) for g in EXPECTED_GEAR] + pod_report = validate_drop_pod() print("=== VEHICLE GLB VALIDATION PASSED ===") for r in v_reports: mech_tag = f" | dofs={r['mechanisms']}" if r["mechanisms"] else "" @@ -472,6 +534,8 @@ def main() -> int: print("=== GEAR GLB VALIDATION PASSED ===") for r in g_reports: print(f" {r['id']:14s} | tris={r['tris']:4d} | size={r['size']} | {r['bytes']/1024:.1f} KiB") + print("=== DROP POD GLB VALIDATION PASSED ===") + print(f" {pod_report['id']:10s} | tris={pod_report['tris']:5d} | size={pod_report['size']} | minY={pod_report['minY']} | petalPivotOffsets={pod_report['petalOffsets']} | {pod_report['bytes']/1024:.1f} KiB") return 0