Files
Rail_Enterprise/client/RailEnterprise.Client/scripts/Audio/AudioManager.cs
T
Alby96andClaude Opus 5.5 b1ee6879a7 F6: audio con bus, volumi, effetti, ambienti e musica per era
Il client ora ha l'audio della F6 senza file esterni né download: effetti,
anelli d'ambiente e temi musicali si sintetizzano in memoria all'avvio, su un
altro thread, con classi senza dipendenze da Godot (Synth, MusicComposer,
AudioMix) e semi fissi.

- Bus Master, Music, Ambience, Sfx, Ui creati da codice in modo idempotente,
  limitatore sul Master; volumi per bus e muto in user://settings.cfg; pannello
  «Audio» dal menu e dall'altoparlante della barra superiore, tasto M.
- AudioManager (figlio di Main) reagisce solo a ciò che il client riceve: clic
  dei pulsanti, esiti dei comandi, notifiche per gravità, cantieri completati
  dal DailyDigest, fischio o tromba all'arrivo in stazione, fino a 3 treni
  vicini al centro con rotolamento, motore e sbuffi modulati dalla velocità,
  ambiente dal terreno visibile e dallo zoom, tema per era con dissolvenza.
- Nessuna allocazione nel ciclo per fotogramma; audio spento nel pilota
  automatico e senza schermo.
- ADR 0022, STATE e ARCHITECTURE aggiornati; testi in strings.csv.

Non ascoltato: Godot non è eseguibile qui. Funzioni pure provate a parte.

Refs #46.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:50:07 +01:00

