Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Audio: the start menu plays a main theme, ready for Afik's (Refs #2240 #39) (#2297)

Eyal Golan25429366f84a
diff --git a/changelog.d/menu-music.md b/changelog.d/menu-music.md
new file mode 100644
index 000000000..65a8ec386
--- /dev/null
+++ b/changelog.d/menu-music.md
@@ -0,0 +1,6 @@
+- The start menu plays a main theme on a loop and fades it out over a second when a game starts (Refs #39). It plays
+ Afik's theme once PR #2240 adds it in `StreamingAssets/audio/music/` (downloaded in full when it is about to play, not
+ streamed); until then the menu is silent. On the web it starts at the first click, tap or key, as browsers require,
+ and it drops low under Ben-Gurion's recording. A new Music row in
+ Settings (Off, Low, High; Low by default) sets its volume and is kept like the other settings; its Hebrew awaits
+ native review (#564).
diff --git a/docs/audio.md b/docs/audio.md
new file mode 100644
index 000000000..f3f302698
--- /dev/null
+++ b/docs/audio.md
@@ -0,0 +1,25 @@
+# Audio
+
+Where the game's sounds live and what plays them (#39).
+
+| What | Where | Played by |
+|---|---|---|
+| Sound effects (turn end, refusal, event card) | `unity/Assets/Resources/Audio/` | `GameAudio`, at the Settings "Sound effects" volume |
+| Ben-Gurion's 1948 recording | `unity/Assets/StreamingAssets/audio/` | `DeclarationRecording`, from its button on the start screen ([declaration-recording.md](declaration-recording.md)) |
+| Music | `unity/Assets/StreamingAssets/audio/music/` | `MenuMusic`, on the start screen, at the Settings "Music" volume |
+
+## Music files
+
+- Music goes in `unity/Assets/StreamingAssets/audio/music/`, as Ogg Vorbis (`.ogg`) only (owner, 2 Nov 2026).
+ StreamingAssets is not imported or re-encoded by Unity, so the file ships byte for byte. It is not part of the first
+ download: the whole file is downloaded when the theme is about to play (on the web, after the page's first click, tap
+ or key), then decoded in full. It is not streamed.
+- Memory: a decoded clip is uncompressed. On the web the browser decodes it to 32-bit float samples, which is about
+ 0.35 MB per second of stereo 44.1 kHz audio, for example about 88 MB for a 4 min 10 s theme. The clip is released
+ when the menu's fade ends.
+- The start menu's theme is the file `MenuMusic.File` names. A renamed file is renamed there too. Once a theme is
+ committed, `MenuMusicTests.ThePlayerPicksTheThemeInStreamingAssetsMusic` fails while the two differ.
+- With no file (or any failed download) the start menu is silent for the rest of the page: no error and no warning,
+ one plain `MUSIC no theme` line in the log. A reload tries again.
+- Each file needs its rows like any other asset: `ASSETS.yaml` (source, licence, SHA-256), `LICENSING.md` and the
+ credit. Keep it under the repository's 10 MiB per-file limit (`scripts/oss/oss_policy.py`).
diff --git a/unity/Assets/Scripts/UI/DeclarationRecording.cs b/unity/Assets/Scripts/UI/DeclarationRecording.cs
index 83d8d2b8b..050853338 100644
--- a/unity/Assets/Scripts/UI/DeclarationRecording.cs
+++ b/unity/Assets/Scripts/UI/DeclarationRecording.cs
@@ -201,16 +201,19 @@ namespace Statecraft.Game.UI
}
/// <summary>The game's fetch: UnityWebRequestMultimedia from StreamingAssets, as WAV.</summary>
- internal static IRequest WebFetch(string url, Action<AudioClip?, string?> done) => new WebRequest(url, done);
+ internal static IRequest WebFetch(string url, Action<AudioClip?, string?> done) => new WebRequest(url, done, AudioType.WAV);
+
+ /// <summary>The same fetch as Ogg Vorbis (the start menu's music, MenuMusic).</summary>
+ internal static IRequest WebFetchOgg(string url, Action<AudioClip?, string?> done) => new WebRequest(url, done, AudioType.OGGVORBIS);
sealed class WebRequest : IRequest
{
readonly UnityWebRequest request;
bool aborted, finished;
- public WebRequest(string url, Action<AudioClip?, string?> done)
+ public WebRequest(string url, Action<AudioClip?, string?> done, AudioType type)
{
- request = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV);
+ request = UnityWebRequestMultimedia.GetAudioClip(url, type);
request.SendWebRequest().completed += _ => Done(done);
}
@@ -242,7 +245,10 @@ namespace Statecraft.Game.UI
{
GameObject? go; AudioSource? source;
- public bool? Ready(AudioClip clip)
+ public bool? Ready(AudioClip clip) => ReadyState(clip);
+
+ /// <summary>IOutput.Ready's rule for any AudioSource output (MenuMusic's too).</summary>
+ internal static bool? ReadyState(AudioClip clip)
{
switch (clip.loadState)
{
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 0f71e30f8..c0c05e122 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -122,6 +122,13 @@ namespace Statecraft.Game.UI
/// <summary>The opening (#530) outside Play mode: off by default, so EditMode tests that press New Game meet the advisors
/// as a player's first game does; the opening's own tests set it.</summary>
internal bool OpeningInEditMode { get; set; }
+ /// <summary>The start menu's music (#39) outside Play mode: off by default, so EditMode tests stay silent and fetch
+ /// nothing; its wiring test sets it.</summary>
+ internal bool MenuMusicInEditMode { get; set; }
+ /// <summary>The start menu's music, kept for the page across Begins (a language switch); null until a start screen
+ /// shows in a player. Disposed with the component (OnDisable).</summary>
+ internal MenuMusic? Music => music;
+ MenuMusic? music;
public void Configure(GameBoot boot, UIDocument document, TextAsset strings, TextAsset stringsHe, PortraitCatalog portraits,
MapScene map, PlacementLayer placements, MapPointer pointer, CameraController cameraController)
@@ -189,6 +196,7 @@ namespace Statecraft.Game.UI
{
if (boot != null) { boot.Ready -= Begin; boot.Failed -= OnBootFailed; }
Shutdown();
+ music?.Dispose(); music = null; // the page's music goes with the component, not with a rebuild (Begin)
}
// "smoke" as a whole query parameter: bare ("?smoke", "&smoke=") or with a number; it ends at '&', '#' or the end, so
@@ -353,8 +361,15 @@ namespace Statecraft.Game.UI
setCompanion = set;
companionSwitch = (() => companion != null, on => { companionPicked = on; set(on); });
}
+ // The start menu's music (#39): made where the start screen first shows, in a player only (in EditMode only where a
+ // test asks: MenuMusicInEditMode), and kept for the page: the rebuild a language switch makes goes on with the same
+ // theme, which turns back up from the old screen's closing instead of being cut and fetched again. Made before
+ // Settings, whose Music row sets its volume. Its duck is the new screen's recording, or none.
+ if (music == null && showsStart && (Application.isPlaying || MenuMusicInEditMode))
+ music = new MenuMusic(root, Application.platform == RuntimePlatform.WebGLPlayer);
+ if (music != null) music.Duck = null;
Own(new SettingsPresenter(root, text, SettingsFile(), switchLanguage, panel: document.panelSettings, audio: audio, advisors: AdvisorSession.Settings,
- companion: companionSwitch));
+ companion: companionSwitch, music: music));
// "Report a bug or idea" (#1169), from Settings and the start screen: the version line names the content GameBoot logged.
feedback = Own(new FeedbackPresenter(root, text, ReportLinks.Version(Application.version, inputs.Content.Hash)));
var feedbackPanel = feedback;
@@ -605,9 +620,11 @@ namespace Statecraft.Game.UI
{
var cam = cameraController;
var recording = Own(new DeclarationRecording(root, text, toast.Show)); // never built in automated runs (Skipped)
+ if (music != null) music.Duck = () => recording.Playing; // the theme drops low under Ben-Gurion's voice
start = Own(new StartScreenPresenter(root, newGame!, resumed, shown =>
{
if (cam != null) cam.enabled = !shown;
+ music?.Show(shown); // loops on the menu, fades out as a game starts
if (!shown) { if (start?.Resumed != false) advisor?.Resume(); else if (opening == null) advisor?.NewGame(); }
}, recording, text, SettingsFile(), switchLanguage));
start.Show();
diff --git a/unity/Assets/Scripts/UI/MenuMusic.cs b/unity/Assets/Scripts/UI/MenuMusic.cs
new file mode 100644
index 000000000..285496705
--- /dev/null
+++ b/unity/Assets/Scripts/UI/MenuMusic.cs
@@ -0,0 +1,295 @@
+#nullable enable
+using System;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+namespace Statecraft.Game.UI
+{
+ /// <summary>The start menu's music (#39): the main theme by Afik (afikomposer, PR #2240; CC BY-NC-ND 4.0, owner 2 Nov 2026),
+ /// an OGG in StreamingAssets/audio/music/ (docs/audio.md). It loops while the start screen shows and fades out over
+ /// FadeMs of real time when a game starts; it never plays in the game. The whole file is downloaded when it is about to
+ /// play (UnityWebRequestMultimedia, DeclarationRecording's fetch; not streamed) and decoded (by the browser on the web);
+ /// the clip is released when the fade ends. Browsers block audio until the page's first activation (a click, a tap or a
+ /// key other than Escape), so on the web nothing is fetched before one (GestureSeen; the desktop has no such rule). The
+ /// Settings screen's Music row sets Volume (SettingsPresenter; MenuMusic's own default is the row's Low, so a missed
+ /// wiring can't play loud); at 0 it is not even fetched. It drops to DipLevel while Ben-Gurion's recording plays on the
+ /// same screen (Duck). No theme (main before #2240, a 404 or any failed fetch) is silence for the rest of the page
+ /// (Absent): one fetch at most, one plain log line, no warning and no error. GameRoot keeps one for the page, across the
+ /// rebuild a language switch makes, and builds it only in a player that shows the start screen, never in the automated
+ /// runs (StartScreenPresenter.Skipped) or in EditMode. Presentation only: the sim and the golden hashes never see it.</summary>
+ public sealed class MenuMusic : IDisposable
+ {
+ /// <summary>The theme's path under StreamingAssets. A renamed file is renamed here too (MenuMusicTests checks a
+ /// committed file against it).</summary>
+ public const string File = "audio/music/Main_1.3.ogg";
+
+ /// <summary>The fade when a game starts (and the dip under the recording), in real time, and the watch's period while
+ /// it loads or plays.</summary>
+ public const int FadeMs = 1000, WatchMs = 50;
+
+ /// <summary>The theme's level under Ben-Gurion's recording, as a share of the Music volume. The owner's ruling on #2297
+ /// (2 Nov 2026), "Dip under the recording (Recommended)": "The theme drops low while the recording plays, then comes
+ /// back". Low, not silence.</summary>
+ public const float DipLevel = 0.2f;
+
+ /// <summary>The volume until Settings sets one: the Music row's default, Low (owner, #2297, 2 Nov 2026: "Low by default
+ /// (Recommended)"; SettingsPresenter.SoundLevels' "low").</summary>
+ public const float DefaultVolume = 0.35f;
+
+ /// <summary>Where the theme plays. The game's is a looping AudioSource on its own GameObject (SourceOutput).</summary>
+ public interface IOutput : IDisposable
+ {
+ /// <summary>As DeclarationRecording.IOutput.Ready: true once decoded, false while not yet, null when it failed.</summary>
+ bool? Ready(AudioClip clip);
+ /// <summary>Plays the clip on a loop.</summary>
+ void Play(AudioClip clip);
+ void Stop();
+ float Volume { set; }
+ }
+
+ /// <summary>Idle (not wanted, or waiting for the screen, the first gesture or a volume above 0); Loading (fetching or
+ /// decoding); Playing; Fading (the game has started); Absent (no theme: silent for the rest of the page).</summary>
+ public enum Phase { Idle, Loading, Playing, Fading, Absent }
+
+ /// <summary>True once the page has had an activation (a click, a tap or a key other than Escape): the browser's rule is
+ /// per page, so it holds for every instance.</summary>
+ public static bool GestureSeen { get; internal set; }
+
+ /// <summary>True once a fetch failed or the file is missing: no theme for the rest of the page, whatever instance asks
+ /// again (no second fetch, no second log line). A failed fetch for any reason counts: a reload tries again.</summary>
+ public static bool ThemeAbsent { get; internal set; }
+
+ static readonly TrickleDown[] Phases = { TrickleDown.TrickleDown, TrickleDown.NoTrickleDown };
+
+ readonly VisualElement root, listener; readonly bool web; readonly string url;
+ readonly DeclarationRecording.Fetch fetch; readonly IOutput output; readonly Func<double> now;
+ readonly EventCallback<PointerDownEvent> onPointerDown; readonly EventCallback<PointerUpEvent> onPointerUp;
+ readonly EventCallback<KeyDownEvent> onKey;
+ readonly IVisualElementScheduledItem timer;
+ DeclarationRecording.IRequest? request; AudioClip? clip; VisualElement? hooked;
+ bool wanted, playing, fadingOut; int generation; double lastTick;
+ float volume = DefaultVolume, dip = 1f, fade = 1f;
+
+ /// <summary>Absent for the page once ThemeAbsent is set; otherwise the instance's own phase.</summary>
+ public Phase State => ThemeAbsent ? Phase.Absent : clip == null ? (request != null ? Phase.Loading : Phase.Idle)
+ : !playing ? Phase.Loading : fadingOut ? Phase.Fading : Phase.Playing;
+
+ /// <summary>Whether the start screen wants it (Show).</summary>
+ internal bool Wanted => wanted;
+
+ /// <summary>True while the theme must drop to DipLevel (GameRoot: while Ben-Gurion's recording plays).</summary>
+ public Func<bool>? Duck { get; set; }
+
+ /// <summary>0 (off) to 1 (the theme as mastered); SettingsPresenter sets it from the player's choice. Applies at once;
+ /// raised from 0, it starts the theme if the start screen is up.</summary>
+ public float Volume
+ {
+ get => volume;
+ set { volume = Mathf.Clamp01(value); Apply(); TryStart(); }
+ }
+
+ /// <param name="web">The browser's rule: nothing before the page's first activation.</param>
+ /// <param name="url">Test seam; null is Url().</param>
+ /// <param name="fetch">Test seam; null fetches with UnityWebRequestMultimedia as Ogg Vorbis.</param>
+ /// <param name="output">Test seam; null plays through an AudioSource.</param>
+ /// <param name="now">Test seam: the clock, in seconds; null is Time.realtimeSinceStartupAsDouble.</param>
+ public MenuMusic(VisualElement root, bool web, string? url = null, DeclarationRecording.Fetch? fetch = null, IOutput? output = null,
+ Func<double>? now = null)
+ {
+ this.root = root; this.web = web;
+ this.url = url ?? Url();
+ this.fetch = fetch ?? DeclarationRecording.WebFetchOgg;
+ this.output = output ?? new SourceOutput();
+ this.now = now ?? (() => Time.realtimeSinceStartupAsDouble);
+ // On the panel's own root: a key with nothing focused goes there, never through the document's root below it.
+ listener = root.panel?.visualTree ?? root;
+ onPointerDown = e => PointerDown(e);
+ onPointerUp = e => { if (e.pointerType != UnityEngine.UIElements.PointerType.mouse) Gesture(); }; // a touch's release activates
+ onKey = e => { if (e.keyCode != KeyCode.Escape && e.character != '\u001b') Gesture(); }; // Escape never activates
+ // Both phases: trickle-down sees an event before any element can stop it; bubble-up sees one aimed at the panel's
+ // root itself. Gesture is idempotent, so an event seen twice counts once.
+ foreach (var phase in Phases)
+ {
+ listener.RegisterCallback(onPointerDown, phase);
+ listener.RegisterCallback(onPointerUp, phase);
+ listener.RegisterCallback(onKey, phase);
+ }
+ timer = root.schedule.Execute(Tick).Every(WatchMs);
+ timer.Pause();
+ }
+
+ /// <summary>The theme's URL, with the build's id on the web (issue #437), as DeclarationRecording.Url.</summary>
+ public static string Url()
+ {
+ var u = Application.streamingAssetsPath + "/" + File;
+ return u.Contains("://") ? Boot.GameInputs.WithBuildId(u, Application.buildGUID) : "file://" + u;
+ }
+
+ /// <summary>The start screen shows (true: play, once allowed; a fade under way turns back up) or closes (false: a game
+ /// starts, so fade out; a load under way is cancelled).</summary>
+ public void Show(bool shown)
+ {
+ wanted = shown;
+ if (shown)
+ {
+ if (playing) fadingOut = false; // shown again before the fade ended: it comes back up from where it is
+ TryStart();
+ return;
+ }
+ if (playing) fadingOut = true;
+ else if (clip != null || request != null) Stop();
+ }
+
+ /// <summary>A mouse press activates. A touch or pen press does not (iOS); its release does. The element pressed (a
+ /// button) captures the pointer, and a captured release goes to it alone, never through the panel's root, so the
+ /// release is also heard on the element pressed.</summary>
+ void PointerDown(PointerDownEvent e)
+ {
+ if (e.pointerType == UnityEngine.UIElements.PointerType.mouse) { Gesture(); return; }
+ if (GestureSeen || !(e.target is VisualElement pressed) || pressed == listener) return;
+ Unhook();
+ hooked = pressed;
+ hooked.RegisterCallback(onPointerUp, TrickleDown.TrickleDown);
+ }
+
+ void Unhook()
+ {
+ hooked?.UnregisterCallback(onPointerUp, TrickleDown.TrickleDown);
+ hooked = null;
+ }
+
+ void Gesture()
+ {
+ if (GestureSeen) return;
+ GestureSeen = true;
+ Unhook();
+ TryStart();
+ }
+
+ void TryStart()
+ {
+ if (!wanted || ThemeAbsent || clip != null || request != null || volume <= 0f || (web && !GestureSeen)) return;
+ if (url.StartsWith("file://", StringComparison.Ordinal) && !System.IO.File.Exists(url.Substring("file://".Length)))
+ {
+ Absent(null);
+ return;
+ }
+ var mine = ++generation;
+ var r = fetch(url, (c, error) =>
+ {
+ if (mine != generation) { Release(c); return; } // stopped meanwhile
+ request = null;
+ if (c == null) { Absent(error); return; }
+ clip = c;
+ Begin();
+ });
+ if (mine == generation && clip == null && !ThemeAbsent) { request = r; timer.Resume(); } // still on its way
+ }
+
+ /// <summary>No theme: silent for the rest of the page, with one line in the log (never a warning: main ships no
+ /// theme until #2240 lands).</summary>
+ void Absent(string? why)
+ {
+ Stop();
+ ThemeAbsent = true;
+ Debug.Log("MUSIC no theme at " + File + ": the start menu is silent" + (why == null ? "" : " (" + why + ")"));
+ }
+
+ /// <summary>Plays the clip once it is decoded; until then the watch asks again.</summary>
+ void Begin()
+ {
+ var ready = output.Ready(clip!);
+ if (ready == null) { Absent("the clip did not decode"); return; }
+ if (ready == false) { timer.Resume(); return; }
+ playing = true; fadingOut = false; fade = 1f;
+ dip = Duck?.Invoke() == true ? DipLevel : 1f; // the recording may have started since the fetch did (N1)
+ lastTick = now();
+ Apply();
+ output.Play(clip!);
+ timer.Resume();
+ }
+
+ /// <summary>Every WatchMs while loading or playing: the play once decoded, and the dip and the fade, by the real time
+ /// since the last tick (a slow or hitching frame rate does not stretch them). Allocates nothing.</summary>
+ internal void Tick()
+ {
+ if (clip == null) return;
+ if (!playing) { Begin(); return; }
+ var t = now();
+ float step = (float)((t - lastTick) * 1000.0 / FadeMs);
+ lastTick = t;
+ dip = Duck?.Invoke() == true ? Mathf.Max(DipLevel, dip - step) : Mathf.Min(1f, dip + step);
+ fade = fadingOut ? Mathf.Max(0f, fade - step) : Mathf.Min(1f, fade + step);
+ if (fadingOut && fade <= 1e-4f) { Stop(); return; } // float steps: 20 x 0.05 may leave a hair above 0
+ // (Shown again before this point, the fade had already turned back up: Show(true) clears fadingOut.)
+ Apply();
+ }
+
+ void Apply()
+ {
+ if (playing) output.Volume = volume * dip * fade;
+ }
+
+ /// <summary>Stops it, cancels a fetch and releases the clip. Safe to call at any time.</summary>
+ void Stop()
+ {
+ generation++;
+ var r = request; request = null; r?.Abort();
+ timer.Pause();
+ output.Stop();
+ Release(clip); clip = null;
+ playing = false; fadingOut = false;
+ }
+
+ static void Release(AudioClip? c)
+ {
+ if (c == null) return;
+ if (Application.isPlaying) UnityEngine.Object.Destroy(c); else UnityEngine.Object.DestroyImmediate(c);
+ }
+
+ public void Dispose()
+ {
+ wanted = false;
+ Stop();
+ Unhook();
+ foreach (var phase in Phases)
+ {
+ listener.UnregisterCallback(onPointerDown, phase);
+ listener.UnregisterCallback(onPointerUp, phase);
+ listener.UnregisterCallback(onKey, phase);
+ }
+ output.Dispose();
+ }
+
+ /// <summary>A looping AudioSource on its own GameObject, made at the first Play.</summary>
+ sealed class SourceOutput : IOutput
+ {
+ GameObject? go; AudioSource? source; float volume = DefaultVolume;
+
+ public bool? Ready(AudioClip clip) => DeclarationRecording.SourceOutput.ReadyState(clip);
+
+ public void Play(AudioClip clip)
+ {
+ if (go == null)
+ {
+ go = new GameObject("MenuMusic");
+ source = go.AddComponent<AudioSource>();
+ source.playOnAwake = false; source.loop = true; source.spatialBlend = 0f;
+ }
+ source!.volume = volume;
+ source.clip = clip;
+ source.Play();
+ }
+
+ public void Stop() { if (source != null) { source.Stop(); source.clip = null; } }
+
+ public float Volume { set { volume = value; if (source != null) source.volume = value; } }
+
+ public void Dispose()
+ {
+ if (go != null) { if (Application.isPlaying) UnityEngine.Object.Destroy(go); else UnityEngine.Object.DestroyImmediate(go); }
+ go = null; source = null;
+ }
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/UI/MenuMusic.cs.meta b/unity/Assets/Scripts/UI/MenuMusic.cs.meta
new file mode 100644
index 000000000..7027f0123
--- /dev/null
+++ b/unity/Assets/Scripts/UI/MenuMusic.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 5b74c7eddb4ab4a11bdda0df7f92c7e4
\ No newline at end of file
diff --git a/unity/Assets/Scripts/UI/SettingsPresenter.cs b/unity/Assets/Scripts/UI/SettingsPresenter.cs
index 449c1477c..fbfa46c4f 100644
--- a/unity/Assets/Scripts/UI/SettingsPresenter.cs
+++ b/unity/Assets/Scripts/UI/SettingsPresenter.cs
@@ -10,7 +10,8 @@ using UnityEngine.UIElements;
namespace Statecraft.Game.UI
{
/// <summary>The Settings screen (#40), opened from the left column's gear like the other screens (ScreenNav). Its options:
- /// the graphics quality (GraphicsQuality: Auto / High / Low), the sound effects volume (GameAudio, #39), the UI's language (#1036),
+ /// the graphics quality (GraphicsQuality: Auto / High / Low), the sound effects volume (GameAudio, #39), the start menu's music
+ /// volume (MenuMusic, #39), the UI's language (#1036),
/// the UI scale (100% / 125% / 150%), the tilt-shift blur, the WebGL companion (#1119, its row only where a page shows it) and a Community row whose "Star on GitHub" opens the repository
/// (#1168, ExternalLink). The blur option turns it off and on: applied at once (TiltShift.Enabled, what the "tiltshift"
/// toggle sets) and kept in the SettingsStore, so it holds after a reload. A stored "off" only ever turns the blur off, so ?notiltshift still boots without it. The
@@ -18,7 +19,7 @@ namespace Statecraft.Game.UI
/// automatic last fallback step (TiltShift.FallbackOff), which it never changes.</summary>
public sealed class SettingsPresenter : IDisposable
{
- public const string TiltShiftKey = "tiltshift", QualityKey = "quality", LanguageKey = "lang", UiScaleKey = "uiscale", SoundKey = "sfx", CompanionKey = "companion", SelectedClass = "settings-choice-selected";
+ public const string TiltShiftKey = "tiltshift", QualityKey = "quality", LanguageKey = "lang", UiScaleKey = "uiscale", SoundKey = "sfx", MusicKey = "music", CompanionKey = "companion", SelectedClass = "settings-choice-selected";
/// <summary>The owner's UI scales (#40, 18 Oct 2026), in percent; the first is the default.</summary>
public static readonly int[] UiScales = { 100, 125, 150 };
/// <summary>The owner's ruling on #1011 (19 Oct 2026): Settings offers only the UI scales verified to fit, and 100% always,
@@ -37,10 +38,15 @@ namespace Statecraft.Game.UI
};
/// <summary>The sound effects' volume steps (#39): the stored word and GameAudio's volume. With no stored choice, "high".</summary>
public static readonly (string level, float volume)[] SoundLevels = { ("off", 0f), ("low", 0.35f), ("high", 1f) };
+ /// <summary>The Music row's step with no stored choice (owner, #2297, 2 Nov 2026: "Low by default (Recommended)").</summary>
+ public const string MusicDefault = "low";
readonly SettingsStore? store; readonly UiText text; readonly VisualElement root, screen; readonly Button tiltShift;
readonly (Button button, GraphicsQuality.Choice choice, Action pick)[] quality;
readonly LanguageButtons languages;
readonly (Button button, string level, Action pick)[] sound;
+ readonly (Button button, string level, Action pick)[] musicLevels;
+ readonly MenuMusic? music;
+ string musicLevel;
readonly AdvisorSettings? advisors;
readonly (Button button, string level, Action pick)[] helpLevels;
readonly GameAudio? audio;
@@ -62,10 +68,11 @@ namespace Statecraft.Game.UI
/// <param name="audio">The sound effects the volume applies to; null keeps only the choice.</param>
/// <param name="companion">The WebGL companion (#1119, WebCompanion): whether it runs, and what turns it on or off at
/// once; null (no page to show it in) hides its row.</param>
+ /// <param name="music">The start menu's music the Music volume applies to; null keeps only the choice.</param>
public SettingsPresenter(VisualElement root, UiText text, SettingsStore? store, Action<string>? switchLanguage = null, PanelSettings? panel = null, GameAudio? audio = null, AdvisorSettings? advisors = null,
- (Func<bool> on, Action<bool> set)? companion = null)
+ (Func<bool> on, Action<bool> set)? companion = null, MenuMusic? music = null)
{
- this.store = store; this.text = text; this.root = root; this.audio = audio; this.advisors = advisors; this.companion = companion;
+ this.store = store; this.text = text; this.root = root; this.audio = audio; this.advisors = advisors; this.companion = companion; this.music = music;
screen = root.Q<VisualElement>("screen-settings");
screen.Q<Label>("settings-screen-title").text = text["settings.title"];
screen.Q<Label>("settings-tiltshift-label").text = text["settings.tiltshift"];
@@ -104,6 +111,21 @@ namespace Statecraft.Game.UI
b.clicked += pick;
return (b, l.level, pick);
});
+ // Music (#39, MenuMusic): the same three steps as the sound effects, kept apart from them. With no stored choice,
+ // "low", the owner's ruling on #2297 (2 Nov 2026): "Low by default (Recommended)", "35% volume: the theme sits
+ // under the menu".
+ screen.Q<Label>("settings-music-label").text = text["settings.music"];
+ var storedMusic = store?.Read(MusicKey);
+ musicLevel = Array.Exists(SoundLevels, l => l.level == storedMusic) ? storedMusic! : MusicDefault;
+ ApplyMusic();
+ musicLevels = Array.ConvertAll(SoundLevels, l =>
+ {
+ var b = screen.Q<Button>("settings-music-" + l.level);
+ b.text = text["settings.music." + l.level];
+ Action pick = () => PickMusic(l.level);
+ b.clicked += pick;
+ return (b, l.level, pick);
+ });
// The help level is presentation-only and read live by the advisor queue (spec6).
var helpLabel = screen.Q<Label>("settings-advisors-label");
helpLabel.text = text["settings.advisors"];
@@ -166,6 +188,7 @@ namespace Statecraft.Game.UI
foreach (var (b, _, pick) in quality) b.clicked -= pick;
languages.Dispose();
foreach (var (b, _, pick) in sound) b.clicked -= pick;
+ foreach (var (b, _, pick) in musicLevels) b.clicked -= pick;
foreach (var (b, _, pick) in scales) b.clicked -= pick;
foreach (var (b, _, pick) in helpLevels) b.clicked -= pick;
unbindStar();
@@ -237,6 +260,23 @@ namespace Statecraft.Game.UI
if (audio != null) audio.Volume = Array.Find(SoundLevels, l => l.level == soundLevel).volume;
}
+ void PickMusic(string level)
+ {
+ musicLevel = level;
+ ApplyMusic();
+ Show();
+ try { store?.Write(MusicKey, level); }
+ catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
+ {
+ Debug.LogWarning($"Settings: could not keep the music choice ({e.Message}); it holds until the page is closed");
+ }
+ }
+
+ void ApplyMusic()
+ {
+ if (music != null) music.Volume = Array.Find(SoundLevels, l => l.level == musicLevel).volume;
+ }
+
void PickScale(int percent)
{
chosen = percent;
@@ -286,6 +326,7 @@ namespace Statecraft.Game.UI
foreach (var (b, c, _) in quality) b.EnableInClassList(SelectedClass, c == GraphicsQuality.Current);
languages.Mark();
foreach (var (b, l, _) in sound) b.EnableInClassList(SelectedClass, l == soundLevel);
+ foreach (var (b, l, _) in musicLevels) b.EnableInClassList(SelectedClass, l == musicLevel);
foreach (var (b, level, _) in helpLevels) b.EnableInClassList(SelectedClass, level == advisors?.Level);
foreach (var (b, p, _) in scales)
{
diff --git a/unity/Assets/Tests/EditMode/HebrewUiTests.cs b/unity/Assets/Tests/EditMode/HebrewUiTests.cs
index dbe982618..a5e01ea5e 100644
--- a/unity/Assets/Tests/EditMode/HebrewUiTests.cs
+++ b/unity/Assets/Tests/EditMode/HebrewUiTests.cs
@@ -510,6 +510,8 @@ public class HebrewUiTests
("settings-quality-high", "settings.quality.high"), ("settings-quality-low", "settings.quality.low"),
("settings-sound-label", "settings.sound"), ("settings-sound-off", "settings.sound.off"),
("settings-sound-low", "settings.sound.low"), ("settings-sound-high", "settings.sound.high"),
+ ("settings-music-label", "settings.music"), ("settings-music-off", "settings.music.off"),
+ ("settings-music-low", "settings.music.low"), ("settings-music-high", "settings.music.high"),
("settings-advisors-label", "settings.advisors"), ("settings-language-label", "settings.language"),
("settings-uiscale-label", "settings.uiscale"), ("settings-companion-label", "settings.companion"), // #1119
("settings-community-label", "settings.community"), ("settings-star", "community.star"), ("start-star", "community.star"),
diff --git a/unity/Assets/Tests/EditMode/MenuMusicTests.cs b/unity/Assets/Tests/EditMode/MenuMusicTests.cs
new file mode 100644
index 000000000..a680df474
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MenuMusicTests.cs
@@ -0,0 +1,501 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Boot;
+using Statecraft.Game.Map;
+using Statecraft.Game.UI;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.TestTools;
+using UnityEngine.TestTools.Constraints;
+using UnityEngine.UIElements;
+using Is = UnityEngine.TestTools.Constraints.Is;
+
+/// <summary>The start menu's music (#39, MenuMusic): Afik's main theme (PR #2240) from StreamingAssets/audio/music/, looped
+/// while the start screen shows and faded out over a second of real time when a game starts. On the web it waits for the
+/// page's first activation (a click, a tap's release, a key other than Escape). No file is silence for the page: no fetch on
+/// the desktop, one line in the log, no warning, no error. The Settings screen's Music row sets its volume and keeps the
+/// choice. The fetch, the audio output and the clock are fakes, so no network, audio device or music file is needed.</summary>
+public class MenuMusicTests
+{
+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
+ static GameInputs? inputs;
+ static GameInputs Inputs => inputs ??= GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+ const float V = MenuMusic.DefaultVolume; // MenuMusic's own volume until Settings sets one
+
+ /// <summary>A fetch the test answers by hand.</summary>
+ sealed class FakeFetch
+ {
+ public readonly List<string> Urls = new List<string>();
+ public Action<AudioClip?, string?>? Pending;
+ public int Aborts;
+ sealed class Request : DeclarationRecording.IRequest
+ {
+ readonly FakeFetch f; public Request(FakeFetch f) { this.f = f; }
+ public ulong Bytes => 0;
+ public void Abort() => f.Aborts++;
+ }
+ public DeclarationRecording.IRequest Start(string url, Action<AudioClip?, string?> done) { Urls.Add(url); Pending = done; return new Request(this); }
+ }
+
+ sealed class FakeOutput : MenuMusic.IOutput
+ {
+ public readonly List<AudioClip> Played = new List<AudioClip>();
+ public bool IsPlaying { get; private set; }
+ public float Volume { get; set; } = -1f;
+ public bool? Decoded = true;
+ public int Stops;
+ public bool? Ready(AudioClip clip) => Decoded;
+ public void Play(AudioClip clip) { Played.Add(clip); IsPlaying = true; }
+ public void Stop() { Stops++; IsPlaying = false; }
+ public void Dispose() { }
+ }
+
+ sealed class Rig : IDisposable
+ {
+ public readonly UiTestKit Ui = new UiTestKit();
+ public readonly FakeFetch Fetch = new FakeFetch();
+ public readonly FakeOutput Out = new FakeOutput();
+ public readonly MenuMusic Music;
+ public bool Ducked;
+ /// <summary>The fake clock, in milliseconds.</summary>
+ public double Clock;
+ public Rig(bool web, string? url = null)
+ {
+ Music = new MenuMusic(Ui.Root, web, url ?? "https://example.invalid/StreamingAssets/" + MenuMusic.File, Fetch.Start, Out,
+ () => Clock / 1000.0);
+ Music.Duck = () => Ducked;
+ }
+ public AudioClip Answer()
+ {
+ var clip = AudioClip.Create("theme", 4410, 2, 44100, false);
+ Fetch.Pending!(clip, null);
+ return clip;
+ }
+ /// <summary>Lets <paramref name="ms"/> of real time pass in ticks of <paramref name="frameMs"/> (the last one shorter).</summary>
+ public void Pass(int ms, int frameMs = MenuMusic.WatchMs)
+ {
+ for (int left = ms; left > 0; left -= frameMs) { Clock += Math.Min(frameMs, left); Music.Tick(); }
+ }
+ Button At => Ui.Q<Button>("start-new-game");
+ /// <summary>A mouse press on a start screen button: an activation.</summary>
+ public void Click()
+ {
+ using var down = PointerDownEvent.GetPooled(new Event { type = EventType.MouseDown, button = 0, mousePosition = Vector2.zero });
+ down.target = At; At.SendEvent(down);
+ }
+ /// <summary>A finger's press (no activation on iOS) or its release (an activation).</summary>
+ public void Tap(bool release)
+ {
+ var touch = new Touch { fingerId = 0, phase = release ? TouchPhase.Ended : TouchPhase.Began, position = Vector2.zero };
+ if (release) { using var up = PointerUpEvent.GetPooled(touch); up.target = At; At.SendEvent(up); }
+ else { using var down = PointerDownEvent.GetPooled(touch); down.target = At; At.SendEvent(down); }
+ }
+ /// <summary>A key on the focused button, or with nothing focused (aimed at the panel's root).</summary>
+ public void Key(KeyCode key = KeyCode.A, char character = 'a', bool unfocused = false)
+ {
+ VisualElement at = unfocused ? Ui.Root.panel.visualTree : At;
+ using var k = KeyDownEvent.GetPooled(character, key, EventModifiers.None);
+ k.target = at; at.SendEvent(k);
+ }
+ public void Dispose() { Music.Dispose(); Ui.Dispose(); }
+ }
+
+ string dir = "";
+
+ [SetUp]
+ public void SetUp()
+ {
+ dir = Path.Combine(Path.GetTempPath(), "sc-music-" + Guid.NewGuid().ToString("N"));
+ MenuMusic.GestureSeen = false; // a new page: no activation yet,
+ MenuMusic.ThemeAbsent = false; // and no failed fetch
+ }
+
+ [TearDown]
+ public void TearDown()
+ {
+ MenuMusic.GestureSeen = false;
+ MenuMusic.ThemeAbsent = false;
+ if (Directory.Exists(dir)) Directory.Delete(dir, true);
+ }
+
+ /// <summary>The player's file: an OGG in StreamingAssets/audio/music/ (owner, 2 Nov 2026), the name Afik's PR #2240 uses.
+ /// Once a theme is committed there, a file and a name that differ fail here (before then the folder check has nothing
+ /// to compare).</summary>
+ [Test]
+ public void ThePlayerPicksTheThemeInStreamingAssetsMusic()
+ {
+ Assert.AreEqual("audio/music/Main_1.3.ogg", MenuMusic.File);
+ StringAssert.EndsWith("/StreamingAssets/" + MenuMusic.File, MenuMusic.Url().Split('?')[0]);
+ StringAssert.StartsWith("file://", MenuMusic.Url(), "the editor and desktop read the file from disk");
+ var folder = Path.Combine(Application.streamingAssetsPath, "audio", "music");
+ var shipped = Directory.Exists(folder)
+ ? Directory.GetFiles(folder).Where(f => !f.EndsWith(".meta") && !Path.GetFileName(f).StartsWith(".")).ToList()
+ : new List<string>();
+ foreach (var f in shipped) StringAssert.EndsWith(".ogg", f, "music is OGG only (owner, 2 Nov 2026)");
+ if (shipped.Count > 0)
+ CollectionAssert.Contains(shipped.Select(f => "audio/music/" + Path.GetFileName(f)).ToList(), MenuMusic.File,
+ "MenuMusic.File names the committed theme");
+ }
+
+ /// <summary>No theme on the desktop (main before #2240 lands): no fetch, nothing played, one plain log line however
+ /// often the screen shows or the player clicks, and no warning or error.</summary>
+ [Test]
+ public void NoFileIsSilentWithOneLogLineAndNoFetch()
+ {
+ var missing = "file://" + Path.Combine(dir, "none.ogg");
+ using var rig = new Rig(web: false, url: missing);
+ LogAssert.Expect(LogType.Log, "MUSIC no theme at " + MenuMusic.File + ": the start menu is silent");
+ Assert.DoesNotThrow(() => rig.Music.Show(true));
+ rig.Click(); rig.Pass(3000);
+ rig.Music.Show(false); rig.Music.Show(true); rig.Pass(1000);
+ LogAssert.NoUnexpectedReceived();
+ Assert.IsEmpty(rig.Fetch.Urls, "no file, no fetch");
+ Assert.IsEmpty(rig.Out.Played);
+ Assert.AreEqual(MenuMusic.Phase.Absent, rig.Music.State);
+ }
+
+ /// <summary>No theme on the web (the server answers 404): silent, one plain log line, no warning or error, and no second
+ /// fetch for the rest of the page.</summary>
+ [Test]
+ public void AFailedFetchIsSilentAndNotRetried()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true);
+ rig.Click();
+ Assert.AreEqual(1, rig.Fetch.Urls.Count);
+ LogAssert.Expect(LogType.Log, "MUSIC no theme at " + MenuMusic.File + ": the start menu is silent (HTTP/1.1 404 Not Found)");
+ rig.Fetch.Pending!(null, "HTTP/1.1 404 Not Found");
+ rig.Pass(2000); rig.Click(); rig.Key();
+ rig.Music.Show(false); rig.Music.Show(true); rig.Pass(1000);
+ LogAssert.NoUnexpectedReceived();
+ Assert.AreEqual(1, rig.Fetch.Urls.Count, "fetched once");
+ Assert.IsEmpty(rig.Out.Played);
+ }
+
+ /// <summary>The absence is the page's, not one instance's: a later MenuMusic (a rebuild) neither fetches again nor logs
+ /// again (second review of #2297, C4).</summary>
+ [Test]
+ public void TheAbsenceHoldsForThePage()
+ {
+ using (var first = new Rig(web: true))
+ {
+ first.Music.Show(true); first.Click();
+ LogAssert.Expect(LogType.Log, "MUSIC no theme at " + MenuMusic.File + ": the start menu is silent (HTTP/1.1 404 Not Found)");
+ first.Fetch.Pending!(null, "HTTP/1.1 404 Not Found");
+ }
+ using var second = new Rig(web: true);
+ second.Music.Show(true); second.Click(); second.Pass(1000);
+ LogAssert.NoUnexpectedReceived();
+ Assert.IsEmpty(second.Fetch.Urls, "no second fetch for the page");
+ Assert.AreEqual(MenuMusic.Phase.Absent, second.Music.State);
+ }
+
+ /// <summary>On the web nothing is fetched or played before the page's first activation; after it, the theme loads and
+ /// loops.</summary>
+ [Test]
+ public void OnTheWebItWaitsForTheFirstClickOrKey([Values(false, true)] bool byKey)
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true);
+ rig.Pass(2000);
+ Assert.IsEmpty(rig.Fetch.Urls, "no gesture yet");
+ if (byKey) rig.Key(); else rig.Click();
+ Assert.AreEqual(1, rig.Fetch.Urls.Count, "the first gesture starts it");
+ var clip = rig.Answer();
+ rig.Pass(MenuMusic.WatchMs);
+ CollectionAssert.AreEqual(new[] { clip }, rig.Out.Played);
+ Assert.AreEqual(MenuMusic.Phase.Playing, rig.Music.State);
+ Assert.AreEqual(V, rig.Out.Volume, 1e-6f, "MenuMusic's own volume, with no Settings row applied, is the row's Low");
+ UnityEngine.Object.DestroyImmediate(clip);
+ }
+
+ /// <summary>Only a real activation counts (second review of #2297, H2): a finger's press is none on iOS (its release
+ /// is), and Escape is never one.</summary>
+ [Test]
+ public void OnlyARealActivationCounts()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true);
+ rig.Tap(release: false);
+ rig.Key(KeyCode.Escape, '\0');
+ rig.Key(KeyCode.None, '\u001b');
+ Assert.IsEmpty(rig.Fetch.Urls, "a touch press and Escape are no activation");
+ rig.Tap(release: true);
+ Assert.AreEqual(1, rig.Fetch.Urls.Count, "a touch's release is");
+ }
+
+ /// <summary>A key with nothing focused goes to the panel's own root, above the document's: it still counts (second
+ /// review of #2297, H1).</summary>
+ [Test]
+ public void AKeyWithNothingFocusedCounts()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true);
+ rig.Key(unfocused: true);
+ Assert.AreEqual(1, rig.Fetch.Urls.Count);
+ }
+
+ /// <summary>On the desktop there is no gesture rule: it loads when the start screen shows. A clip still decoding plays
+ /// once it is ready.</summary>
+ [Test]
+ public void OnTheDesktopItStartsWithTheStartScreen()
+ {
+ var file = Path.Combine(dir, "theme.ogg");
+ Directory.CreateDirectory(dir); File.WriteAllBytes(file, new byte[] { 0x4f, 0x67, 0x67, 0x53 }); // exists; the fetch is fake
+ using var rig = new Rig(web: false, url: "file://" + file);
+ Assert.IsEmpty(rig.Fetch.Urls, "nothing before the screen shows");
+ rig.Music.Show(true);
+ Assert.AreEqual(1, rig.Fetch.Urls.Count);
+ rig.Out.Decoded = false;
+ var clip = rig.Answer();
+ rig.Pass(500);
+ Assert.IsEmpty(rig.Out.Played, "still decoding");
+ rig.Out.Decoded = true;
+ rig.Pass(MenuMusic.WatchMs);
+ CollectionAssert.AreEqual(new[] { clip }, rig.Out.Played);
+ }
+
+ /// <summary>The Music volume applies at once; at 0 the theme is never even fetched (no 5.66 MB download for silence),
+ /// and turning it up later starts it.</summary>
+ [Test]
+ public void TheVolumeAndMuteAreRespected()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Volume = 0f;
+ rig.Music.Show(true);
+ rig.Click(); rig.Pass(1000);
+ Assert.IsEmpty(rig.Fetch.Urls, "muted: not fetched");
+ rig.Music.Volume = 0.35f;
+ Assert.AreEqual(1, rig.Fetch.Urls.Count, "turned up: it starts");
+ var clip = rig.Answer();
+ rig.Pass(MenuMusic.WatchMs);
+ Assert.AreEqual(0.35f, rig.Out.Volume, 1e-6f);
+ rig.Music.Volume = 0f;
+ Assert.AreEqual(0f, rig.Out.Volume, "muted while playing: silent at once");
+ rig.Music.Volume = 1f;
+ Assert.AreEqual(1f, rig.Out.Volume, 1e-6f);
+ UnityEngine.Object.DestroyImmediate(clip);
+ }
+
+ /// <summary>When a game starts (the start screen closes) it fades out over about a second, then stops and lets the clip
+ /// go; it does not play during the game.</summary>
+ [Test]
+ public void ItFadesOutAndStopsWhenAGameStarts()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true); rig.Click();
+ var clip = rig.Answer();
+ rig.Pass(MenuMusic.WatchMs);
+ Assert.AreEqual(MenuMusic.Phase.Playing, rig.Music.State);
+ rig.Music.Show(false);
+ Assert.AreEqual(MenuMusic.Phase.Fading, rig.Music.State);
+ rig.Pass(MenuMusic.FadeMs / 2);
+ Assert.AreEqual(V * 0.5f, rig.Out.Volume, 0.01f, "half way");
+ Assert.AreEqual(0, rig.Out.Stops);
+ rig.Pass(MenuMusic.FadeMs / 2);
+ Assert.AreEqual(1, rig.Out.Stops, "stopped after the fade");
+ Assert.AreEqual(MenuMusic.Phase.Idle, rig.Music.State);
+ Assert.IsTrue(clip == null, "the clip is released");
+ rig.Click(); rig.Pass(2000);
+ Assert.AreEqual(1, rig.Fetch.Urls.Count, "no new fetch in the game");
+ Assert.AreEqual(1, rig.Out.Played.Count, "no play in the game");
+ }
+
+ /// <summary>The fade (and the dip) run on real time: at 60, 10 or 4 frames a second the fade is half way after half a
+ /// second and over after one, and a one-second hitch ends it at once (second review of #2297, C2).</summary>
+ [Test]
+ public void TheFadeTakesASecondOfRealTimeAtAnyFrameRate([Values(16, 100, 250, 1000)] int frameMs)
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true); rig.Click();
+ rig.Answer();
+ rig.Music.Show(false);
+ if (frameMs < MenuMusic.FadeMs)
+ {
+ rig.Pass(MenuMusic.FadeMs / 2, frameMs);
+ Assert.AreEqual(V * 0.5f, rig.Out.Volume, 0.01f, "half way after half a second");
+ Assert.AreEqual(0, rig.Out.Stops);
+ rig.Pass(MenuMusic.FadeMs / 2, frameMs);
+ }
+ else rig.Pass(MenuMusic.FadeMs, frameMs);
+ Assert.AreEqual(1, rig.Out.Stops, "over after a second");
+ Assert.AreEqual(MenuMusic.Phase.Idle, rig.Music.State);
+ }
+
+ /// <summary>The start screen shown again before the fade ends (C1): the theme turns back up from where it was, never
+ /// stops, and is not fetched again.</summary>
+ [Test]
+ public void ShownAgainDuringTheFadeItComesBackUp()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true); rig.Click();
+ rig.Answer();
+ rig.Music.Show(false);
+ rig.Pass(MenuMusic.FadeMs / 2);
+ rig.Music.Show(true);
+ Assert.AreEqual(MenuMusic.Phase.Playing, rig.Music.State, "back to playing at once");
+ rig.Pass(MenuMusic.FadeMs);
+ Assert.AreEqual(V, rig.Out.Volume, 1e-6f, "back up");
+ Assert.AreEqual(0, rig.Out.Stops, "never stopped");
+ Assert.AreEqual(1, rig.Fetch.Urls.Count, "fetched once");
+ Assert.AreEqual(1, rig.Out.Played.Count, "played once: no restart from the top");
+ }
+
+ /// <summary>A game that starts while the theme is still loading cancels the fetch; the late answer plays nothing.</summary>
+ [Test]
+ public void AGameStartedWhileLoadingCancelsTheFetch()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true); rig.Click();
+ var pending = rig.Fetch.Pending!;
+ rig.Music.Show(false);
+ Assert.AreEqual(1, rig.Fetch.Aborts);
+ var clip = AudioClip.Create("late", 441, 1, 44100, false);
+ pending(clip, null);
+ rig.Pass(1000);
+ Assert.IsEmpty(rig.Out.Played);
+ Assert.IsTrue(clip == null, "the late clip is released");
+ }
+
+ /// <summary>Ben-Gurion's recording on the same screen is not played over. The owner's ruling on #2297 (2 Nov 2026), "Dip
+ /// under the recording (Recommended)": "The theme drops low while the recording plays, then comes back". Low, not
+ /// silence: MenuMusic.DipLevel (0.2) of the Music volume while it plays, and back after it.</summary>
+ [Test]
+ public void ItDipsUnderTheDeclarationRecording()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true); rig.Click();
+ var clip = rig.Answer();
+ rig.Pass(MenuMusic.WatchMs);
+ rig.Ducked = true;
+ rig.Pass(MenuMusic.FadeMs);
+ Assert.AreEqual(V * MenuMusic.DipLevel, rig.Out.Volume, 1e-6f, "low under the recording, not silent");
+ Assert.AreEqual(MenuMusic.Phase.Playing, rig.Music.State, "paused in volume only: it goes on looping");
+ rig.Ducked = false;
+ rig.Pass(MenuMusic.FadeMs);
+ Assert.AreEqual(V, rig.Out.Volume, 1e-6f, "back after it");
+ UnityEngine.Object.DestroyImmediate(clip);
+ }
+
+ /// <summary>The page's first click is "Play the recording": the theme starts loading on that click, before the recording
+ /// plays, and is decoded while the recording is already playing. It must start low, not at full volume over Ben-Gurion's
+ /// voice until the next ticks catch up (review of #2297, N1).</summary>
+ [Test]
+ public void AThemeThatStartsDuringTheRecordingStartsLow()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Volume = 0.35f; // the Settings default (Low)
+ rig.Music.Show(true);
+ rig.Click(); // the click on Listen: the fetch starts, the recording not yet
+ Assert.AreEqual(1, rig.Fetch.Urls.Count);
+ rig.Ducked = true; // the recording is now playing
+ var clip = rig.Answer(); // the theme arrives and plays at once
+ CollectionAssert.AreEqual(new[] { clip }, rig.Out.Played);
+ Assert.AreEqual(0.35f * MenuMusic.DipLevel, rig.Out.Volume, 1e-6f, "low from its first sample, relative to the Music volume");
+ UnityEngine.Object.DestroyImmediate(clip);
+ }
+
+ /// <summary>The watch allocates nothing per tick: playing, dipping and fading.</summary>
+ [Test]
+ public void ATickAllocatesNothing()
+ {
+ using var rig = new Rig(web: true);
+ rig.Music.Show(true); rig.Click();
+ var clip = rig.Answer();
+ rig.Pass(MenuMusic.WatchMs);
+ Assert.That(() => { for (int i = 0; i < 50; i++) { rig.Clock += MenuMusic.WatchMs; rig.Music.Tick(); } }, Is.Not.AllocatingGCMemory());
+ rig.Ducked = true;
+ Assert.That(() => { for (int i = 0; i < 50; i++) { rig.Clock += MenuMusic.WatchMs; rig.Music.Tick(); } }, Is.Not.AllocatingGCMemory());
+ rig.Music.Show(false);
+ Assert.That(() => { for (int i = 0; i < 10; i++) { rig.Clock += MenuMusic.WatchMs; rig.Music.Tick(); } }, Is.Not.AllocatingGCMemory());
+ UnityEngine.Object.DestroyImmediate(clip);
+ }
+
+ /// <summary>MenuMusic's own default is the Music row's Low (second review of #2297, C5): a wiring that never applies
+ /// Settings cannot play it loud.</summary>
+ [Test]
+ public void ItsOwnDefaultIsTheRowsLow()
+ {
+ using var rig = new Rig(web: true);
+ Assert.AreEqual(0.35f, rig.Music.Volume, 1e-6f);
+ Assert.AreEqual(Array.Find(SettingsPresenter.SoundLevels, l => l.level == SettingsPresenter.MusicDefault).volume, MenuMusic.DefaultVolume);
+ }
+
+ /// <summary>GameRoot's wiring (C5): one MenuMusic for the page, made where the start screen shows, at Settings' Low, with
+ /// the recording as its duck and the screen's Show; a language switch keeps the same instance (no cut, no new fetch,
+ /// C4), and starting a game hands it Show(false).</summary>
+ [Test]
+ public void GameRootWiresOneMusicForThePage()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ try
+ {
+ UnityEngine.Object.FindFirstObjectByType<MapScene>().Build(Inputs.Map);
+ var game = UnityEngine.Object.FindFirstObjectByType<GameRoot>();
+ game.Store = new SaveStore(Path.Combine(dir, "saves"));
+ game.Settings = new SettingsStore(Path.Combine(dir, "settings"));
+ game.MenuMusicInEditMode = true;
+ MenuMusic.ThemeAbsent = true; // the wiring, not the file: nothing is fetched here
+ game.Begin(Inputs, 0, startScreen: true);
+ var ui = UnityEngine.Object.FindFirstObjectByType<UIDocument>().rootVisualElement;
+ var music = game.Music;
+ Assert.IsNotNull(music, "made where the start screen shows");
+ Assert.IsTrue(music!.Wanted, "the start screen's Show reached it");
+ Assert.AreEqual(0.35f, music.Volume, 1e-6f, "Settings applied the Music row's Low");
+ Assert.IsNotNull(music.Duck, "the recording is its duck");
+ Assert.IsFalse(music.Duck!(), "nothing is playing yet");
+ UiTestKit.Press(ui.Q<Button>("start-language-he")); // the rebuild a language switch makes
+ Assert.AreSame(music, game.Music, "the same music goes on");
+ Assert.IsTrue(music.Wanted, "the rebuilt start screen wants it");
+ Assert.IsNotNull(music.Duck, "the new screen's recording is its duck");
+ UiTestKit.Press(ui.Q<Button>("start-new-game"));
+ Assert.IsFalse(music.Wanted, "a game started: the screen closed");
+ }
+ finally { EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); }
+ }
+
+ /// <summary>The owner's ruling on #2297 (2 Nov 2026): "Low by default (Recommended)", "35% volume: the theme sits under
+ /// the menu". A fresh settings store (no file, or a file with no music line) reads Low, marked, at 0.35.</summary>
+ [Test]
+ public void AFreshSettingsStoreReadsLow([Values(false, true)] bool otherLines)
+ {
+ if (otherLines) new SettingsStore(dir).Write(SettingsPresenter.SoundKey, "high"); // a file from before the Music row
+ using var rig = new Rig(web: true);
+ using var settings = new SettingsPresenter(rig.Ui.Root, En, new SettingsStore(dir), music: rig.Music);
+ Assert.AreEqual(0.35f, rig.Music.Volume, 1e-6f, "Low by default");
+ Assert.IsTrue(rig.Ui.Q<Button>("settings-music-low").ClassListContains(SettingsPresenter.SelectedClass), "Low is marked");
+ Assert.IsFalse(rig.Ui.Q<Button>("settings-music-high").ClassListContains(SettingsPresenter.SelectedClass));
+ Assert.IsNull(new SettingsStore(dir).Read(SettingsPresenter.MusicKey), "the default is not written: only a choice is kept");
+ }
+
+ /// <summary>The sound effects row and the Music row are separate: one does not change the other.</summary>
+ [Test]
+ public void TheSoundEffectsRowLeavesTheMusicAlone()
+ {
+ using var rig = new Rig(web: true);
+ using var settings = new SettingsPresenter(rig.Ui.Root, En, new SettingsStore(dir), music: rig.Music);
+ UiTestKit.Press(rig.Ui.Q<Button>("settings-sound-off"));
+ Assert.AreEqual(0.35f, rig.Music.Volume, 1e-6f, "still the Music row's Low");
+ UiTestKit.Press(rig.Ui.Q<Button>("settings-music-off"));
+ Assert.AreEqual("off", new SettingsStore(dir).Read(SettingsPresenter.SoundKey));
+ Assert.AreEqual("off", new SettingsStore(dir).Read(SettingsPresenter.MusicKey));
+ }
+
+ /// <summary>The new words; the Hebrew waits for the native reviewer (#564).</summary>
+ [Test]
+ public void TheMusicRowIsInBothLanguages()
+ {
+ Assert.AreEqual("Music", En["settings.music"]);
+ Assert.AreEqual("מוזיקה", He["settings.music"]);
+ Assert.AreEqual("כבויה", He["settings.music.off"]);
+ Assert.AreEqual("חלשה", He["settings.music.low"]);
+ Assert.AreEqual("חזקה", He["settings.music.high"]);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/MenuMusicTests.cs.meta b/unity/Assets/Tests/EditMode/MenuMusicTests.cs.meta
new file mode 100644
index 000000000..146773f35
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MenuMusicTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 99ff3efbdef4a46b3900a71692eeb8b7
\ No newline at end of file
diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxml
index a2a68b97b..f57e7fd09 100644
--- a/unity/Assets/UI/Game.uxml
+++ b/unity/Assets/UI/Game.uxml
@@ -474,6 +474,15 @@
<ui:Button name="settings-sound-high" text="High" class="settings-switch" />
</ui:VisualElement>
</ui:VisualElement>
+ <!-- Music (#39, MenuMusic): the start menu's theme, three volume steps like the sound effects'. -->
+ <ui:VisualElement class="row settings-row">
+ <ui:Label name="settings-music-label" text="Music" class="settings-name" />
+ <ui:VisualElement class="row settings-choices">
+ <ui:Button name="settings-music-off" text="Off" class="settings-switch" />
+ <ui:Button name="settings-music-low" text="Low" class="settings-switch" />
+ <ui:Button name="settings-music-high" text="High" class="settings-switch" />
+ </ui:VisualElement>
+ </ui:VisualElement>
<!-- How much the advisors say (spec 6, AdvisorSettings): four levels, the one set carries .settings-choice-selected. -->
<ui:VisualElement class="row settings-row">
<ui:Label name="settings-advisors-label" text="Advisors" class="settings-name" />
diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yaml
index 61b80adaa..c7b14c455 100644
--- a/unity/Assets/UI/strings.en.yaml
+++ b/unity/Assets/UI/strings.en.yaml
@@ -173,6 +173,10 @@ settings.sound: "Sound effects"
settings.sound.off: "Off"
settings.sound.low: "Low"
settings.sound.high: "High"
+settings.music: "Music"
+settings.music.off: "Off"
+settings.music.low: "Low"
+settings.music.high: "High"
# The language choice (#1036). The two languages are named on their buttons in themselves ("English", "עברית"), set in
# SettingsPresenter, not here.
settings.language: "Language"
diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yaml
index 98636f692..0c3074140 100644
--- a/unity/Assets/UI/strings.he.yaml
+++ b/unity/Assets/UI/strings.he.yaml
@@ -184,6 +184,12 @@ settings.sound: "צליל"
settings.sound.off: "כבוי"
settings.sound.low: "חלש"
settings.sound.high: "חזק"
+# The start menu's music volume (#39, MenuMusic), in the sound effects' three steps. The adjectives are feminine, agreeing
+# with "מוזיקה" (as the quality row's agree with "איכות"). Agent-drafted Hebrew; native review pending (#564).
+settings.music: "מוזיקה"
+settings.music.off: "כבויה"
+settings.music.low: "חלשה"
+settings.music.high: "חזקה"
# The language choice (#1036); the languages' names are on their buttons, in themselves (SettingsPresenter). For the
# native reviewer (#564).
settings.language: "שפה"