namespace RailEnterprise.Client.Audio; /// /// 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 Hz. /// 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 } /// Stile di un'era. 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]; /// Progressioni per grado della scala (0 = primo grado), una battuta per accordo. 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], ]; /// Stile dell'era per posizione nell'elenco di eras.json (le ere oltre la quarta riprendono il ciclo). 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), }; /// Seme fisso del tema: hash dell'id dell'era e della sua posizione. public static ulong Seed(int eraIndex, string eraId) => SynthRng.Hash(eraId) ^ ((ulong)(eraIndex + 1) * 0x9E3779B97F4A7C15UL); /// Durata dell'anello in secondi. public static float LengthSeconds(Style style) => Bars * style.BeatsPerBar * 60f / style.Bpm; // ------------------------------------------------------------------ timbri private sealed class Voice { /// Ampiezza della n-esima armonica in Harmonics[n−1]. public required float[] Harmonics { get; init; } public float Attack { get; init; } = 0.005f; /// Decadimento verso il sostegno (s). public float Decay { get; init; } = 0.3f; public float Sustain { get; init; } public float Release { get; init; } = 0.1f; /// Copie leggermente scordate (coro). 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 _tables = []; /// /// Forma d'onda per una nota alla frequenza data, con le sole armoniche sotto /// della frequenza di campionamento: quelle oltre Nyquist /// tornerebbero indietro come toni stonati. /// 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; } } /// Frazione della frequenza di campionamento sotto cui stanno le armoniche (margine per vibrato e coro). private const float MaxHarmonicShare = 0.45f; private const int TableSize = 2048; /// Forma d'onda di un periodo dalla somma delle prime «count» armoniche (ampiezza della n-esima in harmonics[n−1]). 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); /// Suona una nota nell'anello (con la coda che rientra dall'inizio). 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; } } } /// Altezza MIDI del grado della scala (i gradi oltre la scala salgono d'ottava). 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; } /// Compone e sintetizza il tema dell'era: campioni mono in [−1, 1]. 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; } /// Eco con retroazione su un anello (due giri per la continuità all'inizio). 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]; } }