A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using Statecraft.Game.Boot;
using Statecraft.Game.Map;
using Statecraft.Sim;
using UnityEngine;
using UnityEngine.UIElements;
namespace Statecraft.Game.UI
{
/// <summary>Starts the game once GameBoot has loaded the inputs and built the map (GameBoot.Ready): continues the
/// autosave or starts a new game (GameStart.Begin, with its notes in the toast), creates every screen, autosaves each
/// committed order and turn, and wires the camera and the map pointer to the game panel (UiPointer.IsOverUi), map clicks to the info panel,
/// the minimap to the camera, and State.Placements with the built city projects to the placement layer. Disabling it disposes all of that.
/// With "smoke" in the page URL (WebGL, e.g. ?smoke=5) or -smoke N (desktop) it starts a fresh game with the golden
/// seed (the player's autosave is neither read nor written), plays N turns through the UI's own buttons and logs
/// "SMOKE OK ..." (or "SMOKE FAIL ..."). In a player, unless an automated run skips it (StartScreenPresenter.Skipped),
/// the start screen shows over the started game before its first turn, with the camera keys stopped until it closes.
/// ExecuteAlways only so that disabling it disposes the presenters in edit mode too (tests); GameBoot raises Ready
/// in play mode and players only.</summary>
[ExecuteAlways]
public sealed class GameRoot : MonoBehaviour
{
Action<string>? savePersistenceResult;
/// <summary>Unity WebGL SendMessage entry point for IndexedDB save/delete results.</summary>
[UnityEngine.Scripting.Preserve]
public void OnSavePersistenceResult(string result) => savePersistenceResult?.Invoke(result);
/// <summary>Turns a bare smoke flag ("?smoke", "-smoke") plays.</summary>
internal const int DefaultSmokeTurns = 5;
/// <summary>Maximum time after closing the start screen for the normal-media browser check's first card to become usable.
/// This proposed budget needs maintainer sign-off (#909).</summary>
internal const double FirstCardBudgetSeconds = 10;
[SerializeField] GameBoot boot = null!;
[SerializeField] UIDocument document = null!;
[SerializeField] TextAsset strings = null!;
[SerializeField] TextAsset stringsHe = null!;
[SerializeField] PortraitCatalog portraits = null!;
[SerializeField] MapScene map = null!;
[SerializeField] PlacementLayer placements = null!;
[SerializeField] MapPointer pointer = null!;
[SerializeField] CameraController cameraController = null!;
/// <summary>Everything Begin created that must be undone, disposed in reverse order.</summary>
readonly List<IDisposable> owned = new List<IDisposable>();
MinimapPresenter? minimap;
Statecraft.Game.Map.Units.UnitLayer? units;
/// <summary>The units in play (null before Begin).</summary>
internal Statecraft.Game.Map.Units.UnitLayer? Units => units;
/// <summary>The map's region layers (sub-districts, armistice, control; null before Begin): a test aid.</summary>
internal MapRegions? Regions { get; private set; }
MapLabelsPresenter? labels;
ScreenNav? nav;
NavigationGuard? navGuard;
StartScreenPresenter? start;
OpeningPresenter? opening;
RaidCardPresenter? raid;
RaidFlightPresenter? raidFlight;
EventCardPresenter? card;
/// <summary>Tests: the decision card of the last Begin.</summary>
internal EventCardPresenter? Card => card;
WebCompanion? companion;
// The Settings switch for the companion, once pressed in this page's session: it wins over the stored choice and the
// address for every later Begin (a language switch or New Game), so "Off" holds under "?companion=1" too.
bool? companionPicked;
// Outbound test transport only; the shipping bridge remains one-way. Like the WebGL page, it is a page the companion
// can be turned on for; it does not turn it on.
internal Action<string>? CompanionSend { get; set; }
/// <summary>Tests: the page address the companion reads ("?companion=1"); null reads the real one
/// (Application.absoluteURL, which the Editor leaves empty).</summary>
internal string? CompanionAddress { get; set; }
internal WebCompanion? Companion => companion;
bool CompanionPage => Application.platform == RuntimePlatform.WebGLPlayer || CompanionSend != null;
/// <summary>Whether a Begin runs the companion: where a page can show it and WebCompanion.On says so.</summary>
bool CompanionWanted() => CompanionPage && WebCompanion.On(companionPicked, SettingsFile()?.Read(SettingsPresenter.CompanionKey), CompanionAddress ?? Application.absoluteURL);
CaptureDialogPresenter? capture;
/// <summary>Tests: the capture dialog of the last Begin.</summary>
internal CaptureDialogPresenter? Capture => capture;
/// <summary>Tests: the settlement name pills of the last Begin.</summary>
internal MapLabelsPresenter? Labels => labels;
/// <summary>Tests: the minimap of the last Begin.</summary>
internal MinimapPresenter? Minimap => minimap;
string? hoveredCity; // the city HoverCity lit (#1063)
readonly Dictionary<(int q, int r), List<string>> citiesByHex = new Dictionary<(int, int), List<string>>();
OutcomePresenter? outcomes;
EnemyTurnPlayback? playback;
TurnReportPresenter? report;
UiDirection? direction; // Hebrew only
EndScreenPresenter? end;
/// <summary>Set by SwitchLanguage for its Begin: the player had closed the end screen, so the rebuilt one stays closed.</summary>
bool endClosed;
/// <summary>Set by SwitchLanguage for its Begin (#2054): whether the start screen it rebuilds offered Continue.</summary>
bool keptResumed = true;
/// <summary>The Budget screen of the last Begin, whose unsubmitted draft a language switch hands to the next (#2708).</summary>
BudgetPresenter? budgetScreen;
/// <summary>Set by SwitchLanguage for its Begin (#2708): the old Budget screen's draft, for the rebuilt one.</summary>
IReadOnlyDictionary<string, double>? keptBudgetDraft;
/// <summary>The save notices of <see cref="saveNoticeSession"/>, the session Begin last started, as language-independent
/// keys, so a language switch can say them again in the new language (#2552). A New game replaces the bridge's session
/// without Begin, so the keys are said only while the kept session is still the one that raised them.</summary>
readonly List<string> saveNoticeKeys = new List<string>();
GameSession? saveNoticeSession;
AdvisorPresenter? advisor;
CabinetPresenter? cabinet;
/// <summary>The top bar's New Game (none in a smoke run), for Escape's withdrawal of its open request (#2340 L2).</summary>
NewGamePresenter? newGame;
EncyclopediaPresenter? encyclopedia;
/// <summary>Tests supply an in-memory approval copy for Hebrew layout; the shipped review fields are unchanged.</summary>
internal AdvisorCatalog? AdvisorCatalogForTests { get; set; }
/// <summary>Tests: the advisors' popup of the last Begin, and their session (kept across a language switch).</summary>
internal AdvisorPresenter? Advisor => advisor;
internal AdvisorSession? AdvisorSession { get; private set; }
FeedbackPresenter? feedback;
SharePresenter? share;
InfoPanelPresenter? info;
/// <summary>Shows the toast for a unit End turn skipped because it had no token to select (FocusNextUnit).</summary>
Action? unseenSkipped;
/// <summary>Tests: the info panel of the last Begin.</summary>
internal InfoPanelPresenter? Info => info;
CameraRig? rig;
List<(string, int, int, DateTime)>? drawn;
/// <summary>The designated sites on the map (#381), made on first use beside the placements; and their states as drawn.</summary>
SiteLayer? siteLayer; List<string>? drawnSites;
/// <summary>Whether the last Begin was a smoke run: the language switch then leaves the UI as it is, so the golden-seed
/// game never gets the autosave and New Game a normal Begin gives (SwitchLanguage).</summary>
bool smokeRun;
/// <summary>True while Shutdown disposes the presenters: the start screen's Dispose reports it closed, which must not
/// play a New game's intro (the raid flight, card or advisors) for a session that is going away (#3003).</summary>
bool shuttingDown;
public SimBridge? Bridge { get; private set; }
/// <summary>Where the autosave lives; null (the default) = SaveStore.ForPlatform(). Tests set a temporary folder.</summary>
internal SaveStore? Store { get; set; }
/// <summary>The UI's language; null (the default) = UiLanguage.AtStart (a flag, else the choice kept in Settings).
/// Tests set it, and so does Settings' language switch.</summary>
internal string? Language { get; set; }
/// <summary>Where the Settings options are kept; null (the default) = SettingsStore.ForPlatform() in Play mode and
/// players, none outside Play mode (EditMode tests: the developer's own settings must not leak into a test). Tests set
/// a temporary folder.</summary>
internal SettingsStore? Settings { get; set; }
SettingsStore? SettingsFile() => Settings ?? (Application.isPlaying ? SettingsStore.ForPlatform() : null);
/// <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 Tel Aviv raid card on New game outside Play mode: off by default, as OpeningInEditMode; its own tests
/// set it.</summary>
internal bool RaidCardInEditMode { get; set; }
/// <summary>The raid flight before that card (#3000) outside Play mode: off by default, as RaidCardInEditMode; its own
/// tests set it, with <see cref="RaidFlightForTests"/>.</summary>
internal bool RaidFlightInEditMode { get; set; }
/// <summary>Tests: flies the raid in place of the Dakotas (EditMode has no frame clock to fly them by): given what to
/// call when it ends by itself, returns how to stop it, or null when there is nothing to fly.</summary>
internal Func<Action, Action?>? RaidFlightForTests { 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)
{
var oldBoot = this.boot;
this.boot = boot; this.document = document; this.strings = strings; this.stringsHe = stringsHe; this.portraits = portraits; this.map = map;
this.placements = placements; this.pointer = pointer; this.cameraController = cameraController;
// An enabled GameRoot is already subscribed to the old boot's Ready (OnEnable): move the subscription.
if (!isActiveAndEnabled) return;
if (oldBoot != null) { oldBoot.Ready -= Begin; oldBoot.Failed -= OnBootFailed; }
if (this.boot != null) { this.boot.Ready += Begin; this.boot.Failed += OnBootFailed; }
}
void OnEnable() { if (boot != null) { boot.Ready += Begin; boot.Failed += OnBootFailed; } }
/// <summary>The loading line in the UI's language from the first frame (Start runs after every OnEnable, so the
/// document's tree exists).</summary>
void Start() { if (Application.isPlaying) Started(); }
/// <summary>Start's work: the loading line in the UI's language (ShowLoading), unless the boot has already failed or
/// the game has already begun. GameBoot and GameRoot set no execution order, and on the desktop the load reads from
/// disk, so a failure can land inside GameBoot.Start before this runs: its reason must stay (M3 final review I5).</summary>
internal void Started()
{
if ((boot == null || boot.Error == null) && Bridge == null) ShowLoading();
}
/// <summary>A boot failure replaces the loading line with a short reason in the player's language; the loading state
/// stays, so no half-built panel shows (M3 final review I5). <paramref name="reason"/> is an exception's English text
/// (a file path, a content error): it stays in GameBoot.Error and the log, never on screen (#637).</summary>
internal void OnBootFailed(string reason)
{
var text = ShowLoading();
var line = text == null ? null : document.rootVisualElement.Q<Label>("loading");
if (line != null) Say(line, text!.Format("boot.failed", text["boot.reason_other"]), text["ui.lang"] == UiLanguage.Hebrew);
}
/// <summary>Puts the loading line in the UI's language (boot.loading, #193). In Hebrew the root also gets its mark
/// (UiLanguage.HebrewClass) now, before Begin, so the line and a boot failure are set in the Hebrew face. Returns
/// the strings, or null before the scene's fields are set.</summary>
internal UiText? ShowLoading()
{
if (document == null || strings == null || stringsHe == null || document.rootVisualElement == null) return null;
var text = Strings();
var root = document.rootVisualElement;
bool hebrew = text["ui.lang"] == UiLanguage.Hebrew;
(root.Q("root") ?? root).EnableInClassList(UiLanguage.HebrewClass, hebrew);
var line = root.Q<Label>("loading");
if (line != null) Say(line, text["boot.loading"], hebrew);
return text;
}
/// <summary>A loading-line text, with its own direction in Hebrew (UiDirection is not running yet) and none in English.</summary>
static void Say(Label line, string words, bool hebrew)
{
line.text = words;
line.languageDirection = !hebrew ? LanguageDirection.Inherit : UiDirection.RightToLeft(words) ? LanguageDirection.RTL : LanguageDirection.LTR;
}
/// <summary>The strings of the UI's language (UiLanguage): strings.he.yaml when Hebrew is asked for or chosen; a language
/// from translations/ (#1606) as its ui.yaml over the English, per string, once <paramref name="content"/> carries it
/// (before the content loads, the loading line is English); else English.</summary>
UiText Strings(Content? content = null)
{
var language = Language ?? UiLanguage.AtStart(SettingsFile()?.Read(SettingsPresenter.LanguageKey));
if (language == UiLanguage.Hebrew) return UiText.Parse(stringsHe.text, "strings.he.yaml");
var english = UiText.Parse(strings.text);
var set = language == UiLanguage.English ? null : content?.Translations.Find(t => t.Lang == language);
return set == null ? english : english.Over(set.Ui, $"translations/{language}/ui.yaml");
}
void OnDisable()
{
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
// "?smoke-x", "?smoker" and "?smoke=five" are not the flag: UrlFlags' whole-parameter rule, plus digits only (amendment A3).
static readonly Regex SmokeQuery = new Regex(@"[?&]smoke(?:=(\d*))?(?=&|#|$)", RegexOptions.CultureInvariant);
/// <summary>Smoke-test turn count: from the page URL on WebGL, else from the command line. "?smoke=N" / "-smoke N"
/// play N turns (0 = off); a bare "?smoke" / "-smoke" (or "-smoke" followed by another flag) plays DefaultSmokeTurns;
/// a value that is not a non-negative int (too big, negative, not a number) is off on both. 0 when not asked.</summary>
internal static int SmokeTurns(string? url, string[] args, bool webgl)
{
if (webgl)
{
// Only the query counts: a flag after the '#' is the fragment (#2264; UrlFlags does the same since #2215).
var query = url ?? "";
var hash = query.IndexOf('#');
var m = SmokeQuery.Match(hash < 0 ? query : query.Substring(0, hash));
if (!m.Success) return 0;
var digits = m.Groups[1].Value;
return digits.Length == 0 ? DefaultSmokeTurns : int.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? n : 0;
}
var i = Array.IndexOf(args, "-smoke");
if (i < 0) return 0;
if (i + 1 >= args.Length) return DefaultSmokeTurns;
var value = args[i + 1];
if (value.StartsWith("-", StringComparison.Ordinal) && !Regex.IsMatch(value, @"^-\d")) return DefaultSmokeTurns; // the next flag
return int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var t) ? t : 0;
}
public static int SmokeTurns() =>
SmokeTurns(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
/// <summary>"?smoke-orders" (WebGL) or "-smoke-orders" (desktop): the smoke-orders golden's one-turn run (SmokeOrders, #754)
/// instead of the smoke turns. A whole query parameter, so the "smoke" flag never matches it, nor it "?smoke-orders-x".</summary>
internal static bool SmokeOrdersRequested(string? url, string[] args, bool webgl) =>
webgl ? UrlFlags.Has(url, "smoke-orders") : Array.IndexOf(args, "-smoke-orders") >= 0;
/// <summary>GameBoot.Ready: starts the game, smoke-testing when the URL or command line asks, with the start screen
/// unless an automated run skips it.</summary>
public void Begin(GameInputs inputs)
{
bool orders = SmokeOrdersRequested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
Begin(inputs, orders ? 1 : SmokeTurns(), Application.isPlaying && !StartScreenPresenter.Skipped(), smokeOrders: orders);
}
/// <summary>Starts (or restarts) the game over the built map. <paramref name="smoke"/> > 0 plays that many turns
/// (with <paramref name="smokeOrders"/>, the smoke-orders run's one turn instead);
/// <paramref name="startScreen"/> shows the start screen first (never in a smoke run, which has no New Game).
/// <paramref name="keep"/> (Settings' language switch) goes on with that bridge's game and its queued orders instead
/// of loading the autosave; when rebuilding the start screen, its save notices are rendered in the new language.</summary>
internal void Begin(GameInputs inputs, int smoke, bool startScreen = false, SimBridge? keep = null, bool smokeOrders = false)
{
if (inputs == null) throw new ArgumentNullException(nameof(inputs));
foreach (var (value, field) in new (UnityEngine.Object?, string)[] { (document, nameof(document)), (strings, nameof(strings)), (stringsHe, nameof(stringsHe)),
(map, nameof(map)), (placements, nameof(placements)), (pointer, nameof(pointer)), (cameraController, nameof(cameraController)) })
if (value == null) throw new InvalidOperationException($"GameRoot: {field} is not assigned (run MapCapture.MakeScene)");
if (map.Terrain == null) throw new InvalidOperationException("GameRoot: the map is not built (GameBoot builds it before Ready)");
// The opening (#530) plays in Play mode and players, never in a smoke run or an automated one; in EditMode only
// where a test asks for it with the start screen (OpeningInEditMode).
bool enableOpening = smoke == 0 && !StartScreenPresenter.Skipped()
&& (Application.isPlaying || startScreen && OpeningInEditMode);
// The raid card on New game, likewise (RaidCardInEditMode).
bool enableRaid = smoke == 0 && !StartScreenPresenter.Skipped()
&& (Application.isPlaying || startScreen && RaidCardInEditMode);
// A companion this Begin runs again keeps the page's panel until its replacement publishes (WebCompanion.Dispose).
Shutdown(keepCompanionPage: companion != null && CompanionWanted());
smokeRun = smoke > 0;
var text = Strings(inputs.Content);
var store = Store ?? SaveStore.ForPlatform();
if (keep == null) saveNoticeKeys.Clear();
var notes = keep != null && startScreen && ReferenceEquals(keep.Session, saveNoticeSession)
? saveNoticeKeys.Select(key => GameStart.NoticeText(text, key)).ToList()
: new List<string>();
// A smoke run is reproducible: a fresh game with the golden seed, never the player's autosave.
bool resumed = keep == null || keptResumed; // a language switch offers Continue as the start screen it rebuilds did
keptResumed = true;
var session = keep?.Session ?? (smoke > 0
? GameStart.Begin(inputs.Content, store, () => GoldenRun.Seed, notes, text, out resumed,
fresh: true, noticeKeys: saveNoticeKeys)
: GameStart.Begin(inputs.Content, store, GameStart.NewSeed, notes, text, out resumed,
noticeKeys: saveNoticeKeys));
if (keep == null) saveNoticeSession = session;
DiagLog.BootPhase($"session started (turn {session.State.Turn}, replayed)");
var bridge = Bridge = new SimBridge(session, text);
var oldFixedNorth = cameraController.FixedNorth;
ConfigureCameraHeading(cameraController, bridge.Content.Ruleset);
owned.Add(new Undo(() => cameraController.SetFixedNorth(oldFixedNorth)));
if (keep != null) foreach (var order in keep.Queued) bridge.Queue(order); // in their order: each was within the attention left
if (keep != null) foreach (var unit in keep.Skipped) bridge.Skip(unit); // this turn's skips too: no reload, no new turn
if (keep != null) foreach (var id in keep.EndingCardsAnswered) bridge.SeeEndingCard(id); // and the ending turn's answered cards (#2536)
if (Statecraft.HexTiles.HexTilesLook.Requested()) // opt-in hex-tile map (docs/hex-tiles/README.md); presentation only
{
Statecraft.HexTiles.HexTilesLook.Apply(map, true);
owned.Add(new Undo(() => Statecraft.HexTiles.HexTilesLook.Apply(map, false)));
}
var root = document.rootVisualElement;
bool hebrew = text["ui.lang"] == UiLanguage.Hebrew;
// Hebrew: the Hebrew face, the advanced text generator and the mirrored rows (.lang-he); each text's paragraph
// direction comes from its own text (UiDirection, made below once the presenters have rendered).
(root.Q("root") ?? root).EnableInClassList(UiLanguage.HebrewClass, hebrew); // on .root, whose face it replaces
var loading = root.Q<Label>("loading");
if (loading != null) Say(loading, text["boot.loading"], hebrew); // hidden from here on; set for a restart in the other language
// The toast first: the autosave (below) must report a failed write after the toast has shown the turn's refusals.
var toast = Own(new ToastPresenter(root, bridge, text));
savePersistenceResult = result =>
{
if (result.StartsWith("fail save ", StringComparison.Ordinal))
{
toast.SaveFailed(text["save.write_failed"]);
Debug.Log("SAVE FAILURE SHOWN save.write_failed");
}
else if (result.StartsWith("ok save ", StringComparison.Ordinal)) toast.SaveSucceeded(); // #2707: the failure stays until then
};
unseenSkipped = () => toast.Show(text["toast.unit_unseen_skipped"]);
var hudPresenter = Own(new HudPresenter(root, bridge, text, selectUnit: _ => FocusNextUnit()));
nav = Own(new ScreenNav(root, text)); // every screen starts hidden (USS); ScreenNav opens one at a time
Own(new PointerBlur(root)); // a mouse click leaves no focus fill behind (keyboard keeps it)
Own(new FocusScroll(root)); // keyboard focus scrolls its ScrollView to it (a11y H1)
FocusScroll.NoScrollBarIsATabStop(root); // no scroll bar takes a Tab stop (#41 K3, widened from the Cabinet's two)
navGuard = Own(new NavigationGuard(root, () => nav?.Current)); // the camera keys never move UI focus (B6), but Up/Down walk an open screen's rows (L4)
if (DiagLog.Nav) Own(new NavEventLog(root)); // ?navlog: every UI pointer/submit event (playtest 2, P2-4)
// The Illustration switch's silent loops (event-videos.yaml, Resources): none in the automated runs (CardVideo.ForcedOff).
var video = CardVideo.ForcedOff() ? null : Own(new CardVideo());
var mapping = video == null ? default : EventVideoMapping.LoadBoth();
var clips = video == null ? null : mapping.clips.ToDictionary(r => r.Event);
// Event photos: Resources, no scene field, loaded off the boot path (issue #321): in the start screen's idle time,
// or by the first card if it comes sooner. A Continue with a decision waiting builds the card under the start
// screen, which asks for the photograph only when the screen closes (issue #592). One value says whether the
// screen goes up (below) and whether the card waits for it: a card waiting under no screen would never show its photo.
// A smoke run has no New Game, so it shows no start screen. Since the GDD cutover every new game opens on a card
// (One Army, 15 May 1948), so a new game's card waits under the screen too.
bool showsStart = startScreen && smoke == 0;
EventPhotos.ScheduleOn(root);
card = Own(new EventCardPresenter(root, bridge, text, portraits, null, video,
clips == null ? null : id => clips.TryGetValue(id, out var r) ? r : null, EventPhotos.Get,
underStartScreen: showsStart,
// A screenshot run (?shot) captures the map: the opening card would cover it (UnitLayer.HiddenInCaptures' rule).
hiddenInCapture: EventCardPresenter.HiddenInCaptures(Application.absoluteURL, Environment.GetCommandLineArgs(),
Application.platform == RuntimePlatform.WebGLPlayer)));
// The sound effects (#39): End Turn, a refused order, a card coming into view; the Settings screen sets the volume.
// After the card: a card already open when Begin rebuilds the UI (New Game, a language switch) makes no sound.
var audio = Own(new GameAudio(bridge, card));
// The End Turn outcome clips (decision videos, phase 3): none in the automated runs (no video there). Their own
// player, so the card's loop never takes it; an open screen closes when one starts.
outcomes = video == null ? null : Own(new OutcomePresenter(root, bridge, text, Own(new CardVideo()), mapping.outcomes,
() => card?.Render(), () => nav?.Close()));
Own(new DefencePresenter(root, bridge, text, portraits));
var budget = budgetScreen = Own(new BudgetPresenter(root, bridge, text, keptBudgetDraft));
var why = Own(new WhyPresenter(root, bridge, text));
Own(new TimelinePresenter(root, bridge, text));
Own(new ObjectivesPresenter(root, bridge, text));
// The advisors (spec 4.2): their session survives a rebuild over the same game (a language switch keeps the
// queue, the history and the opening chain's place) and is new for any other Begin. They show by themselves only
// on the first new game: the start screen shows and a settings file remembers what was seen. Made before
// Settings, whose help-level row (spec 6) reads and sets the session's level.
if (keep == null || AdvisorSession == null)
{
bool autoShow = showsStart && !FirstCardCheckRequested() && SettingsFile() != null;
AdvisorSession = new AdvisorSession(AdvisorCatalogForTests ?? AdvisorCatalog.Load(), new AdvisorSettings(autoShow ? SettingsFile() : null), autoShow);
}
// Presentation only (#40): never the sim or the save. Outside Play mode (EditMode tests) no file: the developer's
// own settings must not leak into a test. Each Begin (New Game too) reads the file again.
// The language switch (#1036) builds every screen again in the new language over this game (SwitchLanguage).
Action<string> switchLanguage = language => SwitchLanguage(inputs, language); // the start screen's too (#2054)
// The WebGL companion (#1119) is opt-in (WebCompanion.On): Settings turns it on and off at once, where a page shows it.
// While the build does not offer it (WebCompanion.Available, owner 2 Nov 2026), there is no switch, so no row.
Action<bool>? setCompanion = null;
(Func<bool> on, Action<bool> set)? companionSwitch = null;
if (CompanionPage && WebCompanion.Offered())
{
Action<bool> set = on =>
{
if (on == (companion != null)) return;
if (on) { companion = Own(new WebCompanion(root, text, bridge, () => card?.Shown != null, CompanionSend)); return; }
var off = companion!; companion = null;
owned.Remove(off);
off.Dispose(); // clears the page
};
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, music: music, enemyMoves: on => { if (!on) playback?.Skip(); }));
// "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;
cabinet = Own(new CabinetPresenter(root, bridge, text, portraits));
// After End Turn, what changed in the top bar and the sim's causes (#1037); under an outcome clip, which plays first.
report = Own(new TurnReportPresenter(root, bridge, text, nav!));
// #2202: its lines are new labels with their words set, which UiDirection only sees on its next pass. The report
// can open with nothing that schedules one: when the enemy moves end, or when a screen it waited for closes.
report.Showing += turn => { if (turn != null) direction?.Later(); };
// "Share" (#1170), from Settings and the turn report: the frame is captured at its end, before the panel shows.
var sharePanel = share = Own(new SharePresenter(root, bridge, text, done => StartCoroutine(ShareShot.Capture(done))));
// Star, Report and Share as round icons at the map screen's bottom left (#1236): the same actions as Settings' buttons.
Own(new CommunityIconsPresenter(root, text, feedbackPanel, sharePanel));
// Both panels in one hook: the same Escape never closes the screen under the panel too.
nav!.TakesEscape = () => feedbackPanel.Escape() || sharePanel.Escape() || advisor?.CloseOverlay() == true || advisor?.OverlayClosedThisFrame == true || advisor?.Escape() == true || cabinet?.Escape() == true || this.info?.Escape() == true; // the field: the panel is made below
var names = map.SettlementsFor(inputs.Map.SettlementsYaml).ToDictionary(s => s.Id, s => s.Name); // the map's parse (issue #321)
// The capture dialog (GDD Phase 6 PR 10, #802): in the decision layer, after the card, which goes first; the
// places' Hebrew names from the same parse.
capture = Own(new CaptureDialogPresenter(root, bridge, text, card,
map.SettlementsFor(inputs.Map.SettlementsYaml).ToDictionary(s => s.Id, s => s.NameHe)));
// The 1948 sub-districts, outlined on the map, and each front's 1949 armistice line from its agreement's date
// where the line exists (display only: the sim never reads them; docs/visual-v1.md, owner rulings 2026-10-11).
// Since the owner's rulings of 2026-10-14 the areas are coloured by side (control_hexes_1948_49.yaml), from 15 May 1948
// since #674 (the 9 July 1948 lines, adjusted),
// with the legend in the label.
// From their runtime forms when they match the YAML (issue #321: boot time), the sub-districts as the map read them.
var regions = new MapRegions(map.SubdistrictsFor(inputs.Map.RegionsTsv, inputs.Map.RegionsYaml, Debug.LogWarning),
string.IsNullOrWhiteSpace(inputs.Map.ArmisticeYaml) ? null : Armistice1949.ReadRuntimeOrYaml(inputs.Map.ArmisticeTsv, inputs.Map.ArmisticeYaml, Debug.LogWarning),
map.Control, MapRegionNames.Parse(inputs.Map.RegionNamesYaml)); // the map's read, with the map editor's control overrides (#1009); the road vehicles use it too (#725)
if (regions.Names.Stale.Count > 0)
Debug.LogWarning($"{MapRegionNames.FileName}: English changed since the Hebrew was supplied, showing English for: {string.Join(", ", regions.Names.Stale)}");
Regions = regions;
var layerLabel = root.Q<Label>("map-layer");
Action onDate = () =>
{
var probe = TurnProbe.Start(); // ?turnlog (#2905)
var live = bridge.State.Settlements.OrderBy(kv => kv.Key, StringComparer.Ordinal)
.Join(bridge.Content.SettlementHexes, kv => kv.Key, h => h.Id,
(kv, h) => (h.Q, h.R, player: SettlementControlView.PlayerHolds(kv.Value)))
.Where(x => x.player != null).Select(x => (x.Q, x.R, x.player!.Value)).ToList();
regions.Apply(bridge.State.Date, live);
layerLabel.text = regions.ControlLabel(bridge.State.Date, k => text[k])
?? regions.Label(bridge.State.Date, text.Format, text["ui.lang"] == UiLanguage.Hebrew);
ShowLayerLabel();
TurnProbe.Lap("GameRoot.regions", probe);
};
// The caption names the borders while they are drawn: by date, and not while the minimap's button hides them.
void ShowLayerLabel() => layerLabel.style.display = regions.Shown && minimap?.BordersShown != false ? DisplayStyle.Flex : DisplayStyle.None;
onDate();
bridge.Changed += onDate;
owned.Add(new Undo(() => bridge.Changed -= onDate));
// The units in play (docs/units.md): drawn from the state and the sourced unit data, before the info panel so
// the layer has followed a change before the panel renders the selected unit's card.
DiagLog.BootPhase("screens wired"); // issue #321: the splits of the units layer
// The map's own parse of the unit file when it read this text (issue #321: it was parsed twice at boot).
var unitData = map.UnitEntriesFor(inputs.Map.UnitsYaml, Debug.LogWarning);
card.Units = unitData;
card.Render(); // a continued operation card replaces raw row ids with the sourced unit names immediately
why.Units = unitData;
report.Units = unitData; // the turn report names the enemy's units by these rows (#1293)
DiagLog.BootPhase("units layer data read");
var unitLayer = units = Statecraft.Game.Map.Units.UnitLayer.Create(map,
unitData, inputs.Content.Hexes,
Statecraft.Game.Map.Units.UnitShowcase.StillRequested(Application.absoluteURL, Environment.GetCommandLineArgs(),
Application.platform == RuntimePlatform.WebGLPlayer));
// A screenshot run (?shot) leaves the units out unless it also asks for them (&units), so the art log's plain
// checkpoints stay comparable across tracks (review I5; tools/art_checkpoint.sh --units).
if (Statecraft.Game.Map.Units.UnitLayer.HiddenInCaptures(Application.absoluteURL, Environment.GetCommandLineArgs(),
Application.platform == RuntimePlatform.WebGLPlayer))
VisualToggles.Set(Statecraft.Game.Map.Units.UnitLayer.ToggleName, false);
GameSession? shownSession = null;
Action showUnits = () =>
{
// New Game replaces the session, and its sim ids are the old game's: its tokens are drawn where they stand.
var probe = TurnProbe.Start(); // ?turnlog (#2905)
unitLayer.Show(bridge.Content, bridge.State, slide: ReferenceEquals(shownSession, bridge.Session));
probe = TurnProbe.Lap("UnitLayer.Show", probe);
shownSession = bridge.Session;
unitLayer.Dim(unitLayer.Tokens.Where(t => t.Token.Unit.Side == Statecraft.Game.Map.Units.UnitData.Israel)
.Where(t => UnitCard.SimUnit(bridge.Content, bridge.State, t.Token) is int id
&& Movement.ActionsLeft(bridge.Content, bridge.State, id, bridge.Spent) == 0)
.Select(t => t.Token.Unit.Id).ToList());
TurnProbe.Lap("GameRoot.unitsDim", probe);
};
bridge.Changed += showUnits;
owned.Add(new Undo(() => bridge.Changed -= showUnits));
showUnits();
var attacks = new UnitAttackPresenter(bridge, unitLayer.PlayAttack, unitLayer.PlayHit, unitLayer.PlayDestroyed,
unitLayer.PlayDefenderHit, unitLayer.PlayAttack); // after showUnits: the map is redrawn first
owned.Add(attacks);
DiagLog.BootPhase("units layer built");
// #1878: the turn report is up, the hexes the turn attacked show the under-attack look; closing it clears them.
var underAttack = new Statecraft.Game.Map.UnderAttackLayer(map);
var turnReport = report!;
turnReport.Showing += underAttack.Show;
owned.Add(new Undo(() => { turnReport.Showing -= underAttack.Show; underAttack.Clear(); }));
var localitiesAt = LocalitiesAt(map);
var townNamesHe = map.SettlementsFor(inputs.Map.SettlementsYaml).ToDictionary(s => s.Id, s => s.NameHe);
var info = this.info = Own(new InfoPanelPresenter(root, bridge, text, names, nav: nav,
selectedUnit: () => unitLayer.Selected is string id ? unitLayer.Tokens.First(p => p.Token.Unit.Id == id) : (Statecraft.Game.Map.Units.PlacedToken?)null,
regions: regions, localitiesAt: localitiesAt,
townHex: InfoPanelPresenter.TownHex(map.SettlementsFor(inputs.Map.SettlementsYaml), map.Hexes),
townNamesHe: townNamesHe,
showReachable: map.ShowReachable,
unitName: id => unitLayer.Tokens.Where(p => UnitCard.SimUnit(bridge.Content, bridge.State, p.Token) == id)
.Select(p => UnitCard.For(p, bridge.State, text, bridge.Content.IsGdd, bridge.Content, townNamesHe).Title).FirstOrDefault(),
unitDone: FocusNextUnit, showRoute: map.ShowRoute, showArrow: map.ShowMoveArrow, selectPioneer: FocusPioneer, clearSelection: () => { unitLayer.Select(null); map.ClearSelection(); }));
toast.Units = unitData; toast.TownNamesHe = townNamesHe; why.TownNamesHe = townNamesHe; bridge.TownNamesHe = townNamesHe;
report.TownNamesHe = townNamesHe; hudPresenter.TownNamesHe = townNamesHe;
// A smoke session never touches the player's save: no autosave, and no New Game (which writes the autosave).
// Leaving New Game out is safer than handing it a throwaway store: no file is ever written, no path has to be
// right on every platform, and the scripted run never presses it.
NewGamePresenter? newGame = null;
if (smoke == 0)
{
newGame = Own(new NewGamePresenter(root, bridge, store, toast, text, GameStart.NewSeed, gameObject.name));
this.newGame = newGame;
Own(GameStart.Autosave(bridge, store, text, toast.SaveFailed, gameObject.name, toast.SaveSucceeded)); // under the turn's refusals, until a save succeeds (#2707)
}
// Once the game is over, the sim's end report (#812); after the autosave, so the last turn is saved first. New Game
// is its two presses; a smoke run has none.
end = Own(new EndScreenPresenter(root, bridge, text, newGame == null ? null : newGame.Press, show: !endClosed));
endClosed = false;
// The store's achievements (#2152): a no-op unless a Steam build set PlatformServices.Current. A smoke run (the
// golden seed, scripted turns) is not the player's game, so it reports nothing.
if (smoke == 0) Own(new AchievementReporter(bridge, () => PlatformServices.Current));
// An outcome clip holds the pointer while it shows and in the frame it closes (the skipping click selects no hex).
Func<Vector2, bool> overUi = p => opening?.HoldsThePointer == true || raidFlight?.HoldsThePointer == true || raid?.HoldsThePointer == true || outcomes?.HoldsThePointer == true || UiPointer.IsOverUi(root.panel, p, Screen.height);
var terrain = map.Terrain;
var size = terrain.terrainData.size;
var oldBounds = cameraController.Bounds;
var oldGround = cameraController.Ground; var oldTop = cameraController.GroundTop;
cameraController.IsOverUi = overUi;
cameraController.Bounds = new Rect(terrain.transform.position.x, terrain.transform.position.z, size.x, size.z);
cameraController.Ground = CameraController.GroundOf(terrain);
cameraController.GroundTop = CameraController.GroundTopOf(terrain);
pointer.Map = map;
pointer.InvalidateSceneCache();
pointer.View = cameraController.GetComponent<Camera>();
citiesByHex.Clear();
foreach (var h in bridge.Content.SettlementHexes)
{
if (!citiesByHex.TryGetValue((h.Q, h.R), out var ids)) citiesByHex[(h.Q, h.R)] = ids = new List<string>();
ids.Add(h.Id); // preserve content order where settlement rows share a hex
}
// #1617: the lit hexes of a Move or Attack pick show through the unit card, so the map pointer also takes a click
// on the card's text over one of them (InfoPanelPresenter.TakesClickThrough). The camera does not: no drag or wheel
// through the card.
Func<Vector2, bool> pointerOverUi = p => outcomes?.HoldsThePointer == true
|| (UiPointer.PickAt(root.panel, p, Screen.height) is { } picked && !info.TakesClickThrough(picked, () => pointer.HexUnder(p)));
pointer.IsOverUi = pointerOverUi;
// #1654 review: the pointer's tap rule decides both a click and the camera's drag, so a press is never both.
// Either button (#998): whichever is down holds the drag while it could still be a click, so a click never
// nudges the map and a drag past the slop pans.
Func<bool> holdsMouseDrag = () => pointer.RightTapCandidate || pointer.LeftTapCandidate,
holdsTouchDrag = () => pointer.TouchTapCandidate;
cameraController.HoldsMouseDrag = holdsMouseDrag; cameraController.HoldsTouchDrag = holdsTouchDrag;
// Audit L4: while a screen is open, the Up and Down arrows are its rows' (NavigationGuard.Step), not the camera's.
Func<bool> screenTakesUpDown = () => nav?.Current != null;
cameraController.ScreenTakesUpDown = screenTakesUpDown;
// #2712: in the two-row HUD (the tight three-row one too) an open screen covers the whole map, so the camera keys
// are off while it shows, as under the start screen; a desktop screen leaves the map beside it (plan amendment A4).
var hudRoot = root.Q("root") ?? root;
Func<bool> screenCoversMap = () => nav?.Current != null && hudRoot.ClassListContains(HudPresenter.TwoRowClass);
cameraController.ScreenCoversMap = screenCoversMap;
Action<int, int, bool> onHex = (q, r, cityPill) =>
{
OnHexClicked(map, unitLayer, info, q, r, UnityEngine.InputSystem.Pointer.current is UnityEngine.InputSystem.Touchscreen, cityPill);
if (info.ShowsUnit) advisor?.Notice(AdvisorSignals.UnitShown);
else if (info.Selected is (int sq, int sr) && bridge.Content.SettlementHexes.Any(h => h.Q == sq && h.R == sr && bridge.State.Cities.ContainsKey(h.Id)))
advisor?.Notice(AdvisorSignals.CityShown);
};
pointer.HexClicked += onHex;
Action<int, int> onOrder = (q, r) => OnHexOrdered(map, info, q, r);
pointer.HexOrdered += onOrder;
// #1063: a click on a city's name pill is a click on the city's hex (its settlement hex, where the city panel opens).
Func<Vector2, (int q, int r)?> pillHex = p =>
{
if (labels?.PillAt(p) is not string id || !bridge.State.Cities.ContainsKey(id)) return null;
foreach (var x in bridge.Content.SettlementHexes) if (x.Id == id) return (x.Q, x.R);
return null;
};
pointer.PillHex = pillHex;
var camRig = rig = cameraController.GetComponent<CameraRig>();
// #2202: after End turn the map plays the Arab forces' moves, the camera going to each, and the footer names the side
// (EnemyTurnPlayback, EnemyPlaybackBar). Never in a smoke run or EditMode; the Settings switch is read at each End
// turn. It starts once an outcome clip (or the opening) has gone, and the report and the card wait for it (Q1 a).
var play = playback = Own(new EnemyTurnPlayback(bridge, new UnitLayerPlaybackMap(unitLayer, attacks, map, bridge),
new RigPlaybackCamera(camRig, cameraController, () => labels?.Refresh()),
enabled: () => Application.isPlaying && !smokeRun && SettingsPresenter.EnemyMovesOn(SettingsFile()),
waiting: () => outcomes?.Showing != null || opening?.HoldsThePointer == true));
attacks.Claimed = play.Claims;
// The card first, then the report, as at an End turn with no playback: the card comes into view with its cue, then
// the report covers it.
// #2202: the released card and report build new texts with no turn, click or key press: UiDirection walks them.
Action<bool> holding = held => { if (card != null) card.HeldForPlayback = held; if (report != null) report.Held = held; if (!held) direction?.Later(); };
play.Holding += holding;
owned.Add(new Undo(() => play.Holding -= holding)); // disposed before the playback: its last release touches neither
Own(new EnemyPlaybackBar(root, text, play, bridge)).Units = unitData;
Own(new TopBarInset(root, camRig)); // the map is framed below the top bar
Own(new SafeAreaFit(root)); // the HUD keeps clear of the phone's notch
// the map's keyboard stop (#41 B1b): Enter or Space picks the hex under the look-at point, as a click there would
Own(new MapFocusPresenter(root, cameraController.GetComponent<Camera>(), camRig, at => pointer.PickAt(at)));
var mini = minimap = Own(new MinimapPresenter(root, map.Hexes, text));
var labelCamera = cameraController.GetComponent<Camera>();
labels = Own(new MapLabelsPresenter(root, map, labelCamera, null,
p => MapLabelsPresenter.TipOf(p, n => text.Format("map.today", n), text["map.mixed"], hebrew),
() => // the names keep clear of the unit tokens (issue #197), their badges and flags as this camera will draw them,
{ // of the 1948 Collection's ships and C-54 (#669), and of the arms workshops' b21 (#1701 slice F)
IReadOnlyList<Bounds[]>? tokens = null;
if (unitLayer != null) { unitLayer.FaceCamera(labelCamera); tokens = unitLayer.KeepClear; }
return keepClear.Merge(tokens, seaAir != null ? seaAir.KeepClear : null, special != null ? special.KeepClearFor(labelCamera) : null);
},
// Issue #710: the static 1948 tier from cities.yaml's people, not the sim's live count (owner, 15 October 2026).
bridge.Content.Cities.Where(c => c.People != null).ToDictionary(c => c.Id, c => c.People!.Value),
(tier, people) => text.Format("map.tier", tier, MapLabelsPresenter.TierCount, people.ToString("N0", CultureInfo.InvariantCulture)),
hebrew, bridge.Content.MapLocations, // #1008: the GDD v0.2 map locations are named too
r => SettlementControlView.MapText(text, r))); // #803: each place's control state as a tag under its name
// #803 Task 5: the tags follow the state the map shows (the order preview, U1) on every change, apart from the
// placements' own redraw (RenderPlacementsIfChanged); they never rebuild the names.
var shownLabels = labels;
Action showSettlementControl = () => shownLabels.SetSettlementControl(bridge.State.Settlements);
bridge.Changed += showSettlementControl;
owned.Add(new Undo(() => bridge.Changed -= showSettlementControl));
showSettlementControl();
mini.Clicked += (lon, lat) => { camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); cameraController.Settle(); SyncMinimap(); labels?.Refresh(); }; // the click may come after LateUpdate (review M6)
// The minimap's whole-map button: the camera's own farthest zoom, over the middle of the map (no new rule).
mini.Overview += () =>
{
var (lon, lat) = mini.Centre;
camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); camRig.Distance = CameraController.MaxDistance;
cameraController.Settle(); SyncMinimap(); labels?.Refresh();
};
mini.BordersChanged += ShowLayerLabel;
ShowLayerLabel(); // #2227: the caption was set before this minimap was made; a restart keeps borders the player hid
Action onChanged = RenderPlacementsIfChanged;
bridge.Changed += onChanged;
// One console line per turn, so a browser run (reload, Continue) can be checked against the hash.
Action<IReadOnlyList<Rejection>> onTurn = _ =>
Debug.Log(FormattableString.Invariant($"TURN {bridge.State.Turn} {bridge.State.Date:yyyy-MM-dd} hash {bridge.State.Hash()}"));
bridge.TurnEnded += onTurn;
logCamera = CameraLogRequested();
loggedDistance = loggedYaw = float.NaN;
owned.Add(new Undo(() =>
{
bridge.Changed -= onChanged;
bridge.TurnEnded -= onTurn;
pointer.HexClicked -= onHex;
pointer.HexOrdered -= onOrder;
if (pointer.PillHex == pillHex) pointer.PillHex = null;
if (pointer.IsOverUi == pointerOverUi) pointer.IsOverUi = null;
if (cameraController.IsOverUi == overUi) cameraController.IsOverUi = null;
if (cameraController.HoldsMouseDrag == holdsMouseDrag) cameraController.HoldsMouseDrag = null;
if (cameraController.HoldsTouchDrag == holdsTouchDrag) cameraController.HoldsTouchDrag = null;
if (cameraController.ScreenTakesUpDown == screenTakesUpDown) cameraController.ScreenTakesUpDown = null;
if (cameraController.ScreenCoversMap == screenCoversMap) cameraController.ScreenCoversMap = null;
if (pointer.Map == map) { pointer.Map = null; pointer.View = null; }
cameraController.Bounds = oldBounds;
cameraController.Ground = oldGround; cameraController.GroundTop = oldTop;
}));
drawn = null; drawnSites = null;
RenderPlacementsIfChanged();
SyncMinimap();
// The opening (#530): three sourced stills after New Game and before the first turn, skippable, and replayable
// from the start screen. It reads no sim state. A player build shows it only once its text and photographs are
// reviewed (OpeningContent.MayPresent); the Editor shows the draft with a visible preview label, for QA.
// A panel with a clip plays it after its photograph (owner ruling of 2 November 2026, OpeningPresenter).
var replayOpening = root.Q<Button>("start-opening-replay");
replayOpening.style.display = DisplayStyle.None;
if (enableOpening && OpeningContent.Load() is OpeningContent openingSource)
{
var openingData = openingSource.Read();
#if UNITY_EDITOR
const bool editorPreview = true;
#else
const bool editorPreview = false;
#endif
if (OpeningContent.MayPresent(openingData, editorPreview))
{
// A new game's opening hands over to the advisors' opening chain when it closes; a replay returns to
// the start screen. Closing the scene disposes it after the camera is gone, hence the null check.
opening = Own(new OpeningPresenter(root, openingSource, openingData, text,
shown => { if (cameraController != null) cameraController.enabled = !shown && start?.IsOpen != true; },
replay => { if (!replay) PlayNewGameIntro(); },
video == null ? null : Own(new CardVideo()))); // its own player: no clip in the automated runs either
replayOpening.text = text["opening.replay"];
replayOpening.style.display = DisplayStyle.Flex;
Action replayClick = () => { if (start?.IsOpen == true) opening?.Show(replay: true); };
replayOpening.clicked += replayClick;
owned.Add(new Undo(() => replayOpening.clicked -= replayClick));
}
}
// The Tel Aviv raid card (owner, 8 Nov 2026, "Film, raid, card, advisors (Recommended)"): on New game only, after
// the opening and before the turn 1 advisor chain, which its OK starts (PlayNewGameIntro). It reads no sim state.
// A player build shows it only once it is reviewed (RaidCardContent.MayPresent); the Editor shows the labelled draft.
if (enableRaid && RaidCardContent.Load() is RaidCardContent.Document raidData)
{
#if UNITY_EDITOR
const bool raidPreview = true;
#else
const bool raidPreview = false;
#endif
if (RaidCardContent.MayPresent(raidData, raidPreview))
raid = Own(new RaidCardPresenter(root, raidData, text,
shown => { if (cameraController != null) cameraController.enabled = !shown && start?.IsOpen != true; },
() => advisor?.NewGame(),
video == null ? null : Own(new CardVideo()))); // its own player: no clip in the automated runs either
}
// The Dakotas' raid before that card (#3000, PR 2 of #2968; the Dakotas by "Reuse Dakotas (Recommended)"): only where
// the card shows, and only with video on, so never in the automated runs (CardVideo.ForcedOff) nor in EditMode but
// where a test asks for it (RaidFlightInEditMode). It flies the Dakotas already on the map (DakotaRaidFlight) and
// reads no sim state; a click or Escape skips it, and the card follows either way (PlayNewGameIntro).
if (raid != null && video != null && (Application.isPlaying || RaidFlightInEditMode))
{
Func<Action, Action?> fly = RaidFlightForTests ?? (ended =>
{
if (!Application.isPlaying || !Statecraft.Game.Map.Collection.DakotaRaidFlight.Start()) return null;
var poll = root.schedule.Execute(() => { if (Statecraft.Game.Map.Collection.DakotaRaidFlight.Over) ended(); }).Every(100);
return () => { poll.Pause(); Statecraft.Game.Map.Collection.DakotaRaidFlight.Stop(); };
});
raidFlight = Own(new RaidFlightPresenter(root, fly,
shown => { if (cameraController != null) cameraController.enabled = !shown && start?.IsOpen != true; },
() => raid?.Show()));
}
// The start screen goes up in the same frame the loading state ends, so the HUD never flashes before it. While it
// shows, the camera keys are off (keyboard pan would otherwise move the hidden map; plan amendment A4).
if (showsStart) // newGame is made above whenever smoke == 0
{
var cam = cameraController;
var recording = Own(new DeclarationRecording(root, text, toast.RecordingFailed, retry: toast.RecordingRetried)); // 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) PlayNewGameIntro(); }
}, recording, text, SettingsFile(), switchLanguage));
start.Show();
}
// It shows by itself only where the start screen does (never in the automated runs, nor under ?firstcard, which
// times the first card) and a settings file remembers that it has; the encyclopedia opens it again anywhere. Steps 2
// and 3 show its city as a click there would, without selecting a unit on the city's hex; step 4 shows a unit
// that can move, its ring and its card, as a click on it would (OnHexClicked), and centres the camera on its hex.
Action showCity = () =>
{
if (AdvisorTargets.CityHex(bridge.Content, bridge.State) is not (int q, int r)) return;
unitLayer.Select(null); map.Select(q, r); info.Show(q, r);
var cityHex = bridge.Content.HexAt(q, r);
if (cityHex != null)
{
camRig.LookAt = map.Frame.ToWorld(cityHex.Lon, cityHex.Lat, 0);
cameraController.Settle(); SyncMinimap(); labels?.Refresh();
}
};
Action showUnit = () =>
{
if (AdvisorTargets.UnitToShow(bridge, unitLayer.Tokens.Select(t => t.Token)) is not string id) return;
camRig.Distance = Mathf.Min(camRig.Distance, AdvisorTargets.MoveStepDistanceM);
FocusUnit(id);
};
// When it closes, the advisor puts back the selection it found (a hex, a unit, a pioneer group's card, or none),
// unless the player has picked something else meanwhile (the HUD stays usable under it).
Func<Action> keepSelection = () =>
{
// A pioneer card has no token (ShowPioneer clears it), so it is a selection of its own, kept with its game
// (review of #1788): a language switch keeps the session, a load or new game does not.
var pioneer = info.Pioneer; var pioneerSession = bridge.Session;
var hex = info.ShowsUnit ? null : info.Selected;
var unit = info.ShowsUnit ? unitLayer.Selected : null;
var city = AdvisorTargets.CityHex(bridge.Content, bridge.State);
var shownUnit = AdvisorTargets.UnitToShow(bridge, unitLayer.Tokens.Select(t => t.Token));
// It reads the UI of the Begin it runs in, so after a language switch rebuilt the UI it still puts back what
// the advisor found before (AdvisorSession.ChainState.PutBack).
return () =>
{
if (this.info is not { } nowInfo || this.units is not { } nowUnits) return;
// Under a screen, or the player picked another than the advisor's city or unit: kept.
if (nowInfo.Covered || (nowInfo.ShowsUnit ? nowUnits.Selected != shownUnit : nowInfo.Selected != city)) return;
if (pioneer is int pioneerId && Bridge?.Session == pioneerSession)
{
nowInfo.ShowPioneer(pioneerId); // clears the token and the hex outline, as a click on its link does
if (nowInfo.Pioneer == pioneerId) return;
}
nowUnits.Select(unit);
if (nowUnits.Selected != null) { map.ClearSelection(); nowInfo.ShowUnit(); }
else if (hex is (int q, int r)) { map.Select(q, r); nowInfo.Show(q, r); }
else { map.ClearSelection(); nowInfo.Clear(); }
};
};
// The advisors' popup, over the session made before Settings (above).
advisor = Own(new AdvisorPresenter(root, bridge, text, AdvisorSession, portraits,
new AdvisorHooks
{
Card = card, OpenScreen = s => nav?.Open(s), CloseScreens = () => nav?.Close(), ShowCity = showCity, ShowUnit = showUnit, KeepSelection = keepSelection,
OpenPage = p => encyclopedia?.Open(p),
MapTarget = () =>
{
(int q, int r)? selected = info.Selected;
if (info.ShowsUnit)
{
var token = unitLayer.Tokens.FirstOrDefault(t => t.Token.Unit.Id == unitLayer.Selected);
selected = token.Token != null ? (token.Q, token.R) : ((int, int)?)null;
}
if (selected is not (int q, int r) || root.panel == null || bridge.Content.HexAt(q, r) is not { } hex) return null;
var ground = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);
ground.y = map.Terrain.SampleHeight(ground) + map.Terrain.transform.position.y;
var camera = Camera.main;
if (camera == null) return null;
var viewport = camera.WorldToViewportPoint(ground);
if (viewport.z <= 0) return null;
var at = MapLabelsPresenter.ToPanel(viewport, camera.rect, root.panel.visualTree.layout.size, Vector2.zero);
return new Rect(at, Vector2.one);
},
}));
budget.UnsubmittedChanged += advisor.BudgetUnsubmitted;
// A kept draft (#2708) said "unsubmitted" while the screen was built, before this line listened: the advisor
// takes that state without a second Notice, so a put-off budget warning is not pruned after a language switch.
advisor.HoldsBudgetUnsubmitted = bridge.BudgetUnsubmitted(budget.Draft);
// The advisors' encyclopedia (spec 10), which replaces How to play: after the advisor, whose Show me and opening
// chain its buttons call; an advisor's Tell me more opens its pages (OpenPage above).
encyclopedia = Own(new EncyclopediaPresenter(root, text, AdvisorSession.Catalog, nav!, advisor, bridge.Content.Ruleset));
if (video != null)
advisor.Media = new AdvisorMedia(text, new ClipPicture(video), new StillPicture(), DeclarationRecording.WebFetch, new DeclarationRecording.SourceOutput());
// A new game, from the start screen or the top bar's New game, plays the opening first when there is one.
if (newGame != null)
{
// The start screen's no-save New Game has no Started; its closing already starts the advisors when there
// is no opening, so that route only plays the opening.
Action freshGame = () => { if (opening != null) opening.Show(replay: false); else PlayNewGameIntro(); };
Action freshOpened = () => opening?.Show(replay: false);
// #2712: a New Game keeps the map, so the camera goes back to the opening view here, as MapScene.Build sets it
// at boot: Tel Aviv and Jaffa in frame at the start zoom.
Action openingView = () =>
{
var cam = cameraController.GetComponent<Camera>();
camRig.LookAt = CameraRig.OpeningLookAt(map.Frame, cam.aspect,
map.Settlements.Single(s => s.Id == "tel_aviv"), map.Settlements.Single(s => s.Id == "jaffa"));
camRig.Distance = CameraRig.StartDistance;
cameraController.Settle(); SyncMinimap(); labels?.Refresh();
};
newGame.Started += openingView;
newGame.Started += freshGame;
if (start != null) start.FreshGameOpened += freshOpened;
owned.Add(new Undo(() =>
{
newGame.Started -= openingView;
newGame.Started -= freshGame;
if (start != null) start.FreshGameOpened -= freshOpened;
}));
}
if (hebrew) direction = Own(new UiDirection(root, bridge));
root.Q("root")?.RemoveFromClassList("loading"); // ready: the bar, panels and screens may show (P2-1)
if (setCompanion != null && CompanionWanted()) setCompanion(true);
DiagLog.BootPhase("screens ready");
if (notes.Count > 0) toast.Show(notes);
Statecraft.Game.Map.Collection.CollectionStream.GameReady();
Debug.Log(FormattableString.Invariant($"GAME OK {bridge.State.Date:yyyy-MM-dd} turn {bridge.State.Turn} hash {bridge.State.Hash()}"));
// Unlike the other browser instruments, ?firstcard keeps the normal start screen, clip mapping and video players.
// It closes the screen through its real button immediately, then gives tools/web_check.py a bounded result to
// wait for. Console exceptions are collected by that browser-side check (#910).
if (Application.isPlaying && FirstCardCheckRequested())
StartCoroutine(FirstCardCheck(root, card!, Debug.Log));
if (smoke > 0)
{
if (Application.isPlaying) StartCoroutine(smokeOrders ? SmokeOrders(root, bridge, unitLayer, (q, r) => onHex(q, r, false), Debug.Log) : Smoke(root, bridge, card!, smoke, Debug.Log));
else Debug.LogWarning("SMOKE FAIL the smoke run needs play mode or a player");
}
if (Application.isPlaying && PixelErrorProfile.Requested()) StartCoroutine(PixelErrorProfile.Run(map.Terrain));
// The unit art slice at gameplay03 (a showcase, never in normal play; war mode's units are issue #104). Before the
// instruments, so the frame profile lists its "unitshowcase" toggle (the profile reads the toggles when it starts).
if (Application.isPlaying && Statecraft.Game.Map.Units.UnitShowcase.Requested())
Statecraft.Game.Map.Units.UnitShowcase.Spawn(map, Statecraft.Game.Map.Units.UnitShowcase.StillRequested(
Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer));
// The border renderer's synthetic, labelled proof (?borderproof / -borderproof): development builds only.
if (Application.isPlaying && BorderProof.Requested()) BorderProof.Show(map);
// The visual track's instruments (docs/visual-v1.md): both move the camera, so one per run.
if (Application.isPlaying && FrameProfile.Requested())
StartCoroutine(FrameProfile.Run(camRig, map.Frame, Debug.Log, Application.platform != RuntimePlatform.WebGLPlayer));
else if (Application.isPlaying && VisualShots.Requested()) StartCoroutine(VisualShots.Run(camRig, map.Frame, Debug.Log));
}
/// <summary>The language switch of Settings (#1036) and of the start screen (#2054): every screen again in
/// <paramref name="language"/> at once, no reload, over the same game with this turn's orders (Begin's keep), and the
/// place it was pressed in open again with the focus on the choice just made (for a mouse press too: the rebuilt UI
/// has no focus to keep): the start screen, offering Continue only if it did and repeating its save notices in the
/// new language, or else Settings. Not in a smoke run (smokeRun).</summary>
void SwitchLanguage(GameInputs inputs, string language)
{
if (Bridge == null || smokeRun) return;
Language = language;
endClosed = end != null && !end.IsOpen; // read before Begin disposes it
bool fromStart = start?.IsOpen == true;
keptResumed = start?.Resumed ?? true;
keptBudgetDraft = budgetScreen?.Draft; // read before Begin disposes it; the new screen copies it
// #2340: the selection, read before Begin disposes the panel and the unit layer (a pioneer card has no token).
var pioneer = info?.Pioneer;
var unit = info?.ShowsUnit == true ? units?.Selected : null;
var hex = info?.ShowsUnit == true ? null : info?.Selected;
// #2340: the card or capture dialog the player hid; the rebuilt presenters would open it again.
var hiddenCard = card?.Collapsed == true ? card.Shown!.Id : null;
var hiddenCapture = capture?.Collapsed == true ? capture.Shown : null;
// #2202: a turn report waiting for the enemy's moves (or for the screen opened over them). The rebuild ends the
// moves, and the rebuilt report would never hear of the turn (#2967 review, S2).
bool reportWaiting = report?.Waiting == true;
// Cleared even if Begin throws, so the next ordinary Begin (a New game, a load) never picks it up.
try { Begin(inputs, 0, startScreen: fromStart, keep: Bridge); }
finally { keptBudgetDraft = null; }
// Hidden again before the selection is put back: an open card or dialog disables the info panel (ScreenNav).
if (hiddenCard != null && card?.Shown?.Id == hiddenCard) card.Collapse(takeFocus: false);
if (hiddenCapture != null && capture?.Shown == hiddenCapture) capture.Collapse(takeFocus: false);
// Put back before Settings opens again: a screen that covers the panel would ignore it. The map's hex outline
// outlives Begin, so it is set to match (before, the new panel showed nothing under the old outline).
if (info != null && units != null)
{
if (pioneer is int pioneerId) info.ShowPioneer(pioneerId); // clears the token and the outline itself
else
{
units.Select(unit);
if (units.Selected != null) { map.ClearSelection(); info.ShowUnit(); }
else if (hex is (int q, int r)) { map.Select(q, r); info.Show(q, r); }
else map.ClearSelection();
}
}
if (!fromStart) nav?.Open("settings");
if (reportWaiting) report?.Wait(); // after Settings is open again: the report opens when it closes
// Focus the choice again a frame later: a screen shown this same tick cannot take the focus until its
// styles resolve, and a bare Focus() then leaves it wherever it was (#1915's tour test read end-turn).
if (document.rootVisualElement.Q<Button>((fromStart ? "start-language-" : "settings-language-") + language) is Button choice)
{
choice.Focus();
choice.schedule.Execute(() => { if (choice.panel != null) choice.Focus(); });
}
}
/// <summary>The 1948 localities in a hex (by the hex their point lies in, as the map picks hexes), for the info panel.</summary>
internal static Func<int, int, IReadOnlyList<Statecraft.Game.Map.Kits.Localities.Place>> LocalitiesAt(MapScene map)
{
var byHex = Statecraft.Game.Map.Kits.Localities.ByHex(map.Localities, p => HexPicker.FromLonLat(p.Settlement.Lon, p.Settlement.Lat, map.Hexes.bounds, map.Hexes.hex_size_km));
IReadOnlyList<Statecraft.Game.Map.Kits.Localities.Place> none = Array.Empty<Statecraft.Game.Map.Kits.Localities.Place>();
return (q, r) => byHex.TryGetValue((q, r), out var l) ? l : none;
}
T Own<T>(T d) where T : IDisposable { owned.Add(d); return d; }
/// <summary>A map click: on a unit's hex it selects the unit (the ring and its card; the hex outline is cleared, so
/// the unit has the promo's one highlight); a second click on it, or a click anywhere else, shows the hex (so a token
/// never hides the hex's map actions). While the card's Move or Attack pick is open (#754), a target click gives the
/// order and keeps the unit's card; any other click ends the pick first and then selects as usual. A selected unit
/// that can move has its Move pick open (InfoPanelPresenter.RenderLines; Civ, owner 25 Oct 2026), so a click on a lit
/// hex moves it; a click on another unit's hex or on a city selects that unit or shows the city, as in Civ, lit or
/// not (owner, 25 Oct 2026: "Clicking another unit or a city still selects it"; a right click moves there:
/// OnHexOrdered).</summary>
internal static void OnHexClicked(MapScene map, Statecraft.Game.Map.Units.UnitLayer units, InfoPanelPresenter info, int q, int r, bool touch = false, bool cityPill = false)
{
if (info.Covered)
{
// A screen covers the panel: the click moves neither the ring nor the card (#210), and MapPointer's outline
// goes back to the hex the panel shows (or away, while it shows a unit).
if (info.Selected is (int sq, int sr) && !info.ShowsUnit) map.Select(sq, sr); else map.ClearSelection();
return;
}
// A friendly token is drawn where the player tapped (its anchor), which can be a neighbour of its sim hex.
var friendDrawn = units.Tokens.Any(t => t.Q == q && t.R == r && t.Token.Unit.Side == Statecraft.Game.Map.Units.UnitData.Israel
&& t.Token.Unit.Id != units.Selected);
var offerMove = info.PrepareFriendlyMove(q, r, friendDrawn);
// #1661: a name pill means the city even when another unit stands there. A badge/terrain or keyboard
// pick keeps the existing unit-first routing; the event carries intent, not a mutable "last hit" flag.
if (cityPill && info.IsCity(q, r))
{
units.Select(null);
info.Show(q, r);
offerMove?.Invoke();
return;
}
var id = units.UnitToSelectAt(q, r);
if (!(info.MovePicking && (id != null || info.IsCity(q, r))) && info.PickTarget(q, r, touch)) { map.ClearSelection(); return; } // the unit keeps its ring, the one highlight
units.Select(id);
if (id != null) { map.ClearSelection(); info.ShowUnit(); }
else info.Show(q, r);
offerMove?.Invoke();
}
/// <summary>Marks the hex under the pointer (<paramref name="under"/>; null: off the map) only where a click would give the
/// open Move or Attack pick's order (PickTakes), else nothing (#2201: a player could not tell which hex a click would
/// take). A hex the pick does not take, such as water, stays unmarked: a click there ends the pick. The camera distance
/// thins the band up close (MapScene.HoverCloseM).</summary>
internal static void MarkHover(MapScene map, InfoPanelPresenter? info, (int q, int r)? under, float cameraDistanceM = float.PositiveInfinity) =>
map.ShowHover(under is (int q, int r) && info != null && info.PickTakesHovered(q, r) ? under : null, cameraDistanceM);
/// <summary>A right click on the map (MapPointer.HexOrdered; owner, 25 Oct 2026, "Civ: select, then click"): while the
/// shown unit's pick takes (q, r), the order a left click there gives (PickTarget), even on another unit's hex.
/// Otherwise nothing: no unit shown, a hex it cannot reach, or a screen over the panel (#210).</summary>
internal static void OnHexOrdered(MapScene map, InfoPanelPresenter info, int q, int r)
{
if (info.Covered || !info.ShowsUnit || !info.PickTakes(q, r)) return;
if (info.PickTarget(q, r)) map.ClearSelection();
}
void FocusPioneer(int id)
{
// ShowPioneer ends military picks/routes and invokes the same map/token cleanup as Escape.
info?.ShowPioneer(id);
}
/// <summary>Selects a drawn unit row, opens its card and centres the camera on its current hex.</summary>
internal void FocusUnit(string rowId)
{
if (units == null || Bridge == null || info == null || rig == null) return;
units.Select(rowId);
if (units.Selected == null) return;
map.ClearSelection(); info.ShowUnit();
var token = units.Tokens.First(t => t.Token.Unit.Id == rowId);
var hex = Bridge.Content.HexAt(token.Q, token.R);
if (hex == null) return;
rig.LookAt = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);
cameraController.Settle(); SyncMinimap(); labels?.Refresh();
}
/// <summary>Selects and focuses the drawn token of sim unit <paramref name="simId"/>; false when no token is drawn for it.</summary>
bool SelectUnit(int simId)
{
if (units == null || Bridge == null) return false;
var row = units.Tokens.FirstOrDefault(t => UnitCard.SimUnit(Bridge.Content, Bridge.State, t.Token) == simId).Token?.Unit.Id;
if (row == null) return false;
FocusUnit(row);
return units.Selected == row;
}
/// <summary>Selects the next unit that needs orders after the selected one (ascending id, wrapping; spec 2026-10-23
/// section 7.3). Never a dead end (owner, v0.3.0 RC: "the game is saying "a unit needs orders" but clicking on it does
/// nothing"): every unit is drawn (UnitPlacer.OnOwnHex), but should one still have no token to select, it is skipped
/// for this turn with a log line and a toast, and the next is tried, so End turn always gets on. Each unit is tried
/// once per call.</summary>
void FocusNextUnit()
{
if (Bridge == null || units == null || Bridge.NeedsOrders.Count == 0) return;
// An open event card is modal and disables the unit card (ScreenNav.DisableCovered), so the unit End turn selects
// could take no order: the card waits behind "Decision waiting", as its Hide button does.
card?.Collapse(takeFocus: false);
// The capture dialog is modal like the card (#802): End turn must show a unit that can take an order (#1680).
capture?.Collapse(takeFocus: false);
// A side screen can still cover the card (#210). Reveal it through normal navigation, not by
// bypassing Covered: End turn must show the unit whose orders it asks for (#1680).
if (info?.Covered == true) nav?.Open(null);
int? current = units.Selected is string row
? units.Tokens.Where(t => t.Token.Unit.Id == row).Select(t => UnitCard.SimUnit(Bridge.Content, Bridge.State, t.Token)).FirstOrDefault()
: null;
var needs = Bridge.NeedsOrders;
var order = current is int id ? needs.Where(n => n > id).Concat(needs.Where(n => n <= id)).ToList() : needs.ToList();
foreach (var next in order)
{
if (SelectUnit(next)) return;
Debug.Log($"END TURN unit {next} needs orders but has no token to select; skipped this turn");
Bridge.Skip(next);
unseenSkipped?.Invoke(); // after Skip: the toast clears on every bridge change
}
}
/// <summary>#1063 (player report: a city is hard to tell from the land round it and hard to click): the city under a
/// hovering pointer, on its hexes or its name pill, lights its pill and turns the browser's pointer into a hand, so the
/// player sees it can be clicked. Null (and nothing lit) over the UI, off the map, off every city, or with no hovering
/// pointer (a touchscreen). Returns that city's id; called each frame (LateUpdate), it changes the UI only when the city does.</summary>
internal string? HoverCity(Vector2? screenYUp)
{
var under = screenYUp is Vector2 p ? pointer.HexAt(p) : null;
return HoverCity(screenYUp, under);
}
internal string? HoverCity(Vector2? screenYUp, (int q, int r)? under)
{
string? city = null;
if (screenYUp.HasValue && under is (int q, int r) && Bridge != null && citiesByHex.TryGetValue((q, r), out var ids))
foreach (var id in ids) if (Bridge.State.Cities.ContainsKey(id)) { city = id; break; }
if (city == hoveredCity) return city;
hoveredCity = city;
labels?.Highlight(city);
HandCursor(city != null);
return city;
}
internal void UpdateMapHover(Vector2? hover)
{
labels?.Hover(hover);
var under = hover is Vector2 at ? pointer.HexAt(at) : null;
HoverCity(hover, under);
if (under is (int q, int r)) info?.ShowRouteTo(q, r);
else if (UnityEngine.InputSystem.Pointer.current is UnityEngine.InputSystem.Mouse) info?.HideRoute();
MarkHover(map, info, under, rig != null ? rig.Distance : float.PositiveInfinity);
}
/// <summary>The city with a settlement hex at (q, r): one in State.Cities, whose hex opens the city panel (GddHexPanel); or null.</summary>
internal static string? CityAt(Content c, GameState s, int q, int r)
{
foreach (var x in c.SettlementHexes) if (x.Q == q && x.R == r && s.Cities.ContainsKey(x.Id)) return x.Id;
return null;
}
#if UNITY_WEBGL && !UNITY_EDITOR
[System.Runtime.InteropServices.DllImport("__Internal")] static extern void StatecraftHandCursor(int on); // HandCursor.jslib
static void HandCursor(bool on) => StatecraftHandCursor(on ? 1 : 0);
#else
static void HandCursor(bool on) { } // the game ships as the browser build; the editor keeps its own cursor
#endif
// R-CAMERA-001: exact ruleset identity; gdd-0.1 retains orbit.
internal static void ConfigureCameraHeading(CameraController controller, string ruleset) =>
controller.SetFixedNorth(CameraHeadingPolicy.IsFixedNorth(ruleset));
/// <summary>What a new game plays after its opening, or at once without one (owner, 8 Nov 2026, "Film, raid, card,
/// advisors (Recommended)"): the raid card, whose OK starts the turn 1 advisor chain; the chain at once when there is no
/// card. Never on Continue or a load (the start screen's close calls Resume then). New game can report one game twice
/// (the start screen's close and Started); RaidCardPresenter.Show and AdvisorPresenter.NewGame both ignore the second,
/// and so does this while the raid flight (#3000) or the card it leads to is up. The flight, where there is one, flies
/// first and shows the card when it ends or is skipped.</summary>
void PlayNewGameIntro()
{
if (shuttingDown || raidFlight?.IsOpen == true || raid?.IsOpen == true) return;
if (raidFlight != null) raidFlight.Show();
else if (raid != null) raid.Show();
else advisor?.NewGame();
}
/// <summary>Disposes every presenter, the autosave and the camera/pointer hooks (newest first). Safe to call twice.</summary>
/// <param name="keepCompanionPage">A rebuild whose next companion replaces the page's panel: the old one goes without
/// clearing it, so the panel does not blink, the canvas is not resized twice and the status is not read again.</param>
void Shutdown(bool keepCompanionPage = false)
{
StopAllCoroutines();
shuttingDown = true;
// The card first: disposing the start screen uncovers the decision layer, and a card still waiting for it would
// then render and load the photo catalog for a game that is going away (#592; since the GDD cutover a new game's
// card waits under the screen, so New Game's Begin would load it).
// The advisors before the card: a card going away is a layer closing, which must not make a popup that is itself
// going away draw its step again and show its city or unit on a camera being destroyed.
if (advisor != null) { owned.Remove(advisor); advisor.Dispose(); }
if (card != null) { owned.Remove(card); card.Dispose(); }
if (keepCompanionPage && companion != null) { owned.Remove(companion); companion.Dispose(clearPage: false); }
for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();
owned.Clear();
savePersistenceResult = null;
if (hoveredCity != null) { hoveredCity = null; HandCursor(false); } // the next Begin's pills start unlit
companion = null; minimap = null; unseenSkipped = null; labels = null; nav = null; start = null; opening = null; raidFlight = null; raid = null; card = null; outcomes = null; playback = null; report = null; direction = null; end = null; advisor = null; cabinet = null; budgetScreen = null; newGame = null; encyclopedia = null; feedback = null; share = null; info = null; rig = null; drawn = null; drawnSites = null; units = null; Regions = null; logCamera = false;
// A ?profile run cut short (a stopped coroutine never reaches its restore line) must not leave the terrain at the
// profile's pixel error (Task 24 review M1). Nothing else changes it, so restoring is always right.
if (map != null && map.Terrain != null) map.Terrain.heightmapPixelError = MapBuilder.TerrainPixelError;
shuttingDown = false;
}
/// <summary>Draws the placements only when State.Placements with the built city projects (PlacementLayer.Drawn, #1123)
/// differs from what was drawn (every order and every turn raises Changed; rebuilding the markers each time would be
/// wasted work). A project finishing redraws though State.Placements did not change.</summary>
Statecraft.Game.Map.Collection.SeaAirCollection? seaAir; // the 1948 Collection's craft (#669), for the labels to keep clear of
readonly KeepClearLists keepClear = new KeepClearLists();
/// <summary>The names' keep-clear boxes (MapLabelsPresenter's keepClear): the unit tokens', the 1948 Collection's craft
/// (#669) and the arms workshops' b21 (#1701 slice F). One list when only one has boxes; else one merged list, kept
/// until one of them is a new list, so the labels see a new list (and refresh) exactly when one changes. The layers
/// publish a new list on every change, never changing one already handed out.</summary>
internal sealed class KeepClearLists
{
IReadOnlyList<Bounds[]>? keptTokens, keptCraft, keptWorkshops, kept;
public IReadOnlyList<Bounds[]>? Merge(IReadOnlyList<Bounds[]>? tokens, IReadOnlyList<Bounds[]>? craft, IReadOnlyList<Bounds[]>? workshops)
{
bool t = tokens != null && tokens.Count > 0, c = craft != null && craft.Count > 0, w = workshops != null && workshops.Count > 0;
if ((t ? 1 : 0) + (c ? 1 : 0) + (w ? 1 : 0) <= 1) return c ? craft : w ? workshops : tokens;
if (kept == null || !ReferenceEquals(tokens, keptTokens) || !ReferenceEquals(craft, keptCraft) || !ReferenceEquals(workshops, keptWorkshops))
{
keptTokens = tokens; keptCraft = craft; keptWorkshops = workshops;
var merged = new List<Bounds[]>();
if (t) merged.AddRange(tokens!);
if (c) merged.AddRange(craft!);
if (w) merged.AddRange(workshops!);
kept = merged;
}
return kept;
}
}
Statecraft.Game.Map.Collection.SpecialBuildingModels? special; // the arms workshops' b21, for the labels to keep clear of
void RenderPlacementsIfChanged()
{
if (Bridge == null) return;
// ?turnlog (#2905): each layer's time during End turn, as one "@Layer" section each; otherwise no clock is read.
var probe = TurnProbe.Start();
// Dated routes (the Burma Road from June 1948); in the GDD loop the corridors by their built segments (#792).
Statecraft.Game.Map.Routes.RouteLayer.ShowAt(map, Bridge.State.Date,
Bridge.Content.IsGdd ? Statecraft.Game.Map.Routes.RouteLayer.BuiltSegments(Bridge.Content, Bridge.State) : null);
probe = TurnProbe.Lap("RouteLayer", probe);
// The true armistice lines (#237; on unless "noarmisticelines" turns them off, #196), each from its own date.
ArmisticeLines.ShowAt(map, Bridge.State.Date);
probe = TurnProbe.Lap("ArmisticeLines", probe);
// Tal Heuberger's whole-town models on their towns far off (#663, "Whole model far, buildings near"), streamed after the first frame; the ma'abara from its date.
// The camps and housing built as city projects bring theirs too, as the placement layer draws them (#1275).
Statecraft.Game.Map.Collection.TownLandmarks.ShowAt(map, Bridge.State.Date,
PlacementLayer.Drawn(Bridge.State.Placements, Bridge.State.CityProjects.Values), Bridge.Content);
probe = TurnProbe.Lap("TownLandmarks", probe);
// Tal Heuberger's ibex and striped hyena, sparse in their sourced terrain zones and visible only at close zoom (#670).
Statecraft.Game.Map.Collection.WildlifeLayer.Show(map);
probe = TurnProbe.Lap("WildlifeLayer", probe);
// Tal Heuberger's papyrus at the Hula swamp's sourced site, close up only, streamed on the first close view, gone
// once the swamp is drained (#2082; owner, 2 November 2026: "Hula + Arava, map and boards").
Statecraft.Game.Map.Collection.HulaPapyrusLayer.ShowAt(map, Bridge.Content,
Statecraft.Game.Map.Collection.HulaPapyrusLayer.Drained(Bridge.State));
probe = TurnProbe.Lap("HulaPapyrusLayer", probe);
// A plowed field's or drained swamp's ground on its hex (#2877): from the sites, so a loaded save shows its own.
SiteGroundLayer.ShowAt(map, Bridge.Content, Bridge.State.Sites.Values);
probe = TurnProbe.Lap("SiteGroundLayer", probe);
// Tal Heuberger's civilian figures at towns, villages, transit camps and building sites, ambience only and streamed
// after the first frame (#666, #708, #886): the residents follow the settlement state, the builders the projects.
Statecraft.Game.Map.Collection.CivilianPeople.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content,
Bridge.State.Settlements, Bridge.State.CityProjects.Values);
probe = TurnProbe.Lap("CivilianPeople", probe);
// Tal Heuberger's period-generic farm and village scenery, streamed after the first frame (#667); never game units.
Statecraft.Game.Map.Collection.RuralLife.Show(map);
probe = TurnProbe.Lap("RuralLife", probe);
// Tal Heuberger's Tegart fort, barracks and factory at their sourced places and dates, close up only, streamed (#707);
// under gdd-0.3 their artisan workshop (b21) on each built arms workshop's hex (#1701 slice F).
var workshops = Statecraft.Game.Map.Collection.SpecialBuildingModels.ArmsWorkshops(Bridge.Content, Bridge.State.CityProjects.Values);
special = Statecraft.Game.Map.Collection.SpecialBuildingModels.ShowAt(map, Bridge.State.Date, workshops);
probe = TurnProbe.Lap("SpecialBuildingModels", probe);
// Tal Heuberger's hex-tile props (owner, 27 October 2026: "2+3"; 2 November 2026: "Every zoom" for the landmarks): their
// minarets, belfries and Jaffa's clock tower in place of the kit's at every zoom, so the bundle streams after the first
// frame; the stations, camp tents, village hedges and hill scatter close up only, built at the first close camera.
// After the layers they keep clear of (the built arms workshops' b21 too, #1701 slice F).
Statecraft.Game.Map.Collection.HexPropModels.ShowAt(map, Bridge.State.Date, workshops);
probe = TurnProbe.Lap("HexPropModels", probe);
// Tal Heuberger's ships off Haifa, Jaffa, Acre and (on the Altalena's turn) Tel Aviv, and the C-54 at Lod, streamed after the first frame (#669).
seaAir = Statecraft.Game.Map.Collection.SeaAirCollection.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content);
probe = TurnProbe.Lap("SeaAirCollection", probe);
RenderSitesIfChanged();
probe = TurnProbe.Lap("Sites", probe);
var shown = PlacementLayer.Drawn(Bridge.State.Placements, Bridge.State.CityProjects.Values);
var now = shown.Select(p => (p.Action, p.Q, p.R, p.Date)).ToList();
if (drawn != null && drawn.SequenceEqual(now)) { TurnProbe.Lap("Placements", probe); return; }
drawn = now;
placements.Render(shown, Bridge.Content, map);
TurnProbe.Lap("Placements", probe);
}
/// <summary>Draws the designated sites (#381) only when a site's state differs from what was drawn: being built, or
/// built on its date.</summary>
void RenderSitesIfChanged()
{
if (Bridge == null) return;
var now = Bridge.State.Sites.Values.Select(w => w.Site + ":" + (w.BuiltOn?.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) ?? "building")).ToList();
if (drawnSites != null && drawnSites.SequenceEqual(now)) return;
drawnSites = now;
if (siteLayer == null)
{
siteLayer = new GameObject("Sites").AddComponent<SiteLayer>();
siteLayer.transform.SetParent(placements.transform.parent, false);
}
siteLayer.Render(Bridge.State.Sites.Values, Bridge.Content, map);
// A built site's name is a map pill like a town's (#381), against its kit's columns.
labels?.SetSites(siteLayer.Places.Select(p => (p, siteLayer.Columns.TryGetValue(p.Id, out var c) ? c : (Bounds[]?)null)).ToList());
}
void SyncMinimap()
{
if (minimap == null || rig == null) return;
minimap.SetView(map.Frame, rig.LookAt, rig.Distance);
}
bool logCamera;
float loggedDistance = float.NaN, loggedYaw = float.NaN;
/// <summary>"camlog" in the WebGL page URL (a whole query parameter) or -camlog on desktop: log the camera distance and
/// yaw whenever they change (checks the wheel-zoom step in a real browser).</summary>
internal static bool CameraLogRequested(string? url, string[] args, bool webgl) =>
webgl ? UrlFlags.Has(url, "camlog") : Array.IndexOf(args, "-camlog") >= 0;
static bool CameraLogRequested() =>
CameraLogRequested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
internal static string CameraLine(float distance, float yaw) => FormattableString.Invariant($"CAMERA distance={distance:0} yaw={yaw:0.0}");
/// <summary>"firstcard" asks a player build to exercise the first card through the normal media path. It deliberately
/// is not one of StartScreenPresenter.Skipped or CardVideo.ForcedOff's automation flags.</summary>
internal static bool FirstCardCheckRequested(string? url, string[] args, bool webgl) =>
webgl ? UrlFlags.Has(url, "firstcard") : Array.IndexOf(args, "-firstcard") >= 0;
internal static bool FirstCardCheckRequested() =>
FirstCardCheckRequested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
/// <summary>Closes a fresh game's start screen at once through New Game and waits at most
/// <see cref="FirstCardBudgetSeconds"/> seconds for an enabled option plus the archival photograph or documented
/// minister-portrait fallback. The browser check treats FIRST CARD FAIL and console exceptions as failures.</summary>
internal static IEnumerator FirstCardCheck(VisualElement root, EventCardPresenter card, Action<string> log,
Func<double>? now = null)
{
now ??= () => Time.realtimeSinceStartupAsDouble;
var began = now();
var hud = root.Q("root") ?? root;
if (!hud.ClassListContains(StartScreenPresenter.OpenClass))
{
log("FIRST CARD FAIL start screen is not open");
yield break;
}
if (!Press(root.Q<Button>("start-new-game"), s => log(s.Replace("SMOKE FAIL", "FIRST CARD FAIL")))) yield break;
// A reviewed opening is part of the normal media path: the instrument uses its actual Skip control.
if (hud.ClassListContains(OpeningPresenter.OpenClass)
&& !Press(root.Q<Button>("opening-skip"), s => log(s.Replace("SMOKE FAIL", "FIRST CARD FAIL")))) yield break;
// So is the raid flight after it (RaidFlightPresenter, #3000): skipped as a player's Escape skips it; the card follows.
if (hud.ClassListContains(RaidFlightPresenter.OpenClass))
{
var flight = root.Q("raid-flight-layer");
using (var cancel = NavigationCancelEvent.GetPooled()) { cancel.target = flight; flight.SendEvent(cancel); }
if (hud.ClassListContains(RaidFlightPresenter.OpenClass)) { log("FIRST CARD FAIL the raid flight did not skip"); yield break; }
}
// So is the raid card after it (RaidCardPresenter): its only control, OK.
if (hud.ClassListContains(RaidCardPresenter.OpenClass)
&& !Press(root.Q<Button>("raid-ok"), s => log(s.Replace("SMOKE FAIL", "FIRST CARD FAIL")))) yield break;
while (now() - began <= FirstCardBudgetSeconds)
{
var option = root.Q<VisualElement>("event-options")?.Q<Button>();
bool photo = root.Q<VisualElement>("event-photo")?.style.display.value == DisplayStyle.Flex;
bool portrait = root.Q<VisualElement>("event-image")?.style.display.value == DisplayStyle.Flex;
if (!hud.ClassListContains(StartScreenPresenter.OpenClass) && card.Shown != null && !card.Collapsed &&
!card.PhotoWaits && option != null && option.enabledInHierarchy && (photo || portrait))
{
var wait = (now() - began) * 1000;
log(FormattableString.Invariant($"FIRST CARD OK event={card.Shown.Id} media={(photo ? "photo" : "portrait fallback")} wait={wait:0} ms budget={FirstCardBudgetSeconds * 1000:0} ms"));
yield break;
}
yield return null;
}
log(FormattableString.Invariant($"FIRST CARD FAIL not interactive after {FirstCardBudgetSeconds * 1000:0} ms"));
}
/// <summary>After every Update (CameraController moves the camera in its Update), so the pills never trail the camera.</summary>
void LateUpdate()
{
if (labels == null) return;
labels.Refresh();
// Today's name under a 1948 locality's pill: while a mouse (or pen) is over it (owner ruling 2026-10-11), or after a
// tap on it (#245). A touchscreen has no hover: its last touch position stays after the finger lifts.
var hover = MapLabelsPresenter.HoverPosition(UnityEngine.InputSystem.Pointer.current);
UpdateMapHover(hover);
var touch = UnityEngine.InputSystem.Touchscreen.current;
if (touch != null && touch.primaryTouch.press.wasPressedThisFrame) labels.Tap(touch.primaryTouch.position.ReadValue());
}
void Update()
{
// Escape closes the open screen even when no element has the keyboard focus (ScreenNav also takes the UI
// Cancel event from a focused element; closing twice is harmless). On the start screen it withdraws an open New
// Game request (StartScreenPresenter.Escape; idempotent too).
// The advisor handles Escape only while focus is inside its popup.
// With nothing else to close, Escape on the open decision card is Hide (EventCardPresenter.Escape; the card itself
// takes the Cancel event when it has the focus), and so on the open capture dialog (CaptureDialogPresenter.Escape),
// which shows only while the card does not.
// The report panel (#1169) and the share panel (#1170) are over everything: their Escape goes no further.
// Nor does the opening's (#530), over all but those two, in the frame it closes too; nor the raid flight's after it
// (#3000, which shows the card); nor the raid card's after that (its OK).
// Nor does the advisors' popup's, with the focus inside it (AdvisorPresenter.Escape, also in the frame its Cancel closed it).
if (UnityEngine.InputSystem.Keyboard.current?.escapeKey.wasPressedThisFrame == true
&& feedback?.Escape() != true && share?.Escape() != true && advisor?.Escape() != true
&& opening?.ClosedThisFrame != true && opening?.Escape() != true
&& raidFlight?.ClosedThisFrame != true && raidFlight?.Escape() != true
&& raid?.ClosedThisFrame != true && raid?.Escape() != true)
{
bool done = outcomes?.SkipAll() == true || outcomes?.ClosedThisFrame == true;
if (!done) done = advisor?.CloseOverlay() == true || advisor?.OverlayClosedThisFrame == true;
// One press closes one layer, the topmost (#2609): each step below runs only while nothing above took it. The
// start screen covers an ended save's end screen and everything else under it: open, it takes the press,
// withdrawing an armed New Game or doing nothing.
if (!done && start?.IsOpen == true) { start.Escape(); done = true; }
if (!done) done = end?.Close() == true || end?.ClosedThisFrame == true;
if (!done) done = report?.Close() == true || report?.ClosedThisFrame == true;
// Escape in the Cabinet's candidate list goes back to the seat, not out of the screen (#2340 M2). A screen the
// focused element's Cancel already closed this frame took the press too (ClosedThisFrame), as for end and report.
if (!done) done = cabinet?.Escape() == true || nav?.Close() == true || nav?.ClosedThisFrame == true;
// #2202: the Arab forces' moves play on the map, under every screen and overlay: with nothing above them left
// to close, Escape ends them, and nothing else (#2967 review, S1).
if (!done) done = playback?.Skip() == true;
// With nothing above it to close, Escape withdraws a New Game request armed from the top bar too, the start
// screen closed (#2340 L2, #2521), and is used up there, so it does not also clear the map selection. A
// decision card or capture dialog open over it is above it (the top bar stays usable under them): that
// Escape hides the card or dialog and the request stays armed (#2595 review).
if (!done && newGame?.Armed == true)
{
done = capture?.Escape() == true || card?.Escape() == true || card?.CollapsedThisFrame == true;
if (!done) { newGame.Cancel(); done = true; }
}
// A screen/card that consumed this Cancel must not also dismiss the map selection in this frame.
if (!done && nav?.ClosedThisFrame != true && document.rootVisualElement.focusController?.focusedElement == null
&& capture?.Escape() != true && card?.Escape() != true && card?.CollapsedThisFrame != true)
info?.Escape();
}
// PageUp, PageDown, Home and End, with no modifier, scroll the topmost open view (the ending, the turn report, a
// screen, the card's text, the capture dialog or the info panel), with or without focus (KeyScroll; accessibility
// audit H3, K6), but not under an End Turn outcome clip, which covers them. The arrows stay with the camera
// (NavigationGuard, B6), except that Up and Down move between an open screen's rows (audit L4; the owner's answer
// on #2340, Q27: "do the recommended for all"). The UI map reads no keyboard key (B6), so they arrive here.
var keys = UnityEngine.InputSystem.Keyboard.current;
if (keys != null && outcomes?.Showing == null && !(keys.ctrlKey.isPressed || keys.altKey.isPressed || keys.shiftKey.isPressed || keys.leftMetaKey.isPressed || keys.rightMetaKey.isPressed))
{
KeyScroll.Key? page = keys.pageUpKey.wasPressedThisFrame ? KeyScroll.Key.PageUp : keys.pageDownKey.wasPressedThisFrame ? KeyScroll.Key.PageDown
: keys.homeKey.wasPressedThisFrame ? KeyScroll.Key.Home : keys.endKey.wasPressedThisFrame ? KeyScroll.Key.End : (KeyScroll.Key?)null;
if (page != null) KeyScroll.Press(document.rootVisualElement, nav?.Current, card?.Shown != null && !card.Collapsed, page.Value);
// Not under the turn report or the ending: they cover the screen, which ScreenNav.DisableCovered leaves enabled (#2651 review).
if (report?.IsOpen != true && end?.IsOpen != true && (keys.upArrowKey.wasPressedThisFrame || keys.downArrowKey.wasPressedThisFrame))
navGuard?.Step(keys.upArrowKey.wasPressedThisFrame);
}
playback?.Tick(Time.deltaTime); // #2202
SyncMinimap();
if (!logCamera || rig == null || (rig.Distance == loggedDistance && rig.Yaw == loggedYaw)) return;
loggedDistance = rig.Distance; loggedYaw = rig.Yaw;
Debug.Log(CameraLine(rig.Distance, rig.Yaw));
}
/// <summary>Plays turns the way a player does: answers each open event by pressing the card's first option button
/// while the turn's Attention pays for an answer and that option's operation units are in place (R-ENEMY-007), then presses End Turn and closes the turn report it brings (#1037); a card left unanswered goes to its minister
/// (since the GDD cutover, 15 July 1948 brings three cards at full war, where an answer costs 2 of the 4). Logs "SMOKE turn <n> <date> refused <k>" per turn through <paramref name="log"/>,
/// then "SMOKE OK <n> turns <date> <hash>", or "SMOKE FAIL <reason>" when a press does not take effect.
/// Static, so an edit-mode test can drive it step by step.</summary>
public static IEnumerator Smoke(VisualElement root, SimBridge bridge, EventCardPresenter card, int turns, Action<string> log)
{
for (int t = 0; t < turns; t++)
{
yield return null;
for (int guard = 0; card.Shown != null; guard++)
{
var shown = card.Shown;
// Rulesets with Attention keep the smoke's own pool check unchanged; gdd-0.3 has no pool to run out of (#1688).
if (bridge.Content.UsesAttention
&& bridge.AttentionLeft!.Value + 1e-9 < AttentionSystem.Cost(bridge.Content, bridge.State, new ChooseEventOption(shown.Id, "").Kind)) break;
// R-ENEMY-007 (#2621): a first option whose operation units are not in place is disabled, and the smoke gives no
// unit orders, so the card goes to its minister as an unpaid one does (GoldenRun.SmokeOrders plays the same).
if (!EventSystem.OperationStatus(bridge.Content, bridge.State, shown.Options[0]).Met) break;
var option = root.Q<VisualElement>("event-options")?.Q<Button>();
if (option == null || guard >= 50) { log(FormattableString.Invariant($"SMOKE FAIL event {shown.Id} has no option to press")); yield break; }
if (!Press(option, log)) yield break;
if (card.Shown == shown) { log(FormattableString.Invariant($"SMOKE FAIL the option '{option.text}' for event {shown.Id} was not taken")); yield break; }
yield return null;
}
var turn = bridge.State.Turn;
for (int guard = 0; bridge.NeedsOrders.Count > 0; guard++)
{
if (guard >= 200) { log("SMOKE FAIL unit skip loop reached 200"); yield break; }
if (!SkipOneUnit(root, bridge, log)) yield break;
yield return null;
}
int refused = 0;
Action<IReadOnlyList<Rejection>> count = r => refused = r.Count;
bridge.TurnEnded += count;
bool pressed;
try { pressed = Press(root.Q<Button>("end-turn"), log); }
finally { bridge.TurnEnded -= count; }
if (!pressed) yield break;
if (bridge.State.Turn != turn + 1) { log(FormattableString.Invariant($"SMOKE FAIL End Turn did not end turn {turn}")); yield break; }
// The turn report (#1037) covers the HUD after End Turn: a player closes it before the next turn.
var hud = root.Q("root") ?? root;
if (hud.ClassListContains(TurnReportPresenter.OpenClass))
{
if (!Press(root.Q<Button>("turn-report-close"), log)) yield break;
if (hud.ClassListContains(TurnReportPresenter.OpenClass)) { log(FormattableString.Invariant($"SMOKE FAIL the turn report after turn {turn} did not close")); yield break; }
}
var s = bridge.State;
log(FormattableString.Invariant($"SMOKE turn {s.Turn} {s.Date:yyyy-MM-dd} refused {refused}"));
}
log(FormattableString.Invariant($"SMOKE OK {turns} turns {bridge.TurnStart.Date:yyyy-MM-dd} {bridge.TurnStart.Hash()}"));
}
/// <summary>The smoke-orders golden (#754, docs/determinism.md): turn 1 with one unit order given as a player gives it.
/// An open event card takes the panels under it out of reach, so it first presses the card's Hide (the turn's events
/// go to their ministers). It clicks the hex of the unit GoldenRun.SmokeMove names (<paramref name="clickHex"/>: what
/// a map click raises), presses the unit card's Move button, clicks the order's lit hex, then presses End Turn and
/// closes the turn report. Logs "SMOKE ORDERS move unit <id> to <q>,<r>", then
/// "SMOKE ORDERS OK <date> <hash>", or "SMOKE FAIL <reason>" when a click or press does not take effect.
/// Static, so an edit-mode test can drive it.</summary>
public static IEnumerator SmokeOrders(VisualElement root, SimBridge bridge, Statecraft.Game.Map.Units.UnitLayer units,
Action<int, int> clickHex, Action<string> log)
{
yield return null;
var hud = root.Q("root") ?? root;
if (hud.ClassListContains(EventCardPresenter.OpenClass))
{
if (!Press(root.Q<Button>("event-hide"), log)) yield break;
if (hud.ClassListContains(EventCardPresenter.OpenClass)) { log("SMOKE FAIL the event card did not hide"); yield break; }
}
var move = GoldenRun.SmokeMove(bridge.Content, bridge.State);
var token = units.Tokens.Where(p => UnitCard.SimUnit(bridge.Content, bridge.State, p.Token) == move.Unit)
.Select(p => (Statecraft.Game.Map.Units.PlacedToken?)p).FirstOrDefault();
if (!(token is { } t)) { log(FormattableString.Invariant($"SMOKE FAIL unit {move.Unit} has no token on the map")); yield break; }
log(FormattableString.Invariant($"SMOKE ORDERS move unit {move.Unit} to {move.Q},{move.R}"));
clickHex(t.Q, t.R);
if (units.Selected != t.Token.Unit.Id) { log(FormattableString.Invariant($"SMOKE FAIL the click on {t.Q},{t.R} did not select unit {move.Unit}")); yield break; }
if (!Press(root.Q<Button>("info-move"), log)) yield break;
clickHex(move.Q, move.R);
if (!bridge.Session.Committed.OfType<Move>().Any(m => m.Unit == move.Unit && m.Q == move.Q && m.R == move.R))
{ log(FormattableString.Invariant($"SMOKE FAIL the click on {move.Q},{move.R} committed no Move for unit {move.Unit}")); yield break; }
yield return null;
var turn = bridge.State.Turn;
for (int guard = 0; bridge.NeedsOrders.Count > 0; guard++)
{
if (guard >= 200) { log("SMOKE FAIL unit skip loop reached 200"); yield break; }
if (!SkipOneUnit(root, bridge, log)) yield break;
yield return null;
}
if (!Press(root.Q<Button>("end-turn"), log)) yield break;
if (bridge.State.Turn != turn + 1) { log(FormattableString.Invariant($"SMOKE FAIL End Turn did not end turn {turn}")); yield break; }
if (hud.ClassListContains(TurnReportPresenter.OpenClass))
{
if (!Press(root.Q<Button>("turn-report-close"), log)) yield break;
if (hud.ClassListContains(TurnReportPresenter.OpenClass)) { log(FormattableString.Invariant($"SMOKE FAIL the turn report after turn {turn} did not close")); yield break; }
}
log(FormattableString.Invariant($"SMOKE ORDERS OK {bridge.TurnStart.Date:yyyy-MM-dd} {bridge.TurnStart.Hash()}"));
}
/// <summary>One pass of the smoke runs' unit loop: End Turn selects a unit that needs orders, and the unit card's Skip
/// skips it. False, with "SMOKE FAIL info-skip skipped no unit" plus the waiting ids and the unit card's title, when no
/// unit left the cycle (the v0.3.5 smoke spun 200 times behind a dialog, #2436).</summary>
static bool SkipOneUnit(VisualElement root, SimBridge bridge, Action<string> log)
{
var before = bridge.NeedsOrders;
if (!Press(root.Q<Button>("end-turn"), log) || !Press(root.Q<Button>("info-skip"), log)) return false;
if (bridge.NeedsOrders.Count < before.Count) return true;
// Smoke has no unit layer, so it names the units still waiting and the unit card's own title (the unit it shows,
// which End Turn chose and may not be the first waiting).
log(FormattableString.Invariant($"SMOKE FAIL info-skip skipped no unit: waiting {string.Join(",", before)}; the unit card shows '{root.Q<Label>("info-title")?.text}'"));
return false;
}
/// <summary>Presses <paramref name="b"/> as keyboard Submit does. False, with a SMOKE FAIL line, when it is missing,
/// out of reach (disabled, or under a disabled parent: Skip behind the v0.3.5 dialog took no press), or its handler throws.</summary>
static bool Press(Button? b, Action<string> log)
{
if (b == null) { log("SMOKE FAIL button missing"); return false; }
if (!b.enabledInHierarchy) { log("SMOKE FAIL " + b.name + " is not enabled"); return false; }
try
{
using (var e = NavigationSubmitEvent.GetPooled()) { e.target = b; b.SendEvent(e); }
return true;
}
catch (Exception e) { log("SMOKE FAIL " + e.Message); return false; }
}
sealed class Undo : IDisposable
{
readonly Action undo;
public Undo(Action undo) { this.undo = undo; }
public void Dispose() => undo();
}
}
}