using EvilEngine.Client.Audio; using EvilEngine.Formats.Maps; using EvilEngine.Host.Sessions; using Godot; namespace EvilEngine.Client.World; public partial class WorldSounds : Node3D { private readonly WorldBodies? _bodies; private readonly ClientSession _session; private readonly List _voices = []; public WorldSounds(ClientSession session, WorldBodies? bodies) { _session = session; _bodies = bodies; Name = "Sounds"; } public int Heard { get; private set; } public override void _EnterTree() { _session.Arrived += Arrived; } public override void _ExitTree() { _session.Arrived -= Arrived; foreach (var voice in _voices) voice.Stop(); _voices.Clear(); } private void Arrived(Snapshot snapshot) { if (snapshot.Sounds.Count == 0) return; _voices.RemoveAll(voice => voice.Ended); if (AudioManager.Instance is not { } audio) return; foreach (var sound in snapshot.Sounds) { Heard++; var emitter = sound.Emitter; var offset = !emitter.IsNone && ClientSession.Body(snapshot, emitter) is { } body ? Map(sound.Position) - Map(body.Feet) : Vector3.Zero; var place = new SoundPlace(ToGlobal(Map(sound.Position))) { Emitter = emitter, Follow = emitter.IsNone ? null : () => Where(emitter) + offset }; if (audio.Play(sound.Sound, place, sound.Volume) is { } voice) _voices.Add(voice); } } private Vector3? Where(EntityHandle emitter) { if (!IsInsideTree()) return null; if (_bodies?.Body(emitter) is { } node && node.IsInsideTree()) return node.GlobalPosition; return ClientSession.Body(_session.Latest, emitter) is { } state ? ToGlobal(Map(state.Feet)) : null; } private static Vector3 Map(MapVector at) { return new Vector3((float)at.X, (float)at.Y, (float)at.Z); } }