Merge remote-tracking branch 'origin/main' into claude/f6-pannelli
CI / Build e test (pull_request) Successful in 1m35s
CI / Immagine Docker (pull_request) Successful in 36s

# Conflicts:
#	client/RailEnterprise.Client/assets/i18n/strings.csv
#	client/RailEnterprise.Client/scripts/Main.cs
#	client/RailEnterprise.Client/scripts/Screens/MenuScreen.cs
#	docs/ARCHITECTURE.md
#	docs/PROTOCOL.md
#	docs/STATE.md
#	src/RailEnterprise.Protocol/Client/ClientWorld.cs
This commit is contained in:
Alby96 committed 2026-11-08 14:38:09 +01:00
commit 767661957b
52 files changed
+4074 -91

No files matched your search

@@ -0,0 +1,643 @@
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 in moto vicini al centro della telecamera (rotolamento, motore, sbuffi), 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, _chuff;
private readonly Callable _clickCallable;
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];
/// <summary>
/// Età massima (ms) dell'ultimo moto di un treno perché suoni: il server manda i moti dei treni
/// in marcia ogni 100 ms; un moto più vecchio è di un treno fermo in stazione (durante la sosta
/// non arrivano moti) o uscito dalla zona sottoscritta, e non va più ascoltato.
/// </summary>
private const long StaleMotionMs = 500;
// 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;
private bool _settingsDirty;
// 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";
_clickCallable = Callable.From(PlayClick);
}
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();
// chiusura della finestra con un volume appena cambiato: si salva comunque
SaveSettings();
}
/// <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);
_settingsDirty = true;
ApplySettings();
SettingsChanged?.Invoke();
}
public void SetMuted(bool muted)
{
Settings.Muted = muted;
_settingsDirty = true;
ApplySettings();
SettingsChanged?.Invoke();
}
public void ToggleMute()
{
SetMuted(!Settings.Muted);
SaveSettings();
}
/// <summary>Scrive volumi e muto in <c>user://settings.cfg</c> se sono cambiati dall'ultimo salvataggio.</summary>
public void SaveSettings()
{
if (!_settingsDirty) return;
_settingsDirty = false;
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;
}
private void OnMessage(IMessage message)
{
if (!_loaded) return;
switch (message)
{
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;
}
}
/// <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)
{
// un pulsante staccato e riattaccato (MarketPanel lo fa a ogni resoconto) è già collegato
if (node is BaseButton button && !button.IsConnected(BaseButton.SignalName.Pressed, _clickCallable))
button.Connect(BaseButton.SignalName.Pressed, _clickCallable);
}
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, 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(),
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);
_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 && _session is { } session && w.Speed > 0)
{
center = map.Camera.GetScreenCenterPosition();
zoom = map.Zoom;
radius = map.GetViewportRect().Size.Length() / 2;
long now = (long)Time.GetTicksMsec();
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;
if (!session.MotionReceivedMs.TryGetValue(id, out long at) || now - at > StaleMotionMs) continue;
// oltre il raggio non si sentirebbe: niente canale (eviterebbe Play e Stop a ogni fotogramma)
float distance = head.DistanceTo(center) * zoom;
if (distance >= radius) continue;
count = AudioMix.InsertNearest(_nearIds, _nearDistances, count, id, distance);
}
}
// 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;
}
}
@@ -0,0 +1,150 @@
namespace RailEnterprise.Client.Audio;
/// <summary>Frazioni del terreno sotto la telecamera (somma 1 sui campioni letti).</summary>
public struct TerrainMix
{
public float River;
public float Lake;
public float Sea;
public float Town;
public float Forest;
public float Open;
}
/// <summary>Guadagni lineari (0–1) dei quattro anelli d'ambiente e probabilità relativa degli uccelli.</summary>
public readonly record struct AmbienceGains(float Wind, float Water, float Sea, float City, float Birds);
/// <summary>
/// Miscelazione dell'audio senza dipendenze da Godot: guadagni dell'ambiente dal terreno e dallo
/// zoom, volume e intonazione dei treni dalla distanza sullo schermo e dalla velocità, scelta dei
/// treni più vicini senza allocazioni, ere dall'anno, dissolvenze e conversione in PCM. Le costanti
/// sono di resa sonora del client, non della simulazione.
/// </summary>
public static class AudioMix
{
/// <summary>Zoom (pixel per metro) sotto il quale si sente quasi solo il vento della vista d'insieme.</summary>
public const float FarZoom = 0.02f;
/// <summary>Zoom da cui ambiente e treni sono al massimo.</summary>
public const float NearZoom = 0.5f;
/// <summary>Canali dei treni: al più tanti treni suonano insieme.</summary>
public const int TrainChannels = 3;
/// <summary>Velocità (m/s) a cui il rotolamento è al massimo.</summary>
public const float FullSpeedMs = 25f;
/// <summary>Sbuffi al secondo da fermo (al passo) e alla velocità <see cref="ChuffFullSpeedMs"/>.</summary>
public const float ChuffMinRate = 1.2f, ChuffMaxRate = 10f;
/// <summary>Velocità (m/s, circa 110 km/h) a cui gli sbuffi sono più fitti.</summary>
public const float ChuffFullSpeedMs = 30f;
public static float Clamp01(float x) => x < 0 ? 0 : x > 1 ? 1 : x;
public static float SmoothStep(float x)
{
x = Clamp01(x);
return x * x * (3 - 2 * x);
}
/// <summary>Vicinanza della telecamera (0 = vista d'insieme, 1 = da vicino) su scala logaritmica dello zoom.</summary>
public static float Closeness(float zoom)
{
if (zoom <= 0) return 0;
return SmoothStep((MathF.Log(zoom) - MathF.Log(FarZoom)) / (MathF.Log(NearZoom) - MathF.Log(FarZoom)));
}
/// <summary>
/// Ambiente: il vento c'è sempre (più forte da lontano), acqua, mare e città seguono la
/// frazione del terreno visibile e si attenuano allontanandosi; gli uccelli solo da vicino in
/// campagna e nei boschi.
/// </summary>
public static AmbienceGains Ambience(float zoom, in TerrainMix t)
{
float close = Closeness(zoom);
float wind = 0.35f + 0.35f * (1 - close) + 0.15f * t.Open;
float water = Clamp01((t.River * 3 + t.Lake * 1.5f) * (0.25f + 0.75f * close));
float sea = Clamp01(t.Sea * 1.6f * (0.45f + 0.55f * close));
float city = Clamp01(t.Town * 4 * (0.15f + 0.85f * close));
float birds = Clamp01((t.Forest + t.Open * 0.6f) * close * close * (1 - t.Town * 2));
// l'acqua e la città coprono un po' il vento
wind *= 1 - 0.4f * MathF.Max(sea, city);
return new AmbienceGains(Clamp01(wind), water, sea, city, birds);
}
/// <summary>Volume di un treno: vicinanza al centro dello schermo, velocità e zoom.</summary>
/// <param name="distancePx">Distanza in pixel dal centro dello schermo.</param>
/// <param name="radiusPx">Raggio oltre il quale non si sente (di solito metà della diagonale).</param>
public static float TrainGain(float distancePx, float radiusPx, float speedMs, float zoom)
{
if (radiusPx <= 0) return 0;
float near = 1 - Clamp01(distancePx / radiusPx);
float speed = Clamp01(speedMs / FullSpeedMs);
return near * near * (0.25f + 0.75f * speed) * (0.15f + 0.85f * Closeness(zoom));
}
/// <summary>Intonazione del rotolamento: più rapido e acuto con la velocità.</summary>
public static float RumblePitch(float speedMs) => 0.55f + 1.0f * Clamp01(speedMs / FullSpeedMs);
/// <summary>Intonazione del motore (diesel o elettrico) con la velocità.</summary>
public static float EnginePitch(float speedMs) => 0.8f + 0.5f * Clamp01(speedMs / FullSpeedMs);
/// <summary>
/// Secondi tra due sbuffi della vaporiera alla velocità data: la frequenza cresce in modo lineare
/// da <see cref="ChuffMinRate"/> a <see cref="ChuffMaxRate"/> fino a <see cref="ChuffFullSpeedMs"/>,
/// così segue la velocità su tutto l'esercizio normale. È una resa sonora, non il passo reale della
/// ruota: sullo schermo il tempo dei treni corre decine di volte più veloce e gli sbuffi reali
/// sarebbero un ronzio continuo.
/// </summary>
public static float ChuffInterval(float speedMs) => 1f / (ChuffMinRate + (ChuffMaxRate - ChuffMinRate) * Clamp01(speedMs / ChuffFullSpeedMs));
/// <summary>
/// Inserisce un candidato nell'elenco ordinato dei più vicini (al più ids.Length): nessuna
/// allocazione, gli elenchi sono preparati una volta sola. Restituisce il nuovo conteggio.
/// </summary>
public static int InsertNearest(int[] ids, float[] distances, int count, int id, float distance)
{
int capacity = ids.Length;
if (count == capacity && distance >= distances[capacity - 1]) return count;
int i = Math.Min(count, capacity - 1);
while (i > 0 && distances[i - 1] > distance)
{
ids[i] = ids[i - 1];
distances[i] = distances[i - 1];
i--;
}
ids[i] = id;
distances[i] = distance;
return Math.Min(count + 1, capacity);
}
/// <summary>Era dell'anno: l'ultima il cui inizio («from» di eras.json, crescente) non è dopo l'anno.</summary>
public static int EraIndex(int year, IReadOnlyList<int> froms)
{
int index = 0;
for (int i = 0; i < froms.Count; i++)
{
if (froms[i] <= year) index = i;
}
return index;
}
/// <summary>Avvicina un valore al bersaglio con velocità costante (unità al secondo).</summary>
public static float Approach(float current, float target, float ratePerSecond, float dt)
{
float step = ratePerSecond * dt;
return current < target ? MathF.Min(target, current + step) : MathF.Max(target, current - step);
}
/// <summary>Lineare → decibel, con −80 dB come silenzio.</summary>
public static float LinearToDb(float linear) => linear <= 0.0001f ? -80f : 20f * MathF.Log10(linear);
/// <summary>Campioni in [−1, 1] → PCM a 16 bit little-endian (formato di AudioStreamWAV).</summary>
public static byte[] ToPcm16(float[] samples)
{
var bytes = new byte[samples.Length * 2];
for (int i = 0; i < samples.Length; i++)
{
short s = (short)Math.Clamp((int)MathF.Round(samples[i] * 32767f), short.MinValue, short.MaxValue);
bytes[2 * i] = (byte)s;
bytes[2 * i + 1] = (byte)(s >> 8);
}
return bytes;
}
}
@@ -0,0 +1,91 @@
using Godot;
namespace RailEnterprise.Client.Audio;
/// <summary>Bus audio del client: Master e quattro bus che vi confluiscono.</summary>
public static class AudioBuses
{
public const string Master = "Master";
public const string Music = "Music";
public const string Ambience = "Ambience";
public const string Sfx = "Sfx";
public const string Ui = "Ui";
/// <summary>Nell'ordine dei cursori delle impostazioni.</summary>
public static readonly string[] All = [Master, Music, Ambience, Sfx, Ui];
/// <summary>
/// Crea i bus che mancano (idempotente: chiamarla più volte non ne aggiunge altri) e un
/// limitatore sul Master, così la somma di musica, ambiente ed effetti non satura.
/// </summary>
public static void Ensure()
{
foreach (string name in All)
{
if (name == Master || AudioServer.GetBusIndex(name) >= 0) continue;
int index = AudioServer.BusCount;
AudioServer.AddBus(index);
AudioServer.SetBusName(index, name);
AudioServer.SetBusSend(index, Master);
}
bool limited = false;
for (int i = 0; i < AudioServer.GetBusEffectCount(0); i++)
{
if (AudioServer.GetBusEffect(0, i) is AudioEffectHardLimiter) limited = true;
}
if (!limited) AudioServer.AddBusEffect(0, new AudioEffectHardLimiter { CeilingDb = -0.5f });
}
}
/// <summary>
/// Volumi per bus (0–1) e muto generale, salvati nella sezione «audio» di
/// <c>user://settings.cfg</c> (lo stesso file della lingua e del server).
/// </summary>
public sealed class AudioSettings
{
public const string Path = "user://settings.cfg";
private const string Section = "audio";
private static readonly float[] Defaults = [0.8f, 0.55f, 0.7f, 0.8f, 0.7f];
/// <summary>Volumi nell'ordine di <see cref="AudioBuses.All"/>.</summary>
public float[] Volumes { get; } = (float[])Defaults.Clone();
public bool Muted { get; set; }
public static AudioSettings Load()
{
var s = new AudioSettings();
var cfg = new ConfigFile();
if (cfg.Load(Path) != Error.Ok) return s;
for (int i = 0; i < AudioBuses.All.Length; i++)
{
float v = (float)(double)cfg.GetValue(Section, Key(i), Defaults[i]);
s.Volumes[i] = Math.Clamp(v, 0, 1);
}
s.Muted = (bool)cfg.GetValue(Section, "muted", false);
return s;
}
public void Save()
{
var cfg = new ConfigFile();
cfg.Load(Path);
for (int i = 0; i < AudioBuses.All.Length; i++) cfg.SetValue(Section, Key(i), Volumes[i]);
cfg.SetValue(Section, "muted", Muted);
cfg.Save(Path);
}
private static string Key(int i) => AudioBuses.All[i].ToLowerInvariant();
/// <summary>Applica volumi e muto ai bus (il cursore segue il volume percepito: guadagno = valore²).</summary>
public void Apply()
{
for (int i = 0; i < AudioBuses.All.Length; i++)
{
int bus = AudioServer.GetBusIndex(AudioBuses.All[i]);
if (bus >= 0) AudioServer.SetBusVolumeDb(bus, AudioMix.LinearToDb(Volumes[i] * Volumes[i]));
}
AudioServer.SetBusMute(0, Muted);
}
}
@@ -0,0 +1,110 @@
using Godot;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Audio;
/// <summary>
/// Pannello «Audio» sopra a tutto: un cursore per bus (generale, musica, ambiente, effetti,
/// interfaccia) e il muto generale. I cambi si sentono subito; quando il pannello esce dall'albero
/// (anche chiudendo la finestra del gioco) si salvano in <c>user://settings.cfg</c>. Esc o un clic
/// sinistro fuori chiudono.
/// </summary>
public partial class AudioSettingsPanel : Control
{
private readonly AudioManager _audio;
private readonly List<(HSlider Slider, Label Value)> _rows = [];
private readonly CheckBox _mute = new() { Text = T("Muto") };
private static readonly string[] Captions = ["Volume generale", "Musica", "Ambiente", "Effetti", "Interfaccia"];
public AudioSettingsPanel(AudioManager audio) => _audio = audio;
public override void _Ready()
{
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var shade = new ColorRect { Color = new Color(0, 0, 0, 0.5f), MouseFilter = MouseFilterEnum.Stop };
shade.SetAnchorsPreset(LayoutPreset.FullRect);
shade.GuiInput += e =>
{
// solo il clic sinistro: la rotella e il tasto destro arrivano anch'essi come pressioni
if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) Close();
};
AddChild(shade);
var center = new CenterContainer { MouseFilter = MouseFilterEnum.Ignore };
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var panel = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
center.AddChild(panel);
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 12);
panel.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Audio"), 34));
for (int i = 0; i < Captions.Length; i++)
{
int bus = i;
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 12);
var caption = UiTheme.Text(T(Captions[i]), 14, Palette.TextSecondary);
caption.CustomMinimumSize = new Vector2(150, 0);
row.AddChild(caption);
var slider = new HSlider
{
MinValue = 0, MaxValue = 1, Step = 0.05, SizeFlagsHorizontal = SizeFlags.ExpandFill,
SizeFlagsVertical = SizeFlags.ShrinkCenter, Value = _audio.Settings.Volumes[i],
};
var value = UiTheme.Text("", 14, bold: true);
value.CustomMinimumSize = new Vector2(48, 0);
value.HorizontalAlignment = HorizontalAlignment.Right;
slider.ValueChanged += v => _audio.SetVolume(bus, (float)v);
row.AddChild(slider);
row.AddChild(value);
col.AddChild(row);
_rows.Add((slider, value));
}
_mute.ButtonPressed = _audio.Settings.Muted;
_mute.Toggled += on => _audio.SetMuted(on);
col.AddChild(_mute);
var hint = UiTheme.Text(T("Il tasto M attiva e toglie il muto durante la partita."), 13, Palette.TextSecondary);
hint.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(hint);
var close = UiTheme.Primary(T("Chiudi"));
close.Pressed += Close;
col.AddChild(close);
_audio.SettingsChanged += Refresh;
Refresh();
}
public override void _ExitTree()
{
_audio.SettingsChanged -= Refresh;
_audio.SaveSettings();
}
private void Refresh()
{
for (int i = 0; i < _rows.Count; i++)
{
_rows[i].Slider.SetValueNoSignal(_audio.Settings.Volumes[i]);
_rows[i].Value.Text = $"{Math.Round(_audio.Settings.Volumes[i] * 100):0} %";
}
_mute.SetPressedNoSignal(_audio.Settings.Muted);
}
public override void _Input(InputEvent e)
{
if (e is InputEventKey { Pressed: true, Keycode: Key.Escape })
{
Close();
GetViewport().SetInputAsHandled();
}
}
private void Close()
{
if (IsQueuedForDeletion()) return;
QueueFree();
}
}
@@ -0,0 +1,327 @@
namespace RailEnterprise.Client.Audio;
/// <summary>
/// Temi musicali procedurali per era, senza dipendenze da Godot. Ogni era ha uno stile (tempo,
/// metro, scala, timbri: valzer da carillon e fisarmonica per il vapore, organo e basso che
/// cammina per il diesel, vibrafono e archi per l'elettrico, arpeggi a impulsi per l'alta
/// velocità); progressione, arpeggio e melodia escono da un seme fisso (hash dell'id dell'era),
/// quindi lo stesso tema a ogni avvio. Forma in 16 battute: introduzione (accompagnamento),
/// melodia, melodia variata, coda; le code delle note rientrano dall'inizio, così l'anello si
/// ripete senza scatti. Uscita mono a <see cref="Synth.Rate"/> Hz.
/// </summary>
public static class MusicComposer
{
public const int Bars = 16;
public enum Timbre { MusicBox, Accordion, Organ, Vibraphone, Strings, Pulse, Saw, SoftBass, PluckBass }
public enum Comping { Held, Waltz }
/// <summary>Stile di un'era.</summary>
public sealed record Style(int Bpm, int BeatsPerBar, int[] Scale, int RootMidi, Timbre Pad, Comping Comping,
Timbre Arp, int ArpPerBeat, Timbre Lead, Timbre Bass, bool WalkingBass, float Swing);
private static readonly int[] Major = [0, 2, 4, 5, 7, 9, 11];
private static readonly int[] Mixolydian = [0, 2, 4, 5, 7, 9, 10];
private static readonly int[] Dorian = [0, 2, 3, 5, 7, 9, 10];
/// <summary>Progressioni per grado della scala (0 = primo grado), una battuta per accordo.</summary>
private static readonly int[][] Progressions =
[
[0, 3, 4, 0], [0, 5, 3, 4], [0, 4, 5, 3], [1, 4, 0, 5], [5, 3, 0, 4], [0, 3, 1, 4],
];
/// <summary>Stile dell'era per posizione nell'elenco di eras.json (le ere oltre la quarta riprendono il ciclo).</summary>
public static Style StyleFor(int eraIndex) => (Math.Max(0, eraIndex) % 4) switch
{
0 => new Style(116, 3, Major, 62, Timbre.Accordion, Comping.Waltz, Timbre.MusicBox, 0, Timbre.MusicBox, Timbre.SoftBass, false, 0),
1 => new Style(96, 4, Mixolydian, 60, Timbre.Organ, Comping.Held, Timbre.Vibraphone, 1, Timbre.Organ, Timbre.PluckBass, true, 0.18f),
2 => new Style(104, 4, Major, 65, Timbre.Strings, Comping.Held, Timbre.Vibraphone, 2, Timbre.Vibraphone, Timbre.SoftBass, false, 0),
_ => new Style(124, 4, Dorian, 57, Timbre.Saw, Comping.Held, Timbre.Pulse, 4, Timbre.Saw, Timbre.SoftBass, false, 0),
};
/// <summary>Seme fisso del tema: hash dell'id dell'era e della sua posizione.</summary>
public static ulong Seed(int eraIndex, string eraId) => SynthRng.Hash(eraId) ^ ((ulong)(eraIndex + 1) * 0x9E3779B97F4A7C15UL);
/// <summary>Durata dell'anello in secondi.</summary>
public static float LengthSeconds(Style style) => Bars * style.BeatsPerBar * 60f / style.Bpm;
// ------------------------------------------------------------------ timbri
private sealed class Voice
{
/// <summary>Ampiezza della n-esima armonica in Harmonics[n−1].</summary>
public required float[] Harmonics { get; init; }
public float Attack { get; init; } = 0.005f;
/// <summary>Decadimento verso il sostegno (s).</summary>
public float Decay { get; init; } = 0.3f;
public float Sustain { get; init; }
public float Release { get; init; } = 0.1f;
/// <summary>Copie leggermente scordate (coro).</summary>
public float[] Detune { get; init; } = [0];
public float TremoloHz { get; init; }
public float TremoloDepth { get; init; }
public float VibratoDepth { get; init; }
// tabelle per numero di armoniche tenute (una per registro, costruite al primo uso)
private readonly Dictionary<int, float[]> _tables = [];
/// <summary>
/// Forma d'onda per una nota alla frequenza data, con le sole armoniche sotto
/// <see cref="MaxHarmonicShare"/> della frequenza di campionamento: quelle oltre Nyquist
/// tornerebbero indietro come toni stonati.
/// </summary>
public float[] TableFor(float frequency)
{
int n = Math.Clamp((int)(MaxHarmonicShare * Synth.Rate / frequency), 1, Harmonics.Length);
if (!_tables.TryGetValue(n, out var table))
{
table = Table(Harmonics, n);
_tables[n] = table;
}
return table;
}
}
/// <summary>Frazione della frequenza di campionamento sotto cui stanno le armoniche (margine per vibrato e coro).</summary>
private const float MaxHarmonicShare = 0.45f;
private const int TableSize = 2048;
/// <summary>Forma d'onda di un periodo dalla somma delle prime «count» armoniche (ampiezza della n-esima in harmonics[n−1]).</summary>
private static float[] Table(float[] harmonics, int count)
{
var t = new float[TableSize];
for (int i = 0; i < TableSize; i++)
{
float x = MathF.PI * 2 * i / TableSize;
float v = 0;
for (int h = 0; h < count; h++) v += harmonics[h] * MathF.Sin(x * (h + 1));
t[i] = v;
}
Synth.Normalize(t, 1);
return t;
}
private static float[] SawHarmonics(int n)
{
var h = new float[n];
for (int i = 0; i < n; i++) h[i] = 1f / (i + 1);
return h;
}
private static float[] PulseHarmonics(int n, float duty)
{
var h = new float[n];
for (int i = 0; i < n; i++) h[i] = MathF.Abs(MathF.Sin(MathF.PI * (i + 1) * duty)) / (i + 1);
return h;
}
private static Voice VoiceFor(Timbre timbre) => timbre switch
{
Timbre.MusicBox => new Voice { Harmonics = [1, 0.1f, 0.35f, 0, 0.12f], Attack = 0.002f, Decay = 0.7f, Sustain = 0, Release = 0.6f },
Timbre.Accordion => new Voice { Harmonics = [1, 0.5f, 0.6f, 0.3f, 0.25f, 0.15f], Attack = 0.03f, Decay = 0.2f, Sustain = 0.8f, Release = 0.08f, Detune = [0, 0.004f], TremoloHz = 5, TremoloDepth = 0.12f },
Timbre.Organ => new Voice { Harmonics = [1, 0.8f, 0.6f, 0.4f, 0, 0.3f, 0, 0.2f], Attack = 0.01f, Decay = 0.1f, Sustain = 0.9f, Release = 0.06f, TremoloHz = 6, TremoloDepth = 0.1f },
Timbre.Vibraphone => new Voice { Harmonics = [1, 0, 0, 0.25f], Attack = 0.003f, Decay = 1.1f, Sustain = 0, Release = 0.8f, TremoloHz = 5, TremoloDepth = 0.3f },
Timbre.Strings => new Voice { Harmonics = SawHarmonics(8), Attack = 0.3f, Decay = 0.5f, Sustain = 0.85f, Release = 0.35f, Detune = [-0.003f, 0, 0.003f], VibratoDepth = 0.003f },
Timbre.Pulse => new Voice { Harmonics = PulseHarmonics(9, 0.25f), Attack = 0.004f, Decay = 0.22f, Sustain = 0, Release = 0.15f },
Timbre.Saw => new Voice { Harmonics = SawHarmonics(10), Attack = 0.08f, Decay = 0.4f, Sustain = 0.7f, Release = 0.25f, Detune = [-0.005f, 0.005f], VibratoDepth = 0.002f },
Timbre.PluckBass => new Voice { Harmonics = [1, 0.5f, 0.25f, 0.1f], Attack = 0.005f, Decay = 0.35f, Sustain = 0.15f, Release = 0.08f },
_ => new Voice { Harmonics = [1, 0.3f, 0.1f], Attack = 0.01f, Decay = 0.4f, Sustain = 0.6f, Release = 0.1f },
};
private static float Frequency(float midi) => 440f * MathF.Pow(2, (midi - 69) / 12f);
/// <summary>Suona una nota nell'anello (con la coda che rientra dall'inizio).</summary>
private static void Note(float[] loop, Voice v, float startS, float durS, float midi, float gain)
{
int rate = Synth.Rate;
float f = Frequency(midi);
var table = v.TableFor(f);
int start = (int)(startS * rate);
float total = durS + v.Release;
int samples = Math.Min(loop.Length, (int)(total * rate));
foreach (float detune in v.Detune)
{
float inc = f * (1 + detune) * TableSize / rate;
float phase = (detune + 0.5f) * 97 % TableSize;
float g = gain / v.Detune.Length;
for (int i = 0; i < samples; i++)
{
float t = i / (float)rate;
float env = t < v.Attack ? t / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(t - v.Attack) / v.Decay);
if (t > durS)
{
// rilascio dal livello raggiunto alla fine della nota
float atEnd = durS < v.Attack ? durS / v.Attack : v.Sustain + (1 - v.Sustain) * MathF.Exp(-(durS - v.Attack) / v.Decay);
env = atEnd * MathF.Max(0, 1 - (t - durS) / v.Release);
}
if (v.TremoloDepth > 0) env *= 1 - v.TremoloDepth * (0.5f + 0.5f * MathF.Sin(MathF.PI * 2 * v.TremoloHz * t));
float step = v.VibratoDepth > 0 ? inc * (1 + v.VibratoDepth * MathF.Sin(MathF.PI * 2 * 5.5f * t)) : inc;
phase += step;
if (phase >= TableSize) phase -= TableSize;
int i0 = (int)phase;
float frac = phase - i0;
float s = table[i0] + (table[(i0 + 1) & (TableSize - 1)] - table[i0]) * frac;
loop[(start + i) % loop.Length] += s * env * g;
}
}
}
/// <summary>Altezza MIDI del grado della scala (i gradi oltre la scala salgono d'ottava).</summary>
private static int Degree(Style s, int degree)
{
int n = s.Scale.Length;
int octave = (int)Math.Floor(degree / (double)n);
int d = degree - octave * n;
return s.RootMidi + s.Scale[d] + 12 * octave;
}
/// <summary>Compone e sintetizza il tema dell'era: campioni mono in [−1, 1].</summary>
public static float[] Compose(int eraIndex, string eraId)
{
var style = StyleFor(eraIndex);
var rng = new SynthRng(Seed(eraIndex, eraId));
float beat = 60f / style.Bpm;
float bar = beat * style.BeatsPerBar;
var loop = new float[(int)(LengthSeconds(style) * Synth.Rate)];
var progression = Progressions[rng.Next(Progressions.Length)];
var pad = VoiceFor(style.Pad);
var arp = VoiceFor(style.Arp);
var lead = VoiceFor(style.Lead);
var bass = VoiceFor(style.Bass);
bool arpDown = rng.Next(2) == 0;
// motivo di quattro battute: un ritmo per battuta (in ottavi) e gradi vicini all'accordo
int eighths = style.BeatsPerBar * 2;
var motif = new List<(int Bar, int Eighth, int Length, int Degree)>();
int current = 7 + progression[0];
for (int b = 0; b < 4; b++)
{
int chord = progression[b];
int e = 0;
while (e < eighths)
{
int len = rng.Next(4) switch { 0 => 1, 1 or 2 => 2, _ => 3 };
len = Math.Min(len, eighths - e);
if (rng.Next(5) == 0 && e > 0)
{
e += len; // pausa
continue;
}
bool strong = e % (style.BeatsPerBar == 3 ? 6 : 4) == 0;
if (strong)
{
// sui tempi forti una nota dell'accordo vicina alla precedente
int best = current, bestD = int.MaxValue;
for (int k = -1; k <= 2; k++)
{
foreach (int ct in new[] { 0, 2, 4 })
{
int cand = chord + ct + 7 * k;
int dist = Math.Abs(cand - current);
if (cand >= 4 && cand <= 13 && dist < bestD)
{
bestD = dist;
best = cand;
}
}
}
current = best;
}
else current = Math.Clamp(current + rng.Next(5) - 2, 4, 13);
motif.Add((b, e, len, current));
e += len;
}
}
// l'ultima nota del motivo torna sulla tonica
if (motif.Count > 0) motif[^1] = motif[^1] with { Degree = 7 };
for (int barIndex = 0; barIndex < Bars; barIndex++)
{
int chord = progression[barIndex % 4];
float t0 = barIndex * bar;
int[] tones = [Degree(style, chord), Degree(style, chord + 2), Degree(style, chord + 4)];
// accompagnamento
if (style.Comping == Comping.Waltz)
{
for (int k = 1; k < style.BeatsPerBar; k++)
foreach (int m in tones) Note(loop, pad, t0 + k * beat, beat * 0.55f, m, 0.11f);
}
else
{
foreach (int m in tones) Note(loop, pad, t0, bar * 0.95f, m, 0.12f);
}
// basso: fondamentale (e quinta) o basso che cammina sulle note dell'accordo
int root = Degree(style, chord) - 24;
if (style.WalkingBass)
{
int next = Degree(style, progression[(barIndex + 1) % 4]) - 24;
int[] walk = [root, root + (tones[1] - tones[0]), root + 7, next + (next > root ? -1 : 1)];
for (int k = 0; k < style.BeatsPerBar; k++) Note(loop, bass, t0 + k * beat, beat * 0.9f, walk[k % walk.Length], 0.32f);
}
else if (style.Comping == Comping.Waltz) Note(loop, bass, t0, beat * 0.9f, root, 0.34f);
else
{
Note(loop, bass, t0, beat * 1.8f, root, 0.32f);
Note(loop, bass, t0 + 2 * beat, beat * 1.8f, root + 7, 0.26f);
}
// arpeggio (in introduzione e coda più presente)
if (style.ArpPerBeat > 0)
{
int steps = style.BeatsPerBar * style.ArpPerBeat;
float step = beat / style.ArpPerBeat;
float gain = barIndex is < 4 or >= 12 ? 0.13f : 0.08f;
for (int k = 0; k < steps; k++)
{
int idx = arpDown ? 3 - k % 4 : k % 4;
int m = idx < 3 ? tones[idx] + 12 : tones[0] + 24;
float swing = style.Swing > 0 && k % 2 == 1 ? style.Swing * step : 0;
Note(loop, arp, t0 + k * step + swing, step * 0.8f, m, gain);
}
}
// melodia nelle battute 4–11 (la seconda volta un'ottava sopra le ultime due battute)
if (barIndex is >= 4 and < 12)
{
int motifBar = barIndex % 4;
bool variation = barIndex >= 8;
foreach (var n in motif)
{
if (n.Bar != motifBar) continue;
float eighth = beat / 2;
float swing = style.Swing > 0 && n.Eighth % 2 == 1 ? style.Swing * eighth : 0;
int midi = Degree(style, n.Degree) + (variation && motifBar >= 2 ? 12 : 0);
Note(loop, lead, t0 + n.Eighth * eighth + swing, n.Length * eighth * 0.92f, midi, 0.2f);
}
}
}
// un po' di spazio: due echi smorzati sull'anello, poi limitazione morbida
Echo(loop, 0.27f, 0.22f);
Echo(loop, 0.41f, 0.15f);
Synth.Normalize(loop, 1);
for (int i = 0; i < loop.Length; i++) loop[i] = MathF.Tanh(loop[i] * 1.2f) * 0.7f;
return loop;
}
/// <summary>Eco con retroazione su un anello (due giri per la continuità all'inizio).</summary>
private static void Echo(float[] loop, float delayS, float feedback)
{
int d = Math.Max(1, (int)(delayS * Synth.Rate));
var lp = Biquad.LowPass(2500, 0.7f, Synth.Rate);
var wet = new float[loop.Length];
for (int pass = 0; pass < 2; pass++)
{
for (int i = 0; i < loop.Length; i++)
{
int j = (i - d + loop.Length) % loop.Length;
wet[i] = lp.Process(loop[j] + wet[j] * feedback) * feedback;
}
}
for (int i = 0; i < loop.Length; i++) loop[i] += wet[i];
}
}
@@ -0,0 +1,49 @@
using Godot;
using RailEnterprise.Client.App;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Audio;
/// <summary>Altoparlante nella barra superiore: apre il pannello «Audio»; barrato quando il muto è attivo.</summary>
public partial class SpeakerButton : Button
{
public SpeakerButton()
{
Flat = true;
CustomMinimumSize = new Vector2(40, 40);
TooltipText = T("Audio (M: muto)");
Pressed += () => AudioManager.Instance?.ShowSettings();
MouseEntered += QueueRedraw;
MouseExited += QueueRedraw;
}
public override void _EnterTree()
{
if (AudioManager.Instance is { } audio) audio.SettingsChanged += QueueRedraw;
}
public override void _ExitTree()
{
if (AudioManager.Instance is { } audio) audio.SettingsChanged -= QueueRedraw;
}
public override void _Draw()
{
bool muted = AudioManager.Instance?.Settings.Muted ?? false;
var col = IsHovered() ? Palette.AmberLight : muted ? Palette.TextSecondary : Palette.Text;
var c = Size / 2;
const float w = 2f;
// cassa e cono
DrawColoredPolygon([c + new Vector2(-10, -4), c + new Vector2(-5, -4), c + new Vector2(1, -10), c + new Vector2(1, 10), c + new Vector2(-5, 4), c + new Vector2(-10, 4)], col);
if (muted)
{
DrawLine(c + new Vector2(5, -5), c + new Vector2(13, 5), Palette.Danger, w);
DrawLine(c + new Vector2(13, -5), c + new Vector2(5, 5), Palette.Danger, w);
}
else
{
DrawArc(c + new Vector2(1, 0), 6, -0.9f, 0.9f, 10, col, w);
DrawArc(c + new Vector2(1, 0), 11, -0.9f, 0.9f, 14, col, w);
}
}
}
@@ -0,0 +1,554 @@
namespace RailEnterprise.Client.Audio;
/// <summary>
/// Generatore pseudo-casuale xorshift64* per la sintesi dei suoni. Non è il <c>Rng</c> della
/// simulazione: serve solo a rendere ripetibili rumori, variazioni e temi musicali del client.
/// </summary>
public struct SynthRng
{
private ulong _s;
public SynthRng(ulong seed) => _s = seed == 0 ? 0x9E3779B97F4A7C15UL : seed;
public ulong NextU64()
{
_s ^= _s >> 12;
_s ^= _s << 25;
_s ^= _s >> 27;
return _s * 2685821657736338717UL;
}
/// <summary>Numero in [0, 1).</summary>
public float Next01() => (NextU64() >> 40) * (1f / (1 << 24));
/// <summary>Numero in [−1, 1).</summary>
public float NextSigned() => Next01() * 2f - 1f;
/// <summary>Intero in [0, n).</summary>
public int Next(int n) => (int)((NextU64() >> 33) % (ulong)n);
/// <summary>Numero in [a, b).</summary>
public float Range(float a, float b) => a + (b - a) * Next01();
/// <summary>FNV-1a a 64 bit di una stringa: semi fissi derivati da un identificatore (per esempio l'id dell'era).</summary>
public static ulong Hash(string text)
{
ulong h = 14695981039346656037UL;
foreach (char c in text)
{
h ^= c;
h *= 1099511628211UL;
}
return h;
}
}
/// <summary>Filtro biquadratico (formule RBJ): passa-basso, passa-alto, passa-banda a guadagno di picco unitario.</summary>
public struct Biquad
{
private float _b0, _b1, _b2, _a1, _a2, _z1, _z2;
private static Biquad Make(float b0, float b1, float b2, float a0, float a1, float a2) =>
new() { _b0 = b0 / a0, _b1 = b1 / a0, _b2 = b2 / a0, _a1 = a1 / a0, _a2 = a2 / a0 };
private static (float Cos, float Alpha) W(float freq, float q, int rate)
{
float w0 = 2 * MathF.PI * Math.Clamp(freq, 1, rate * 0.45f) / rate;
return (MathF.Cos(w0), MathF.Sin(w0) / (2 * q));
}
public static Biquad LowPass(float freq, float q, int rate)
{
var (c, a) = W(freq, q, rate);
return Make((1 - c) / 2, 1 - c, (1 - c) / 2, 1 + a, -2 * c, 1 - a);
}
public static Biquad HighPass(float freq, float q, int rate)
{
var (c, a) = W(freq, q, rate);
return Make((1 + c) / 2, -(1 + c), (1 + c) / 2, 1 + a, -2 * c, 1 - a);
}
public static Biquad BandPass(float freq, float q, int rate)
{
var (c, a) = W(freq, q, rate);
return Make(a, 0, -a, 1 + a, -2 * c, 1 - a);
}
/// <summary>Cambia i coefficienti mantenendo lo stato (filtri a frequenza variabile).</summary>
public void Retune(Biquad coefficients)
{
_b0 = coefficients._b0;
_b1 = coefficients._b1;
_b2 = coefficients._b2;
_a1 = coefficients._a1;
_a2 = coefficients._a2;
}
public float Process(float x)
{
float y = _b0 * x + _z1;
_z1 = _b1 * x - _a1 * y + _z2;
_z2 = _b2 * x - _a2 * y;
return y;
}
}
/// <summary>
/// Sintesi procedurale di tutti gli effetti del gioco, senza dipendenze da Godot: ogni funzione
/// restituisce campioni mono in virgola mobile a <see cref="Rate"/> Hz, da convertire in PCM a
/// 16 bit con <see cref="AudioMix.ToPcm16"/>. Gli anelli («Loop») si ripetono senza scatti: i
/// filtri girano due volte sullo stesso rumore (la seconda passata parte dallo stato della fine),
/// le modulazioni hanno un numero intero di periodi nell'anello e le code degli eventi brevi
/// rientrano dall'inizio. Semi fissi: stesso suono a ogni avvio.
/// </summary>
public static class Synth
{
/// <summary>Frequenza di campionamento di tutti i suoni (Hz).</summary>
public const int Rate = 22050;
private const float Tau = MathF.PI * 2;
public static float[] Buffer(float seconds) => new float[Math.Max(1, (int)(seconds * Rate))];
/// <summary>Inviluppo attacco lineare e decadimento esponenziale.</summary>
public static float Env(float t, float attack, float decay) =>
t < 0 ? 0 : t < attack ? t / attack : MathF.Exp(-(t - attack) / decay);
/// <summary>Porta il picco al valore indicato.</summary>
public static void Normalize(float[] buffer, float peak)
{
float max = 0;
foreach (float s in buffer) max = Math.Max(max, Math.Abs(s));
if (max < 1e-6f) return;
float k = peak / max;
for (int i = 0; i < buffer.Length; i++) buffer[i] *= k;
}
/// <summary>Sfuma gli ultimi millisecondi di un suono singolo (niente scatto alla fine).</summary>
public static void FadeOut(float[] buffer, float seconds = 0.01f)
{
int n = Math.Min(buffer.Length, (int)(seconds * Rate));
for (int i = 0; i < n; i++) buffer[buffer.Length - 1 - i] *= i / (float)n;
}
/// <summary>Rumore bianco ripetibile.</summary>
public static float[] Noise(int length, ulong seed)
{
var rng = new SynthRng(seed);
var n = new float[length];
for (int i = 0; i < length; i++) n[i] = rng.NextSigned();
return n;
}
/// <summary>Filtra un anello due volte: la seconda passata riparte dallo stato della fine della prima.</summary>
public static float[] LoopFilter(float[] input, Biquad filter)
{
var output = new float[input.Length];
for (int pass = 0; pass < 2; pass++)
{
for (int i = 0; i < input.Length; i++) output[i] = filter.Process(input[i]);
}
return output;
}
/// <summary>Rumore marrone in anello: integrazione con perdita del rumore bianco, due passate.</summary>
public static float[] BrownLoop(int length, ulong seed, float leak)
{
var white = Noise(length, seed);
var brown = new float[length];
float acc = 0;
for (int pass = 0; pass < 2; pass++)
{
for (int i = 0; i < length; i++)
{
acc = acc * leak + white[i] * (1 - leak) * 10;
brown[i] = acc;
}
}
return brown;
}
/// <summary>Somma un suono breve nell'anello a partire da «at» campioni, con la coda che rientra dall'inizio.</summary>
public static void MixWrapped(float[] loop, float[] sound, int at, float gain)
{
for (int i = 0; i < sound.Length; i++) loop[(at + i) % loop.Length] += sound[i] * gain;
}
// ------------------------------------------------------------------ interfaccia
/// <summary>Clic dell'interfaccia: un colpetto secco e brillante.</summary>
public static float[] Click()
{
var b = Buffer(0.035f);
var noise = Noise(b.Length, 11);
var hp = Biquad.HighPass(2500, 0.7f, Rate);
for (int i = 0; i < b.Length; i++)
{
float t = i / (float)Rate;
b[i] = MathF.Sin(Tau * 1800 * t) * MathF.Exp(-t / 0.006f) * 0.6f + hp.Process(noise[i]) * MathF.Exp(-t / 0.003f) * 0.5f;
}
Normalize(b, 0.5f);
FadeOut(b, 0.005f);
return b;
}
/// <summary>Nota con armoniche (ampiezze in «harmonics», la prima è la fondamentale) e decadimento esponenziale.</summary>
private static void Tone(float[] b, float start, float freq, float decay, float gain, float[] harmonics)
{
int s0 = (int)(start * Rate);
for (int i = s0; i < b.Length; i++)
{
float t = (i - s0) / (float)Rate;
float env = Env(t, 0.005f, decay);
if (env < 1e-4f && t > 0.01f) break;
float v = 0;
for (int h = 0; h < harmonics.Length; h++)
{
float f = freq * (h + 1);
if (harmonics[h] != 0 && f < Rate * 0.45f) v += harmonics[h] * MathF.Sin(Tau * f * t);
}
b[i] += v * env * gain;
}
}
/// <summary>Esito positivo di un comando: due note ascendenti (la, mi).</summary>
public static float[] Confirm()
{
var b = Buffer(0.32f);
float[] h = [1, 0.3f];
Tone(b, 0, 880, 0.09f, 1, h);
Tone(b, 0.07f, 1318.5f, 0.11f, 0.9f, h);
Normalize(b, 0.42f);
FadeOut(b);
return b;
}
/// <summary>Comando rifiutato: due note scure discendenti.</summary>
public static float[] Error()
{
var b = Buffer(0.38f);
float[] h = [1, 0, 0.33f, 0, 0.2f];
Tone(b, 0, 330, 0.12f, 1, h);
Tone(b, 0.1f, 247, 0.14f, 1, h);
var lp = Biquad.LowPass(1800, 0.7f, Rate);
for (int i = 0; i < b.Length; i++) b[i] = lp.Process(b[i]);
Normalize(b, 0.45f);
FadeOut(b);
return b;
}
/// <summary>Campana in modulazione di frequenza (portante f, modulante 1,4·f, indice che decade).</summary>
private static void Bell(float[] b, float start, float freq, float gain, float decay = 0.6f)
{
int s0 = (int)(start * Rate);
for (int i = s0; i < b.Length; i++)
{
float t = (i - s0) / (float)Rate;
float index = 2.5f * MathF.Exp(-t / 0.3f);
b[i] += MathF.Sin(Tau * freq * t + index * MathF.Sin(Tau * freq * 1.4f * t)) * Env(t, 0.003f, decay) * gain;
}
}
/// <summary>Notifica: 0 = informazione o opportunità, 1 = avviso, 2 = critica.</summary>
public static float[] Notify(int level)
{
float[] b;
switch (level)
{
case <= 0:
b = Buffer(1.0f);
Bell(b, 0, 1046.5f, 1);
Bell(b, 0.12f, 1568f, 0.6f);
break;
case 1:
b = Buffer(1.2f);
Bell(b, 0, 784f, 1, 0.7f);
Bell(b, 0.18f, 622.3f, 1, 0.7f);
break;
default:
// tre impulsi dissonanti: si distinguono anche sopra la musica
b = Buffer(1.0f);
float[] h = [1, 0, 0.33f, 0, 0.2f];
for (int k = 0; k < 3; k++)
{
Tone(b, k * 0.22f, 523.3f, 0.09f, 0.8f, h);
Tone(b, k * 0.22f, 554.4f, 0.09f, 0.6f, h);
}
break;
}
Normalize(b, 0.55f);
FadeOut(b);
return b;
}
/// <summary>Cantiere completato: due colpi metallici e un arpeggio maggiore.</summary>
public static float[] BuildComplete()
{
var b = Buffer(1.5f);
var noise = Noise(b.Length, 23);
foreach (var (at, gain) in new[] { (0f, 1f), (0.16f, 0.7f) })
{
int s0 = (int)(at * Rate);
var bp = Biquad.BandPass(2500, 4, Rate);
for (int i = s0; i < b.Length; i++)
{
float t = (i - s0) / (float)Rate;
float metal = MathF.Sin(Tau * 420 * t + 3 * MathF.Exp(-t / 0.08f) * MathF.Sin(Tau * 420 * 2.76f * t));
b[i] += (bp.Process(noise[i]) * 2 * Env(t, 0.001f, 0.04f) + metal * Env(t, 0.002f, 0.25f)) * gain * 0.6f;
}
}
float[] pluck = [1, 0.4f, 0.15f];
float[] notes = [523.3f, 659.3f, 784f, 1046.5f];
for (int k = 0; k < notes.Length; k++) Tone(b, 0.32f + k * 0.08f, notes[k], k == notes.Length - 1 ? 0.35f : 0.15f, 0.7f, pluck);
Normalize(b, 0.55f);
FadeOut(b, 0.05f);
return b;
}
// ------------------------------------------------------------------ treni
/// <summary>Fischio a vapore all'arrivo: accordo 4:5:6 con salita d'intonazione, vibrato e soffio.</summary>
public static float[] SteamWhistle()
{
var b = Buffer(1.35f);
var noise = Noise(b.Length, 31);
var bp = Biquad.BandPass(1500, 1.2f, Rate);
float[] freqs = [520, 650, 780];
float[] phase = new float[freqs.Length];
for (int i = 0; i < b.Length; i++)
{
float t = i / (float)Rate;
float amp = t < 0.06f ? t / 0.06f : t < 1.05f ? 1 : MathF.Max(0, 1 - (t - 1.05f) / 0.3f);
float bend = 0.94f + 0.06f * MathF.Min(1, t / 0.08f) - (t > 1.0f ? 0.03f * (t - 1.0f) : 0);
float vib = 1 + 0.004f * MathF.Sin(Tau * 5.5f * t);
float v = 0;
for (int k = 0; k < freqs.Length; k++)
{
phase[k] += Tau * freqs[k] * bend * vib / Rate;
v += MathF.Sin(phase[k]) / (k + 1.5f);
}
b[i] = (v + bp.Process(noise[i]) * 0.25f) * amp;
}
Normalize(b, 0.6f);
FadeOut(b);
return b;
}
/// <summary>Tromba bitonale delle locomotive diesel ed elettriche.</summary>
public static float[] Horn()
{
var b = Buffer(0.95f);
float[] freqs = [311.1f, 370f];
var lp = Biquad.LowPass(2500, 0.7f, Rate);
for (int i = 0; i < b.Length; i++)
{
float t = i / (float)Rate;
float amp = t < 0.03f ? t / 0.03f : t < 0.78f ? 1 : MathF.Max(0, 1 - (t - 0.78f) / 0.15f);
float v = 0;
foreach (float f in freqs)
{
for (int h = 1; h <= 6; h++) v += MathF.Sin(Tau * f * h * t) / h;
}
b[i] = lp.Process(v) * amp;
}
Normalize(b, 0.55f);
FadeOut(b);
return b;
}
/// <summary>Sbuffo del vapore: rumore filtrato a banda con un tonfo grave.</summary>
public static float[] Chuff()
{
var b = Buffer(0.17f);
var noise = Noise(b.Length, 41);
var bp = Biquad.BandPass(900, 0.8f, Rate);
var lp = Biquad.LowPass(2500, 0.7f, Rate);
for (int i = 0; i < b.Length; i++)
{
float t = i / (float)Rate;
b[i] = lp.Process(bp.Process(noise[i])) * Env(t, 0.004f, 0.05f) + MathF.Sin(Tau * 70 * t) * Env(t, 0.002f, 0.04f) * 0.5f;
}
Normalize(b, 0.6f);
FadeOut(b, 0.02f);
return b;
}
/// <summary>Rotolamento in anello (1,6 s a intonazione 1): rumore grave e il «tu-tum» dei carrelli sui giunti.</summary>
public static float[] RailRumbleLoop()
{
int n = (int)(1.6f * Rate);
var loop = LoopFilter(BrownLoop(n, 53, 0.995f), Biquad.LowPass(300, 0.7f, Rate));
Normalize(loop, 0.5f);
var clack = Buffer(0.08f);
var cn = Noise(clack.Length, 59);
var bp = Biquad.BandPass(1800, 2, Rate);
for (int i = 0; i < clack.Length; i++)
{
float t = i / (float)Rate;
clack[i] = bp.Process(cn[i]) * 1.5f * Env(t, 0.001f, 0.012f) + MathF.Sin(Tau * 90 * t) * Env(t, 0.002f, 0.03f) * 0.6f;
}
MixWrapped(loop, clack, (int)(0.20f * Rate), 0.8f);
MixWrapped(loop, clack, (int)(0.32f * Rate), 0.7f);
MixWrapped(loop, clack, (int)(1.00f * Rate), 0.75f);
MixWrapped(loop, clack, (int)(1.12f * Rate), 0.65f);
Normalize(loop, 0.6f);
return loop;
}
/// <summary>Motore diesel in anello (1 s): 48 Hz con armoniche e scoppi a 8 Hz.</summary>
public static float[] DieselDroneLoop()
{
int n = Rate;
var b = new float[n];
var noise = LoopFilter(Noise(n, 61), Biquad.LowPass(900, 0.7f, Rate));
for (int i = 0; i < n; i++)
{
float t = i / (float)Rate;
float v = 0;
for (int h = 1; h <= 10; h++) v += MathF.Sin(Tau * 48 * h * t) / h;
float firing = 0.7f + 0.3f * MathF.Sin(Tau * 8 * t);
b[i] = v * firing * 0.5f + noise[i] * 0.4f;
}
Normalize(b, 0.6f);
return b;
}
/// <summary>Ronzio elettrico in anello (1 s): 100, 200 e 300 Hz e un fischio dei motori.</summary>
public static float[] ElectricHumLoop()
{
int n = Rate;
var b = new float[n];
var hiss = LoopFilter(Noise(n, 67), Biquad.LowPass(3000, 0.7f, Rate));
for (int i = 0; i < n; i++)
{
float t = i / (float)Rate;
b[i] = 0.4f * MathF.Sin(Tau * 100 * t) + 0.2f * MathF.Sin(Tau * 200 * t) + 0.25f * MathF.Sin(Tau * 300 * t)
+ 0.06f * MathF.Sin(Tau * 1150 * t) * (0.6f + 0.4f * MathF.Sin(Tau * t)) + hiss[i] * 0.12f;
}
Normalize(b, 0.5f);
return b;
}
// ------------------------------------------------------------------ ambiente
/// <summary>Vento e campagna in anello (8 s): rumore con passa-basso mobile e raffiche.</summary>
public static float[] WindLoop()
{
const float seconds = 8;
int n = (int)(seconds * Rate);
var white = Noise(n, 71);
var b = new float[n];
var f = Biquad.LowPass(400, 0.9f, Rate);
for (int pass = 0; pass < 2; pass++)
{
for (int i = 0; i < n; i++)
{
float t = i / (float)Rate;
float g = 0.55f + 0.25f * MathF.Sin(Tau * t / seconds) + 0.2f * MathF.Sin(Tau * 3 * t / seconds + 1.3f);
if ((i & 127) == 0) f.Retune(Biquad.LowPass(250 + 550 * g, 0.9f, Rate));
b[i] = f.Process(white[i]) * g;
}
}
Normalize(b, 0.5f);
return b;
}
/// <summary>Acqua di fiume in anello (6 s): rumore a banda con un gorgoglio lento e bolle.</summary>
public static float[] RiverLoop()
{
const float seconds = 6;
int n = (int)(seconds * Rate);
var main = LoopFilter(Noise(n, 73), Biquad.BandPass(1200, 0.7f, Rate));
var mod = LoopFilter(Noise(n, 79), Biquad.LowPass(6, 0.7f, Rate));
Normalize(mod, 1);
var b = new float[n];
for (int i = 0; i < n; i++) b[i] = main[i] * (0.6f + 0.4f * mod[i]);
Normalize(b, 1);
var rng = new SynthRng(83);
var bubble = Buffer(0.05f);
for (int k = 0; k < 60; k++)
{
float f0 = rng.Range(400, 1000);
for (int i = 0; i < bubble.Length; i++)
{
float t = i / (float)Rate;
bubble[i] = MathF.Sin(Tau * f0 * (1 + 4 * t) * t) * Env(t, 0.002f, 0.012f);
}
MixWrapped(b, bubble, rng.Next(n), rng.Range(0.1f, 0.3f));
}
Normalize(b, 0.45f);
return b;
}
/// <summary>Mare in anello (10 s): due onde con risacca e schiuma.</summary>
public static float[] SeaLoop()
{
const float seconds = 10;
int n = (int)(seconds * Rate);
var low = LoopFilter(Noise(n, 89), Biquad.LowPass(700, 0.7f, Rate));
var foam = LoopFilter(Noise(n, 97), Biquad.HighPass(3000, 0.7f, Rate));
var b = new float[n];
for (int i = 0; i < n; i++)
{
float t = i / (float)Rate;
float s = 0.5f + 0.5f * MathF.Sin(Tau * 2 * t / seconds - MathF.PI / 2);
float swell = 0.35f + 0.65f * s * s;
b[i] = low[i] * swell + foam[i] * swell * swell * 0.3f;
}
Normalize(b, 0.5f);
return b;
}
/// <summary>Città in anello (8 s): brusio grave, voci lontane e qualche colpo di carri e porte.</summary>
public static float[] CityLoop()
{
const float seconds = 8;
int n = (int)(seconds * Rate);
var rumble = LoopFilter(BrownLoop(n, 101, 0.996f), Biquad.LowPass(200, 0.7f, Rate));
Normalize(rumble, 1);
var murmur = LoopFilter(Noise(n, 103), Biquad.BandPass(500, 1, Rate));
Normalize(murmur, 1);
var mod = LoopFilter(Noise(n, 107), Biquad.LowPass(3, 0.7f, Rate));
Normalize(mod, 1);
var b = new float[n];
for (int i = 0; i < n; i++) b[i] = rumble[i] * 0.5f + murmur[i] * (0.2f + 0.15f * mod[i]);
var rng = new SynthRng(109);
var knock = Buffer(0.06f);
for (int k = 0; k < 24; k++)
{
var kn = Noise(knock.Length, 200 + (ulong)k);
var bp = Biquad.BandPass(rng.Range(1500, 3000), 3, Rate);
float decay = rng.Range(0.01f, 0.03f);
for (int i = 0; i < knock.Length; i++) knock[i] = bp.Process(kn[i]) * 3 * Env(i / (float)Rate, 0.001f, decay);
MixWrapped(b, knock, rng.Next(n), rng.Range(0.2f, 0.5f));
}
Normalize(b, 0.45f);
return b;
}
/// <summary>Cinguettio (varianti per numero): due–quattro brevi glissati acuti.</summary>
public static float[] Bird(int variant)
{
var rng = new SynthRng(300 + (ulong)variant);
int chirps = 2 + rng.Next(3);
float chirp = rng.Range(0.05f, 0.08f);
float gap = rng.Range(0.03f, 0.07f);
var b = Buffer(chirps * (chirp + gap) + 0.02f);
float f0 = rng.Range(2800, 3600), f1 = f0 * rng.Range(1.15f, 1.45f);
if (rng.Next(2) == 0) (f0, f1) = (f1, f0);
for (int k = 0; k < chirps; k++)
{
int s0 = (int)(k * (chirp + gap) * Rate);
float phase = 0;
for (int i = 0; i < (int)(chirp * Rate) && s0 + i < b.Length; i++)
{
float u = i / (chirp * Rate);
phase += Tau * (f0 + (f1 - f0) * u) / Rate;
b[s0 + i] += MathF.Sin(phase) * MathF.Sin(MathF.PI * u);
}
}
Normalize(b, 0.5f);
return b;
}
}
@@ -7,7 +7,7 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Hud;
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server.</summary>
/// <summary>Barra superiore (immagine 01): compagnia e livello, data, velocità, cassa, patrimonio, rating, stato del server, audio.</summary>
public partial class TopBar : PanelContainer
{
private GameSession? _session;
@@ -82,6 +82,9 @@ public partial class TopBar : PanelContainer
var chipCenter = new CenterContainer();
chipCenter.AddChild(chip);
row.AddChild(chipCenter);
var audio = new CenterContainer();
audio.AddChild(new Audio.SpeakerButton());
row.AddChild(audio);
}
private static VBoxContainer Stat(string caption, Label value)
+8 -2
View File
@@ -1,5 +1,6 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Audio;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Screens;
using RailEnterprise.Core.Data;
@@ -27,16 +28,20 @@ public partial class Main : Node
Localization.Load(locale);
GetWindow().Theme = UiTheme.Build();
GetWindow().Title = "Rail Enterprise";
var args = OS.GetCmdlineUserArgs();
int i = Array.IndexOf(args, "--autopilot");
// audio: niente nel pilota automatico e senza schermo (non rallenta il collaudo)
var audio = new AudioManager(enabled: i < 0 && DisplayServer.GetName() != "headless");
AddChild(audio);
try
{
_data = GodotDataSource.LoadGameData();
audio.SetEras(_data.Eras.Eras);
}
catch (Exception e)
{
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
}
var args = OS.GetCmdlineUserArgs();
int i = Array.IndexOf(args, "--autopilot");
if (i >= 0 && _data is not null)
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
// nel collaudo la schermata di connessione non avvia un suo server: lo avvia StartLocal qui sotto
@@ -73,6 +78,7 @@ public partial class Main : Node
}
var screen = new ConnectScreen(_data, autoStart: autoStart, handover: handover);
screen.PlayRequested += ShowGame;
screen.AudioRequested += () => AudioManager.Instance?.ShowSettings();
screen.LanguageChanged += code =>
{
var cfg = new ConfigFile();
@@ -3,6 +3,7 @@ using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
@@ -11,7 +12,8 @@ namespace RailEnterprise.Client.Panels;
/// <summary>
/// Officine (sezione 10.3): politica della flotta, avvisi, flotta ordinata per condizione con la
/// mappa di calore, cartella di manutenzione del treno scelto, depositi con il Registro officina e
/// la scorta di ricambi. Le cartelle e i registri arrivano su richiesta dal server.
/// la scorta di ricambi, rinnovo della flotta (ere e obsolescenza, ADR 0020). Le cartelle, i registri
/// e il quadro della flotta arrivano su richiesta dal server: età, successori e valori non si calcolano qui.
/// </summary>
public partial class MaintenancePanel : VBoxContainer
{
@@ -29,12 +31,19 @@ public partial class MaintenancePanel : VBoxContainer
private readonly VBoxContainer _workshop = PanelKit.Column(8);
private readonly VBoxContainer _workshopDetails = PanelKit.Column(6);
private readonly HBoxContainer _orderRow = PanelKit.Row();
private readonly VBoxContainer _fleet = PanelKit.Column(6);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<int> _trainIds = [];
private readonly List<int> _depotIds = [];
private int _train = -1, _depot = -1;
private int _entityVersion = -1, _detailVersion = -1;
private double _request;
private long _fleetDay = long.MinValue;
private double _sinceFleet = double.MaxValue;
// quadro della flotta mostrato: la sezione si ricostruisce solo quando ne arriva uno nuovo, così i
// pulsanti «Rinnova» non si ricreano sotto il cursore a ogni aggiornamento della cartella
private FleetReport? _fleetShown;
private bool _fleetBuilt;
private bool _updating;
public event Action<bool>? HeatMapToggled;
@@ -69,6 +78,9 @@ public partial class MaintenancePanel : VBoxContainer
AddChild(_workshop);
AddChild(_workshopDetails);
AddChild(_orderRow);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Rinnovo della flotta"), 14, bold: true));
AddChild(_fleet);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
@@ -113,10 +125,26 @@ public partial class MaintenancePanel : VBoxContainer
if (_depot >= 0) _session.Send(new RequestDetail { Kind = DetailKind.Workshop, Target = _depot });
}
var w = _session.World;
// quadro della flotta: all'apertura e a ogni nuovo giorno; di nuovo dopo 5 s se non arriva
_sinceFleet += delta;
long today = Fmt.Today(w);
if (today != _fleetDay || (w.Fleet is null && _sinceFleet > 5)) RequestFleet(today);
if (w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) Refresh();
}
private void Result(CommandResultMessage r) => _status.Text = r.Message;
private void RequestFleet(long day)
{
_fleetDay = day;
_sinceFleet = 0;
_session.Send(new RequestDetail { Kind = DetailKind.Fleet, Target = 0 });
}
private void Result(CommandResultMessage r)
{
_status.Text = r.Message;
// un rinnovo prenotato o completato cambia il quadro della flotta
RequestFleet(Fmt.Today(_session.World));
}
private void Refresh()
{
@@ -160,6 +188,7 @@ public partial class MaintenancePanel : VBoxContainer
BuildCard();
BuildWorkshop();
if (!_fleetBuilt || !ReferenceEquals(w.Fleet, _fleetShown)) BuildFleet();
}
private string DueText(TrainInfo t)
@@ -212,6 +241,12 @@ public partial class MaintenancePanel : VBoxContainer
{
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
_cardDetails.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {v.OdometerKm / 1000:0.#} {T("mila km")} · {v.AgeYears:0.#} {T("anni")}", 13, bold: true));
if (w.Fleet?.Vehicles.FirstOrDefault(f => f.Vehicle == v.Vehicle) is { } info)
{
var value = UiTheme.Text(VehicleOutlook(info), 12, info.Superseded ? Palette.Amber : Palette.TextSecondary);
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_cardDetails.AddChild(value);
}
foreach (var c in v.Components)
{
var row = PanelKit.Row(6);
@@ -261,8 +296,98 @@ public partial class MaintenancePanel : VBoxContainer
actions.AddChild(b);
}
_cardControls.AddChild(actions);
// rinnovo: l'intervento con effetto «renew» dei dati, vende i veicoli superati e compra i successori
if (w.Data.Maintenance.Interventions.FirstOrDefault(i => i.Effect == InterventionEffect.Renew) is { } renewal)
{
var renew = new Button { Text = renewal.NameIt };
renew.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(_train), renewal.Id), Result);
_cardControls.AddChild(renew);
}
}
// ------------------------------------------------------------------ rinnovo della flotta
/// <summary>Riga di obsolescenza di un veicolo: superato, successore con prestazioni e prezzo, valori, costo di manutenzione.</summary>
private string VehicleOutlook(FleetVehicleInfo v)
{
var parts = new List<string>();
if (v.Superseded)
{
parts.Add(string.Format(T("superato dal {0}"), v.SupersededYear));
var next = _session.World.Data.Vehicles.FirstOrDefault(d => d.Id == v.Successor);
if (next is not null)
parts.Add(string.Format(T("successore {0} ({1} kW, {2} km/h, {3})"), next.NameIt, next.PowerKw, next.MaxSpeedKmh, new Money(next.Price)));
}
if (!v.InProduction) parts.Add(T("fuori produzione"));
parts.Add(string.Format(T("valore {0}"), v.BookValue));
parts.Add(string.Format(T("rivendita {0}"), v.Resale));
if (v.MaintenanceFactor > 1.001f) parts.Add(string.Format(T("manutenzione ×{0:0.##}"), v.MaintenanceFactor));
return string.Join(" · ", parts);
}
private void BuildFleet()
{
foreach (var c in _fleet.GetChildren()) c.QueueFree();
var w = _session.World;
var report = w.Fleet;
_fleetShown = report;
_fleetBuilt = true;
if (report is null)
{
_fleet.AddChild(UiTheme.Text(T("Quadro della flotta in arrivo dal server…"), 13, Palette.TextSecondary));
return;
}
_fleet.AddChild(PanelKit.Pair(T("Era"), PanelKit.Value(EraName(report.Era))));
if (report.NextEra.Length > 0)
_fleet.AddChild(PanelKit.Pair(T("Prossima era"), PanelKit.Value($"{EraName(report.NextEra)} · {report.NextEraYear}")));
_fleet.AddChild(PanelKit.Pair(T("Valore della flotta"), PanelKit.Value(report.BookValueTotal.ToString())));
var superseded = report.Vehicles.Where(v => v.Superseded).ToList();
if (superseded.Count == 0)
{
_fleet.AddChild(UiTheme.Text(T("Nessun veicolo superato"), 13, Palette.TextSecondary));
return;
}
foreach (var v in superseded.Take(8))
{
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
string where = v.Train >= 0 && w.Trains.TryGetValue(v.Train, out var t) ? t.Name
: v.Depot >= 0 && w.Depots.TryGetValue(v.Depot, out var d) ? d.Name : "";
_fleet.AddChild(UiTheme.Text($"{def?.NameIt ?? v.Type} #{v.Vehicle} · {where} · {v.AgeYears:0.#}/{v.LifeYears} {T("anni")}", 13, bold: true));
var line = UiTheme.Text(VehicleOutlook(v), 12, Palette.Amber);
line.AutowrapMode = TextServer.AutowrapMode.WordSmart;
_fleet.AddChild(line);
}
if (superseded.Count > 8)
_fleet.AddChild(UiTheme.Text(string.Format(T("e altri {0} veicoli superati"), superseded.Count - 8), 12, Palette.TextSecondary));
foreach (var r in report.Trains)
{
string name = w.Trains.TryGetValue(r.Train, out var t) ? t.Name : $"#{r.Train}";
var row = PanelKit.Row(6);
var text = UiTheme.Text(string.Format(T("{0}: {1} veicoli da rinnovare, spesa netta {2}"), name, r.Vehicles, r.NetCost), 13,
r.Affordable ? Palette.Text : Palette.Danger);
text.SizeFlagsHorizontal = SizeFlags.ExpandFill;
text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
row.AddChild(text);
if (r.Booked)
{
// rinnovo già prenotato: niente pulsante, ripremerlo rifarebbe la prenotazione
row.AddChild(UiTheme.Text(T("rinnovo prenotato"), 13, Palette.TextSecondary));
}
else
{
int train = r.Train;
string intervention = report.RenewalIntervention;
var button = new Button { Text = T("Rinnova") };
button.Pressed += () => _session.Command(new ScheduleServiceCommand(new TrainId(train), intervention), Result);
row.AddChild(button);
}
_fleet.AddChild(row);
}
}
/// <summary>Nome italiano dell'era dal suo id in eras.json (il quadro della flotta manda l'id).</summary>
private string EraName(string id) => _session.World.Data.Eras.Eras.FirstOrDefault(e => e.Id == id)?.NameIt ?? id;
// ------------------------------------------------------------------ registro officina
private void BuildWorkshop()
@@ -11,8 +11,11 @@ using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro.
/// Ogni azione è un comando; la lista si aggiorna con i delta del server.
/// Treni: acquisto dei veicoli in un deposito, composizione, assegnazione alle linee, rientro, vendita
/// dei veicoli liberi e rinnovo dei treni con veicoli superati. Ogni azione è un comando; la lista si
/// aggiorna con i delta del server. Catalogo, obsolescenza, successori e valori di rivendita vengono dal
/// quadro della flotta (FleetReport, ADR 0020), chiesto all'apertura, a ogni nuovo giorno e dopo i comandi:
/// il pannello non calcola nulla.
/// </summary>
public partial class TrainsPanel : VBoxContainer
{
@@ -20,10 +23,12 @@ public partial class TrainsPanel : VBoxContainer
private readonly OptionButton _depot = new();
private readonly OptionButton _vehicle = new();
private readonly SpinBox _count = new() { MinValue = 1, MaxValue = 12, Value = 1 };
private readonly Label _modelInfo = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly ItemList _inDepot = new() { SelectMode = ItemList.SelectModeEnum.Multi, CustomMinimumSize = new Vector2(0, 120) };
private readonly LineEdit _name = new() { PlaceholderText = T("Nome del treno") };
private readonly ItemList _trains = new() { CustomMinimumSize = new Vector2(0, 140) };
private readonly OptionButton _line = new();
private readonly Label _renewInfo = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly List<int> _depotIds = [];
private readonly List<VehicleDef> _catalog = [];
@@ -31,6 +36,9 @@ public partial class TrainsPanel : VBoxContainer
private readonly List<int> _trainIds = [];
private readonly List<int> _lineIds = [];
private int _version = -1;
private FleetReport? _fleetShown;
private long _requestedDay = long.MinValue;
private double _sinceRequest = double.MaxValue;
public event Action<int>? TrainSelected;
@@ -46,6 +54,8 @@ public partial class TrainsPanel : VBoxContainer
buy.AddChild(_vehicle);
buy.AddChild(_count);
AddChild(buy);
_modelInfo.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_modelInfo);
var buyButton = UiTheme.Primary(T("Compra veicoli"));
buyButton.Pressed += Buy;
AddChild(buyButton);
@@ -57,6 +67,9 @@ public partial class TrainsPanel : VBoxContainer
var composeButton = new Button { Text = T("Componi") };
composeButton.Pressed += Compose;
compose.AddChild(composeButton);
var sellButton = new Button { Text = T("Vendi") };
sellButton.Pressed += Sell;
compose.AddChild(sellButton);
AddChild(compose);
AddChild(PanelKit.Separator());
AddChild(UiTheme.Text(T("Treni della compagnia"), 14, bold: true));
@@ -71,15 +84,38 @@ public partial class TrainsPanel : VBoxContainer
var home = new Button { Text = T("Manda al deposito") };
home.Pressed += SendHome;
AddChild(home);
var renew = new Button { Text = T("Rinnova i veicoli superati") };
renew.Pressed += Renew;
AddChild(renew);
_renewInfo.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_renewInfo);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
AddChild(_status);
_depot.ItemSelected += _ => Refresh(force: true);
_trains.ItemSelected += i => TrainSelected?.Invoke(_trainIds[(int)i]);
_vehicle.ItemSelected += _ => ShowModel();
_trains.ItemSelected += i =>
{
TrainSelected?.Invoke(_trainIds[(int)i]);
ShowRenewal();
};
}
public override void _Process(double delta)
{
if (_session.World.EntityVersion != _version) Refresh(force: false);
var w = _session.World;
_sinceRequest += delta;
// quadro della flotta: all'apertura e a ogni nuovo giorno; di nuovo dopo 5 s se non arriva
long today = Fmt.Today(w);
if (today != _requestedDay || (w.Fleet is null && _sinceRequest > 5)) RequestFleet(today);
bool fleetChanged = !ReferenceEquals(w.Fleet, _fleetShown);
if (w.EntityVersion != _version || fleetChanged) Refresh(force: fleetChanged);
}
private void RequestFleet(long day)
{
_requestedDay = day;
_sinceRequest = 0;
_session.Send(new RequestDetail { Kind = DetailKind.Fleet, Target = 0 });
}
private int Company => _session.World.Summary?.CompanyId ?? 0;
@@ -87,7 +123,9 @@ public partial class TrainsPanel : VBoxContainer
private void Refresh(bool force)
{
var w = _session.World;
var fleet = w.Fleet;
_version = w.EntityVersion;
_fleetShown = fleet;
int selectedDepot = _depot.Selected >= 0 && _depot.Selected < _depotIds.Count ? _depotIds[_depot.Selected] : -1;
_depotIds.Clear();
_depot.Clear();
@@ -101,16 +139,33 @@ public partial class TrainsPanel : VBoxContainer
if (_catalog.Count == 0 || force)
{
int keep = _vehicle.Selected;
string? keep = _vehicle.Selected >= 0 && _vehicle.Selected < _catalog.Count ? _catalog[_vehicle.Selected].Id : null;
_catalog.Clear();
_vehicle.Clear();
foreach (var def in w.Data.Vehicles.Where(v => v.EraFrom <= w.Year && (v.EraTo is null || v.EraTo >= w.Year)))
if (fleet is not null)
{
_catalog.Add(def);
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
// catalogo del server: solo i modelli in produzione, i superati segnati con il successore
foreach (var m in fleet.Models)
{
if (Def(m.Type) is not { } def) continue;
_catalog.Add(def);
string mark = m.Superseded ? $" · {T("superato")}" + (m.Successor.Length > 0 ? $" → {Def(m.Successor)?.NameIt ?? m.Successor}" : "") : "";
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}{mark}");
}
}
_vehicle.Selected = keep >= 0 && keep < _catalog.Count ? keep : 0;
else
{
// in attesa del quadro del server: i modelli dell'anno, senza segni
foreach (var def in w.Data.Vehicles.Where(v => v.EraFrom <= w.Year && (v.EraTo is null || v.EraTo >= w.Year)))
{
_catalog.Add(def);
_vehicle.AddItem($"{def.NameIt} — {new Money(def.Price)}");
}
}
int index = keep is null ? -1 : _catalog.FindIndex(d => d.Id == keep);
_vehicle.Selected = index >= 0 ? index : _catalog.Count > 0 ? 0 : -1;
}
ShowModel();
int depot = _depot.Selected >= 0 ? _depotIds[_depot.Selected] : -1;
_vehicleIds.Clear();
@@ -118,18 +173,25 @@ public partial class TrainsPanel : VBoxContainer
foreach (var v in w.Vehicles.Values.Where(v => v.Owner == Company && v.Depot == depot && v.Train < 0).OrderBy(v => v.Id))
{
_vehicleIds.Add(v.Id);
var def = w.Data.Vehicles.FirstOrDefault(d => d.Id == v.Type);
_inDepot.AddItem($"{def?.NameIt ?? v.Type} #{v.Id}");
var info = fleet?.Vehicles.FirstOrDefault(x => x.Vehicle == v.Id);
string extra = info is null
? ""
: (info.Superseded ? $" · {T("superato")}" : "") + " · " + string.Format(T("rivendita {0}"), info.Resale);
_inDepot.AddItem($"{Def(v.Type)?.NameIt ?? v.Type} #{v.Id}{extra}");
if (info is { Superseded: true }) _inDepot.SetItemCustomFgColor(_inDepot.ItemCount - 1, Palette.Amber);
}
var selectedTrain = _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
var selectedTrain = SelectedTrain;
_trainIds.Clear();
_trains.Clear();
foreach (var t in w.Trains.Values.Where(t => t.Owner == Company).OrderBy(t => t.Id))
{
_trainIds.Add(t.Id);
string line = t.Line >= 0 && w.Lines.TryGetValue(t.Line, out var l) ? l.Name : T("senza linea");
_trains.AddItem($"{t.Name} · {StateName((TrainState)t.State)} · {line}");
var renewal = fleet?.Trains.FirstOrDefault(r => r.Train == t.Id);
string mark = renewal is null ? "" : " · " + (renewal.Booked ? T("rinnovo prenotato") : T("da rinnovare"));
_trains.AddItem($"{t.Name} · {StateName((TrainState)t.State)} · {line}{mark}");
if (renewal is { Booked: false }) _trains.SetItemCustomFgColor(_trains.ItemCount - 1, Palette.Amber);
}
int ti = _trainIds.IndexOf(selectedTrain);
if (ti >= 0) _trains.Select(ti);
@@ -146,6 +208,40 @@ public partial class TrainsPanel : VBoxContainer
}
int li = _lineIds.IndexOf(selectedLine);
_line.Selected = li >= 0 ? li : Math.Min(1, _lineIds.Count - 1);
ShowRenewal();
}
private VehicleDef? Def(string id) => _session.World.Data.Vehicles.FirstOrDefault(v => v.Id == id);
/// <summary>Modello scelto nel catalogo: superato o no, successore con prestazioni e prezzo, ultimo anno di produzione.</summary>
private void ShowModel()
{
var fleet = _session.World.Fleet;
if (fleet is null || _vehicle.Selected < 0 || _vehicle.Selected >= _catalog.Count) { _modelInfo.Text = ""; return; }
var model = fleet.Models.FirstOrDefault(m => m.Type == _catalog[_vehicle.Selected].Id);
if (model is null) { _modelInfo.Text = ""; return; }
var parts = new List<string>();
if (model.Superseded)
{
var next = Def(model.Successor);
parts.Add(next is null
? string.Format(T("Superato dal {0}."), model.SupersededYear)
: string.Format(T("Superato dal {0}: successore {1} ({2} kW, {3} km/h, {4})."),
model.SupersededYear, next.NameIt, next.PowerKw, next.MaxSpeedKmh, new Money(next.Price)));
}
if (model.LastYear > 0) parts.Add(string.Format(T("In produzione fino al {0}."), model.LastYear));
_modelInfo.Text = string.Join(" ", parts);
}
/// <summary>Rinnovo del treno scelto: veicoli superati e spesa netta calcolati dal server.</summary>
private void ShowRenewal()
{
int train = SelectedTrain;
var renewal = train >= 0 ? _session.World.Fleet?.Trains.FirstOrDefault(r => r.Train == train) : null;
_renewInfo.Text = renewal is null
? ""
: string.Format(T("Rinnovo: {0} veicoli superati, spesa netta {1} dopo le rivendite."), renewal.Vehicles, renewal.NetCost)
+ (renewal.Booked ? " " + T("Rinnovo già prenotato.") : renewal.Affordable ? "" : " " + T("Cassa insufficiente."));
}
public static string StateName(TrainState s) => s switch
@@ -160,7 +256,12 @@ public partial class TrainsPanel : VBoxContainer
_ => s.ToString(),
};
private void Result(CommandResultMessage r) => _status.Text = r.Message;
private void Result(CommandResultMessage r)
{
_status.Text = r.Message;
// acquisti, vendite e rinnovi cambiano il quadro della flotta
RequestFleet(Fmt.Today(_session.World));
}
private void Buy()
{
@@ -177,7 +278,14 @@ public partial class TrainsPanel : VBoxContainer
_session.Command(new ComposeTrainCommand(new DepotId(_depotIds[_depot.Selected]), selected, name), Result);
}
private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel ? _trainIds[sel[0]] : -1;
private void Sell()
{
var selected = _inDepot.GetSelectedItems().OrderBy(i => i).Select(i => _vehicleIds[i]).ToList();
if (selected.Count == 0) { _status.Text = T("Seleziona i veicoli da vendere"); return; }
foreach (int id in selected) _session.Command(new SellVehicleCommand(new VehicleId(id)), Result);
}
private int SelectedTrain => _trains.GetSelectedItems() is { Length: > 0 } sel && sel[0] < _trainIds.Count ? _trainIds[sel[0]] : -1;
private void Assign()
{
@@ -192,4 +300,13 @@ public partial class TrainsPanel : VBoxContainer
if (train < 0 || _depot.Selected < 0) { _status.Text = T("Seleziona un treno e un deposito"); return; }
_session.Command(new SendToDepotCommand(new TrainId(train), new DepotId(_depotIds[_depot.Selected])), Result);
}
private void Renew()
{
int train = SelectedTrain;
if (train < 0) { _status.Text = T("Seleziona un treno"); return; }
string intervention = _session.World.Fleet?.RenewalIntervention ?? "";
if (intervention.Length == 0) { _status.Text = T("Quadro della flotta in arrivo dal server…"); return; }
_session.Command(new ScheduleServiceCommand(new TrainId(train), intervention), Result);
}
}
@@ -68,6 +68,8 @@ public partial class ConnectScreen : Control
/// <summary>La sessione di prova diventa la partita: la schermata non la chiude più.</summary>
public event Action<GameSession>? PlayRequested;
public event Action<string>? LanguageChanged;
/// <summary>Apre il pannello delle impostazioni audio.</summary>
public event Action? AudioRequested;
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
/// <param name="autoStart">Avvia subito il server locale o verifica il server ricordato (falso nel collaudo).</param>
@@ -219,7 +221,7 @@ public partial class ConnectScreen : Control
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
// piede: lingua, uscita, avviso sulla cifratura
// piede: lingua, audio, uscita, avviso sulla cifratura
var foot = PanelKit.Row(8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
@@ -227,6 +229,9 @@ public partial class ConnectScreen : Control
b.Pressed += () => LanguageChanged?.Invoke(code);
foot.AddChild(b);
}
var audio = new Button { Text = T("Audio") };
audio.Pressed += () => AudioRequested?.Invoke();
foot.AddChild(audio);
foot.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(100, 0) };
quit.Pressed += () => GetTree().Quit();
@@ -1,5 +1,6 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Audio;
using RailEnterprise.Client.Hud;
using RailEnterprise.Client.Map;
using RailEnterprise.Client.Net;
@@ -257,13 +258,18 @@ public partial class GameScreen : Node
_session.MessageApplied += OnMessage;
_session.Notified += e => _ticker.Add(e);
_session.CommandFailed += r => Toast(r.Message, error: true);
AudioManager.Instance?.Bind(_session, _map);
SelectTool(Tool.None);
SendViewport(force: true);
// il Registro degli impieghi alimenta anche le schede di industrie e città
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
}
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
public override void _ExitTree()
{
_session.MessageApplied -= OnMessage;
AudioManager.Instance?.Unbind(_session);
}
/// <summary>Codice di EventKind.World nel protocollo (notizie degli eventi del mondo, ADR 0017).</summary>
private const byte WorldEventKind = 10;