using Godot;
namespace RailEnterprise.Client.Audio;
/// Bus audio del client: Master e quattro bus che vi confluiscono.
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";
/// Nell'ordine dei cursori delle impostazioni.
public static readonly string[] All = [Master, Music, Ambience, Sfx, Ui];
///
/// 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.
///
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 });
}
}
///
/// Volumi per bus (0–1) e muto generale, salvati nella sezione «audio» di
/// user://settings.cfg (lo stesso file della lingua e del server).
///
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];
/// Volumi nell'ordine di .
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();
/// Applica volumi e muto ai bus (il cursore segue il volume percepito: guadagno = valore²).
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);
}
}