A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(unity): boot failures shown, navy loading page, shareable-build gate, End Turn never soft-locks (M3 final review I4 I5 M1 M4 M5 M7)
eyalgolanca3f3618d75d
diff --git a/unity/Assets/Editor/Build.cs b/unity/Assets/Editor/Build.csindex 6cab13d2c..5fb0f9e23 100644--- a/unity/Assets/Editor/Build.cs+++ b/unity/Assets/Editor/Build.cs@@ -34,9 +34,24 @@ namespace Statecraft.Game.EditorTools_ => throw new ArgumentException($"-compression must be disabled, gzip or brotli (got '{name}')"),};+ /// <summary>Why a shareable build may not be made, or null: every event with a sensitive tag needs the owner's+ /// sensitivity review first (status sensitivity-reviewed; docs/m3-release.md, M3 final review I4).</summary>+ public static string? ShareableRefusal(Statecraft.Sim.Content c)+ {+ var open = Statecraft.Sim.ReleaseGate.SensitiveUnreviewed(c);+ return open.Count == 0 ? null+ : "a shareable build needs the owner's sensitivity review of: " + string.Join(", ", open) + " (set status: sensitivity-reviewed; see docs/m3-release.md)";+ }+public static void Web(){var name = Arg("-compression") ?? "disabled";+ if (Flag("-shareable") && ShareableRefusal(Statecraft.Sim.ContentLoader.Load(Paths.Content)) is string refusal)+ {+ Debug.LogError("BUILD REFUSED " + refusal);+ EditorApplication.Exit(1);+ return;+ }ProjectSetup.Apply();PlayerSettings.WebGL.compressionFormat = Compression(name);PlayerSettings.WebGL.decompressionFallback = false; // itch.io serves .br/.gz with Content-Encodingdiff --git a/unity/Assets/Scripts/Boot/GameBoot.cs b/unity/Assets/Scripts/Boot/GameBoot.csindex 91364bd71..b46c3f326 100644--- a/unity/Assets/Scripts/Boot/GameBoot.cs+++ b/unity/Assets/Scripts/Boot/GameBoot.cs@@ -15,9 +15,20 @@ namespace Statecraft.Game.Bootpublic GameInputs? Inputs { get; private set; }public string? Error { get; private set; }public event Action<GameInputs>? Ready;+ /// <summary>Raised with the reason when the boot fails (a failed fetch, a content error): GameRoot shows it on the+ /// loading line (M3 final review I5).</summary>+ public event Action<string>? Failed;public void Configure(MapScene mapScene) => map = mapScene;+ /// <summary>Records and logs a boot failure and raises Failed, so the player sees it (not an endless loading line).</summary>+ internal void Fail(string reason)+ {+ Error = reason;+ Debug.LogError("BOOT FAIL " + reason);+ Failed?.Invoke(reason);+ }+async void Start(){DiagLog.Init();@@ -41,8 +52,7 @@ namespace Statecraft.Game.Boot}catch (Exception e){- Error = e.Message;- Debug.LogError("BOOT FAIL " + e.Message);+ Fail(e.Message);Debug.LogException(e);if (GoldenCheck.QuitCodeOnError(GoldenCheck.Requested(), Application.platform == RuntimePlatform.WebGLPlayer) is int code) Application.Quit(code);}diff --git a/unity/Assets/Scripts/UI/DefencePresenter.cs b/unity/Assets/Scripts/UI/DefencePresenter.csindex 1c7b7df3f..1454bde90 100644--- a/unity/Assets/Scripts/UI/DefencePresenter.cs+++ b/unity/Assets/Scripts/UI/DefencePresenter.cs@@ -97,7 +97,7 @@ namespace Statecraft.Game.UIscreen.Q<VisualElement>($"rung-{rung}").EnableInClassList("rung-current", rung == s.Rung);}screen.Q<Label>("defence-command").text = text.Format("defence.command",- Cabinet.Holder(c, s, "defense_minister")?.Name ?? "-", Cabinet.Holder(c, s, "chief_of_staff")?.Name ?? "-");+ Cabinet.Holder(c, s, "defense_minister")?.Name ?? text["cabinet.vacant"], Cabinet.Holder(c, s, "chief_of_staff")?.Name ?? text["cabinet.vacant"]);var delta = QueuedDelta;var target = TargetRung;var ceasefire = screen.Q<Label>("ceasefire");@@ -110,7 +110,7 @@ namespace Statecraft.Game.UIvar floor = SecuritySystem.MinMobilization(c, target);var proposed = EffectiveAt(ProposedMobilization); // what the call-up will be: the sim raises a lower order to the minimumscreen.Q<Label>("mob-level").text = text.Format("defence.mob", PlayerText.Percent(proposed), target, PlayerText.Percent(floor));- screen.Q<Label>("mob-cost").text = text.Format("defence.mob_cost", PlayerText.Money(c, "treasury", c.Rules.MobilizationCostPerYear * proposed));+ screen.Q<Label>("mob-cost").text = text.Format("defence.mob_cost", PlayerText.Money(c, "treasury", EconomySystem.MobilizationCost(c, proposed)));screen.Q<Button>("escalate").SetEnabled(target < 5);screen.Q<Button>("de-escalate").SetEnabled(target > 1);}diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 5b7691eed..5452c5720 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -55,15 +55,24 @@ namespace Statecraft.Game.UIthis.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;- if (this.boot != null) this.boot.Ready += Begin;+ 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; }+ void OnEnable() { if (boot != null) { boot.Ready += Begin; boot.Failed += OnBootFailed; } }++ /// <summary>A boot failure replaces the loading line with the reason; the loading state stays, so no half-built panel+ /// shows (M3 final review I5).</summary>+ internal void OnBootFailed(string reason)+ {+ if (document == null || strings == null) return;+ var line = document.rootVisualElement.Q<Label>("loading");+ if (line != null) line.text = UiText.Parse(strings.text).Format("boot.failed", reason);+ }void OnDisable(){- if (boot != null) boot.Ready -= Begin;+ if (boot != null) { boot.Ready -= Begin; boot.Failed -= OnBootFailed; }Shutdown();}diff --git a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs b/unity/Assets/Scripts/UI/InfoPanelPresenter.csindex 1cf16f218..69a8603b1 100644--- a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs+++ b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs@@ -56,7 +56,7 @@ namespace Statecraft.Game.UI}var (q, r) = Selected.Value;var hex = c.HexAt(q, r);- var owned = c.SettlementHexes.Where(x => x.Q == q && x.R == r).Select(x => settlementNames.TryGetValue(x.Id, out var n) ? n : x.Id).ToList();+ var owned = c.SettlementHexes.Where(x => x.Q == q && x.R == r).Select(x => settlementNames[x.Id]).ToList(); // strict: every settlement hex has a name (final review M4)title.text = owned.Count > 0 ? owned[0] : hex == null ? text["info.off_map"] : text["info.biome." + hex.Biome];subtitle.text = hex == null ? "" : text.Format("info.hex", text["info.biome." + hex.Biome], hex.ElevM); // no debug coordinates in player text (playtest 2, P2-6)settlements.text = owned.Count > 0 ? text.Format("info.owned", string.Join(", ", owned)) : "";diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.csindex 8d50dd93c..ed5976acb 100644--- a/unity/Assets/Scripts/UI/SimBridge.cs+++ b/unity/Assets/Scripts/UI/SimBridge.cs@@ -107,7 +107,7 @@ namespace Statecraft.Game.UI}/// <summary>Runs the turn with the queued orders, clears the queue, and notifies. If the simulation refuses the- /// batch outright (ArgumentException), the state is unchanged, the queue is cleared, and the reason is raised+ /// batch outright (any exception: an ArgumentException is a refusal, anything else is also logged), the state is unchanged, the queue is cleared, and the reason is raised/// through TurnEnded like any refusal.</summary>public StepResult EndTurn(){@@ -115,8 +115,9 @@ namespace Statecraft.Game.UIvar before = Session.Last;var batch = queue.ToList();try { r = step(Session, batch); }- catch (ArgumentException e)+ catch (Exception e) // any exception (M3 final review M7): never leave a queue that fails on every End Turn{+ if (!(e is ArgumentException)) UnityEngine.Debug.LogException(e); // unexpected: the full exception for the logqueue.Clear();var reason = text.Format("order.failed", e.Message);var failed = new StepResult(State, new Cause[0], batch.Select(x => new Rejection(x, reason)).ToList());diff --git a/unity/Assets/Tests/EditMode/BuildGateTests.cs b/unity/Assets/Tests/EditMode/BuildGateTests.csnew file mode 100644index 000000000..50c81da5f--- /dev/null+++ b/unity/Assets/Tests/EditMode/BuildGateTests.cs@@ -0,0 +1,30 @@+#nullable enable+using System;+using System.Linq;+using System.Reflection;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Sim;++/// <summary>Final review I4: a shareable build (Build.Web -shareable) is refused while any sensitive event lacks the owner's+/// sensitivity review, and the refusal names each one.</summary>+public class BuildGateTests+{+ static string? Refusal(Content c)+ {+ var t = Type.GetType("Statecraft.Game.EditorTools.Build, Assembly-CSharp-Editor");+ Assert.IsNotNull(t, "Build exists");+ return (string?)t!.GetMethod("ShareableRefusal", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, new object[] { c });+ }++ [Test]+ public void AShareableBuildWaitsForTheSensitivityReview()+ {+ var c = ContentLoader.Load(Paths.Content);+ var refusal = Refusal(c);+ Assert.IsNotNull(refusal, "the seven sensitive events are not reviewed yet");+ foreach (var id in ReleaseGate.SensitiveUnreviewed(c)) StringAssert.Contains(id, refusal);+ foreach (var e in c.Events) if (ReleaseGate.SensitiveEvents(c).Contains(e.Id)) e.Status = ReleaseGate.ReviewedStatus; // as the owner's sign-off would+ Assert.IsNull(Refusal(c), "all reviewed: the build may be shared");+ }+}diff --git a/unity/Assets/Tests/EditMode/BuildGateTests.cs.meta b/unity/Assets/Tests/EditMode/BuildGateTests.cs.metanew file mode 100644index 000000000..c034216aa--- /dev/null+++ b/unity/Assets/Tests/EditMode/BuildGateTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 17f18de3aef99483dad919b96e88b2d4\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/DefenceScreenTests.cs b/unity/Assets/Tests/EditMode/DefenceScreenTests.csindex 6639711b6..4aef5036f 100644--- a/unity/Assets/Tests/EditMode/DefenceScreenTests.cs+++ b/unity/Assets/Tests/EditMode/DefenceScreenTests.cs@@ -201,4 +201,19 @@ public class DefenceScreenTestsAssert.DoesNotThrow(() => { var _ = text[DefencePresenter.TurnKey((TurnLength)v)]; }, v.ToString());Assert.Throws<System.ArgumentOutOfRangeException>(() => DefencePresenter.TurnKey((TurnLength)99));}++ /// <summary>Final review M5: the call-up cost comes from the sim's one rule, and a vacant office reads "(vacant)" as on+ /// the Cabinet and Budget screens.</summary>+ [Test]+ public void TheCostComesFromTheSimAndAVacancySaysSo()+ {+ var c = ContentLoader.Load(Paths.Content);+ foreach (var p in c.People) p.Offices.RemoveAll(t => t.Office == "defense_minister"); // no Minister of Defense+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(c, GoldenRun.Seed, Mode.Historical), Text);+ new DefencePresenter(ui.Root, bridge, Text);+ StringAssert.StartsWith("Minister of Defense (vacant) · Chief of Staff ", ui.Q<Label>("defence-command").text);+ Assert.AreEqual(Text.Format("defence.mob_cost", PlayerText.Money(c, "treasury", EconomySystem.MobilizationCost(c, bridge.State.Mobilization))),+ ui.Q<Label>("mob-cost").text);+ }}diff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.csindex f1b6dee79..0acab7417 100644--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs@@ -543,4 +543,69 @@ public class GameSceneTestsBoot();Assert.IsFalse(Ui.Q("root").ClassListContains("loading"), "GameRoot clears the loading state");}++ /// <summary>Final review M1: once ready, the root is transparent again, so the map shows.</summary>+ [UnityTest]+ public IEnumerator TheLoadingBackgroundGoesWhenTheGameIsReady()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var doc = Object.FindFirstObjectByType<UIDocument>();+ var rt = new RenderTexture(1280, 720, 0);+ var ps = Object.Instantiate(doc.panelSettings); ps.targetTexture = rt;+ try+ {+ doc.panelSettings = ps;+ Object.FindFirstObjectByType<MapScene>().Build(Inputs.Map);+ var root = Object.FindFirstObjectByType<GameRoot>();+ root.Store = new SaveStore(saveDir);+ root.Begin(Inputs, 0);+ for (int i = 0; i < 5; i++) yield return null;+ Assert.AreEqual(0f, doc.rootVisualElement.Q("root").resolvedStyle.backgroundColor.a, 1e-3f);+ }+ finally+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ }+ }++ /// <summary>Final review I5: a boot failure (a failed StreamingAssets fetch, a content error) is shown on the loading+ /// line, naming the reason, instead of "Loading the map of 1948..." forever; no panel appears.</summary>+ [UnityTest]+ public IEnumerator ABootFailureIsShownOnTheLoadingLine()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var doc = Object.FindFirstObjectByType<UIDocument>();+ var rt = new RenderTexture(1280, 720, 0);+ var ps = Object.Instantiate(doc.panelSettings); ps.targetTexture = rt;+ try+ {+ doc.panelSettings = ps;+ var boot = Object.FindFirstObjectByType<GameBoot>();+ LogAssert.Expect(LogType.Error, "BOOT FAIL people.yaml: people[x].name: required");+ boot.Fail("people.yaml: people[x].name: required");+ for (int i = 0; i < 5; i++) yield return null;+ var ui = doc.rootVisualElement;+ Assert.AreEqual("Statecraft could not start: people.yaml: people[x].name: required. Reload the page.", ui.Q<Label>("loading").text);+ Assert.AreEqual(DisplayStyle.Flex, ui.Q<Label>("loading").resolvedStyle.display);+ Assert.IsTrue(ui.Q("root").ClassListContains("loading"), "the panels stay hidden");+ Assert.AreEqual(Visibility.Hidden, ui.Q("info-panel").resolvedStyle.visibility);+ Assert.AreEqual("people.yaml: people[x].name: required", boot.Error);+ }+ finally+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ }+ }++ /// <summary>Final review M4: every settlement that owns a hex has a display name (the info panel looks names up strictly).</summary>+ [Test]+ public void EverySettlementHexHasAName()+ {+ var names = SettlementPlacer.Parse(Inputs.Map.SettlementsYaml).Select(s => s.Id).ToHashSet();+ foreach (var sh in Inputs.Content.SettlementHexes) Assert.IsTrue(names.Contains(sh.Id), sh.Id);+ }}diff --git a/unity/Assets/Tests/EditMode/HudTests.cs b/unity/Assets/Tests/EditMode/HudTests.csindex a1184bb68..30d6ef514 100644--- a/unity/Assets/Tests/EditMode/HudTests.cs+++ b/unity/Assets/Tests/EditMode/HudTests.cs@@ -253,11 +253,17 @@ public class HudTestsAssert.AreEqual(0, bridge.State.Turn);}- [Test]- public void ABatchTheSimRefusesOutrightKeepsTheStateAndShowsTheReason()+ /// <summary>Any exception from the sim (not only ArgumentException; final review M7) keeps the state, clears the queue+ /// and shows the reason: End Turn can never soft-lock. An unexpected kind is also logged in full.</summary>+ [TestCase(typeof(System.ArgumentException))]+ [TestCase(typeof(System.InvalidOperationException))]+ [TestCase(typeof(System.NullReferenceException))]+ public void ABatchTheSimRefusesOutrightKeepsTheStateAndShowsTheReason(System.Type kind){using var ui = new UiTestKit();- var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text, (s, cmds) => throw new System.ArgumentException("boom"));+ if (kind != typeof(System.ArgumentException)) LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("boom"));+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text,+ (s, cmds) => throw (System.Exception)System.Activator.CreateInstance(kind, "boom")!);new ToastPresenter(ui.Root, bridge, Text);var order = new SecurityOrder(-1);Assert.IsNull(bridge.Queue(order));diff --git a/unity/Assets/Tests/EditMode/UiFoundationTests.cs b/unity/Assets/Tests/EditMode/UiFoundationTests.csindex f0b3a0a5c..44b838775 100644--- a/unity/Assets/Tests/EditMode/UiFoundationTests.cs+++ b/unity/Assets/Tests/EditMode/UiFoundationTests.cs@@ -124,6 +124,7 @@ public class UiFoundationTestsfor (int i = 0; i < 10 && float.IsNaN(loading.worldBound.width); i++) yield return null;Assert.IsTrue(ui.Q<VisualElement>("root").ClassListContains("loading"), "the tree starts in the loading state");Assert.AreEqual(DisplayStyle.Flex, loading.resolvedStyle.display);+ Assert.AreEqual(1f, ui.Q<VisualElement>("root").resolvedStyle.backgroundColor.a, 1e-3f, "a navy page while loading, not the grey sky (final review M1)");Assert.IsNotEmpty(loading.text);foreach (var s in ScreenNav.Screens)Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("screen-" + s).resolvedStyle.display, s);diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.ussindex 08f146164..60fd510a7 100644--- a/unity/Assets/UI/Statecraft.uss+++ b/unity/Assets/UI/Statecraft.uss@@ -131,4 +131,5 @@ Button:disabled { color: var(--ink-dim); border-color: rgba(120, 120, 120, 0.4);right-hand column are kept out of sight (visibility, so the layout does not jump when they appear). */.loading-line { display: none; position: absolute; left: 0; right: 0; top: 45%; -unity-text-align: middle-center; font-size: 28px; color: var(--ink); }.loading .loading-line { display: flex; }+.root.loading { background-color: var(--navy-solid); } /* the template's navy, not the default sky (final review M1) */.loading .date-box, .loading .meters, .loading .nav, .loading .turn-box, .loading .info-panel, .loading .right-column { visibility: hidden; }diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex fa9776e77..c1d590c9b 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -85,4 +85,5 @@ newgame.confirm: "Press New Game again to abandon this game and start over."newgame.delete_failed: "The old saved game could not be removed; it will be replaced after your next turn."save.unreadable: "Your saved game could not be loaded ({0}). A new game has started."save.reason_other: "the file could not be read or replayed"+boot.failed: "Statecraft could not start: {0}. Reload the page."save.write_failed: "Your game could not be saved."