Files
Project-M/Assets/_Project/Scripts/Client/Presentation/AmbientAudioSystem.cs
T
kronic e0c59ad663 Perf: pool one-shot SFX + authored VFX, cut per-frame presentation allocation
Track B. All 21 one-shot cues funnelled through FeedbackFx.PlayClip ->
AudioSource.PlayClipAtPoint, which allocates a GameObject + AudioSource per call
and schedules a delayed Destroy — ~20-33 times a second in light combat. New
OneShotAudioPool is a 32-voice 3D ring behind an UNCHANGED PlayClip signature, so
all 20 consuming call sites are untouched.

Parity is the whole game here: PlayClipAtPoint sets spatialBlend = 1 explicitly (a
fresh AudioSource is 2D) and leaves the rest at stock defaults. Two deliberate
divergences, both forced by the voices being long-lived: playOnAwake = false, and
dopplerLevel = 0 because a pooled voice TELEPORTS between events and would
otherwise pitch-bend. Root is DontDestroyOnLoad (WorldLauncher does
LoadScene(Single) while the client world is alive) with a SubsystemRegistration
reset, or session two rents destroyed voices.

Authored impact VFX are pooled per prefab instead of Instantiate/Destroy per hit:
components cached per INSTANCE (refs are instance-scoped), main.stopAction forced
to None (a prefab set to Destroy silently drains the pool), instances filled under
an inactive root so Awake/Start never run — which is what makes the DestroyImmediate
in StripCosmetic safe — ps.Clear before Play, TrailRenderer.Clear after the
reposition, and a Rented flag as the at-most-once guard against a double Return
aliasing one instance to two callers.

Per-frame allocation: the slash-arc and enemy-wedge mesh builders each allocated
four arrays on every call (up to twice a frame, and once per winding enemy); HUD
and ability-bar labels rebuilt their strings every frame; damage-number fades
rewrote TextMesh vertex colours every frame; health bars pushed uGUI writes
unconditionally; two systems played back an empty EntityCommandBuffer (a
structural-change sync point) every frame.

Also closes an AudioClip leak across all seven clip-owning systems: an
AudioClip.Create'd clip is a standalone UnityEngine.Object, so destroying a
system's FX root left it alive (MusicSystem ~6.8 MB, AmbientAudioSystem ~2 MB per
client-world teardown).

CombatFeedbackSystem's TryHold call sites go with this commit because they share
the file; the camera-side removal lands in the next one.

Verified live: PlayClipAtPoint's "One shot audio" GameObject never appears again
across 270 frames of combat with kills; the VFX pool fills to its retain cap and
stabilises; real cues route through the ring. 304/304 EditMode green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-13 23:02:50 -07:00

161 lines
7.4 KiB
C#