644 lines
24 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Godot;
using RailEnterprise.Client.Map;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Map;
using RailEnterprise.Core.Rail;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
namespace RailEnterprise.Client.Audio;
/// <summary>
/// Regia dell'audio, figlia di <c>Main</c> per tutta la vita del client: bus e volumi, effetti
/// dell'interfaccia (clic di ogni pulsante, esito dei comandi), notifiche, cantieri completati,
/// treni vicini al centro della telecamera (rotolamento, motore, sbuffi, fischio all'arrivo),
/// ambiente dal terreno sotto la telecamera e musica per era. Non decide nulla del gioco: reagisce
/// a ciò che il client riceve (esiti, notifiche, <c>DailyDigest</c>, moti dei treni) e alla vista.
/// I suoni si sintetizzano all'avvio su un altro thread (<see cref="Synth"/>, <see cref="MusicComposer"/>);
/// nel ciclo per fotogramma non si alloca (elenchi preparati, nessuna LINQ).
/// </summary>
public partial class AudioManager : Node
{
/// <summary>Unica istanza (nulla prima dell'avvio del client).</summary>
public static AudioManager? Instance { get; private set; }
/// <summary>Volumi e muto attuali (anche con l'audio disattivato, per il pannello).</summary>
public AudioSettings Settings { get; private set; } = new();
/// <summary>Cambio di volumi o muto (per aggiornare il pannello e l'icona della barra).</summary>
public event Action? SettingsChanged;
private readonly bool _enabled;
private Task<SoundBank>? _bankTask;
private bool _loaded;
// suoni singoli
private AudioStreamWav? _click, _confirm, _error, _build, _whistle, _horn, _chuff;
private readonly AudioStreamWav?[] _notify = new AudioStreamWav?[3];
private AudioStreamWav[] _birds = [];
private AudioStreamWav? _diesel, _hum;
// riproduttori polifonici per bus e nomi dei bus già pronti (niente StringName per chiamata)
private readonly StringName _busUi = AudioBuses.Ui, _busSfx = AudioBuses.Sfx, _busAmbience = AudioBuses.Ambience;
private AudioStreamPlaybackPolyphonic? _ui, _sfx, _ambience;
// ambiente: vento, acqua, mare, città
private const int AmbienceLoops = 4;
private static readonly float[] AmbienceLevel = [0.55f, 0.6f, 0.6f, 0.5f];
private readonly AudioStreamPlayer[] _ambiencePlayers = new AudioStreamPlayer[AmbienceLoops];
private readonly float[] _ambienceGain = new float[AmbienceLoops];
private readonly float[] _ambienceTarget = new float[AmbienceLoops];
private float _birdsChance;
private float _sinceAmbience = 1, _birdTimer = 3;
// treni
private sealed class TrainChannel
{
public int Train = -1;
public Traction Traction;
public float Gain, Target, ChuffTimer;
public bool Kept;
public required AudioStreamPlayer Rumble { get; init; }
public required AudioStreamPlayer Engine { get; init; }
}
private readonly TrainChannel[] _channels = new TrainChannel[AudioMix.TrainChannels];
private readonly int[] _nearIds = new int[AudioMix.TrainChannels];
private readonly float[] _nearDistances = new float[AudioMix.TrainChannels];
private readonly Dictionary<int, byte> _trainStates = [];
// musica: due riproduttori per la dissolvenza incrociata
private const float MusicLevel = 0.6f;
private const float FadeSeconds = 3f;
private readonly AudioStreamPlayer[] _music = new AudioStreamPlayer[2];
private readonly float[] _musicGain = new float[2];
private int _activeMusic;
private int _musicEra = -1;
private readonly Dictionary<int, AudioStreamWav> _themes = [];
private readonly HashSet<int> _failedThemes = [];
private Task<float[]>? _composing;
private int _composingEra;
private string[] _eraIds = ["steam"];
private int[] _eraFroms = [0];
// partita in corso
private GameSession? _session;
private MapView? _map;
private Dictionary<string, VehicleDef> _vehicles = [];
private SynthRng _rng = new(0xA0D10);
private ulong _lastUiMs, _lastNotifyMs, _lastWhistleMs;
// pannello delle impostazioni
private CanvasLayer? _overlay;
private AudioSettingsPanel? _panel;
/// <param name="enabled">Falso nel pilota automatico e senza schermo: niente sintesi né riproduzione, Master muto.</param>
public AudioManager(bool enabled)
{
_enabled = enabled;
Name = "AudioManager";
}
public AudioManager() : this(true)
{
}
public override void _Ready()
{
Instance = this;
AudioBuses.Ensure();
Settings = AudioSettings.Load();
ApplySettings();
if (!_enabled) return;
_bankTask = Task.Run(SoundBank.Create);
GetTree().NodeAdded += OnNodeAdded;
}
public override void _ExitTree()
{
if (Instance == this) Instance = null;
Unbind();
}
/// <summary>Ere di eras.json (id e anno d'inizio, crescenti): scelgono il tema musicale.</summary>
public void SetEras(IReadOnlyList<EraDef> eras)
{
if (eras.Count == 0) return;
_eraIds = new string[eras.Count];
_eraFroms = new int[eras.Count];
for (int i = 0; i < eras.Count; i++)
{
_eraIds[i] = eras[i].Id;
_eraFroms[i] = eras[i].From;
}
}
// ------------------------------------------------------------------ impostazioni
private void ApplySettings()
{
Settings.Apply();
// senza audio (collaudo, server senza schermo) il Master resta muto, senza toccare il file
if (!_enabled) AudioServer.SetBusMute(0, true);
}
/// <summary>Cambia il volume di un bus (indice in <see cref="AudioBuses.All"/>) e lo applica subito.</summary>
public void SetVolume(int bus, float value)
{
Settings.Volumes[bus] = Math.Clamp(value, 0, 1);
ApplySettings();
SettingsChanged?.Invoke();
}
public void SetMuted(bool muted)
{
Settings.Muted = muted;
ApplySettings();
SettingsChanged?.Invoke();
}
public void ToggleMute()
{
SetMuted(!Settings.Muted);
Settings.Save();
}
public void SaveSettings() => Settings.Save();
/// <summary>Apre il pannello «Audio» sopra a tutto (menu o partita).</summary>
public void ShowSettings()
{
if (_panel is not null && IsInstanceValid(_panel)) return;
if (_overlay is null)
{
_overlay = new CanvasLayer { Layer = 50 };
AddChild(_overlay);
}
_panel = new AudioSettingsPanel(this);
_panel.TreeExited += () => _panel = null;
_overlay.AddChild(_panel);
}
public override void _UnhandledKeyInput(InputEvent e)
{
if (e is InputEventKey { Pressed: true, Echo: false, Keycode: Key.M } key && !key.CtrlPressed && !key.AltPressed && !key.MetaPressed)
{
ToggleMute();
GetViewport().SetInputAsHandled();
}
}
// ------------------------------------------------------------------ partita
/// <summary>Collega la partita: messaggi della sessione e vista della mappa.</summary>
public void Bind(GameSession session, MapView map)
{
Unbind();
_session = session;
_map = map;
_vehicles = session.World.Data.Vehicles.ToDictionary(v => v.Id);
SetEras(session.World.Data.Eras.Eras);
session.MessageApplied += OnMessage;
}
/// <summary>
/// Scollega la partita (ritorno al menu): treni e ambiente sfumano. Con «only» scollega solo
/// se è ancora quella sessione (la schermata vecchia esce dall'albero dopo l'arrivo della nuova).
/// </summary>
public void Unbind(GameSession? only = null)
{
if (only is not null && !ReferenceEquals(only, _session)) return;
if (_session is not null) _session.MessageApplied -= OnMessage;
_session = null;
_map = null;
_trainStates.Clear();
}
private void OnMessage(IMessage message)
{
if (!_loaded) return;
switch (message)
{
case TrainMotion m:
byte previous = _trainStates.TryGetValue(m.TrainId, out byte p) ? p : (byte)255;
_trainStates[m.TrainId] = m.State;
if (previous == (byte)TrainState.Moving && m.State == (byte)TrainState.Loading) Whistle(m.TrainId);
break;
case CommandResultMessage r:
PlayUi(r.Ok ? _confirm : _error, r.Ok ? 0.7f : 0.85f);
break;
case Notification n:
Notify(n.Event);
break;
case DailyDigest d:
int me = _session?.World.Summary?.CompanyId ?? -1;
for (int i = 0; i < d.Events.Count; i++)
{
var e = d.Events[i];
if (e.Kind == ConstructionEventKind && e.Company == me && me >= 0)
{
Play(_sfx, _build, 0.8f, 1, _busSfx);
break;
}
}
break;
case Welcome:
_trainStates.Clear();
break;
}
}
/// <summary>Codice di EventKind.Construction nel protocollo (cantiere completato, sempre informativo).</summary>
private const byte ConstructionEventKind = 5;
private void Notify(EventInfo e)
{
int me = _session?.World.Summary?.CompanyId ?? -1;
if (e.Company >= 0 && e.Company != me) return;
int level = e.Severity switch { 3 => 2, 2 => 1, _ => 0 };
ulong now = Time.GetTicksMsec();
// più notizie insieme: una sola campanella (le critiche suonano sempre)
if (level < 2 && now - _lastNotifyMs < 600) return;
_lastNotifyMs = now;
Play(_ui, _notify[level], level == 2 ? 0.9f : 0.75f, 1, _busUi);
}
private void OnNodeAdded(Node node)
{
if (node is BaseButton button) button.Pressed += PlayClick;
}
private void PlayClick() => PlayUi(_click, 0.6f);
private void PlayUi(AudioStreamWav? stream, float gain)
{
ulong now = Time.GetTicksMsec();
if (stream == _click && now - _lastUiMs < 40) return;
_lastUiMs = now;
Play(_ui, stream, gain, 1, _busUi);
}
private static void Play(AudioStreamPlaybackPolyphonic? playback, AudioStreamWav? stream, float gain, float pitch, StringName bus)
{
if (playback is null || stream is null || gain <= 0.001f) return;
playback.PlayStream(stream, 0, AudioMix.LinearToDb(gain), pitch, AudioServer.PlaybackType.Default, bus);
}
// ------------------------------------------------------------------ caricamento
/// <summary>Campioni di tutti gli effetti e degli anelli, sintetizzati fuori dal thread principale.</summary>
private sealed class SoundBank
{
public required float[] Click, Confirm, Error, Construction, Whistle, Horn, Chuff, Rumble, Diesel, Hum, Wind, River, Sea, City;
public required float[][] Notify, Birds;
public static SoundBank Create() => new()
{
Click = Synth.Click(), Confirm = Synth.Confirm(), Error = Synth.Error(), Construction = Synth.BuildComplete(),
Whistle = Synth.SteamWhistle(), Horn = Synth.Horn(), Chuff = Synth.Chuff(), Rumble = Synth.RailRumbleLoop(),
Diesel = Synth.DieselDroneLoop(), Hum = Synth.ElectricHumLoop(), Wind = Synth.WindLoop(), River = Synth.RiverLoop(),
Sea = Synth.SeaLoop(), City = Synth.CityLoop(),
Notify = [Synth.Notify(0), Synth.Notify(1), Synth.Notify(2)],
Birds = [Synth.Bird(0), Synth.Bird(1), Synth.Bird(2)],
};
}
private static AudioStreamWav Wav(float[] samples, bool loop = false)
{
var w = new AudioStreamWav
{
Format = AudioStreamWav.FormatEnum.Format16Bits,
MixRate = Synth.Rate,
Stereo = false,
Data = AudioMix.ToPcm16(samples),
};
if (loop)
{
w.LoopMode = AudioStreamWav.LoopModeEnum.Forward;
w.LoopBegin = 0;
w.LoopEnd = samples.Length;
}
return w;
}
private AudioStreamPlayer Player(string bus, AudioStream? stream = null)
{
var p = new AudioStreamPlayer { Bus = bus, Stream = stream };
AddChild(p);
return p;
}
private AudioStreamPlaybackPolyphonic? Polyphonic(string bus, int voices)
{
var p = Player(bus, new AudioStreamPolyphonic { Polyphony = voices });
p.Play();
return p.GetStreamPlayback() as AudioStreamPlaybackPolyphonic;
}
private void Load(SoundBank bank)
{
_click = Wav(bank.Click);
_confirm = Wav(bank.Confirm);
_error = Wav(bank.Error);
_build = Wav(bank.Construction);
_whistle = Wav(bank.Whistle);
_horn = Wav(bank.Horn);
_chuff = Wav(bank.Chuff);
for (int i = 0; i < _notify.Length; i++) _notify[i] = Wav(bank.Notify[i]);
_birds = bank.Birds.Select(b => Wav(b)).ToArray();
_diesel = Wav(bank.Diesel, loop: true);
_hum = Wav(bank.Hum, loop: true);
var rumble = Wav(bank.Rumble, loop: true);
_ui = Polyphonic(AudioBuses.Ui, 8);
_sfx = Polyphonic(AudioBuses.Sfx, 16);
_ambience = Polyphonic(AudioBuses.Ambience, 4);
float[][] loops = [bank.Wind, bank.River, bank.Sea, bank.City];
for (int i = 0; i < AmbienceLoops; i++)
{
var p = Player(AudioBuses.Ambience, Wav(loops[i], loop: true));
p.VolumeLinear = 0;
_ambiencePlayers[i] = p;
}
for (int i = 0; i < _channels.Length; i++)
{
var r = Player(AudioBuses.Sfx, rumble);
var e = Player(AudioBuses.Sfx);
r.VolumeLinear = e.VolumeLinear = 0;
_channels[i] = new TrainChannel { Rumble = r, Engine = e };
}
for (int i = 0; i < _music.Length; i++) _music[i] = Player(AudioBuses.Music);
_loaded = true;
}
// ------------------------------------------------------------------ ciclo
public override void _Process(double delta)
{
if (!_enabled) return;
if (!_loaded)
{
if (_bankTask is not { IsCompleted: true }) return;
if (_bankTask.IsCompletedSuccessfully) Load(_bankTask.Result);
else
{
GD.PrintErr($"Audio: sintesi non riuscita: {_bankTask.Exception?.GetBaseException().Message}");
_bankTask = null;
return;
}
}
float dt = (float)Math.Min(delta, 0.1);
UpdateMusic(dt);
UpdateAmbience(dt);
UpdateTrains(dt);
}
private int WantedEra()
{
var w = _session?.World;
if (w?.Calendar is null) return 0;
return AudioMix.EraIndex(w.Year, _eraFroms);
}
private void UpdateMusic(float dt)
{
int want = WantedEra();
if (_composing is { IsCompleted: true })
{
if (_composing.IsCompletedSuccessfully) _themes[_composingEra] = Wav(_composing.Result, loop: true);
else
{
_failedThemes.Add(_composingEra);
GD.PrintErr($"Audio: tema dell'era non composto: {_composing.Exception?.GetBaseException().Message}");
}
_composing = null;
}
if (want != _musicEra)
{
if (_themes.TryGetValue(want, out var theme))
{
// dissolvenza incrociata: il nuovo tema entra sull'altro riproduttore
_activeMusic = 1 - _activeMusic;
var p = _music[_activeMusic];
p.Stream = theme;
_musicGain[_activeMusic] = 0;
p.VolumeLinear = 0;
p.Play();
_musicEra = want;
}
else if (_composing is null && !_failedThemes.Contains(want))
{
int era = want;
string id = _eraIds[Math.Clamp(era, 0, _eraIds.Length - 1)];
_composingEra = era;
_composing = Task.Run(() => MusicComposer.Compose(era, id));
}
}
for (int i = 0; i < _music.Length; i++)
{
float target = i == _activeMusic && _musicEra >= 0 ? 1 : 0;
_musicGain[i] = AudioMix.Approach(_musicGain[i], target, 1 / FadeSeconds, dt);
_music[i].VolumeLinear = _musicGain[i] * MusicLevel;
if (_musicGain[i] <= 0 && i != _activeMusic && _music[i].Playing) _music[i].Stop();
}
}
private void UpdateAmbience(float dt)
{
_sinceAmbience += dt;
if (_sinceAmbience >= 0.25f)
{
_sinceAmbience = 0;
var gains = _map is not null && _session?.World.Terrain is { } terrain
? AudioMix.Ambience(_map.Zoom, SampleTerrain(terrain, _map.VisibleRect()))
: default;
_ambienceTarget[0] = gains.Wind;
_ambienceTarget[1] = gains.Water;
_ambienceTarget[2] = gains.Sea;
_ambienceTarget[3] = gains.City;
_birdsChance = gains.Birds;
}
for (int i = 0; i < AmbienceLoops; i++)
{
_ambienceGain[i] = AudioMix.Approach(_ambienceGain[i], _ambienceTarget[i], 0.5f, dt);
var p = _ambiencePlayers[i];
p.VolumeLinear = _ambienceGain[i] * AmbienceLevel[i];
if (_ambienceGain[i] > 0 && !p.Playing) p.Play(_rng.Next01() * 4);
else if (_ambienceGain[i] <= 0 && p.Playing) p.Stop();
}
if (_birdsChance > 0.05f && _birds.Length > 0)
{
_birdTimer -= dt;
if (_birdTimer <= 0)
{
Play(_ambience, _birds[_rng.Next(_birds.Length)], _birdsChance * 0.45f, _rng.Range(0.9f, 1.15f), _busAmbience);
_birdTimer = _rng.Range(1.5f, 6f) / (0.3f + _birdsChance);
}
}
}
/// <summary>Frazioni del terreno su una griglia 8×8 della vista (allargata di un quarto per sentire l'acqua vicina).</summary>
private static TerrainMix SampleTerrain(Terrain t, Rect2 view)
{
const int grid = 8;
view = view.Grow(Math.Max(view.Size.X, view.Size.Y) * 0.125f);
int river = 0, lake = 0, sea = 0, town = 0, forest = 0, open = 0, total = 0;
for (int gy = 0; gy < grid; gy++)
{
for (int gx = 0; gx < grid; gx++)
{
double x = view.Position.X + (gx + 0.5) / grid * view.Size.X;
double y = view.Position.Y + (gy + 0.5) / grid * view.Size.Y;
int cx = (int)Math.Floor(x / t.CellSizeM), cy = (int)Math.Floor(y / t.CellSizeM);
if (!t.InBounds(cx, cy)) continue;
int i = t.Index(cx, cy);
total++;
switch ((CellType)t.Types[i])
{
case CellType.Water when t.RiverWidth[i] > 0: river++; break;
case CellType.Water: lake++; break;
case CellType.Sea: sea++; break;
case CellType.Town or CellType.Industry: town++; break;
case CellType.Forest: forest++; break;
default: open++; break;
}
}
}
if (total == 0) return default;
float k = 1f / total;
return new TerrainMix { River = river * k, Lake = lake * k, Sea = sea * k, Town = town * k, Forest = forest * k, Open = open * k };
}
private void UpdateTrains(float dt)
{
var w = _session?.World;
var map = _map;
int count = 0;
Vector2 center = default;
float zoom = 1, radius = 1;
if (w is not null && map is not null && w.Speed > 0)
{
center = map.Camera.GetScreenCenterPosition();
zoom = map.Zoom;
radius = map.GetViewportRect().Size.Length() / 2;
foreach (var (id, head) in map.Trains.Heads)
{
if (!w.Motions.TryGetValue(id, out var m) || m.State != (byte)TrainState.Moving || m.Speed < 0.5f) continue;
count = AudioMix.InsertNearest(_nearIds, _nearDistances, count, id, head.DistanceTo(center) * zoom);
}
}
// i canali restano ai loro treni finché sono tra i più vicini; gli altri sfumano
foreach (var ch in _channels) ch.Kept = ch.Train >= 0 && Contains(_nearIds, count, ch.Train);
for (int k = 0; k < count; k++)
{
int id = _nearIds[k];
if (HasChannel(id)) continue;
foreach (var ch in _channels)
{
if (ch.Train >= 0 && (ch.Kept || ch.Gain > 0.01f)) continue;
Assign(ch, id, w!);
ch.Kept = true;
break;
}
}
foreach (var ch in _channels)
{
float speed = 0;
if (ch.Kept && w is not null && map is not null && w.Motions.TryGetValue(ch.Train, out var m) && map.Trains.Heads.TryGetValue(ch.Train, out var head))
{
speed = m.Speed;
ch.Target = AudioMix.TrainGain(head.DistanceTo(center) * zoom, radius, speed, zoom);
}
else ch.Target = 0;
ch.Gain = AudioMix.Approach(ch.Gain, ch.Target, 2.5f, dt);
if (ch.Train < 0) continue;
if (ch.Gain <= 0 && ch.Target <= 0)
{
ch.Train = -1;
ch.Rumble.Stop();
ch.Engine.Stop();
continue;
}
if (speed > 0)
{
ch.Rumble.PitchScale = AudioMix.RumblePitch(speed);
ch.Engine.PitchScale = AudioMix.EnginePitch(speed);
}
ch.Rumble.VolumeLinear = ch.Gain * 0.7f;
bool steam = ch.Traction == Traction.Steam;
ch.Engine.VolumeLinear = steam ? 0 : ch.Gain * 0.45f;
if (steam && speed > 0 && ch.Gain > 0.02f)
{
ch.ChuffTimer -= dt;
if (ch.ChuffTimer <= 0)
{
Play(_sfx, _chuff, ch.Gain * 0.9f, _rng.Range(0.92f, 1.08f), _busSfx);
ch.ChuffTimer = Math.Max(ch.ChuffTimer, 0) + AudioMix.ChuffInterval(speed);
}
}
}
}
private static bool Contains(int[] ids, int count, int id)
{
for (int i = 0; i < count; i++)
{
if (ids[i] == id) return true;
}
return false;
}
private bool HasChannel(int train)
{
foreach (var ch in _channels)
{
if (ch.Train == train) return true;
}
return false;
}
private void Assign(TrainChannel ch, int train, Protocol.Client.ClientWorld w)
{
ch.Train = train;
ch.Traction = TractionOf(train, w);
ch.Gain = 0;
ch.ChuffTimer = _rng.Next01() * 0.2f;
ch.Rumble.VolumeLinear = 0;
ch.Rumble.Play(_rng.Next01() * 1.5f);
ch.Engine.VolumeLinear = 0;
if (ch.Traction == Traction.Steam) ch.Engine.Stop();
else
{
ch.Engine.Stream = ch.Traction == Traction.Diesel ? _diesel : _hum;
ch.Engine.Play(_rng.Next01() * 0.9f);
}
}
/// <summary>Trazione della prima locomotiva del treno (vapore se non si sa).</summary>
private Traction TractionOf(int train, Protocol.Client.ClientWorld w)
{
if (!w.Trains.TryGetValue(train, out var info)) return Traction.Steam;
foreach (int vid in info.Vehicles)
{
if (w.Vehicles.TryGetValue(vid, out var v) && _vehicles.TryGetValue(v.Type, out var def) && def.Kind == VehicleKind.Locomotive && def.Traction is { } traction) return traction;
}
return Traction.Steam;
}
/// <summary>Fischio (vapore) o tromba all'arrivo in stazione di un treno visibile vicino al centro.</summary>
private void Whistle(int train)
{
var w = _session?.World;
if (w is null || _map is null || !_map.Trains.Heads.TryGetValue(train, out var head)) return;
ulong now = Time.GetTicksMsec();
if (now - _lastWhistleMs < 700) return;
float zoom = _map.Zoom;
float d = head.DistanceTo(_map.Camera.GetScreenCenterPosition()) * zoom;
float gain = AudioMix.TrainGain(d, _map.GetViewportRect().Size.Length() * 0.6f, AudioMix.FullSpeedMs, zoom);
if (gain < 0.03f) return;
_lastWhistleMs = now;
Play(_sfx, TractionOf(train, w) == Traction.Steam ? _whistle : _horn, gain * 0.9f, _rng.Range(0.97f, 1.03f), _busSfx);
}
}