using ProjectM.Simulation;
using Unity.Entities;
using Unity.NetCode;
using UnityEngine;
namespace ProjectM.Client
{
/// <summary>
/// Client-only AMBIENT audio bed + run cues. A managed presentation <see cref="SystemBase"/>
/// (<see cref="PresentationSystemGroup"/>, main thread, no Burst) that plays a low, seamless-looping
/// procedural drone (asset-free, <c>AudioClip.Create</c> like <c>CombatFeedbackSystem.MakeClip</c>) plus
/// launch-countdown beeps and the boss-arrival roar — replicated-state observations only. Lives only in the
/// client world, so the server never creates audio and nothing here affects determinism. Volumes are
/// deliberately conservative. (The cycle-phase stingers + Core alarm retired with the siege loop — LANTERN purge.)
/// </summary>
[WorldSystemFilter(WorldSystemFilterFlags.ClientSimulation)]
[UpdateInGroup(typeof(PresentationSystemGroup))]
public partial class AmbientAudioSystem : SystemBase
{
AudioSource _ambient;
AudioClip _ambientClip;
GameObject _root;
AudioClip _stingBeep, _stingRoar;
int _lastCountdownSec = -1;
bool _bossRoared;
// 07-16 underwater re-voice: the bed volume + groan cadence live on FeelConfig (live-tunable).
AudioSource _groanSrc;
AudioClip _groanClip;
float _nextGroanIn = 12f; // first distant groan ~12s into a session
protected override void OnCreate()
{
_ambientClip = MakeDrone();
_groanClip = MakeGroan();
_stingBeep = MakeSting(880f, 880f, 0.09f, 0.30f); // countdown tick
_stingRoar = MakeSting(90f, 38f, 0.90f, 0.60f); // boss-arrival roar (low falling growl)
}
protected override void OnStartRunning()
{
if (_root != null) return;
_root = new GameObject("~AmbientAudio");
_ambient = _root.AddComponent<AudioSource>();
_ambient.clip = _ambientClip;
_ambient.loop = true;
_ambient.playOnAwake = false;
_ambient.spatialBlend = 0f; // 2D bed
_ambient.volume = FeelConfig.AmbienceVolume * GameVolume.Music;
_ambient.Play();
_groanSrc = _root.AddComponent<AudioSource>();
_groanSrc.playOnAwake = false;
_groanSrc.spatialBlend = 0f; // distant, directionless
_groanSrc.loop = false;
}
protected override void OnDestroy()
{
if (_root != null) Object.Destroy(_root);
// The AudioSources die with _root, but the clips they played do NOT — see FeedbackFx.DestroyClip.
// _ambientClip alone is ~1.4 MB of native audio per client-world teardown.
FeedbackFx.DestroyClip(ref _ambientClip);
FeedbackFx.DestroyClip(ref _groanClip);
FeedbackFx.DestroyClip(ref _stingBeep);
FeedbackFx.DestroyClip(ref _stingRoar);
}
protected override void OnUpdate()
{
if (_ambient == null) return;
float dt = SystemAPI.Time.DeltaTime;
_ambient.volume = Mathf.MoveTowards(_ambient.volume, FeelConfig.AmbienceVolume * GameVolume.Music, dt * 0.25f);
// Distant groans (07-16 gap-list): a slow low sweep with a soft attack, jittered interval + pitch —
// the murk answering back. Presentation-only wall-clock randomness is fine here.
if (_groanSrc != null && FeelConfig.GroanIntervalSec > 0f)
{
_nextGroanIn -= dt;
if (_nextGroanIn <= 0f)
{
_nextGroanIn = FeelConfig.GroanIntervalSec * (0.6f + Random.value * 0.8f);
_groanSrc.pitch = 0.85f + Random.value * 0.3f;
_groanSrc.PlayOneShot(_groanClip, FeelConfig.GroanVolume * GameVolume.Music);
}
}
// 2026-08-07 audit purge: the 3-2-1 launch countdown beeps and the boss-arrival roar keyed off
// RunInfo.Lifecycle / RoomTypeId. Both went with the run FSM and the boss.
}
// ---- Procedural audio (asset-free; mirrors CombatFeedbackSystem.MakeClip) ----
// A low, seamless-looping pad: each partial completes an integer number of cycles over the buffer
// (freq snapped to k/duration) so the loop point has no click. A slow tremolo adds motion.
// A low, seamless-looping UNDERWATER pressure bed (07-16 re-voice): sub-heavy partials + a pair of
// detuned subs whose beat completes exactly once per loop (Snap keeps every partial click-free at the
// loop point) — reads as slow water-column pressure swell rather than a musical pad.
static AudioClip MakeDrone()
{
const int rate = 44100;
const float dur = 8f;
int len = (int)(dur * rate);
var clip = AudioClip.Create("underwater_bed", len, 1, rate, false);
var data = new float[len];
float f0 = Snap(38f, dur); // deep sub
float f0b = f0 + 1f / dur; // detuned sub: beats exactly once per loop (seamless)
float f1 = Snap(55f, dur);
float f2 = Snap(82.4f, dur); // faint upper body
float swell = Snap(0.25f, dur); // very slow amplitude swell
for (int i = 0; i < len; i++)
{
float t = i / (float)rate;
float s = 0.46f * Mathf.Sin(2f * Mathf.PI * f0 * t)
+ 0.34f * Mathf.Sin(2f * Mathf.PI * f0b * t)
+ 0.22f * Mathf.Sin(2f * Mathf.PI * f1 * t)
+ 0.07f * Mathf.Sin(2f * Mathf.PI * f2 * t);
float amp = 0.7f + 0.3f * Mathf.Sin(2f * Mathf.PI * swell * t);
data[i] = s * amp * 0.5f;
}
clip.SetData(data, 0);
return clip;
}
// A distant whale-adjacent groan: slow 58->34Hz sweep with a soft sin^2 attack/decay window and a
// subtle wobble — never a jump-scare, just the deep being large somewhere off-screen.
static AudioClip MakeGroan()
{
const int rate = 44100;
const float dur = 3.4f;
int len = (int)(dur * rate);
var clip = AudioClip.Create("distant_groan", len, 1, rate, false);
var data = new float[len];
float phase = 0f;
for (int i = 0; i < len; i++)
{
float t01 = i / (float)len;
float t = i / (float)rate;
float freq = Mathf.Lerp(58f, 34f, t01) * (1f + 0.03f * Mathf.Sin(2f * Mathf.PI * 1.7f * t));
phase += 2f * Mathf.PI * freq / rate;
float window = Mathf.Sin(Mathf.PI * t01);
float env = window * window; // soft attack AND release
data[i] = (0.8f * Mathf.Sin(phase) + 0.2f * Mathf.Sin(2f * phase)) * env * 0.55f;
}
clip.SetData(data, 0);
return clip;
}
// freq snapped so freq*dur is an integer -> the waveform closes seamlessly at the loop point.
static float Snap(float freq, float dur)
{
float cycles = Mathf.Max(1f, Mathf.Round(freq * dur));
return cycles / dur;
}
// Short one-shot tone sweeping f0->f1 with an exponential decay envelope.
static AudioClip MakeSting(float f0, float f1, float dur, float vol) => FeedbackFx.MakeClip("sting", f0, f1, dur, vol, decay: 3.5f);
}
}