A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Civ movement U1 to U5: instant moves and attacks, go-to, End turn waits for orders, units named in Why lines (Refs #1398) (#1527)
Eyal Golan1613d2b65e67
diff --git a/changelog.d/1398-u1.md b/changelog.d/1398-u1.mdnew file mode 100644index 000000000..3d5b8cebd--- /dev/null+++ b/changelog.d/1398-u1.md@@ -0,0 +1,2 @@+- Units now move as soon as their order is given, their card shows the movement points left, and Why lines name units instead+ of showing simulation numbers (#1398, #1399).diff --git a/changelog.d/1398-u2.md b/changelog.d/1398-u2.mdnew file mode 100644index 000000000..f54ae1f2c--- /dev/null+++ b/changelog.d/1398-u2.md@@ -0,0 +1,3 @@+## Changed++- Attacks now resolve as soon as their target is chosen, and the result appears immediately with the units' names.diff --git a/changelog.d/1398-u3.md b/changelog.d/1398-u3.mdnew file mode 100644index 000000000..8a52324d2--- /dev/null+++ b/changelog.d/1398-u3.md@@ -0,0 +1,3 @@+## Added++- Units can follow routes over several turns. The map previews each turn’s stopping point, and touch confirms a route on the second tap.diff --git a/changelog.d/1398-u4.md b/changelog.d/1398-u4.mdnew file mode 100644index 000000000..4cdce0f80--- /dev/null+++ b/changelog.d/1398-u4.md@@ -0,0 +1 @@+- End turn now waits for every military unit to move or receive an order, with a Skip this turn action, automatic unit cycling and dimmed spent-unit badges.diff --git a/docs/UX_GLOSSARY.md b/docs/UX_GLOSSARY.mdindex 813a28e02..79d839195 100644--- a/docs/UX_GLOSSARY.md+++ b/docs/UX_GLOSSARY.md@@ -2,7 +2,7 @@Source of truth: `UX_GLOSSARY.yaml`. This Markdown is its readable view; update the YAML first and keep both views in sync. DRAFT for review. Adopted decisions are identified individually; other recommendations await maintainer or native Hebrew review. Snapshot date 2026-10-17.-Entries: 6 contested, 7 decision-needed, 3 pending-gdd, 27 preferred, 6 use-with-caution (49 concepts, 6 conventions).+Entries: 6 contested, 8 decision-needed, 3 pending-gdd, 27 preferred, 6 use-with-caution (50 concepts, 6 conventions).Revision 19 October 2026: targeted terminology and implementation checks against upstream/main 9e571342 address the #970 review. The original snapshot date remains above; this is not a full review of every new string.@@ -19,6 +19,7 @@ Revision 21 October 2026, localisation follow-up: the Cabinet reads government a| security-level | contested | security level | open | Eyal and the native reviewer || attention | decision-needed | Attention at the start of a label, attention inside a sentence (sentence case, as in the strings) | open | Eyal || turn | preferred | turn | תור | Eyal |+| movement-points | decision-needed | movement points | נקודות תנועה | Eyal and the native reviewer || end-turn | preferred | End turn (the button), 'end the turn' (the action) | סיום התור (the button); 'לסיים את התור' in sentences | Eyal || decision | preferred | decision | החלטה | Eyal, for the plural form || event | preferred | event (data and history), 'event card' (the card the player sees) | open | Eyal |@@ -221,6 +222,31 @@ Category: game-system. Scope: ui, docs, marketing, code.**Decision owner.** Eyal.+### movement-points (decision-needed)++Category: game-system. Scope: ui, docs, code.++**Definition.** The number of points a military unit can spend entering hexes during one turn.++**English.** Preferred: movement points.++| In use | Where |+|---|---|+| Movement points: {0} of {1} | strings.en.yaml unit.points |++**Hebrew.** Preferred: נקודות תנועה.++| In use | Where |+|---|---|+| נקודות תנועה: {0} מתוך {1} | strings.he.yaml unit.points |++**Recommendation (see status).**+- English: Use movement points in the card and rules.+- Hebrew: The candidate נקודות תנועה needs a native review.+- Reasons: (1) The term is new on screen with Civ-style movement.++**Decision owner.** Eyal and the native reviewer.+### end-turn (preferred)Category: game-system. Scope: ui, docs.diff --git a/docs/UX_GLOSSARY.yaml b/docs/UX_GLOSSARY.yamlindex 07da31e7f..62c8c6953 100644--- a/docs/UX_GLOSSARY.yaml+++ b/docs/UX_GLOSSARY.yaml@@ -208,6 +208,32 @@ concepts:reasons:- The current rules set all five turn lengths to month.decision_owner: Eyal+- id: movement-points+ status: decision-needed+ category: game-system+ definition: The number of points a military unit can spend entering hexes during one turn.+ scope:+ - ui+ - docs+ - code+ en:+ preferred: movement points+ avoid: []+ in_use:+ - form: 'Movement points: {0} of {1}'+ where: strings.en.yaml unit.points+ he:+ preferred: נקודות תנועה+ avoid: []+ in_use:+ - form: 'נקודות תנועה: {0} מתוך {1}'+ where: strings.he.yaml unit.points+ recommendation:+ en: Use movement points in the card and rules.+ he: The candidate נקודות תנועה needs a native review.+ reasons:+ - The term is new on screen with Civ-style movement.+ decision_owner: Eyal and the native reviewer- id: end-turnstatus: preferredcategory: game-systemdiff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex 22b9c774e..0c06a9c6b 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -154,8 +154,12 @@ namespace Statecraft.Game.Map/// <summary>The hexes a unit's Move can go to, outlined while the player picks one (#754): a child of the terrain.</summary>public const string ReachableName = "ReachableHexes";+ /// <summary>The multi-turn route preview's mesh, beside <see cref="ReachableName"/> under the terrain.</summary>+ public const string RouteName = "UnitRoute";/// <summary>The reachable hexes' band, half the selection's, so the lit hexes read as choices and not as the selection.</summary>public const float ReachableWidth = SelectionWidth / 2;+ /// <summary>The route last passed to <see cref="ShowRoute"/>, for the turn-number labels.</summary>+ public IReadOnlyList<(int q, int r, int turn)> ShownRoute { get; private set; } = Array.Empty<(int, int, int)>();/// <summary>Outlines every hex in <paramref name="hexes"/> (Movement.Reachable's, from InfoPanelPresenter) with a thin/// band in one mesh, drawn and draped as <see cref="Select"/>'s outline and with its material; nothing to light (none,@@ -211,6 +215,58 @@ namespace Statecraft.Game.Mapgo.GetComponent<MeshRenderer>().enabled = verts.Count > 0;}+ /// <summary>Shows the sim's multi-turn route as thin hex bands. Each item carries its arrival turn;+ /// <see cref="Statecraft.Game.UI.MapLabelsPresenter"/> labels the last hex of each turn. Empty hides the preview.</summary>+ public void ShowRoute(IReadOnlyList<(int q, int r, int turn)> route)+ {+ ShownRoute = route?.ToList() ?? new List<(int, int, int)>();+ if (Terrain == null || Hexes == null) return;+ var found = Terrain.transform.Find(RouteName);+ var go = found != null ? found.gameObject : null;+ if (go == null)+ {+ go = new GameObject(RouteName);+ go.transform.SetParent(Terrain.transform, false);+ var mesh = Terrain.GetComponent<MapRuntimeAssets>().Own(new Mesh { name = RouteName });+ go.AddComponent<MeshFilter>().sharedMesh = mesh;+ var renderer = go.AddComponent<MeshRenderer>();+ renderer.sharedMaterial = selectionMaterial;+ renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;+ }+ var byHex = new Dictionary<(int, int), HexJson>();+ foreach (var h in Hexes.hexes) byHex[(h.q, h.r)] = h;+ float size = Hexes.hex_size_km * 1000f;+ int n = MapBuilder.RingVertices;+ var verts = new List<Vector3>(); var tris = new List<int>();+ var ring = new List<Vector3>(2 * n); var middle = new List<Vector3>(n);+ foreach (var at in ShownRoute)+ {+ if (!byHex.TryGetValue((at.q, at.r), out var hex)) continue;+ var c = Frame.ToWorld(hex.lon, hex.lat, 0);+ var centre = new Vector2(c.x, c.z);+ ring.Clear(); middle.Clear();+ MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size, SelectionClearanceM, ring);+ MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - ReachableWidth), SelectionClearanceM, ring);+ MapBuilder.DrapedRing(Frame, Terrain.terrainData, centre, size * (1f - ReachableWidth / 2), SelectionClearanceM, middle);+ int b0 = verts.Count;+ for (int j = 0; j < n; j++)+ {+ float y = Mathf.Max(ring[j].y, Mathf.Max(ring[n + j].y, middle[j].y));+ ring[j] = new Vector3(ring[j].x, y, ring[j].z);+ ring[n + j] = new Vector3(ring[n + j].x, y, ring[n + j].z);+ }+ verts.AddRange(ring);+ for (int j = 0; j < n; j++)+ {+ int a = b0 + j, b = b0 + (j + 1) % n, ai = b0 + n + j, bi = b0 + n + (j + 1) % n;+ tris.AddRange(new[] { a, ai, b, b, ai, bi });+ }+ }+ var m = go.GetComponent<MeshFilter>().sharedMesh;+ m.Clear(); m.SetVertices(verts); m.SetTriangles(tris, 0); m.RecalculateBounds();+ go.GetComponent<MeshRenderer>().enabled = verts.Count > 0;+ }+public void Configure(Material terrain, Material marker, Material selection, Material sea, Material frame){terrainMaterial = terrain; markerMaterial = marker; selectionMaterial = selection;diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.csindex 72f563511..a296fdfb4 100644--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs@@ -20,6 +20,9 @@ namespace Statecraft.Game.Map.Unitspublic sealed class UnitLayer : MonoBehaviour{public const string RootName = "Units", ToggleName = "units";+ /// <summary>A player unit with no movement points left this turn has its badge drawn at this share of its colours+ /// (plate and glyph alike, so the glyph keeps its contrast on the plate).</summary>+ public const float DimShade = 0.5f;/// <summary>A parked aircraft's centre of gravity above the ground, in real metres (on its undercarriage).</summary>public const float ParkedHeightM = 1.4f;public const float ParkedHeadingDegrees = 200f;@@ -262,6 +265,27 @@ namespace Statecraft.Game.Map.Unitsreturn true;}+ /// <summary>Dims the listed unit rows' badges for this turn (each badge renderer at <see cref="DimShade"/> of its+ /// material's colour); every other badge has no property override.</summary>+ public void Dim(IReadOnlyCollection<string> rowIds)+ {+ var dim = new HashSet<string>(rowIds ?? Array.Empty<string>());+ var block = new MaterialPropertyBlock();+ for (int i = 0; i < tokensRoot.childCount; i++)+ {+ var token = tokensRoot.GetChild(i);+ var badge = token.Find("Badge");+ if (badge == null) continue;+ foreach (var renderer in badge.GetComponentsInChildren<Renderer>(true))+ {+ if (!dim.Contains(token.name)) { renderer.SetPropertyBlock(null); continue; }+ var c = renderer.sharedMaterial.color;+ block.SetColor("_BaseColor", new Color(c.r * DimShade, c.g * DimShade, c.b * DimShade, c.a));+ renderer.SetPropertyBlock(block);+ }+ }+ }+/// <summary>The anchor of <paramref name="row"/>'s unit on sim hex (<paramref name="q"/>, <paramref name="r"/>) after a/// move: the hex's centre, no place name and no sources (the card then gives the row's), with the starting anchor's/// window. The same object every time, so the roster compares equal and the spot is placed once.</summary>diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 3f64d4527..0e3d00bca 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -15,7 +15,7 @@ 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- /// turn, and wires the camera and the map pointer to the game panel (UiPointer.IsOverUi), map clicks to the info panel,+ /// 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@@ -247,7 +247,7 @@ namespace Statecraft.Game.UI// 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));- Own(new HudPresenter(root, bridge, text));+ Own(new HudPresenter(root, bridge, text, selectUnit: _ => FocusNextUnit()));nav = Own(new ScreenNav(root)); // every screen starts hidden (USS); ScreenNav opens one at a timeOwn(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)@@ -281,7 +281,7 @@ namespace Statecraft.Game.UI() => card?.Render(), () => nav?.Close()));Own(new DefencePresenter(root, bridge, text, portraits));var budget = Own(new BudgetPresenter(root, bridge, text));- Own(new WhyPresenter(root, bridge, text));+ var why = Own(new WhyPresenter(root, bridge, text));Own(new TimelinePresenter(root, bridge, text));Own(new HowToPlayPresenter(root, text));Own(new ObjectivesPresenter(root, bridge, text));@@ -343,6 +343,7 @@ namespace Statecraft.Game.UIDiagLog.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);+ 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,@@ -354,7 +355,14 @@ namespace Statecraft.Game.UIif (Statecraft.Game.Map.Units.UnitLayer.HiddenInCaptures(Application.absoluteURL, Environment.GetCommandLineArgs(),Application.platform == RuntimePlatform.WebGLPlayer))VisualToggles.Set(Statecraft.Game.Map.Units.UnitLayer.ToggleName, false);- Action showUnits = () => unitLayer.Show(bridge.Content, bridge.State);+ Action showUnits = () =>+ {+ unitLayer.Show(bridge.Content, bridge.State);+ 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.PointsLeft(bridge.Content, bridge.State, id, bridge.Spent) == 0)+ .Select(t => t.Token.Unit.Id).ToList());+ };bridge.Changed += showUnits;owned.Add(new Undo(() => bridge.Changed -= showUnits));showUnits();@@ -368,7 +376,9 @@ namespace Statecraft.Game.UItownNamesHe: 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()));+ .Select(p => UnitCard.For(p, bridge.State, text, bridge.Content.IsGdd, bridge.Content, townNamesHe).Title).FirstOrDefault(),+ unitDone: FocusNextUnit, showRoute: map.ShowRoute));+ toast.Units = unitData; toast.TownNamesHe = townNamesHe; why.TownNamesHe = townNamesHe;// A smoke session never touches the player's save: no autosave, and no New Game (which deletes the autosave).// Leaving New Game out is safer than handing it a throwaway store: no file is ever deleted, no path has to be// right on every platform, and the scripted run never presses it.@@ -397,7 +407,7 @@ namespace Statecraft.Game.UIpointer.IsOverUi = overUi;Action<int, int> onHex = (q, r) =>{- OnHexClicked(map, unitLayer, info, q, r);+ OnHexClicked(map, unitLayer, info, q, r, UnityEngine.InputSystem.Pointer.current is UnityEngine.InputSystem.Touchscreen);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);@@ -502,16 +512,8 @@ namespace Statecraft.Game.UIAction showUnit = () =>{if (AdvisorTargets.UnitToShow(bridge.Content, bridge.State, unitLayer.Tokens.Select(t => t.Token)) is not string id) return;- unitLayer.Select(id);- if (unitLayer.Selected != null)- {- map.ClearSelection(); info.ShowUnit();- var token = unitLayer.Tokens.First(t => t.Token.Unit.Id == id);- var hex = bridge.Content.HexAt(token.Q, token.R)!;- camRig.LookAt = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);- camRig.Distance = Mathf.Min(camRig.Distance, AdvisorTargets.MoveStepDistanceM);- cameraController.Settle(); SyncMinimap(); labels?.Refresh();- }+ 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, or none), unless the player has// picked something else meanwhile (the HUD stays usable under it).@@ -617,9 +619,9 @@ namespace Statecraft.Game.UI/// <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 click on a lit hex queues- /// the order and keeps the unit's card; any other click ends the pick first and then selects as usual.</summary>- internal static void OnHexClicked(MapScene map, Statecraft.Game.Map.Units.UnitLayer units, InfoPanelPresenter info, int q, int r)+ /// 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.</summary>+ internal static void OnHexClicked(MapScene map, Statecraft.Game.Map.Units.UnitLayer units, InfoPanelPresenter info, int q, int r, bool touch = false){if (info.Covered){@@ -628,13 +630,49 @@ namespace Statecraft.Game.UIif (info.Selected is (int sq, int sr) && !info.ShowsUnit) map.Select(sq, sr); else map.ClearSelection();return;}- if (info.PickTarget(q, r)) { map.ClearSelection(); return; } // the unit keeps its ring, the one highlight+ if (info.PickTarget(q, r, touch)) { map.ClearSelection(); return; } // the unit keeps its ring, the one highlightvar id = units.UnitToSelectAt(q, r);units.Select(id);if (id != null) { map.ClearSelection(); info.ShowUnit(); }else info.Show(q, r);}+ /// <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();+ }++ void SelectUnit(int simId)+ {+ if (units == null || Bridge == null) return;+ var row = units.Tokens.FirstOrDefault(t => UnitCard.SimUnit(Bridge.Content, Bridge.State, t.Token) == simId).Token?.Unit.Id;+ if (row != null) FocusUnit(row);+ }++ 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);+ 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 next = current is int id+ ? Bridge.NeedsOrders.Where(n => n > id).Select(n => (int?)n).FirstOrDefault() ?? Bridge.NeedsOrders[0]+ : Bridge.NeedsOrders[0];+ SelectUnit(next);+ }+/// <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@@ -806,6 +844,8 @@ namespace Statecraft.Game.UIvar hover = MapLabelsPresenter.HoverPosition(UnityEngine.InputSystem.Pointer.current);labels.Hover(hover);HoverCity(hover);+ if (hover is Vector2 at && pointer.HexAt(at) is (int q, int r)) info?.ShowRouteTo(q, r);+ else if (UnityEngine.InputSystem.Pointer.current is UnityEngine.InputSystem.Mouse) info?.HideRoute();var touch = UnityEngine.InputSystem.Touchscreen.current;if (touch != null && touch.primaryTouch.press.wasPressedThisFrame) labels.Tap(touch.primaryTouch.position.ReadValue());}@@ -859,6 +899,13 @@ namespace Statecraft.Game.UIyield 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 (!Press(root.Q<Button>("end-turn"), log)) yield break;+ if (!Press(root.Q<Button>("info-skip"), log)) yield break;+ yield return null;+ }int refused = 0;Action<IReadOnlyList<Rejection>> count = r => refused = r.Count;bridge.TurnEnded += count;@@ -877,7 +924,7 @@ namespace Statecraft.Game.UIvar 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.State.Date:yyyy-MM-dd} {bridge.State.Hash()}"));+ 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.@@ -906,10 +953,17 @@ namespace Statecraft.Game.UIif (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.Queued.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} queued no Move for unit {move.Unit}")); yield break; }+ 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 (!Press(root.Q<Button>("end-turn"), log)) yield break;+ if (!Press(root.Q<Button>("info-skip"), 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))@@ -917,7 +971,7 @@ namespace Statecraft.Game.UIif (!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.State.Date:yyyy-MM-dd} {bridge.State.Hash()}"));+ log(FormattableString.Invariant($"SMOKE ORDERS OK {bridge.TurnStart.Date:yyyy-MM-dd} {bridge.TurnStart.Hash()}"));}static bool Press(Button? b, Action<string> log)diff --git a/unity/Assets/Scripts/UI/GameStart.cs b/unity/Assets/Scripts/UI/GameStart.csindex 2206af939..27e1c5845 100644--- a/unity/Assets/Scripts/UI/GameStart.cs+++ b/unity/Assets/Scripts/UI/GameStart.cs@@ -60,7 +60,7 @@ namespace Statecraft.Game.UIreturn GameSession.New(c, newSeed(), Mode.Historical);}- /// <summary>Writes the save after every turn. A write that fails (a full or read-only disk) never stops the game:+ /// <summary>Writes the save after every committed order and every turn. A write that fails (a full or read-only disk) never stops the game:/// the reason goes to <paramref name="onError"/>. Dispose the result to stop autosaving.</summary>public static IDisposable Autosave(SimBridge bridge, SaveStore store, UiText text, Action<string>? onError = null){@@ -70,7 +70,7 @@ namespace Statecraft.Game.UI{store.WriteAutosave(bridge.Session.Save.Write());// Capture this save, not the mutable session at an asynchronous commit's completion.- var state = bridge.State;+ var state = bridge.TurnStart;var generation = System.Threading.Interlocked.Increment(ref saveGeneration);var receipt = FormattableString.Invariant($"{generation} {state.Date:yyyy-MM-dd} turn {state.Turn} hash {state.Hash()}");UnityEngine.Debug.Log("AUTOSAVE PENDING " + receipt);@@ -86,8 +86,10 @@ namespace Statecraft.Game.UIonError?.Invoke(text["save.write_failed"]);}}+ Action<IReadOnlyList<Cause>> onCommit = _ => Save(Array.Empty<Rejection>());+ bridge.Committed += onCommit;bridge.TurnEnded += Save;- return new Unsubscribe(() => bridge.TurnEnded -= Save);+ return new Unsubscribe(() => { bridge.Committed -= onCommit; bridge.TurnEnded -= Save; });}#if UNITY_WEBGL && !UNITY_EDITORdiff --git a/unity/Assets/Scripts/UI/GddHexPanel.cs b/unity/Assets/Scripts/UI/GddHexPanel.csindex 5c78a34aa..cc8d688d4 100644--- a/unity/Assets/Scripts/UI/GddHexPanel.cs+++ b/unity/Assets/Scripts/UI/GddHexPanel.cs@@ -168,22 +168,17 @@ namespace Statecraft.Game.UI/// <summary>A pioneer group's Return (R-QUAL-003; #1511): the sim's unit order return_civilian, offered where/// Qualification.CheckReturn takes the group (not one at work). Pioneer groups have no map token and so no unit card:- /// this sits beside the places that list them. Once ordered the button reads "Ordered" and is off.</summary>+ /// this sits beside the places that list them. A unit order, it takes effect at once (R-TURN-004): the group leaves+ /// the lists, and its Build buttons with it.</summary>static void PioneerReturn(VisualElement host, SimBridge bridge, UiText text, int unit){if (Qualification.CheckReturn(bridge.State, unit) != null) return;- var ordered = ReturnQueued(bridge, unit);- // A queued Build or Stop for the group is another key (unit:N), so the queue would not replace it: the sim would refuse one of them.+ // A Build or Stop queued for the group waits for End turn, which the group would no longer be there for.var working = bridge.Queued.Any(x => (x is PioneerWork w && w.Unit == unit) || (x is StopWork sw && sw.Unit == unit));- Button(host, $"pioneer-return-{unit}", ordered ? text["site.ordered"] : text.Format("pioneer.return", Group(text, bridge.State, unit)),- () => bridge.Queue(new UnitOrder(unit, Qualification.ReturnOrder))).SetEnabled(!ordered && !working);+ Button(host, $"pioneer-return-{unit}", text.Format("pioneer.return", Group(text, bridge.State, unit)),+ () => bridge.Queue(new UnitOrder(unit, Qualification.ReturnOrder))).SetEnabled(!working);}- /// <summary>A Return is queued for the group. It runs before Build at End turn, so the unit has left by then and the sim- /// refuses the Build ("no such unit"): the Build buttons are off once it is.</summary>- static bool ReturnQueued(SimBridge bridge, int unit) =>- bridge.QueuedLike(new UnitOrder(unit, Qualification.ReturnOrder)) is UnitOrder o && o.Order == Qualification.ReturnOrder;-static void Workers(SimBridge bridge, string city, int current, int count){if (count != current) { bridge.Queue(new AssignWorkers(city, "job", count)); return; }@@ -230,7 +225,7 @@ namespace Statecraft.Game.UIButton(host, $"site-build-{u.Id}", ordered ? text["site.ordered"]: text.Format("site.build" + key, Group(text, s, u.Id), PlayerText.Money(c, "treasury", terms.Cost),Turns(text, Projects.TurnsToBuild(c, s, u.Id, site, terms.Turns, 0))),- () => bridge.Queue(new PioneerWork(u.Id, action, site.Id))).SetEnabled(!ordered && !taken && !ReturnQueued(bridge, u.Id));+ () => bridge.Queue(new PioneerWork(u.Id, action, site.Id))).SetEnabled(!ordered && !taken);PioneerReturn(host, bridge, text, u.Id);}}@@ -270,7 +265,7 @@ namespace Statecraft.Game.UIButton(host, $"corridor-build-{u.Id}", ordered ? text["site.ordered"]: text.Format("corridor.build_" + d.Kind, Group(text, s, u.Id), PlayerText.Money(c, "treasury", terms.Cost),Turns(text, Corridors.TurnsToBuild(c, s, u.Id, terms.Turns, 0))),- () => bridge.Queue(new PioneerWork(u.Id, action, target))).SetEnabled(!ordered && !taken && !ReturnQueued(bridge, u.Id));+ () => bridge.Queue(new PioneerWork(u.Id, action, target))).SetEnabled(!ordered && !taken);PioneerReturn(host, bridge, text, u.Id);}}diff --git a/unity/Assets/Scripts/UI/HudPresenter.cs b/unity/Assets/Scripts/UI/HudPresenter.csindex 40c20e577..522388303 100644--- a/unity/Assets/Scripts/UI/HudPresenter.cs+++ b/unity/Assets/Scripts/UI/HudPresenter.cs@@ -129,11 +129,16 @@ namespace Statecraft.Game.UI/// <summary>Statecraft.uss .hud-three-row .top-bar height.</summary>const float ThreeRowBarPx = 440f;- public HudPresenter(VisualElement root, SimBridge bridge, UiText text)+ public HudPresenter(VisualElement root, SimBridge bridge, UiText text, System.Action<int>? selectUnit = null){this.root = root; this.bridge = bridge; this.text = text;endTurn = root.Q<Button>("end-turn");- onEndTurn = () => bridge.EndTurn();+ onEndTurn = () =>+ {+ var needs = bridge.NeedsOrders;+ if (needs.Count > 0) selectUnit?.Invoke(needs[0]);+ else bridge.EndTurn();+ };endTurn.clicked += onEndTurn;endTurn.generateVisualContent += PaintHourglass;bar = root.Q<VisualElement>("top-bar");@@ -271,7 +276,7 @@ namespace Statecraft.Game.UI/// size), and the turn box widened in step. The one-row and icon tiers read the bar's width less this.</summary>float FloorGrowth(){- float growth = TurnBoxPx * (smallTextSize / SmallTextPx - 1f) + (RaisedPlateWidth() - PlateWidthPx);+ float growth = TurnBoxWidth - TurnBoxPx + (RaisedPlateWidth() - PlateWidthPx);foreach (var l in smallText){if (l.name == "attention" || string.IsNullOrEmpty(l.text)) continue;@@ -284,6 +289,9 @@ namespace Statecraft.Game.UI}// Statecraft.uss .turn-box width, .meter .meter-name max-width (170 on the three-row bar, where the tier is fixed), .date-box width.const float TurnBoxPx = 150f, CaptionMaxPx = 120f, PlateWidthPx = 230f;+ // The button keeps its stylesheet font; only the attention line grows with the text floor.+ float TurnBoxWidth => UnityEngine.Mathf.Max(bridge.NeedsOrders.Count > 0 ? 230f : TurnBoxPx,+ TurnBoxPx * smallTextSize / SmallTextPx);/// <summary>The widest date line's width per px of font size, with a little to spare: the Hebrew 31 October 1956 is/// about 7.8 times its size (196 px at 25 px), the English "30 September 1956" 7.2 (TopBarScoreLayoutTests.WorstDate).</summary>const float DateLinePerPx = 8f;@@ -331,7 +339,7 @@ namespace Statecraft.Game.UIdateRow.style.flexDirection = raised ? new StyleEnum<FlexDirection>(FlexDirection.Column) : new StyleEnum<FlexDirection>(StyleKeyword.Null);if (dateRow.parent != null) PadPlate(dateRow.parent, raised);}- var box = TurnBoxPx * smallTextSize / SmallTextPx;+ var box = TurnBoxWidth;turnBox.style.width = raised ? new StyleLength(box) : new StyleLength(StyleKeyword.Null);turnBox.style.minWidth = raised ? new StyleLength(box) : new StyleLength(StyleKeyword.Null);}@@ -481,6 +489,8 @@ namespace Statecraft.Game.UISet("cohesion", m.Cohesion);said["cohesion"].element.style.display = m.ShowsCohesion ? DisplayStyle.Flex : DisplayStyle.None;root.Q<Button>("end-turn").SetEnabled(bridge.State.GameOver == null);+ endTurn.text = text[bridge.NeedsOrders.Count > 0 ? "hud.end_turn_needs_orders" : "hud.end_turn"];+ turnBox.EnableInClassList("needs-orders", bridge.NeedsOrders.Count > 0);// #1109: a vacant seat the player can fill lights the Cabinet disc's badge, and its tip says why.var cabinet = root.Q<Button>("nav-cabinet"); bool vacant = bridge.Vacancies.Count > 0;cabinet.EnableInClassList(ActionClass, vacant);diff --git a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs b/unity/Assets/Scripts/UI/InfoPanelPresenter.csindex d4261c7be..9532f8c9c 100644--- a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs+++ b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs@@ -26,18 +26,22 @@ namespace Statecraft.Game.UIreadonly List<(VisualElement row, Label line)> rows = new List<(VisualElement, Label)>();readonly VisualElement panel; readonly SimBridge bridge; readonly UiText text;- readonly Button campButton, housingButton, defenceButton, moveButton, fortifyButton, holdButton, attackButton, sendHomeButton, reinforceButton;+ readonly Button campButton, housingButton, defenceButton, moveButton, fortifyButton, holdButton, attackButton, sendHomeButton, skipButton, reinforceButton;/// <summary>The Reinforce order the card offers now (#1510), or null: what its button queues.</summary>Reinforce? reinforce;- readonly System.Action onCamp, onHousing, onDefence, onMove, onFortify, onHold, onAttack, onSendHome, onReinforce;+ readonly System.Action onCamp, onHousing, onDefence, onMove, onFortify, onHold, onAttack, onSendHome, onSkip, onReinforce;readonly System.Func<PlacedToken?> selectedUnit;+ readonly System.Action? unitDone;bool unitMode;/// <summary>Lights the hexes the Move or Attack pick offers on the map (none: clears them); null: nothing is drawn.</summary>readonly System.Action<IReadOnlyCollection<(int q, int r)>>? showReachable;+ /// <summary>Draws a multi-turn go-to route and its arrival-turn numbers; null keeps picking functional without it.</summary>+ readonly System.Action<IReadOnlyList<(int q, int r, int turn)>>? showRoute;/// <summary>While the player picks a Move's or an Attack's hex: the unit, the hexes the sim gave (Movement.Reachable's,/// or those Combat.Check takes: the only ones a click takes), the session and turn they were read on (a turn or a/// load ends the pick, as the hexes change), and whether it is the attack's.</summary>- (int unit, HashSet<(int q, int r)> hexes, GameSession session, int turn, bool attack)? pick;+ (int unit, HashSet<(int q, int r)> hexes, GameSession session, int turn, bool attack, (int q, int r)? touchRoute)? pick;+ (int q, int r)? shownRoute;/// <summary>A sim unit's name on screen, for the attack's targets (GameRoot: its token's card title); null, or no/// name, gives the hex's coordinates.</summary>readonly System.Func<int, string?>? unitName;@@ -81,7 +85,9 @@ namespace Statecraft.Game.UIScreenNav? nav = null, System.Func<PlacedToken?>? selectedUnit = null, MapRegions? regions = null,System.Func<int, int, IReadOnlyList<Statecraft.Game.Map.Kits.Localities.Place>>? localitiesAt = null,System.Func<string, (int q, int r)>? townHex = null, IReadOnlyDictionary<string, string>? townNamesHe = null,- System.Action<IReadOnlyCollection<(int q, int r)>>? showReachable = null, System.Func<int, string?>? unitName = null)+ System.Action<IReadOnlyCollection<(int q, int r)>>? showReachable = null, System.Func<int, string?>? unitName = null,+ System.Action? unitDone = null,+ System.Action<IReadOnlyList<(int q, int r, int turn)>>? showRoute = null){panel = root.Q<VisualElement>("info-panel"); this.bridge = bridge; this.text = text;this.settlementNames = settlementNames; this.regions = regions; this.localitiesAt = localitiesAt; this.townHex = townHex;@@ -103,6 +109,8 @@ namespace Statecraft.Game.UIdefenceButton.clicked += onDefence;defenceButton.text = text["unit.defence"];this.showReachable = showReachable;+ this.unitDone = unitDone;+ this.showRoute = showRoute;moveButton = panel.Q<Button>("info-move");onMove = () => TogglePick(attack: false);moveButton.clicked += onMove;@@ -121,6 +129,10 @@ namespace Statecraft.Game.UIonSendHome = () => GiveOrder(Demobilization.SendHome);sendHomeButton.clicked += onSendHome;sendHomeButton.text = text["unit.order.send_home"];+ skipButton = panel.Q<Button>("info-skip");+ onSkip = Skip;+ skipButton.clicked += onSkip;+ skipButton.text = text["unit.order.skip"];reinforceButton = panel.Q<Button>("info-reinforce");onReinforce = () => { if (reinforce is Reinforce r) { bridge.Queue(r); Render(); } };reinforceButton.clicked += onReinforce;@@ -132,7 +144,7 @@ namespace Statecraft.Game.UIvoid OnHudGeometry(GeometryChangedEvent e) => panel.EnableInClassList(ShortClass, e.newRect.height < ShortBelowPx);/// <summary>Unsubscribes from the bridge and the buttons (the owner calls this when disabled).</summary>- public void Dispose() { presses.Dispose(); bridge.Changed -= Render; panel.parent?.UnregisterCallback<GeometryChangedEvent>(OnHudGeometry); campButton.clicked -= onCamp; housingButton.clicked -= onHousing; defenceButton.clicked -= onDefence; moveButton.clicked -= onMove; fortifyButton.clicked -= onFortify; holdButton.clicked -= onHold; attackButton.clicked -= onAttack; sendHomeButton.clicked -= onSendHome; reinforceButton.clicked -= onReinforce; EndPick(); }+ public void Dispose() { presses.Dispose(); bridge.Changed -= Render; panel.parent?.UnregisterCallback<GeometryChangedEvent>(OnHudGeometry); campButton.clicked -= onCamp; housingButton.clicked -= onHousing; defenceButton.clicked -= onDefence; moveButton.clicked -= onMove; fortifyButton.clicked -= onFortify; holdButton.clicked -= onHold; attackButton.clicked -= onAttack; sendHomeButton.clicked -= onSendHome; skipButton.clicked -= onSkip; reinforceButton.clicked -= onReinforce; EndPick(); }/// <summary>Below this window height (logical px; 1366x657 is about 998) the panel gets ShortClass, and the city's own/// hex folds its projects behind their toggle as on a stacked bar (GddHexPanel.ToggleName): there the full list ran into@@ -190,7 +202,7 @@ namespace Statecraft.Game.UI{var unit = unitMode ? selectedUnit() : null;if (unit == null || bridge.State.GameOver != null || !(UnitCard.SimUnit(bridge.Content, bridge.State, unit.Value.Token) is int id)) return null;- var reach = Movement.Reachable(bridge.Content, bridge.State, id);+ var reach = Movement.Reachable(bridge.Content, bridge.State, id, bridge.Spent);return reach.Count == 0 ? null : (id, reach);}@@ -205,7 +217,7 @@ namespace Statecraft.Game.UIvar hexes = new List<(int q, int r)>(); var refused = new List<string>();foreach (var (q, r) in s.Units.Values.Select(u => (u.Q, u.R)).Distinct()){- var why = Combat.Check(c, s, id, q, r);+ var why = Combat.Check(c, s, id, q, r, spent: bridge.Spent);if (why == null) hexes.Add((q, r));else if (Combat.Preview(c, s, id, q, r) != null && !refused.Contains(why)) refused.Add(why);}@@ -223,7 +235,7 @@ namespace Statecraft.Game.UIif (!again && !attack && MoveTargets() is { } m) offer = (m.unit, m.hexes.Keys.Select(h => (h.Q, h.R)).ToList());if (offer is { } o){- pick = (o.unit, new HashSet<(int q, int r)>(o.hexes), bridge.Session, bridge.State.Turn, attack);+ pick = (o.unit, new HashSet<(int q, int r)>(o.hexes), bridge.Session, bridge.State.Turn, attack, null);showReachable?.Invoke(o.hexes);}Render();@@ -231,8 +243,7 @@ namespace Statecraft.Game.UI/// <summary>Q-UI-1's preview of the shown unit's attack on (q, r), for the card: the defenders' names and the sim's/// strength ratio (Combat.Preview), then its combat_table row's outcome bands (Combat.Outcomes); empty where Preview- /// has none. Every number is the sim's, read on the state as it is: attacks queued for this turn and not yet stepped- /// are not in it (as for Fortify and Hold), so End turn can still refuse one with the sim's reason.</summary>+ /// has none. Every number is the sim's, read on the state after the turn's committed orders.</summary>string Odds(int unit, int q, int r){var c = bridge.Content; var s = bridge.State;@@ -258,31 +269,112 @@ namespace Statecraft.Game.UIvoid GiveOrder(string order){if (!(OrderUnit() is int id)) return;- bridge.Queue(new UnitOrder(id, order));+ if (bridge.Queue(new UnitOrder(id, order)) == null) UnitFinished();Render();}+ void Skip()+ {+ if (!(OrderUnit() is int id)) return;+ var keyboard = presses.ByKeyboard;+ bridge.Skip(id);+ UnitFinished();+ Render();+ // Skip hides its current button before cycling. Keep keyboard navigation on the next card, or End turn.+ if (keyboard) FocusReturn.To(skipButton.style.display.value == DisplayStyle.Flex+ ? skipButton : panel.panel?.visualTree.Q<Button>("end-turn"));+ }++ void UnitFinished()+ {+ if (bridge.NeedsOrders.Count > 0) unitDone?.Invoke();+ }+void EndPick(){if (pick == null) return;pick = null;+ shownRoute = null;showReachable?.Invoke(System.Array.Empty<(int q, int r)>());+ showRoute?.Invoke(System.Array.Empty<(int q, int r, int turn)>());+ }++ IReadOnlyList<(int q, int r, int turn)> RouteTo(+ (int unit, HashSet<(int q, int r)> hexes, GameSession session, int turn, bool attack, (int q, int r)? touchRoute) p,+ int q, int r)+ {+ if (p.attack || p.hexes.Contains((q, r))) return System.Array.Empty<(int, int, int)>();+ var now = bridge.Session.Now;+ return Movement.Route(bridge.Content, now.State, p.unit, q, r, now.Spent)+ .Select(h => (h.Q, h.R, h.Turn)).ToList();+ }++ /// <summary>Clears a hovered route (the mouse left the map): once, and so that the same hex shows it again later.</summary>+ public void HideRoute()+ {+ if (shownRoute == null) return;+ shownRoute = null;+ showRoute?.Invoke(System.Array.Empty<(int q, int r, int turn)>());}- /// <summary>A map click while the player picks a Move's or an Attack's hex (GameRoot.OnHexClicked asks first): on a lit- /// hex it queues the sim's Move, or its UnitOrder(unit, attack, q, r), through the bridge and returns true (the click is- /// taken, the card stays); anywhere else it only ends the pick and returns false, so the click selects as usual. False- /// when no pick is open.</summary>- public bool PickTarget(int q, int r)+ /// <summary>Shows the route to the hovered unlit hex while Move is picking; otherwise clears it.</summary>+ public void ShowRouteTo(int q, int r)+ {+ if (shownRoute == (q, r)) return;+ shownRoute = (q, r);+ var route = pick is { } p ? RouteTo(p, q, r) : System.Array.Empty<(int, int, int)>();+ showRoute?.Invoke(route);+ }++ /// <summary>A map click while the player picks a Move's or an Attack's hex (GameRoot.OnHexClicked asks first): a lit+ /// hex gives the Move or attack; an unlit hex with a route gives go-to. Touch previews that route on the first tap and+ /// confirms it on a second tap of the same hex. A hex with no target ends the pick and selects as usual.</summary>+ public bool PickTarget(int q, int r, bool touch = false){if (!(pick is { } p)) return false;+ Command? command = p.hexes.Contains((q, r))+ ? p.attack ? new UnitOrder(p.unit, Combat.Attack, q, r) : new Move(p.unit, q, r)+ : null;+ if (command == null && !p.attack)+ {+ var route = RouteTo(p, q, r);+ if (route.Count > 0)+ {+ if (touch && p.touchRoute != (q, r))+ {+ pick = (p.unit, p.hexes, p.session, p.turn, p.attack, (q, r));+ shownRoute = (q, r);+ showRoute?.Invoke(route);+ Render();+ return true;+ }+ command = new UnitOrder(p.unit, Movement.GoTo, q, r);+ }+ }EndPick();- if (!p.hexes.Contains((q, r))) return false;- bridge.Queue(p.attack ? new UnitOrder(p.unit, Combat.Attack, q, r) : (Command)new Move(p.unit, q, r)); // a refusal is raised by the bridge (Refused)- Render(); // the card drops the pick line either way: a refused Queue raises no Changed+ if (command == null) return false;+ var refused = bridge.Queue(command); // a refusal is raised by the bridge (Refused)+ if (refused == null && (command is UnitOrder || Movement.PointsLeft(bridge.Content, bridge.State, p.unit, bridge.Spent) == 0))+ {+ UnitFinished();+ Render();+ }+ else if (refused == null && command is Move && MoveTargets() is { }) TogglePick(false);+ else Render(); // a refused Queue raises no Changedreturn true;}+ string GoToLine(int unit)+ {+ var now = bridge.Session.Now;+ if (!now.State.Units.TryGetValue(unit, out var u) || u.Order != Movement.GoTo) return "";+ var parts = u.OrderTarget.Split(',');+ if (parts.Length != 2 || !int.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var q)+ || !int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var r)) return "";+ var route = Movement.Route(bridge.Content, now.State, unit, q, r, now.Spent);+ return route.Count == 0 ? "" : text.Format("unit.go_to_given", System.Math.Max(0, route[route.Count - 1].Turn - 1));+ }+void Build(string action){if (Selected == null) return;@@ -404,6 +496,14 @@ namespace Statecraft.Game.UIvar c = bridge.Content; var s = bridge.State;var camp = campButton; var housing = housingButton;var unit = unitMode ? selectedUnit() : null;+ // A unit that has left the state (destroyed or surrendered in its own attack) closes its card; a row with no+ // sim unit at all (an aircraft squadron, the legacy loop) keeps its card.+ if (unit != null && (unit.Value.Token.SimId != null || c.StartingForces.Any(f => f.Row == unit.Value.Token.Unit.Id))+ && UnitCard.SimUnit(c, s, unit.Value.Token) == null)+ {+ unitMode = false;+ unit = null;+ }defenceButton.style.display = unit != null ? DisplayStyle.Flex : DisplayStyle.None;// A pick read on another turn or session, or for a unit no longer shown, is over: its hexes are not the sim's now.if (pick is { } open@@ -428,8 +528,9 @@ namespace Statecraft.Game.UIforeach (var why in attacks?.refused ?? new List<string>()) if (own && !refusals.Contains(why)) refusals.Add(why);// Send home (#1309): Demobilization.Check is the complete eligibility rule. A refusal hides the order and adds// no card copy; the player sees it only after the relevant armistice makes the order available.- var sendHomeWhy = orderUnit is int du ? Demobilization.Check(c, s, du) : null;+ var sendHomeWhy = orderUnit is int du ? Demobilization.Check(c, s, du, bridge.Session.Now.Attacked) : null;sendHomeButton.style.display = orderUnit != null && sendHomeWhy == null ? DisplayStyle.Flex : DisplayStyle.None;+ skipButton.style.display = own == true && orderUnit != null && bridge.NeedsOrders.Contains(orderUnit.Value) ? DisplayStyle.Flex : DisplayStyle.None;// Reinforce (#1510, R-TRAIN-004): offered for a unit of Israel's that has lost strength and stands in a city, for// the missing strength up to the city's free civilians; the sim's own Reinforce, run on a copy, decides, and its// refusal shows as the other orders' do. None while one is queued for the unit.@@ -450,16 +551,19 @@ namespace Statecraft.Game.UI{var card = UnitCard.For(unit.Value, s, text, c.IsGdd, c, townNamesHe);panel.EnableInClassList("info-empty", false);- // The orders' state under the card's lines: the pick asks for a hex (an attack's with each lit hex's odds, Q-UI-1);- // a queued Move, Fortify, Hold, Attack or Send home waits for End turn (an attack's with its hex's odds).+ // The orders' state under the card's lines: the pick asks for a hex (an attack's with each lit hex's odds, Q-UI-1).var order = pick is { attack: true } ap ? string.Join("\n", new[] { text["unit.attack_pick"] }.Concat(ap.hexes.Select(h => Odds(ap.unit, h.q, h.r))).Where(x => x != ""))- : pick != null ? text["unit.move_pick"]- : moves is { } m && bridge.QueuedLike(new Move(m.unit, 0, 0)) != null ? text["unit.move_queued"] : "";- var standing = orderUnit is int su && bridge.QueuedLike(new UnitOrder(su, Orders.Hold)) is UnitOrder given- ? given.Order == Orders.Fortify ? text["unit.fortify_queued"] : given.Order == Orders.Hold ? text["unit.hold_queued"]- : given.Order == Combat.Attack && given.Q is int gq && given.R is int gr ? text["unit.attack_queued"] + "\n" + Odds(su, gq, gr)- : given.Order == Demobilization.SendHome ? text["unit.send_home_queued"] : "" : "";- var lines = new[] { card.Body, order, standing, reinforceQueued ? text["unit.reinforce_queued"] : "" }.Where(x => x != "");+ : pick != null ? text["unit.move_pick"] : "";+ var standing = orderUnit is int su && s.Units.TryGetValue(su, out var shown)+ ? shown.Order == Orders.Fortify || shown.Order == Orders.Fortifying ? text["unit.fortify_queued"]+ : shown.Order == Orders.Hold ? text["unit.hold_queued"]+ : bridge.QueuedLike(new UnitOrder(su, Demobilization.SendHome)) != null ? text["unit.send_home_queued"] : ""+ : "";+ var points = orderUnit is int pu && s.Units.TryGetValue(pu, out var military) && military.Side == Movement.PlayerSide+ && c.UnitTypes.FirstOrDefault(t => t.Id == military.Type) is { MovementPoints: > 0 } type+ ? text.Format("unit.points", Movement.PointsLeft(c, s, pu, bridge.Spent), type.MovementPoints) : "";+ var routeLine = orderUnit is int routeUnit ? GoToLine(routeUnit) : "";+ var lines = new[] { card.Body, points, order, routeLine, standing, reinforceQueued ? text["unit.reinforce_queued"] : "" }.Where(x => x != "");title.text = card.Title; subtitle.text = card.Subtitle; settlements.text = string.Join("\n", lines);ShowLocalities("");region.text = ""; // a unit's card names no sub-district (the last hex's would stay under it)diff --git a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs b/unity/Assets/Scripts/UI/MapLabelsPresenter.csindex a88a7e70e..ccf4f72bb 100644--- a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs+++ b/unity/Assets/Scripts/UI/MapLabelsPresenter.cs@@ -2,6 +2,7 @@using System;using System.Collections.Generic;using System.Globalization;+using System.Linq;using Statecraft.Game.Map;using UnityEngine;using UnityEngine.UIElements;@@ -70,6 +71,7 @@ namespace Statecraft.Game.UIpublic sealed class MapLabelsPresenter : IDisposable{public const string ContainerName = "map-labels", SlotClass = "map-label-slot", LabelClass = "map-label";+ public const string RouteTurnClass = "map-route-turn";public const float LiftPx = 6f, MarginPx = 4f, DeclutterDistanceM = 150000f;/// <summary>The 1948 localities are named only nearer than this (owner ruling 2026-10-11: names at closer zoom, so/// the map is not cluttered); farther out their pills are hidden and their places are nobody's neighbour.</summary>@@ -334,6 +336,8 @@ namespace Statecraft.Game.UImap.TryKitColumns(s.Id, out var columns) ? columns : MarkerBox(s, markerTop);readonly List<Item> siteItems = new List<Item>();+ readonly List<(VisualElement slot, Label label, int q, int r)> routeLabels = new List<(VisualElement, Label, int, int)>();+ IReadOnlyList<(int q, int r, int turn)> labelledRoute = Array.Empty<(int, int, int)>();/// <summary>GDD Phase 1 PR 8 (#381): the built sites' pills (SiteLayer.Places), replacing the last ones given. Each is/// placed like a kibbutz's: after the game settlements and before the 1948 localities, against its kit's columns@@ -363,6 +367,29 @@ namespace Statecraft.Game.UI/// <summary>The built sites' pills (SetSites), in the order given.</summary>public IReadOnlyList<Label> SiteLabels { get { var l = new List<Label>(); foreach (var x in siteItems) l.Add(x.Label); return l; } }+ /// <summary>Rebuilds the presentation-only number at the last hex of each shown route turn.</summary>+ void SyncRouteLabels()+ {+ var route = map.ShownRoute;+ if (route.Count == labelledRoute.Count && route.SequenceEqual(labelledRoute)) return;+ foreach (var x in routeLabels) x.slot.RemoveFromHierarchy();+ routeLabels.Clear();+ for (int i = 0; i < route.Count; i++)+ {+ if (i + 1 < route.Count && route[i + 1].turn == route[i].turn) continue;+ var h = route[i];+ var slot = new VisualElement { name = "route-turn-slot-" + h.turn, pickingMode = PickingMode.Ignore };+ slot.AddToClassList(SlotClass);+ var label = new Label(h.turn.ToString(CultureInfo.InvariantCulture))+ { name = "route-turn-" + h.turn, pickingMode = PickingMode.Ignore };+ label.AddToClassList(LabelClass); label.AddToClassList(RouteTurnClass);+ slot.Add(label); container.Insert(System.Math.Max(0, container.IndexOf(Tooltip)), slot);+ routeLabels.Add((slot, label, h.q, h.r));+ }+ labelledRoute = route.ToList();+ geometryDirty = true;+ }+/// <summary>A settlement's marker box (what is drawn while the "kits" toggle is off).</summary>public static Bounds[] MarkerBox(Settlement s, Vector3 markerTop){@@ -425,14 +452,15 @@ namespace Statecraft.Game.UIpublic void Refresh(bool force = false){+ SyncRouteLabels();var panel = container.panel;- if (panel == null || camera == null) return;+ if (panel == null || camera == null || map == null) return;var viewProjection = camera.projectionMatrix * camera.worldToCameraMatrix;var cameraRect = camera.rect;var screen = panel.visualTree.layout.size; // the whole panel, which the camera's view fillsvar origin = container.worldBound.position; // slots translate from the layer's top-leftfloat distance = Zoom();- bool kitsShown = map != null && map.KitsShown; // with the "kits" toggle off the marker boxes are drawn instead+ bool kitsShown = map.KitsShown; // with the "kits" toggle off the marker boxes are drawn insteadint mask = OccluderMask();float labelSizes = 0f; // a pill that grows or shrinks (a late font, a new text) is re-placed (re-review N2)bool localities = distance <= LocalityDistanceM; // farther out the localities are skipped outright (cost)@@ -526,6 +554,18 @@ namespace Statecraft.Game.UIit.Slot.style.visibility = shown ? Visibility.Visible : Visibility.Hidden;if (shown && laidOut) it.Slot.style.translate = new Translate(at.x + shift.x, at.y + shift.y);}+ foreach (var x in routeLabels)+ {+ var hex = map.Hexes.hexes.FirstOrDefault(h => h.q == x.q && h.r == x.r);+ if (hex == null || map.Terrain == null) { x.slot.style.visibility = Visibility.Hidden; continue; }+ var world = map.Frame.ToWorld(hex.lon, hex.lat, 0);+ world.y = map.Terrain.SampleHeight(world) + MapScene.SelectionClearanceM;+ var viewport = camera.WorldToViewportPoint(world);+ var at = ToPanel(viewport, cameraRect, screen, origin);+ bool shown = viewport.z > 0f && viewport.x >= 0f && viewport.x <= 1f && viewport.y >= 0f && viewport.y <= 1f && !UnderAPanel(at);+ x.slot.style.visibility = shown ? Visibility.Visible : Visibility.Hidden;+ if (shown) x.slot.style.translate = new Translate(at.x, at.y);+ }}/// <summary>Whether the pill fits at <paramref name="spot"/>; if so records it as placed and sets the shift from@@ -730,6 +770,8 @@ namespace Statecraft.Game.UIforeach (var slot in LocationSlots) slot.RemoveFromHierarchy();foreach (var it in siteItems) it.Slot.RemoveFromHierarchy();siteItems.Clear();+ foreach (var x in routeLabels) x.slot.RemoveFromHierarchy();+ routeLabels.Clear(); labelledRoute = Array.Empty<(int, int, int)>();Tooltip.RemoveFromHierarchy();items.Clear(); settlementOrder.Clear();}diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.csindex ecf71c3f5..deb61d3c4 100644--- a/unity/Assets/Scripts/UI/SimBridge.cs+++ b/unity/Assets/Scripts/UI/SimBridge.cs@@ -7,18 +7,29 @@ using Statecraft.Sim;namespace Statecraft.Game.UI{/// <summary>The UI's only door into the simulation (spec section 6). Holds the GameSession, collects this turn's- /// orders, runs End Turn and tells the screens to refresh. Orders take effect at End Turn, in the order given; each- /// order replaces an earlier one with the same key (one choice per event, one call-up level, one budget, one appointee+ /// orders, runs End Turn and tells the screens to refresh. R-TURN-004's instant orders are committed and shown at once;+ /// deferred orders take effect at End Turn, in the order given. Each deferred order replaces an earlier one with the same key (one choice per event, one call-up level, one budget, one appointee/// per office, one policy level per policy, one build per hex, one work order per city, one training order per city and/// track, one cancel per cohort, one pioneer order per unit).</summary>public sealed class SimBridge{- readonly List<Command> queue = new List<Command>();+ readonly List<Command> deferred = new List<Command>();+ readonly HashSet<int> skipped = new HashSet<int>();public GameSession Session { get; private set; }public Content Content => Session.Content;- public GameState State => Session.State;- public IReadOnlyList<Command> Queued => queue;+ /// <summary>The state the map and the cards show: the turn's start after its committed orders (R-TURN-004).</summary>+ // An empty order preview is equivalent to the turn start only without automatic go-to work.+ // RunOrders advances standing routes before any player order (spec6.3).+ public GameState State => Session.Committed.Count == 0 && !Session.State.Units.Values.Any(u => u.Order == Movement.GoTo)+ ? Session.State : Session.Now.State;+ /// <summary>The state the turn began with (the saved one): what End turn and the orders' prices start from.</summary>+ public GameState TurnStart => Session.State;+ /// <summary>The movement points each unit has spent this turn.</summary>+ public IReadOnlyDictionary<int, int> Spent => Session.Now.Spent;+ public IReadOnlyList<Command> Queued => deferred;+ /// <summary>R-MOVE-010: the units End turn waits for, in ascending id, less those skipped this turn and those going home.</summary>+ public IReadOnlyList<int> NeedsOrders => Movement.NeedsOrders(Content, State, Spent).Where(id => !skipped.Contains(id) && !GoingHome(id)).ToList();/// <summary>The orders the last turn ran with (empty until a turn has run, and after a refused batch): what the player/// chose, as against what the turn delegated (OutcomePresenter plays a clip only for a choice).</summary>public IReadOnlyList<Command> LastBatch { get; private set; } = Array.Empty<Command>();@@ -31,6 +42,8 @@ namespace Statecraft.Game.UIpublic event Action? Changed;/// <summary>Raised after End Turn with the orders the simulation refused (possibly none).</summary>public event Action<IReadOnlyList<Rejection>>? TurnEnded;+ /// <summary>Raised after a move or unit order is committed, with the Why lines it added (an attack's result).</summary>+ public event Action<IReadOnlyList<Cause>>? Committed;/// <summary>Raised when Queue refuses an order, with the player-facing reason.</summary>public event Action<string>? Refused;/// <summary>A validated order was refused specifically for Attention; presentation-only advice signal.</summary>@@ -39,11 +52,11 @@ namespace Statecraft.Game.UIreadonly UiText text;readonly Func<GameSession, IReadOnlyList<Command>, StepResult> step;- /// <param name="step">How a turn is run; the default is Session.Step. Tests pass a stepper that throws, to prove+ /// <param name="step">How a turn is run; the default is Session.EndTurn. Tests pass a stepper that throws, to prove/// that a batch the simulation refuses outright cannot soft-lock the game.</param>public SimBridge(GameSession session, UiText text, Func<GameSession, IReadOnlyList<Command>, StepResult>? step = null){- this.step = step ?? ((s, cmds) => s.Step(cmds));+ this.step = step ?? ((s, cmds) => s.EndTurn(cmds));Session = session ?? throw new ArgumentNullException(nameof(session));this.text = text ?? throw new ArgumentNullException(nameof(text));}@@ -65,17 +78,16 @@ namespace Statecraft.Game.UIReinforce x => FormattableString.Invariant($"reinforce:{x.Unit}"),PioneerWork w => FormattableString.Invariant($"unit:{w.Unit}"),StopWork w => FormattableString.Invariant($"unit:{w.Unit}"),- UnitOrder o => FormattableString.Invariant($"order:{o.Unit}"),+ UnitOrder o when o.Order == Demobilization.SendHome => FormattableString.Invariant($"order:{o.Unit}"),StartProject p => FormattableString.Invariant($"project:{p.Q},{p.R}"),CancelProject x => FormattableString.Invariant($"unproject:{x.Project}"),- Move m => FormattableString.Invariant($"move:{m.Unit}"),ResolveCapture r => "capture:" + r.Settlement,EndOccupation e => "endocc:" + e.Settlement,_ => c.Kind,};/// <summary>The order's Attention price at this turn's prices: what <see cref="Queue"/> charges and the card shows.</summary>- public double Price(Command c) => AttentionSystem.Price(Content, State, c);+ public double Price(Command c) => AttentionSystem.Price(Content, TurnStart, c);/// <summary>Whether the Attention left pays for the order (a queued order with its key is refunded first): the one/// check <see cref="Queue"/> refuses on, so the event card (#1034) and a refusal can never disagree.</summary>@@ -85,21 +97,29 @@ namespace Statecraft.Game.UI/// <summary>Who End Turn hands the event to with the orders queued now (Simulation.DelegatedTo), or null for the/// cabinet: an appointment queued this turn is in office by then (#1034).</summary>- public Person? DelegatedTo(GameEvent e) => Simulation.DelegatedTo(Content, State, queue, e.Id);+ public Person? DelegatedTo(GameEvent e) => Simulation.DelegatedTo(Content, TurnStart, All, e.Id);/// <summary>The vacant seats the player can fill, less those an appointment queued now fills (Cabinet.Vacancies): the/// side menu's Cabinet badge (#1109).</summary>- public IReadOnlyList<Office> Vacancies => Cabinet.Vacancies(Content, State, queue);+ public IReadOnlyList<Office> Vacancies => Cabinet.Vacancies(Content, TurnStart, All);/// <summary>Whether the Budget screen's <paramref name="draft"/> is not what End turn will apply and Submit can apply it/// (EconomySystem.Unsubmitted): the side menu's Budget badge (#1109).</summary>- public bool BudgetUnsubmitted(IReadOnlyDictionary<string, double> draft) => EconomySystem.Unsubmitted(Content, State, draft, queue);+ public bool BudgetUnsubmitted(IReadOnlyDictionary<string, double> draft) => EconomySystem.Unsubmitted(Content, TurnStart, draft, deferred);/// <summary>Attention left after paying for the queued orders at this turn's prices.</summary>- public double AttentionLeft => AttentionSystem.Left(Content, State, queue);+ public double AttentionLeft => AttentionSystem.Left(Content, TurnStart, All);/// <summary>The queued order with this key, or null.</summary>- public Command? QueuedLike(Command c) => queue.FirstOrDefault(q => Key(q) == Key(c));+ public Command? QueuedLike(Command c) => deferred.FirstOrDefault(q => Key(q) == Key(c));++ IReadOnlyList<Command> All => Session.Committed.Concat(deferred).ToList();++ bool GoingHome(int unit) => deferred.Any(x => x is UnitOrder o && o.Unit == unit && o.Order == Demobilization.SendHome);++ /// <summary>Skips the unit for this turn: not an order, not saved, nothing in the game changes (spec 7.2).</summary>+ public void Skip(int unit) { if (skipped.Add(unit)) Notify(Changed); }+ public bool IsSkipped(int unit) => skipped.Contains(unit);/// <summary>Null if the id is known, else the player-facing reason. The player sees only the kind of thing (#622: a/// content id means nothing to them), in the UI's language: the string order.kind.<kind> (#595). The id goes to@@ -201,6 +221,17 @@ namespace Statecraft.Game.UIvar bad = Validate(c);if (bad != null) return Refuse(bad);if (State.GameOver != null) return Refuse(text["order.game_over"]);+ if (Simulation.IsInstant(c))+ {+ var unit = c is Move m ? m.Unit : ((UnitOrder)c).Unit;+ if (GoingHome(unit)) return Refuse(text["order.going_home"]);+ var before = Session.Now.Why.Count;+ var refused = Session.Commit(c);+ if (refused != null) return Refuse(refused);+ Notify(Changed);+ Notify(Committed, Session.Now.Why.Skip(before).ToList());+ return null;+ }if (c is AllocateBudget ab) c = new AllocateBudget(new Dictionary<string, double>(ab.Shares)); // a snapshot: later edits to the caller's dictionary must not change the orderif (!CanPay(c)){@@ -208,31 +239,31 @@ namespace Statecraft.Game.UIreturn Refuse(text.Format("order.no_attention", Price(c), LeftFor(c)));}var old = QueuedLike(c);- if (old != null) queue[queue.IndexOf(old)] = c; else queue.Add(c);- Changed?.Invoke();+ if (old != null) deferred[deferred.IndexOf(old)] = c; else deferred.Add(c);+ Notify(Changed);return null;}public void Withdraw(Command c){- if (queue.Remove(c)) Changed?.Invoke();+ if (deferred.Remove(c)) Notify(Changed);}- /// <summary>Runs the turn with the queued orders, clears the queue, and notifies. If the simulation refuses the- /// 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>+ /// <summary>Runs the turn with the committed then deferred orders, clears the deferred queue, and notifies. If the+ /// simulation refuses the batch outright, committed orders stay in the open turn and deferred orders are cleared;+ /// the reason is raised through TurnEnded like any refusal.</summary>public StepResult EndTurn(){StepResult r;- var batch = queue.ToList();- var date = State.Date;- try { r = step(Session, batch); }+ var batch = Session.Committed.Concat(deferred).ToList();+ var date = TurnStart.Date;+ try { r = step(Session, deferred.ToList()); } // a snapshot: the queue is cleared belowcatch (Exception e) // any exception (M3 final review M7): never leave a queue that fails on every End Turn{// A refusal (ArgumentException) is a clear warning, anything else the full exception: both leave a trace.if (e is ArgumentException) UnityEngine.Debug.LogWarning("End Turn refused: " + e.Message);else UnityEngine.Debug.LogException(e);- queue.Clear();+ deferred.Clear(); skipped.Clear();LastBatch = Array.Empty<Command>();var reason = text["order.failed"]; // the message stays in the log above, not on screen (#622)var failed = new StepResult(State, new Cause[0], batch.Select(x => new Rejection(x, reason)).ToList());@@ -241,7 +272,7 @@ namespace Statecraft.Game.UIreturn failed;}LastBatch = batch; LastBatchDate = date;- queue.Clear();+ deferred.Clear(); skipped.Clear();Notify(Changed);Notify(TurnEnded, r.Rejected);return r;@@ -252,8 +283,8 @@ namespace Statecraft.Game.UI{Session = session ?? throw new ArgumentNullException(nameof(session));LastBatch = Array.Empty<Command>();- queue.Clear();- Changed?.Invoke();+ deferred.Clear(); skipped.Clear();+ Notify(Changed);}}}diff --git a/unity/Assets/Scripts/UI/ToastPresenter.cs b/unity/Assets/Scripts/UI/ToastPresenter.csindex 04ffe1a97..3794b47cf 100644--- a/unity/Assets/Scripts/UI/ToastPresenter.cs+++ b/unity/Assets/Scripts/UI/ToastPresenter.cs@@ -1,6 +1,9 @@#nullable enable+using System;using System.Collections.Generic;using System.Linq;+using Statecraft.Game.Map.Units;+using Statecraft.Sim;using UnityEngine.UIElements;namespace Statecraft.Game.UI@@ -10,19 +13,38 @@ namespace Statecraft.Game.UIpublic sealed class ToastPresenter : System.IDisposable{readonly Label label; readonly UiText text; readonly SimBridge bridge;- readonly System.Action<IReadOnlyList<Statecraft.Sim.Rejection>> onTurnEnded;+ readonly Action<IReadOnlyList<Rejection>> onTurnEnded, onRouteStep;+ readonly Action<IReadOnlyList<Cause>> onCommitted;+ IReadOnlyList<UnitEntry> units = Array.Empty<UnitEntry>();++ /// <summary>The units_1948.yaml rows that name starting forces in the committed orders' Why lines (GameRoot sets+ /// them once the map has read them, as for WhyPresenter); without them a starting force is named by its type.</summary>+ public IReadOnlyList<UnitEntry> Units { get => units; set => units = value ?? Array.Empty<UnitEntry>(); }+ /// <summary>Each settlement's Hebrew name, by id (the map's parse), for a raised unit's home city in Hebrew.</summary>+ public IReadOnlyDictionary<string, string>? TownNamesHe { get; set; }public ToastPresenter(VisualElement root, SimBridge bridge, UiText text){label = root.Q<Label>("toast"); this.text = text; this.bridge = bridge;onTurnEnded = r => Show(r.Select(x => text.Format("toast.refused", x.Reason)));+ onCommitted = why => Show(why.Where(x => !string.IsNullOrEmpty(x.Key))+ .Select(x => UnitNames.Line(x, bridge.Content, units, text, TownNamesHe)));+ onRouteStep = _ =>+ {+ var lines = bridge.Session.Now.Why+ .Where(x => x.Key == WhyKeys.Arrived || x.Key == WhyKeys.StoppedNoRoute || x.Key == WhyKeys.StoppedFull)+ .Select(x => UnitNames.Line(x, bridge.Content, units, text, TownNamesHe)).ToList();+ if (lines.Count > 0) Append(string.Join("\n", lines));+ };bridge.TurnEnded += onTurnEnded;+ bridge.TurnEnded += onRouteStep;bridge.Refused += Refuse;bridge.Changed += Clear;+ bridge.Committed += onCommitted;Clear();}- public void Dispose() { bridge.TurnEnded -= onTurnEnded; bridge.Refused -= Refuse; bridge.Changed -= Clear; }+ public void Dispose() { bridge.TurnEnded -= onTurnEnded; bridge.TurnEnded -= onRouteStep; bridge.Refused -= Refuse; bridge.Changed -= Clear; bridge.Committed -= onCommitted; }/// <summary>Shows the lines as they are (none = hide).</summary>public void Show(IEnumerable<string> lines)diff --git a/unity/Assets/Scripts/UI/TurnReportPresenter.cs b/unity/Assets/Scripts/UI/TurnReportPresenter.csindex b37942d9a..fce4df46e 100644--- a/unity/Assets/Scripts/UI/TurnReportPresenter.cs+++ b/unity/Assets/Scripts/UI/TurnReportPresenter.cs@@ -117,18 +117,17 @@ namespace Statecraft.Game.UI{var turn = bridge.Session.Last;if (turn == null) return Array.Empty<string>();- var forces = bridge.Content.StartingForces; bool hebrew = text["ui.lang"] == UiLanguage.Hebrew;- string Name(int id)+ string Name(Cause cause, int id){- var row = id < forces.Count ? units?.FirstOrDefault(u => u.Id == forces[id].Row) : null;- if (row == null) return text.Format("report.unit", id);- return hebrew && !string.IsNullOrEmpty(row.NameHe) ? row.NameHe : row.Name;+ var snapshot = cause.Units.FirstOrDefault(u => u.Id == id);+ if (snapshot != null) return UnitNames.Of(snapshot, bridge.Content, units ?? Array.Empty<UnitEntry>(), text);+ return text.Format("report.unit", id);}// An engagement (#1297) names its enemy attackers, one line each, and gives no line if it names none: its Target is// a hex, not a unit. An order names its unit, Target.return turn.Why.Where(w => w.EnemyOrder != "").SelectMany(w => (w.EnemyOrder == Combat.Attack ? w.EnemyAttackers : new[] { int.Parse(w.Target, CultureInfo.InvariantCulture) })- .Select(id => text.Format("report.enemy_" + w.EnemyOrder, Name(id)))).ToList();+ .Select(id => text.Format("report.enemy_" + w.EnemyOrder, Name(w, id)))).ToList();}void Show()diff --git a/unity/Assets/Scripts/UI/UnitCard.cs b/unity/Assets/Scripts/UI/UnitCard.csindex 83278f0c2..f5f11cfe1 100644--- a/unity/Assets/Scripts/UI/UnitCard.cs+++ b/unity/Assets/Scripts/UI/UnitCard.cs@@ -34,6 +34,17 @@ namespace Statecraft.Game.UIpublic static int? SimUnit(Content c, GameState s, UnitToken token) =>token.SimId is int id ? s.Units.ContainsKey(id) ? id : (int?)null : SimUnit(c, s, token.Unit);+ /// <summary>A raised unit's type on screen (#1396), or null for a type no raised unit has. The card's title and the+ /// Why lines' unit names (UnitNames, #1399) both read it.</summary>+ public static string? RaisedType(string type, UiText text) => type switch+ {+ "recruit" => text["city.track_recruit"],+ StartingForces.IsraeliBrigadeType => text["unit.type.veteran_soldier"],+ "artillery" => text["city.track_artillery"],+ "armoured_car" => text["city.track_armoured_car"],+ _ => null,+ };+public static UnitCard For(PlacedToken placed, GameState state, UiText text, bool gddLoop = false, Content? content = null,IReadOnlyDictionary<string, string>? settlementNamesHe = null){@@ -53,14 +64,7 @@ namespace Statecraft.Game.UI? text.Format("date.month_year", text["date.month_" + m.Month], m.Year) : english;}var lines = new List<string>();- string? raisedType = t.Raised && t.StateUnit != null ? t.StateUnit.Type switch- {- "recruit" => text["city.track_recruit"],- StartingForces.IsraeliBrigadeType => text["unit.type.veteran_soldier"],- "artillery" => text["city.track_artillery"],- "armoured_car" => text["city.track_armoured_car"],- _ => null,- } : null;+ string? raisedType = t.Raised && t.StateUnit != null ? RaisedType(t.StateUnit.Type, text) : null;string home = t.StateUnit != null && t.StateUnit.HomeCity != "" && content != null&& content.SettlementNames.TryGetValue(t.StateUnit.HomeCity, out var city) ? city : "";if (hebrew && t.StateUnit != null && settlementNamesHe != nulldiff --git a/unity/Assets/Scripts/UI/UnitNames.cs b/unity/Assets/Scripts/UI/UnitNames.csnew file mode 100644index 000000000..a25047337--- /dev/null+++ b/unity/Assets/Scripts/UI/UnitNames.cs@@ -0,0 +1,61 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Globalization;+using System.Linq;+using Statecraft.Game.Map.Units;+using Statecraft.Sim;++namespace Statecraft.Game.UI+{+ /// <summary>#1399: names a unit snapshot and formats the structured Why lines that contain one. A starting force is+ /// named by its units_1948.yaml row (name_he in Hebrew where the row has one); a raised unit by its type and home city+ /// (UnitCard.RaisedType; the city's Hebrew name from <c>namesHe</c>, the map's parse, as the unit card does).</summary>+ public static class UnitNames+ {+ public static string Of(UnitRef unit, Content c, IReadOnlyList<UnitEntry> rows, UiText text,+ IReadOnlyDictionary<string, string>? namesHe = null)+ {+ if (unit.Id >= 0 && unit.Id < c.StartingForces.Count)+ {+ var force = c.StartingForces[unit.Id];+ if (force.Type == unit.Type && force.Side == unit.Side)+ {+ var row = rows.FirstOrDefault(x => x.Id == force.Row);+ if (row != null)+ return text["ui.lang"] == UiLanguage.Hebrew && !string.IsNullOrEmpty(row.NameHe) ? row.NameHe : row.Name;+ }+ }++ var type = UnitCard.RaisedType(unit.Type, text) ?? unit.Type;+ return string.IsNullOrEmpty(unit.HomeCity)+ ? type+ : text.Format("unit.raised_name", type, ContentNames.Settlement(text, c, unit.HomeCity, namesHe));+ }++ public static string Line(Cause cause, Content c, IReadOnlyList<UnitEntry> rows, UiText text,+ IReadOnlyDictionary<string, string>? namesHe = null)+ {+ if (string.IsNullOrEmpty(cause.Key)) return cause.Message;+ if (cause.Key == WhyKeys.Engagement)+ {+ var attackers = int.Parse(cause.Args[4], CultureInfo.InvariantCulture);+ return text.Format("why.line." + cause.Key,+ string.Join(", ", cause.Units.Take(attackers).Select(u => Of(u, c, rows, text, namesHe))),+ string.Join(", ", cause.Units.Skip(attackers).Select(u => Of(u, c, rows, text, namesHe))),+ cause.Args[0], Number(cause.Args[1]), Number(cause.Args[2]), Number(cause.Args[3]));+ }++ var args = cause.Args.ToArray();+ if (cause.Key == WhyKeys.SentHome && args.Length > 1)+ args[1] = ContentNames.Settlement(text, c, args[1], namesHe);+ else if (cause.Key == WhyKeys.Withdrew && args.Length > 0)+ args[0] = ContentNames.Settlement(text, c, args[0], namesHe);+ var values = cause.Units.Select(u => (object)Of(u, c, rows, text, namesHe))+ .Concat(args.Select(Number)).ToArray();+ return text.Format("why.line." + cause.Key, values);+ }++ static object Number(string value) => int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : value;+ }+}diff --git a/unity/Assets/Scripts/UI/UnitNames.cs.meta b/unity/Assets/Scripts/UI/UnitNames.cs.metanew file mode 100644index 000000000..e9fb9a432--- /dev/null+++ b/unity/Assets/Scripts/UI/UnitNames.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 1f5a6b91fd7b4d25b53d2b1f1bbaf349diff --git a/unity/Assets/Scripts/UI/WhyPresenter.cs b/unity/Assets/Scripts/UI/WhyPresenter.csindex 30b141615..e0d866014 100644--- a/unity/Assets/Scripts/UI/WhyPresenter.cs+++ b/unity/Assets/Scripts/UI/WhyPresenter.cs@@ -1,5 +1,7 @@#nullable enable+using System.Collections.Generic;using System.Linq;+using Statecraft.Game.Map.Units;using Statecraft.Sim;using UnityEngine.UIElements;@@ -11,6 +13,19 @@ namespace Statecraft.Game.UI{public static readonly string[] Order = { "era", "events", "politics", "cabinet", "security", "economy", "population", "city", "map", "policy", "effects", "situations" };readonly VisualElement screen; readonly SimBridge bridge; readonly UiText text;+ IReadOnlyList<UnitEntry> units = new List<UnitEntry>();+ public IReadOnlyList<UnitEntry> Units+ {+ get => units;+ set { units = value ?? new List<UnitEntry>(); shown = null; Render(); }+ }+ IReadOnlyDictionary<string, string>? townNamesHe;+ /// <summary>Each settlement's Hebrew name, by id (the map's parse), for a raised unit's home city in Hebrew.</summary>+ public IReadOnlyDictionary<string, string>? TownNamesHe+ {+ get => townNamesHe;+ set { townNamesHe = value; shown = null; Render(); }+ }public WhyPresenter(VisualElement root, SimBridge bridge, UiText text){@@ -52,7 +67,7 @@ namespace Statecraft.Game.UIrows.Add(header);foreach (var w in lines){- var line = new Label(w.Message) { name = "why-" + i++ };+ var line = new Label(UnitNames.Line(w, bridge.Content, units, text, townNamesHe)) { name = "why-" + i++ };line.AddToClassList("why-line");rows.Add(line);}diff --git a/unity/Assets/Tests/EditMode/AdvisorOpeningParityTests.cs b/unity/Assets/Tests/EditMode/AdvisorOpeningParityTests.csindex 0d431dff4..45755876b 100644--- a/unity/Assets/Tests/EditMode/AdvisorOpeningParityTests.cs+++ b/unity/Assets/Tests/EditMode/AdvisorOpeningParityTests.cs@@ -366,6 +366,7 @@ public class AdvisorOpeningParityTestsgame.Advisor.OpenChain();for (int i = 0; i < step; i++) UiTestKit.Press(Ui.Q<Button>("advisor-got-it"));var turn = game.Bridge!.State.Turn;+ foreach (var id in game.Bridge.NeedsOrders.ToList()) game.Bridge.Skip(id);UiTestKit.Press(Ui.Q<Button>("end-turn"));Assert.AreEqual(turn + 1, game.Bridge.State.Turn, "precondition: End turn ran the turn");Assert.IsFalse(game.Advisor.InChain, "the advisor closes when the turn advances");@@ -533,6 +534,60 @@ public class AdvisorOpeningParityTestsAssert.IsEmpty(problems, string.Join("\n", problems));}+ /// <summary>Spec 7.3: End turn, while a unit needs orders, selects it and centres the camera on its hex.</summary>+ [UnityTest]+ public IEnumerator EndTurnFocusesTheNextUnitThatNeedsOrders()+ {+ var game = OpenScene(new SaveStore(TempDir()), new SettingsStore(TempDir()));+ game.Begin(Inputs, 0, startScreen: true);+ UiTestKit.Press(Ui.Q<Button>("start-new-game"));+ UiTestKit.Press(Ui.Q<Button>("advisor-close"));+ yield return null;+ var bridge = game.Bridge!; var units = game.Units!;+ // At the advisor's move-step framing, the map bounds permit the selected hex to be centred exactly.+ Object.FindFirstObjectByType<CameraRig>().Distance = AdvisorTargets.MoveStepDistanceM;+ var next = bridge.NeedsOrders[0];+ UiTestKit.Press(Ui.Q<Button>("end-turn"));+ yield return null;+ var token = units.Tokens.Single(t => UnitCard.SimUnit(bridge.Content, bridge.State, t.Token.Unit) == next);+ Assert.AreEqual(token.Token.Unit.Id, units.Selected);+ var hex = bridge.Content.HexAt(token.Q, token.R)!;+ var map = Object.FindFirstObjectByType<MapScene>();+ var rig = Object.FindFirstObjectByType<CameraRig>();+ Assert.Less(Vector3.Distance(map.Frame.ToWorld(hex.Lon, hex.Lat, 0), rig.LookAt), 1f);+ }++ /// <summary>Spec 7.3: repeated blocked End turn presses move past the selected needing unit and wrap.</summary>+ [UnityTest]+ public IEnumerator BlockedEndTurnCyclesPastTheSelectionAndWraps()+ {+ var game = OpenScene(new SaveStore(TempDir()), new SettingsStore(TempDir()));+ game.Begin(Inputs, 0, startScreen: true);+ UiTestKit.Press(Ui.Q<Button>("start-new-game"));+ UiTestKit.Press(Ui.Q<Button>("advisor-close"));+ yield return null;+ var bridge = game.Bridge!; var units = game.Units!;+ var needs = bridge.NeedsOrders.ToList();+ Assert.Greater(needs.Count, 1, "precondition: several units need orders");+ var turn = bridge.TurnStart.Turn;+ int? SelectedId() => units.Selected is string row+ ? units.Tokens.Where(t => t.Token.Unit.Id == row)+ .Select(t => UnitCard.SimUnit(bridge.Content, bridge.State, t.Token.Unit)).FirstOrDefault()+ : null;+ // Begin from the first needing unit, then prove advance and a complete wrap without issuing an order.+ UiTestKit.Press(Ui.Q<Button>("end-turn"));+ yield return null;+ Assert.AreEqual(needs[0], SelectedId());+ for (var step = 1; step <= needs.Count; step++)+ {+ UiTestKit.Press(Ui.Q<Button>("end-turn"));+ yield return null;+ Assert.AreEqual(needs[step % needs.Count], SelectedId(),+ "blocked End turn advances beyond the selected unit and wraps");+ }+ Assert.AreEqual(turn, bridge.TurnStart.Turn, "cycling never ends the turn");+ }+// --- Each step with what it explains (owner's report on v0.1.4) ---------------------------------------------------/// <summary>The first card's first option, pressed as a click would.</summary>diff --git a/unity/Assets/Tests/EditMode/CityPanelTests.cs b/unity/Assets/Tests/EditMode/CityPanelTests.csindex 1bbfdeff4..7b5c32739 100644--- a/unity/Assets/Tests/EditMode/CityPanelTests.cs+++ b/unity/Assets/Tests/EditMode/CityPanelTests.cs@@ -1071,9 +1071,9 @@ public class CityPanelTests}[Test]- public void AGroupWithAReturnOrderedCannotBeSentToBuildToo()+ public void AReturnedGroupLeavesTheSiteListAtOnce(){- // Return runs first at End turn, so the unit has left when Build runs and the sim refuses it (Projects.cs, "no such unit").+ // R-TURN-004: Return is a unit order, so it takes effect at once; the group is a civilian again and offers no Build.using var ui = new UiTestKit();int idle = 0;var bridge = Bridge(En, s => idle = AddHalutz(s));@@ -1081,11 +1081,13 @@ public class CityPanelTestspanel.Show(SiteDef.Q, SiteDef.R);Assert.IsTrue(ui.Q<Button>($"site-build-{idle}").enabledSelf, "precondition: an idle group can build");UiTestKit.Press(ui.Q<Button>($"pioneer-return-{idle}"));- Assert.IsFalse(ui.Q<Button>($"site-build-{idle}").enabledSelf);+ Assert.IsFalse(bridge.State.Units.ContainsKey(idle));+ Assert.IsNull(ui.Root.Q<Button>($"site-build-{idle}"));+ Assert.IsNull(ui.Root.Q<Button>($"pioneer-return-{idle}"));}[Test]- public void ACorridorGroupWithAReturnOrderedCannotBeSentToBuildToo()+ public void AReturnedCorridorGroupLeavesTheSegmentAtOnce(){using var ui = new UiTestKit();int idle = 0;@@ -1096,7 +1098,8 @@ public class CityPanelTestsvar box = SegmentBox(ui, "burma_road", 1);Assert.IsTrue(box.Q<Button>($"corridor-build-{idle}").enabledSelf, "precondition: an idle group can build");UiTestKit.Press(box.Q<Button>($"pioneer-return-{idle}"));- Assert.IsFalse(SegmentBox(ui, "burma_road", 1).Q<Button>($"corridor-build-{idle}").enabledSelf);+ Assert.IsFalse(bridge.State.Units.ContainsKey(idle));+ Assert.IsNull(SegmentBox(ui, "burma_road", 1).Q<Button>($"corridor-build-{idle}"));}[Test]@@ -1129,10 +1132,11 @@ public class CityPanelTestsvar button = ui.Q<Button>($"pioneer-return-{idle}");Assert.AreEqual(t.Format("pioneer.return", GddHexPanel.Group(t, bridge.State, idle)), button.text);UiTestKit.Press(button);- var order = bridge.QueuedLike(new UnitOrder(idle, Qualification.ReturnOrder)) as UnitOrder;- Assert.IsNotNull(order); Assert.AreEqual((idle, Qualification.ReturnOrder), (order!.Unit, order.Order));- Assert.AreEqual(t["site.ordered"], ui.Q<Button>($"pioneer-return-{idle}").text);- Assert.IsFalse(ui.Q<Button>($"pioneer-return-{idle}").enabledSelf);+ // R-TURN-004: a unit order is committed at once, not queued.+ var order = bridge.Session.Committed.OfType<UnitOrder>().Single();+ Assert.AreEqual((idle, Qualification.ReturnOrder), (order.Unit, order.Order));+ Assert.IsEmpty(bridge.Queued);+ Assert.IsNull(ui.Root.Q<Button>($"pioneer-return-{idle}"), "the group has returned");}}diff --git a/unity/Assets/Tests/EditMode/CivMovementShots.cs b/unity/Assets/Tests/EditMode/CivMovementShots.csnew file mode 100644index 000000000..cb8daa7b5--- /dev/null+++ b/unity/Assets/Tests/EditMode/CivMovementShots.cs@@ -0,0 +1,181 @@+#nullable enable+using System;+using System.Collections;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>Writes the stills for #1398's Civ-style movement (U1 to U5), in English and Hebrew, to+/// `.superpowers/civ-1398-shots/` at the repository root (local, not committed). It uses only calls main had before the+/// change, so the same file run on main gives the "before" stills and on the branch the "after" ones, from the same+/// game state, camera and zoom: Golani's card on the first turn, its attack on the Syrian unit beside it, a move by the+/// next unit, and the Why screen after the turn. Each still is the map camera with the UI drawn over it. Explicit, so it+/// does not run with the checks.</summary>+[Explicit("writes stills for a pull request, not a check")]+public class CivMovementShots+{+ internal const int Width = 1280, Height = 720;+ string saveDir = "";+ internal static string ShotDir => Path.GetFullPath(Path.Combine(Application.dataPath, "..", "..", ".superpowers", "civ-1398-shots"));+ RenderTexture? rt; PanelSettings? ps;+ VisualElement ui = null!;+ GameRoot root = null!;++ [SetUp]+ public void TempSaves()+ {+ saveDir = Path.Combine(Path.GetTempPath(), "statecraft-civ-shots-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(ShotDir);+ }++ [TearDown]+ public void DiscardScene()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);+ }++ static IEnumerator Frames(int n) { for (int i = 0; i < n; i++) yield return null; }++ /// <summary>Opens the game scene in the language, with the UI drawn into a transparent texture (Shot puts it over the+ /// map camera's frame), the opening card hidden and the first-turn guide closed.</summary>+ internal static IEnumerator Boot(bool hebrew, string saveDir, Action<RenderTexture, PanelSettings, VisualElement, GameRoot> booted)+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var doc = Object.FindFirstObjectByType<UIDocument>();+ var rt = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);+ var ps = Object.Instantiate(doc.panelSettings);+ ps.targetTexture = rt; ps.clearColor = true; ps.colorClearValue = Color.clear;+ doc.panelSettings = ps;+ Object.FindFirstObjectByType<MapScene>().Build(MapFocusTests.Inputs.Map);+ var root = Object.FindFirstObjectByType<GameRoot>();+ root.Store = new SaveStore(saveDir);+ if (hebrew) root.Language = UiLanguage.Hebrew;+ root.Begin(MapFocusTests.Inputs, 0);+ var ui = doc.rootVisualElement;+ for (int i = 0; i < 30 && !(ui.Q("top-bar").worldBound.height > 0); i++) yield return null;+ yield return Frames(5);+ GameSceneTests.HideTheOpeningCard(ui);+ if (root.Advisor != null && root.Advisor.IsOpen) UiTestKit.Press(ui.Q<Button>("advisor-close"));+ yield return Frames(3);+ booted(rt, ps, ui, root);+ }++ /// <summary>Points the camera straight at the sim hex from <paramref name="distance"/> metres.</summary>+ internal static void Aim(int q, int r, float distance)+ {+ var map = Object.FindFirstObjectByType<MapScene>();+ var hex = MapFocusTests.Inputs.Content.HexAt(q, r)!;+ var ground = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);+ ground.y = map.Terrain.SampleHeight(ground) + map.Terrain.transform.position.y;+ var rig = Camera.main.GetComponent<CameraRig>();+ rig.LookAt = ground; rig.Distance = distance;+ rig.Apply();+ }++ static Color[] Read(RenderTexture from)+ {+ var prev = RenderTexture.active;+ RenderTexture.active = from;+ var tex = new Texture2D(from.width, from.height, TextureFormat.RGBA32, false);+ tex.ReadPixels(new Rect(0, 0, from.width, from.height), 0, 0);+ tex.Apply();+ RenderTexture.active = prev;+ var px = tex.GetPixels();+ Object.DestroyImmediate(tex);+ return px;+ }++ /// <summary>The map camera's frame with the UI texture over it (the UI's pixels are premultiplied by their alpha).</summary>+ internal static void Shot(RenderTexture uiTexture, string name)+ {+ var cam = Camera.main;+ var frame = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);+ var before = cam.targetTexture;+ cam.targetTexture = frame; cam.Render(); cam.targetTexture = before;+ var map = Read(frame); var over = Read(uiTexture);+ frame.Release(); Object.DestroyImmediate(frame);+ var outPx = new Color[map.Length];+ for (int i = 0; i < map.Length; i++)+ {+ var u = over[i]; var m = map[i];+ outPx[i] = new Color(u.r + m.r * (1f - u.a), u.g + m.g * (1f - u.a), u.b + m.b * (1f - u.a), 1f);+ }+ var tex = new Texture2D(Width, Height, TextureFormat.RGB24, false);+ tex.SetPixels(outPx); tex.Apply();+ File.WriteAllBytes(Path.Combine(ShotDir, name + ".png"), tex.EncodeToPNG());+ Object.DestroyImmediate(tex);+ Debug.Log("SHOT " + name);+ }++ IEnumerator Shots(bool hebrew)+ {+ var lang = hebrew ? "he" : "en";+ yield return Boot(hebrew, saveDir, (t, p, u, g) => { rt = t; ps = p; ui = u; root = g; });+ var bridge = root.Bridge!; var units = root.Units!; var info = root.Info!;+ var map = Object.FindFirstObjectByType<MapScene>();+ var c = bridge.Content;+ string RowOf(int id) => units.Tokens.First(t => UnitCard.SimUnit(c, bridge.State, t.Token) == id).Token.Unit.Id;+ (int q, int r) HexOf(int id) => (bridge.State.Units[id].Q, bridge.State.Units[id].R);++ // 1. Golani's card on the first turn: the End turn button, the card's lines and its orders.+ var golani = HexOf(0);+ Aim(golani.q, golani.r, 40000f);+ GameRoot.OnHexClicked(map, units, info, golani.q, golani.r);+ yield return Frames(5);+ Shot(rt!, $"1-card-{lang}");++ // 2. Golani attacks the Syrian unit beside it (as UnitOrdersTests.AnAttackShowsItsResultAtOnce).+ var syrian = bridge.State.Units.Values.First(x => x.Side == "syria" && MapActions.Distance(x.Q, x.R, golani.q, golani.r) == 1);+ UiTestKit.Press(ui.Q<Button>("info-attack"));+ yield return Frames(2);+ GameRoot.OnHexClicked(map, units, info, syrian.Q, syrian.R);+ yield return Frames(2);+ Aim(golani.q, golani.r, 40000f); // the same camera as the card's still (the branch's cycle moves it on)+ yield return Frames(3);+ Shot(rt!, $"2-attack-{lang}");++ // 3. The next Israeli unit with a one-point step moves there.+ var mover = bridge.State.Units.Values.Where(x => x.Id != 0 && x.Side == "israel")+ .OrderBy(x => x.Id)+ .First(x => units.Tokens.Any(t => UnitCard.SimUnit(c, bridge.State, t.Token) == x.Id)+ && Movement.Reachable(c, bridge.State, x.Id).Any(kv => kv.Value == 1)).Id;+ var from = HexOf(mover);+ var step = Movement.Reachable(c, bridge.State, mover).Where(kv => kv.Value == 1).Select(kv => kv.Key).OrderBy(h => h.Q).ThenBy(h => h.R).First();+ Aim(from.q, from.r, 40000f);+ // A click selects the unit; on the branch the attack's cycle has already selected it (a second click shows its hex).+ if (units.Selected != RowOf(mover)) GameRoot.OnHexClicked(map, units, info, from.q, from.r);+ yield return Frames(2);+ UiTestKit.Press(ui.Q<Button>("info-move"));+ yield return Frames(2);+ GameRoot.OnHexClicked(map, units, info, step.Q, step.R);+ yield return Frames(2);+ Aim(from.q, from.r, 40000f);+ yield return Frames(3);+ Debug.Log($"SHOT 3 unit {mover} ({RowOf(mover)}) {from.q},{from.r} -> {step.Q},{step.R}");+ Shot(rt!, $"3-move-{lang}");++ // 4. The turn ends (the bridge's own End turn, which main and the branch both have) and the Why screen opens.+ bridge.EndTurn();+ yield return Frames(3);+ var close = ui.Q<Button>("turn-report-close");+ if (close != null && close.resolvedStyle.display == DisplayStyle.Flex) UiTestKit.Press(close);+ UiTestKit.Press(ui.Q<Button>("nav-why"));+ yield return Frames(5);+ Shot(rt!, $"4-why-{lang}");+ }++ [UnityTest] public IEnumerator English() { yield return Shots(false); }+ [UnityTest] public IEnumerator Hebrew() { yield return Shots(true); }+}diff --git a/unity/Assets/Tests/EditMode/CivMovementShots.cs.meta b/unity/Assets/Tests/EditMode/CivMovementShots.cs.metanew file mode 100644index 000000000..b8070d995--- /dev/null+++ b/unity/Assets/Tests/EditMode/CivMovementShots.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 7a3b5ad7a86ae4fb2ad168a4dd9efa11\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/CivRouteShots.cs b/unity/Assets/Tests/EditMode/CivRouteShots.csnew file mode 100644index 000000000..833ca2717--- /dev/null+++ b/unity/Assets/Tests/EditMode/CivRouteShots.cs@@ -0,0 +1,73 @@+#nullable enable+using System;+using System.Collections;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>#1398's go-to (U3), which main has no "before" for: Golani's Move pick with the route to a hex two turns away+/// shown, and the turn numbers on each turn's last hex, in English and Hebrew, to CivMovementShots' folder. Explicit.</summary>+[Explicit("writes stills for a pull request, not a check")]+public class CivRouteShots+{+ string saveDir = "";+ RenderTexture? rt; PanelSettings? ps;++ [SetUp]+ public void TempSaves()+ {+ saveDir = Path.Combine(Path.GetTempPath(), "statecraft-civ-route-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(CivMovementShots.ShotDir);+ }++ [TearDown]+ public void DiscardScene()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);+ }++ IEnumerator Shots(bool hebrew)+ {+ VisualElement ui = null!; GameRoot root = null!;+ yield return CivMovementShots.Boot(hebrew, saveDir, (t, p, u, g) => { rt = t; ps = p; ui = u; root = g; });+ var bridge = root.Bridge!; var units = root.Units!; var info = root.Info!;+ var map = Object.FindFirstObjectByType<MapScene>();+ var c = bridge.Content;+ var golani = (bridge.State.Units[0].Q, bridge.State.Units[0].R);+ var lit = Movement.Reachable(c, bridge.State, 0).Keys.ToHashSet();+ var none = new System.Collections.Generic.Dictionary<int, int>();+ // A land hex two turns away, the nearest such in sim order (as UnitOrdersTests.AClickBeyondTheLitHexesGivesAGoTo).+ var far = c.Hexes.Where(h => h.Land && !lit.Contains((h.Q, h.R)) && (h.Q, h.R) != golani)+ .Select(h => (h.Q, h.R)).First(h => Movement.Route(c, bridge.State, 0, h.Q, h.R, none).LastOrDefault().Turn == 2);+ CivMovementShots.Aim(golani.Item1, golani.Item2, 60000f);+ GameRoot.OnHexClicked(map, units, info, golani.Item1, golani.Item2);+ yield return null;+ UiTestKit.Press(ui.Q<Button>("info-move"));+ yield return null;+ // GameRoot.Update follows the batch editor's own pointer every frame; once it has settled (its hover cache then calls+ // nothing more), the route a hover over the far hex shows is drawn on the map directly.+ for (int i = 0; i < 3; i++) yield return null;+ map.ShowRoute(Movement.Route(c, bridge.State, 0, far.Q, far.R, bridge.Spent).Select(h => (h.Q, h.R, h.Turn)).ToList());+ root.Labels?.Refresh(true);+ for (int i = 0; i < 5; i++) yield return null;+ root.Labels?.Refresh(true);+ yield return null;+ Debug.Log($"SHOT route to {far.Q},{far.R}: {map.ShownRoute.Count} hexes");+ CivMovementShots.Shot(rt!, $"5-route-{(hebrew ? "he" : "en")}");+ }++ [UnityTest] public IEnumerator English() { yield return Shots(false); }+ [UnityTest] public IEnumerator Hebrew() { yield return Shots(true); }+}diff --git a/unity/Assets/Tests/EditMode/CivRouteShots.cs.meta b/unity/Assets/Tests/EditMode/CivRouteShots.cs.metanew file mode 100644index 000000000..e0d06f433--- /dev/null+++ b/unity/Assets/Tests/EditMode/CivRouteShots.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 93e6968535ee04ee3b17f73576b7fa00\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/EndTurnCycleSceneTests.cs b/unity/Assets/Tests/EditMode/EndTurnCycleSceneTests.csnew file mode 100644index 000000000..49330595a--- /dev/null+++ b/unity/Assets/Tests/EditMode/EndTurnCycleSceneTests.cs@@ -0,0 +1,54 @@+#nullable enable+using System;+using System.Collections;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.UI;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>Spec 7.3 in the real scene: End turn, blocked while a unit needs orders, selects that unit with its card usable+/// even while a turn's event card is open (the event card is modal: it disables the unit card). Found by the WebGL smoke+/// run, which stalled on turn 3 when the turn's card stayed open.</summary>+public class EndTurnCycleSceneTests+{+ RenderTexture? rt; PanelSettings? ps; string dir = "";++ [TearDown]+ public void DiscardScene()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ if (dir != "" && Directory.Exists(dir)) Directory.Delete(dir, true);+ }++ [UnityTest]+ public IEnumerator BlockedEndTurnHidesAnOpenEventCardSoTheUnitCanBeSkipped()+ {+ VisualElement ui = null!; GameRoot root = null!;+ dir = Path.Combine(Path.GetTempPath(), "statecraft-endturn-cycle-" + Guid.NewGuid().ToString("N"));+ yield return CivMovementShots.Boot(false, dir, (t, p, u, g) => { rt = t; ps = p; ui = u; root = g; });+ var bridge = root.Bridge!;+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);+ UiTestKit.Press(ui.Q<Button>("end-turn"));+ yield return null;+ if (ui.Q("root").ClassListContains(TurnReportPresenter.OpenClass)) UiTestKit.Press(ui.Q<Button>("turn-report-close"));+ yield return null;+ Assert.IsTrue(ui.Q("root").ClassListContains(EventCardPresenter.OpenClass), "precondition: the new turn's event card is open");+ Assert.IsFalse(ui.Q("info-panel").enabledInHierarchy, "precondition: the open card disables the unit card");+ var needs = bridge.NeedsOrders.Count;+ Assert.Greater(needs, 0, "precondition: units need orders");+ UiTestKit.Press(ui.Q<Button>("end-turn"));+ yield return null;+ Assert.IsTrue(ui.Q("info-panel").enabledInHierarchy, "the selected unit's card takes orders");+ UiTestKit.Press(ui.Q<Button>("info-skip"));+ yield return null;+ Assert.AreEqual(needs - 1, bridge.NeedsOrders.Count, "Skip took the selected unit out of the cycle");+ }+}diff --git a/unity/Assets/Tests/EditMode/EndTurnCycleSceneTests.cs.meta b/unity/Assets/Tests/EditMode/EndTurnCycleSceneTests.cs.metanew file mode 100644index 000000000..ea7d3f6d8--- /dev/null+++ b/unity/Assets/Tests/EditMode/EndTurnCycleSceneTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 0337ddf7c0b3d457f8839d11d1525ca9\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.csindex 47a5a2f5e..0c09dc516 100644--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs@@ -684,6 +684,8 @@ public class GameSceneTestsusing var card = new EventCardPresenter(ui.Root, bridge, text, null);var turn = g.State.Turn;var log = new List<string>();+ // This event-only fixture has no map or unit-card presenter; its units have already been skipped.+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);var run = GameRoot.Smoke(ui.Root, bridge, card, 1, log.Add);while (run.MoveNext()) { }StringAssert.StartsWith("SMOKE OK 1 turns", log[log.Count - 1], string.Join("\n", log));@@ -709,6 +711,8 @@ public class GameSceneTestsusing var hud = new HudPresenter(ui.Root, bridge, text);using var card = new EventCardPresenter(ui.Root, bridge, text, null);var log = new List<string>();+ // This event-only fixture has no map or unit-card presenter; its units have already been skipped.+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);var run = GameRoot.Smoke(ui.Root, bridge, card, 1, log.Add);while (run.MoveNext()) { }StringAssert.StartsWith("SMOKE OK 1 turns 1948-08-15", log[log.Count - 1], string.Join("\n", log));diff --git a/unity/Assets/Tests/EditMode/HebrewUiTests.cs b/unity/Assets/Tests/EditMode/HebrewUiTests.csindex 94ebd06d1..22830eeaa 100644--- a/unity/Assets/Tests/EditMode/HebrewUiTests.cs+++ b/unity/Assets/Tests/EditMode/HebrewUiTests.cs@@ -281,7 +281,7 @@ public class HebrewUiTests("meter-cohesion/meter-name", "hud.caption.cohesion"), ("meter-standing/meter-name", "hud.caption.standing"), ("meter-fx/meter-name", "hud.caption.fx"),("nav-cabinet", "hud.nav.cabinet"), ("nav-budget", "hud.nav.budget"), ("nav-defence", "hud.nav.defence"),("nav-why", "hud.nav.why"), ("nav-timeline", "nav.timeline"), ("nav-how-to-play", "hud.nav.how_to_play"), ("nav-objectives", "hud.nav.objectives"),- ("new-game", "hud.new_game"), ("end-turn", "hud.end_turn"),+ ("new-game", "hud.new_game"), ("end-turn", "hud.end_turn_needs_orders"),("event-draft", "event.draft"),("budget-screen-title", "budget.title"), ("budget-reset", "budget.reset"), ("budget-submit", "budget.submit"),("defence-screen-title", "defence.title"), ("de-escalate", "defence.lower"), ("escalate", "defence.raise"),diff --git a/unity/Assets/Tests/EditMode/HudTests.cs b/unity/Assets/Tests/EditMode/HudTests.csindex 04b0f7c6d..13868823d 100644--- a/unity/Assets/Tests/EditMode/HudTests.cs+++ b/unity/Assets/Tests/EditMode/HudTests.cs@@ -1,5 +1,6 @@#nullable enableusing System.Collections;+using System.Collections.Generic;using System.Linq;using NUnit.Framework;using Statecraft.Game;@@ -116,6 +117,40 @@ public class HudTests/// <summary>The real game: the GDD loop since the cutover (the ?mvp=1 slice is gone with MvpSlice).</summary>static SimBridge GddBridge() => new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ [Test]+ public void EndTurnWaitsWhileAUnitNeedsOrders()+ {+ using var ui = new UiTestKit();+ var bridge = GddBridge();+ var selected = new List<int>();+ using var hud = new HudPresenter(ui.Root, bridge, Text, selectUnit: selected.Add);+ var endTurn = ui.Q<Button>("end-turn");+ var turn = bridge.TurnStart.Turn;+ Assert.AreEqual(Text["hud.end_turn_needs_orders"], endTurn.text);+ UiTestKit.Press(endTurn);+ Assert.AreEqual(turn, bridge.TurnStart.Turn, "the turn did not end");+ Assert.AreEqual(bridge.NeedsOrders[0], selected.Single());+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);+ Assert.AreEqual(Text["hud.end_turn"], endTurn.text);+ UiTestKit.Press(endTurn);+ Assert.AreEqual(turn + 1, bridge.TurnStart.Turn);+ }++ /// <summary>Review Focus 4: a unit with Send home queued is not selected.</summary>+ [Test]+ public void TheCycleSkipsUnitsGoingHome()+ {+ using var ui = new UiTestKit();+ var bridge = GddBridge();+ var selected = new List<int>();+ using var hud = new HudPresenter(ui.Root, bridge, Text, selectUnit: selected.Add);+ var first = bridge.NeedsOrders[0];+ Assert.IsNull(bridge.Queue(new UnitOrder(first, Demobilization.SendHome)));+ UiTestKit.Press(ui.Q<Button>("end-turn"));+ Assert.AreNotEqual(first, selected.Single());+ Assert.AreEqual(bridge.NeedsOrders[0], selected.Single());+ }+[Test]public void TheLegacyLoopShowsNoScore(){@@ -209,6 +244,7 @@ public class HudTestsusing var ui = new UiTestKit();var bridge = NewBridge();new HudPresenter(ui.Root, bridge, Text);+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);ui.Press("end-turn");Assert.AreEqual(1, bridge.State.Turn);Assert.AreEqual("Turn 1", ui.Q<Label>("turn").text);@@ -245,6 +281,7 @@ public class HudTestsnew ToastPresenter(ui.Root, bridge, text);Assert.AreEqual(DisplayStyle.None, ui.Q<Label>("toast").style.display.value);bridge.Queue(new SetPolicy(C.At(bridge.State.Date).Policies[0].Id, 2)); // a policy in force now at an impossible level: the sim refuses it+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);ui.Press("end-turn");Assert.AreEqual("Not done: Policy level must be between 0 and 1", ui.Q<Label>("toast").text);Assert.AreEqual(DisplayStyle.Flex, ui.Q<Label>("toast").style.display.value);@@ -637,6 +674,7 @@ public class HudTests}var open = ScreenNav.Screens[turn % ScreenNav.Screens.Length];ui.Press("nav-" + open);+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);ui.Press("end-turn");Assert.AreEqual(turn + 1, bridge.State.Turn, $"turn {turn}: End Turn did not run");Assert.AreEqual(DisplayStyle.Flex, Shown(open), $"turn {turn}: End Turn closed {open}");diff --git a/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs b/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.csindex 803d1725d..530ca76c4 100644--- a/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs+++ b/unity/Assets/Tests/EditMode/InfoPanelLayoutTests.cs@@ -82,7 +82,9 @@ public class InfoPanelLayoutTestsif (natural.x <= box.width + 1f) return true;if (l.resolvedStyle.whiteSpace != WhiteSpace.Normal) return false;var wrapped = l.MeasureTextSize(l.text, box.width, VisualElement.MeasureMode.Exactly, 0, VisualElement.MeasureMode.Undefined);- return wrapped.y <= box.height + 1f;+ // Text and layout round to raster pixels: at fractional panel scale one pixel can exceed one logical px.+ var pixel = l.panel == null ? 1f : 1f / l.panel.scaledPixelsPerPoint;+ return wrapped.y <= box.height + pixel + 0.01f;}static bool Inside(Rect inner, Rect outer) =>diff --git a/unity/Assets/Tests/EditMode/KeyboardOrdersTests.cs b/unity/Assets/Tests/EditMode/KeyboardOrdersTests.csindex f9e0bddf8..2183e4521 100644--- a/unity/Assets/Tests/EditMode/KeyboardOrdersTests.cs+++ b/unity/Assets/Tests/EditMode/KeyboardOrdersTests.cs@@ -141,7 +141,7 @@ public class KeyboardOrdersTests"Enter on Move lights the reachable hexes");var (q, r) = reach.Last();yield return EnterOnTheMapAt(q, r);- var queued = Bridge.Queued.OfType<Move>().Single();+ var queued = Bridge.Session.Committed.OfType<Move>().Single();Assert.AreEqual((id, q, r), (queued.Unit, queued.Q, queued.R), "Enter on a lit hex queues the Move");Assert.AreEqual("golani", Object.FindFirstObjectByType<UnitLayer>().Selected, "Golani stays selected");}@@ -165,7 +165,10 @@ public class KeyboardOrdersTests"Enter on Attack lights the hexes it can name");var (q, r) = targets[0];yield return EnterOnTheMapAt(q, r);- var queued = Bridge.Queued.OfType<UnitOrder>().Single();- Assert.AreEqual((id, Combat.Attack, (int?)q, (int?)r), (queued.Unit, queued.Order, queued.Q, queued.R), "Enter on a lit hex queues the attack");+ // Plan Task 11; spec 4.1 lines131–136: the key press fights the attack now, not at End turn.+ var committed = Bridge.Session.Committed.OfType<UnitOrder>().Single();+ Assert.AreEqual((id, Combat.Attack, (int?)q, (int?)r), (committed.Unit, committed.Order, committed.Q, committed.R), "Enter on a lit hex commits the attack");+ // Event answers correctly stay deferred (spec3.2:89); only the attack must be absent.+ Assert.IsEmpty(Bridge.Queued.OfType<UnitOrder>().Where(o => o.Order == Combat.Attack), "the attack does not wait for End turn");}}diff --git a/unity/Assets/Tests/EditMode/KeyboardTurnTests.cs b/unity/Assets/Tests/EditMode/KeyboardTurnTests.csindex 62cbc42bc..277506f10 100644--- a/unity/Assets/Tests/EditMode/KeyboardTurnTests.cs+++ b/unity/Assets/Tests/EditMode/KeyboardTurnTests.cs@@ -105,6 +105,22 @@ public class KeyboardTurnTestsfor (int i = 0; i < n; i++) { yield return Tab(back); into.Add(FocusedName); }}+ // Give each still-needing unit Skip through the keyboard, before requesting the actual turn end.+ IEnumerator SkipTheRemainingUnits()+ {+ for (var guard = 0; Bridge.NeedsOrders.Count > 0; guard++)+ {+ Assert.Less(guard, 200, "keyboard Skip must make progress");+ yield return TabTo("end-turn");+ yield return Enter();+ yield return Frames(2);+ yield return TabTo("info-skip");+ yield return Enter();+ yield return Frames(2);+ }+ yield return TabTo("end-turn");+ }+/// <summary>The side menu, New Game, End Turn: the HUD's own controls, in the order Game.uxml gives them.</summary>static readonly string[] Menu = { "nav-cabinet", "nav-budget", "nav-defence", "nav-why", "nav-timeline", "nav-how-to-play", "nav-objectives", "nav-settings", "new-game", "end-turn" };@@ -153,6 +169,7 @@ public class KeyboardTurnTestsyield return TabTo("end-turn");var turn = Bridge.State.Turn;+ yield return SkipTheRemainingUnits();yield return Enter();yield return Frames(5);Assert.AreEqual(turn + 1, Bridge.State.Turn, "Enter on End Turn ends the turn");@@ -227,6 +244,7 @@ public class KeyboardTurnTests// End the turn.yield return TabTo("end-turn");var turn = Bridge.State.Turn;+ yield return SkipTheRemainingUnits();yield return Enter();yield return Frames(5);Assert.AreEqual(turn + 1, Bridge.State.Turn, "the turn ends");diff --git a/unity/Assets/Tests/EditMode/SaveUiTests.cs b/unity/Assets/Tests/EditMode/SaveUiTests.csindex 6b65340bc..f6a7eeb59 100644--- a/unity/Assets/Tests/EditMode/SaveUiTests.cs+++ b/unity/Assets/Tests/EditMode/SaveUiTests.cs@@ -57,6 +57,44 @@ public class SaveUiTestsAssert.AreEqual(2, resumed.State.Turn);}+ /// <summary>Spec 3.4 (No undo across a reload): the autosave is written after every committed order, with the open+ /// turn in click order, and reloading it shows the same state.</summary>+ [Test]+ public void AutosaveWritesEveryCommittedOrder()+ {+ var store = TempStore();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ using (GameStart.Autosave(bridge, store, Text))+ {+ var move = GoldenRun.SmokeMove(C, bridge.State);+ Assert.IsNull(bridge.Queue(move));+ var first = store.ReadAutosave()!;+ StringAssert.Contains($"\nopen\nmove {move.Unit} {move.Q} {move.R}\n", first);+ var loaded = GameSession.Load(C, first, out var warnings);+ Assert.IsEmpty(warnings);+ Assert.AreEqual(bridge.State.Hash(), loaded.Now.State.Hash());+ Assert.IsNull(bridge.Queue(new UnitOrder(move.Unit, Orders.Hold)));+ var again = GameSession.Load(C, store.ReadAutosave()!, out _);+ CollectionAssert.AreEqual(new[] { "move", "unit_order" }, again.Committed.Select(x => x.Kind).ToArray());+ Assert.AreEqual(bridge.State.Hash(), again.Now.State.Hash());+ }+ }++ /// <summary>Spec 3.4: an attack's result survives a reload of the autosave, unchanged (no re-roll).</summary>+ [Test]+ public void AutosaveKeepsAnAttacksResult()+ {+ var store = TempStore();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ using (GameStart.Autosave(bridge, store, Text))+ {+ var syrian = bridge.State.Units.Values.First(u => u.Side == "syria" && MapActions.Distance(u.Q, u.R, bridge.State.Units[0].Q, bridge.State.Units[0].R) == 1);+ Assert.IsNull(bridge.Queue(new UnitOrder(0, Combat.Attack, syrian.Q, syrian.R)));+ var loaded = GameSession.Load(C, store.ReadAutosave()!, out _);+ Assert.AreEqual(bridge.State.Hash(), loaded.Now.State.Hash());+ }+ }+[Test]public void AutosaveReceiptsKeepTheirGenerationAndSavedState(){@@ -485,6 +523,7 @@ public class SaveUiTestsvar hud = new HudPresenter(ui.Root, bridge, Text);var toast = new ToastPresenter(ui.Root, bridge, Text);new NewGamePresenter(ui.Root, bridge, store, toast, Text, () => 4UL);+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);ui.Press("end-turn");Assert.AreEqual("Turn 1", ui.Q<Label>("turn").text);ui.Press("new-game"); ui.Press("new-game");diff --git a/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs b/unity/Assets/Tests/EditMode/SimBridgeGddTests.csindex 50e12dcea..a8de063df 100644--- a/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs+++ b/unity/Assets/Tests/EditMode/SimBridgeGddTests.cs@@ -1,4 +1,5 @@#nullable enable+using System.Collections.Generic;using System.Linq;using NUnit.Framework;using Statecraft.Game;@@ -34,6 +35,59 @@ public class SimBridgeGddTestsstatic UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);static SimBridge Bridge(Content c) => new SimBridge(GameSession.New(c, GoldenRun.Seed, Mode.Historical), Text);+ /// <summary>R-TURN-004: a Move given through the bridge shows at once (State), and End turn keeps it.</summary>+ [Test]+ public void AMoveShowsAtOnce()+ {+ var bridge = new SimBridge(GameSession.New(Slice, GoldenRun.Seed, Mode.Historical), Text);+ var move = GoldenRun.SmokeMove(Slice, bridge.State);+ var start = (bridge.State.Units[move.Unit].Q, bridge.State.Units[move.Unit].R);+ IReadOnlyList<Cause>? lines = null; bridge.Committed += w => lines = w;+ Assert.IsNull(bridge.Queue(move));+ Assert.AreEqual((move.Q, move.R), (bridge.State.Units[move.Unit].Q, bridge.State.Units[move.Unit].R));+ Assert.AreEqual(start, (bridge.TurnStart.Units[move.Unit].Q, bridge.TurnStart.Units[move.Unit].R));+ Assert.IsEmpty(bridge.Queued, "a committed order is not queued");+ Assert.IsTrue(lines!.Any(w => w.Key == WhyKeys.UnitMoved));+ bridge.EndTurn();+ Assert.AreEqual(GoldenRun.PlaySmokeOrders(Slice).Hash(), bridge.TurnStart.Hash());+ }++ /// <summary>No undo: a committed move is not withdrawn; a second move for the same unit is kept beside it.</summary>+ [Test]+ public void ACommittedMoveCannotBeWithdrawn()+ {+ var bridge = new SimBridge(GameSession.New(Slice, GoldenRun.Seed, Mode.Historical), Text);+ var move = GoldenRun.SmokeMove(Slice, bridge.State);+ bridge.Queue(move);+ bridge.Withdraw(move);+ Assert.AreEqual(1, bridge.Session.Committed.Count);+ }++ /// <summary>Spec 3.2: Send home stays deferred, and a unit with it queued takes no more moves or orders.</summary>+ [Test]+ public void AUnitWithSendHomeQueuedTakesNoMoreOrders()+ {+ var bridge = new SimBridge(GameSession.New(Slice, GoldenRun.Seed, Mode.Historical), Text);+ var move = GoldenRun.SmokeMove(Slice, bridge.State);+ Assert.IsNull(bridge.Queue(new UnitOrder(move.Unit, Demobilization.SendHome)));+ Assert.AreEqual(1, bridge.Queued.Count, "deferred, as today");+ Assert.AreEqual(Text["order.going_home"], bridge.Queue(move));+ Assert.IsEmpty(bridge.Session.Committed);+ }++ [Test]+ public void SkippedUnitsAndUnitsGoingHomeDoNotNeedOrders()+ {+ var bridge = new SimBridge(GameSession.New(Slice, GoldenRun.Seed, Mode.Historical), Text);+ var first = bridge.NeedsOrders[0]; var second = bridge.NeedsOrders[1];+ bridge.Skip(first);+ bridge.Queue(new UnitOrder(second, Demobilization.SendHome));+ CollectionAssert.DoesNotContain(bridge.NeedsOrders.ToList(), first);+ CollectionAssert.DoesNotContain(bridge.NeedsOrders.ToList(), second);+ bridge.EndTurn();+ Assert.IsFalse(bridge.IsSkipped(first), "a skip ends with the turn");+ }+/// <summary>A slice bridge after one turn that opened a halutz cohort, and that cohort's id.</summary>static (SimBridge bridge, int cohort) WithACohort(){diff --git a/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs b/unity/Assets/Tests/EditMode/SimBridgeGuardTests.csindex 199ba468b..61fb90361 100644--- a/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs+++ b/unity/Assets/Tests/EditMode/SimBridgeGuardTests.cs@@ -68,7 +68,7 @@ public class SimBridgeGuardTestsforeach (var t in CommandTypes().Where(Samples.ContainsKey)){var key = SimBridge.Key(Samples[t]);- if (OnePerTurn.Contains(t)) Assert.AreEqual(Samples[t].Kind, key, t.Name);+ if (OnePerTurn.Contains(t) || Simulation.IsInstant(Samples[t])) Assert.AreEqual(Samples[t].Kind, key, t.Name);else Assert.AreNotEqual(Samples[t].Kind, key, t.Name + " has no branch in SimBridge.Key: add one, or list it in OnePerTurn");}}diff --git a/unity/Assets/Tests/EditMode/TurnReportTests.cs b/unity/Assets/Tests/EditMode/TurnReportTests.csindex 96c00ed31..8b43e7da0 100644--- a/unity/Assets/Tests/EditMode/TurnReportTests.cs+++ b/unity/Assets/Tests/EditMode/TurnReportTests.cs@@ -244,6 +244,10 @@ public class TurnReportTestspublic void TheSmokeRunClosesTheReportEachTurn(){using var k = new Kit(En);+ // This report-only fixture has no map/card. Supply its unit skips at each turn start.+ void SkipUnits() { foreach (var id in k.Bridge.NeedsOrders.ToList()) k.Bridge.Skip(id); }+ SkipUnits();+ k.Bridge.TurnEnded += _ => SkipUnits();var log = new List<string>();var run = GameRoot.Smoke(k.Ui.Root, k.Bridge, k.Card, 3, log.Add);while (run.MoveNext()) { }diff --git a/unity/Assets/Tests/EditMode/UiLayoutTests.cs b/unity/Assets/Tests/EditMode/UiLayoutTests.csindex 77cb4761e..17a079e20 100644--- a/unity/Assets/Tests/EditMode/UiLayoutTests.cs+++ b/unity/Assets/Tests/EditMode/UiLayoutTests.cs@@ -75,6 +75,42 @@ public class UiLayoutTests}static readonly Content C = ContentLoader.Load(Paths.Content);+ static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");++ /// <summary>Review Focus 3: the longer blocked End turn label, including its hourglass padding, fits at phone width in+ /// English and Hebrew.</summary>+ [UnityTest]+ public IEnumerator TheBlockedEndTurnLabelFitsAtPhoneWidth()+ {+ foreach (var (language, text) in new[] { (UiLanguage.English, Text), (UiLanguage.Hebrew, He) })+ {+ var rt = new RenderTexture(390, 844, 0);+ var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));+ ps.targetTexture = rt;+ var go = new GameObject("BlockedEndTurnLayoutTest");+ go.SetActive(false);+ var doc = go.AddComponent<UIDocument>();+ doc.panelSettings = ps;+ doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);+ go.SetActive(true);+ try+ {+ var root = doc.rootVisualElement;+ root.Q("root").EnableInClassList(UiLanguage.HebrewClass, language == UiLanguage.Hebrew);+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);+ using var hud = new HudPresenter(root, bridge, text);+ var button = root.Q<Button>("end-turn");+ for (int i = 0; i < 20 && !(button.resolvedStyle.width > 0); i++) yield return null;+ for (int i = 0; i < 4; i++) yield return null;+ Assert.AreEqual(text["hud.end_turn_needs_orders"], button.text);+ var preferred = button.MeasureTextSize(button.text, 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined).x;+ var padding = button.resolvedStyle.paddingLeft + button.resolvedStyle.paddingRight;+ Assert.GreaterOrEqual(button.resolvedStyle.width + 0.5f, preferred + padding,+ $"{language}: blocked End turn text and hourglass padding fit at 390x844");+ }+ finally { Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt); }+ }+ }/// <summary>Review I3: a wide screen (Cabinet, Defence) covers the info panel, so while it is open the panel is hidden:/// it is drawn under the screen, takes no keyboard focus (its build buttons cannot be reached with Tab), and a map@@ -548,7 +584,8 @@ public class UiLayoutTestsif (root.Q("event-photo").resolvedStyle.display == DisplayStyle.Flex && scroll.contentContainer.layout.height > scroll.contentViewport.layout.height + 1f)problems.Add($"{where}: the body scrolls ({scroll.contentContainer.layout.height:0} px of text in {scroll.contentViewport.layout.height:0} px) while the photograph shows");var band = root.Q("event-photo");- if (band.resolvedStyle.display == DisplayStyle.Flex && c.height < l.height - 1f)+ // The layer's padding is reserved space, so only its content rectangle can leave room for a full header.+ if (band.resolvedStyle.display == DisplayStyle.Flex && card.layout.height < layer.contentRect.height - 1f){var want = band.layout.width / EventCardPresenter.MediaAspect;if (Mathf.Abs(band.layout.height - want) > 2.5f) problems.Add($"{where}: the media header is {band.layout.width:0}x{band.layout.height:0}, not 16:9 ({want:0} px tall), with room to spare; {LayoutState(root)}");diff --git a/unity/Assets/Tests/EditMode/UnitOrdersTests.cs b/unity/Assets/Tests/EditMode/UnitOrdersTests.csindex a33ecd455..e3e683a66 100644--- a/unity/Assets/Tests/EditMode/UnitOrdersTests.cs+++ b/unity/Assets/Tests/EditMode/UnitOrdersTests.cs@@ -18,7 +18,7 @@ using UnityEngine.UIElements;/// sim's Move through SimBridge, and a click anywhere else ends the pick and selects as before. Slice 2, Fortify and Hold:/// each shows only where the sim's Orders.Check takes it, else the sim's reason, and a press queues the sim's UnitOrder./// Slice 3, Attack: shown only where the sim's Combat.Check takes some hex; pressing it lights those hexes with-/// Combat.Preview's strength ratio and Combat.Outcomes' bands for each (Q-UI-1), and a click on one queues the attack.</summary>+/// Combat.Preview's strength ratio and Combat.Outcomes' bands for each (Q-UI-1), and a click on one commits the attack.</summary>public class UnitOrdersTests{static readonly Content C = ContentLoader.Load(Paths.Content);@@ -84,11 +84,11 @@ public class UnitOrdersTestsinfo.Dispose();}- /// <summary>Move lights exactly Movement.Reachable's hexes. A click on one queues Move(unit, q, r) through SimBridge and- /// keeps the card, which says the move waits for End turn; a click on an unlit hex queues nothing and shows that hex;+ /// <summary>Move lights exactly Movement.Reachable's hexes. A click on one commits Move(unit, q, r) through SimBridge and+ /// keeps the card; a click on an unreachable water hex commits nothing and shows that hex;/// a second press of Move ends the pick. Each end of the pick clears the overlay.</summary>[Test]- public void AClickOnALitHexQueuesTheMoveAndAnyOtherClickEndsThePick()+ public void AClickOnALitHexCommitsTheMoveAndAnUnreachableClickEndsThePick(){var map = BuildMap();using var ui = new UiTestKit();@@ -115,46 +115,30 @@ public class UnitOrdersTestsUiTestKit.Press(move); // a second press ends the pickAssert.IsEmpty(lit.Last());Assert.IsFalse(map.Terrain.transform.Find(MapScene.ReachableName).GetComponent<MeshRenderer>().enabled);- // An unlit hex: nothing queued, the pick ends and the click selects as before (the hex, as the unit is not on it).- var tlv = C.SettlementHexes.Single(t => t.Id == "tel_aviv");- Assert.IsFalse(reach.Contains((tlv.Q, tlv.R)), "precondition: Tel Aviv is out of Golani's reach");+ // Task12/spec8.1:248: unlit land with a route now gives go-to (tested below); water ends the pick.+ var water = C.Hexes.First(h => !h.Land);+ Assert.IsFalse(reach.Contains((water.Q, water.R)), "precondition: water has no move or go-to route");UiTestKit.Press(move);- GameRoot.OnHexClicked(map, layer, info, tlv.Q, tlv.R);+ GameRoot.OnHexClicked(map, layer, info, water.Q, water.R);Assert.IsEmpty(lit.Last());Assert.IsEmpty(bridge.Queued);+ Assert.IsEmpty(bridge.Session.Committed);Assert.IsFalse(info.ShowsUnit);- Assert.AreEqual((tlv.Q, tlv.R), info.Selected);- // A lit hex: the sim's Move is queued, the unit stays selected and its card says the move waits for End turn.+ Assert.AreEqual((water.Q, water.R), info.Selected);+ // A lit hex: the sim's Move is committed, the unit stays selected and the card has no queued-move line.GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);UiTestKit.Press(move);var (q, r) = reach.Last();map.Select(q, r); // MapPointer outlines the hex before it raises HexClickedGameRoot.OnHexClicked(map, layer, info, q, r);- var queued = bridge.Queued.OfType<Move>().Single();- Assert.AreEqual((id, q, r), (queued.Unit, queued.Q, queued.R));- Assert.IsEmpty(lit.Last());+ var committed = bridge.Session.Committed.OfType<Move>().Single();+ Assert.AreEqual((id, q, r), (committed.Unit, committed.Q, committed.R));+ CollectionAssert.AreEquivalent(Movement.Reachable(C, bridge.State, id, bridge.Spent).Keys.Select(h => (h.Q, h.R)).ToList(), lit.Last(), "movement reopens only the remaining reach");Assert.AreEqual("golani", layer.Selected);Assert.IsTrue(info.ShowsUnit);Assert.IsFalse(map.Terrain.transform.Find(MapScene.SelectionName).GetComponent<MeshRenderer>().enabled, "one highlight: the ring");- Assert.IsTrue(ui.Q<Label>("info-settlements").text.Contains(Text["unit.move_queued"]), ui.Q<Label>("info-settlements").text);- // A refused order (here the game ends while the pick is open): nothing more is queued and the pick line goes.- bridge.Withdraw(queued);- UiTestKit.Press(move);- bridge.State.GameOver = GameOverCodes.MvpEnded;- GameRoot.OnHexClicked(map, layer, info, q, r);- Assert.IsEmpty(bridge.Queued, "the bridge refuses an order once the game is over");- Assert.IsEmpty(lit.Last());- Assert.IsFalse(ui.Q<Label>("info-settlements").text.Contains(Text["unit.move_pick"]), ui.Q<Label>("info-settlements").text);- bridge.State.GameOver = null;- // A turn ends the pick (its hexes were the last turn's), as does another selection.- UiTestKit.Press(move);- Assert.IsNotEmpty(lit.Last());- bridge.EndTurn();- Assert.IsEmpty(lit.Last(), "End turn ends the pick");- Assert.IsFalse(ui.Q<Label>("info-settlements").text.Contains(Text["unit.move_pick"]));- Assert.IsTrue(info.ShowsUnit && Shown(move), "precondition: Golani's card still offers Move on the next turn");- UiTestKit.Press(move);- Assert.IsNotEmpty(lit.Last());+ Assert.IsFalse(ui.Q<Label>("info-settlements").text.Contains("Move ordered"), ui.Q<Label>("info-settlements").text);+ // Another selection ends any pick reopened by movement points left.info.Clear();Assert.IsEmpty(lit.Last(), "another selection ends the pick");info.Dispose();@@ -162,6 +146,36 @@ public class UnitOrdersTestsfinally { Object.DestroyImmediate(map.gameObject); }}+ /// <summary>R-MOVE-001 on screen: a click on a lit hex moves the unit at once, the Move pick opens again on what the+ /// points left reach, and the card shows the points.</summary>+ [Test]+ public void TheLitReachShrinksAfterAMove()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ layer.Show(bridge.Content, bridge.State);+ var lit = new List<IReadOnlyCollection<(int q, int r)>>();+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(),+ selectedUnit: () => layer.Selected is string sel ? layer.Tokens.First(p => p.Token.Unit.Id == sel) : (PlacedToken?)null,+ showReachable: hexes => lit.Add(hexes.ToList()));+ var golani = layer.Tokens.Single(p => p.Token.Unit.Id == "golani");+ var id = UnitCard.SimUnit(C, bridge.State, golani.Token.Unit)!.Value;+ var cheap = Movement.Reachable(C, bridge.State, id).Where(kv => kv.Value == 1).Select(kv => kv.Key).ToList();+ Assert.IsNotEmpty(cheap, "precondition: Golani has a one-point step");+ GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);+ UiTestKit.Press(ui.Q<Button>("info-move"));+ var before = lit.Last().Count;+ GameRoot.OnHexClicked(map, layer, info, cheap[0].Q, cheap[0].R);+ Assert.AreEqual((cheap[0].Q, cheap[0].R), (bridge.State.Units[id].Q, bridge.State.Units[id].R), "the unit moved at once");+ CollectionAssert.AreEquivalent(Movement.Reachable(C, bridge.State, id, bridge.Spent).Keys.Select(h => (h.Q, h.R)).ToList(), lit.Last());+ Assert.Less(lit.Last().Count, before);+ var full = C.UnitTypes.Single(t => t.Id == bridge.State.Units[id].Type).MovementPoints;+ StringAssert.Contains(Text.Format("unit.points", full - 1, full), ui.Q<Label>("info-settlements").text);+ info.Dispose();+ }+/// <summary>Slice 2 (#754): for every unit with a sim unit, Israel's and the enemy's, the card shows Fortify and Hold each/// only where the sim's Orders.Check takes it, and where it does not, on Israel's units the sim's reason, whatever it is/// (so a refusal the sim adds later, such as artillery's hold, shows with no change here); an enemy's card gives no reason@@ -223,19 +237,64 @@ public class UnitOrdersTestsstring Lines() => ui.Q<Label>("info-settlements").text;Assert.IsFalse(Lines().Contains(Text["unit.fortify_queued"]) || Lines().Contains(Text["unit.hold_queued"]), Lines());UiTestKit.Press(ui.Q<Button>("info-fortify"));- var queued = bridge.Queued.OfType<UnitOrder>().Single();+ var queued = bridge.Session.Committed.OfType<UnitOrder>().Last();Assert.AreEqual((id, Orders.Fortify, (int?)null, (int?)null), (queued.Unit, queued.Order, queued.Q, queued.R));StringAssert.Contains(Text["unit.fortify_queued"], Lines());UiTestKit.Press(ui.Q<Button>("info-hold"));- queued = bridge.Queued.OfType<UnitOrder>().Single();+ queued = bridge.Session.Committed.OfType<UnitOrder>().Last();Assert.AreEqual((id, Orders.Hold), (queued.Unit, queued.Order));StringAssert.Contains(Text["unit.hold_queued"], Lines());Assert.IsFalse(Lines().Contains(Text["unit.fortify_queued"]), Lines());- Assert.IsEmpty(bridge.EndTurn().Rejected, "the sim takes the order the card queued");+ Assert.IsEmpty(bridge.Queued, "standing orders commit immediately");+ Assert.AreEqual(2, bridge.Session.Committed.Count, "both clicks remain in the committed history");+ Assert.IsEmpty(bridge.EndTurn().Rejected, "the sim replays the committed orders once");Assert.AreEqual(Orders.Hold, bridge.State.Units[id].Order);info.Dispose();}+ /// <summary>Spec 7.3: an order that finishes the unit for the turn asks for the next unit.</summary>+ [Test]+ public void AFinishingOrderAsksForTheNextUnit()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var tokens = UnitRoster.FromState(Units, C, bridge.State, _ => true, (row, a, q, r) => a);+ PlacedToken? shown = new PlacedToken(tokens.Single(t => t.Unit.Id == "golani"), new AnchorSpot(0, 0, 0, 0, false));+ var asked = 0;+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(), selectedUnit: () => shown, unitDone: () => asked++);+ info.ShowUnit();+ UiTestKit.Press(ui.Q<Button>("info-fortify"));+ Assert.AreEqual(1, asked);+ info.Dispose();+ }++ [Test]+ public void ATokenWithNoPointsLeftIsDimmed()+ {+ var map = BuildMap();+ try+ {+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ layer.Show(bridge.Content, bridge.State);+ layer.Dim(new[] { "golani" });+ var block = new MaterialPropertyBlock();+ var badge = layer.transform.Find("Tokens/golani/Badge").GetComponentsInChildren<Renderer>();+ Assert.Greater(badge.Length, 1, "precondition: the badge has a plate and a glyph");+ foreach (var part in badge)+ {+ part.GetPropertyBlock(block);+ var own = part.sharedMaterial.color;+ var want = new Vector4(own.r * UnitLayer.DimShade, own.g * UnitLayer.DimShade, own.b * UnitLayer.DimShade, own.a);+ Assert.Less(Vector4.Distance(want, (Vector4)block.GetColor("_BaseColor")), 1e-3f,+ part.name + ": dimmed from its own colour, so the glyph keeps its contrast");+ }+ layer.Dim(new string[0]);+ foreach (var part in badge) { part.GetPropertyBlock(block); Assert.IsTrue(block.isEmpty, part.name + ": undimmed when it has points again"); }+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }+/// <summary>R-UNIT-005 (#1309): Send home is absent until the shown Israeli unit's own front has signed its armistice,/// then carries the localized label, queues the sim's UnitOrder through the same bridge as the standing orders and shows/// its queued line under the card's lines.</summary>@@ -394,11 +453,10 @@ public class UnitOrdersTests}/// <summary>Attack lights exactly the hexes Combat.Check takes, and the card gives each its units' names with- /// Combat.Preview's strength ratio and Combat.Outcomes' bands for its row (Q-UI-1). A click on an unlit hex queues- /// nothing; a click on a lit one queues UnitOrder(unit, attack, q, r) through SimBridge and the card says the attack- /// waits for End turn, with that hex's odds; the sim takes the queued attack at End turn.</summary>+ /// Combat.Preview's strength ratio and Combat.Outcomes' bands for its row (Q-UI-1). A click on an unlit hex commits+ /// nothing; a click on a lit one commits UnitOrder(unit, attack, q, r) through SimBridge and fights it at once.</summary>[Test]- public void AttackShowsEachTargetsOddsAndAClickOnOneQueuesTheAttack()+ public void AttackShowsEachTargetsOddsAndAClickOnOneCommitsTheAttack(){var map = BuildMap();using var ui = new UiTestKit();@@ -433,30 +491,60 @@ public class UnitOrdersTestsStringAssert.Contains(Text["unit.attack_pick"], Lines());foreach (var (q, r) in targets) StringAssert.Contains(Odds(q, r), Lines());StringAssert.Contains("strength ratio", Lines());- // An unlit hex: nothing queued, the pick ends.+ // An unlit hex: nothing committed, the pick ends.var tlv = C.SettlementHexes.Single(t => t.Id == "tel_aviv");Assert.IsFalse(targets.Contains((tlv.Q, tlv.R)), "precondition");GameRoot.OnHexClicked(map, layer, info, tlv.Q, tlv.R);Assert.IsEmpty(lit.Last());Assert.IsEmpty(bridge.Queued);- // A lit hex: the sim's attack is queued and the card keeps the unit, with the order's line and its odds.+ Assert.IsEmpty(bridge.Session.Committed);+ // A lit hex: the sim's attack is committed and fought at once.GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);UiTestKit.Press(attack);var at = targets[0];GameRoot.OnHexClicked(map, layer, info, at.q, at.r);- var queued = bridge.Queued.OfType<UnitOrder>().Single();- Assert.AreEqual((id, Combat.Attack, (int?)at.q, (int?)at.r), (queued.Unit, queued.Order, queued.Q, queued.R));+ var committed = bridge.Session.Committed.OfType<UnitOrder>().Single();+ Assert.AreEqual((id, Combat.Attack, (int?)at.q, (int?)at.r), (committed.Unit, committed.Order, committed.Q, committed.R));+ Assert.IsEmpty(bridge.Queued);Assert.IsEmpty(lit.Last());- Assert.IsTrue(info.ShowsUnit);Assert.IsFalse(Lines().Contains(Text["unit.attack_pick"]), Lines());- StringAssert.Contains(Text["unit.attack_queued"], Lines());- StringAssert.Contains(Odds(at.q, at.r), Lines());- Assert.IsEmpty(bridge.EndTurn().Rejected, "the sim takes the attack the card queued");+ Assert.IsEmpty(bridge.EndTurn().Rejected, "End turn keeps the committed attack result");info.Dispose();}finally { Object.DestroyImmediate(map.gameObject); }}+ /// <summary>R-COMBAT-001 on screen: the attack is fought at the click; the toast names the units, and the card shows+ /// the unit spent, or no unit if its own attack destroyed it (Review Focus 4). The seed fixes the draw, so one branch runs.</summary>+ [Test]+ public void AnAttackShowsItsResultAtOnce()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var tokens = UnitRoster.FromState(Units, C, bridge.State, _ => true, (row, a, q, r) => a);+ var golani = tokens.Single(t => t.Unit.Id == "golani");+ PlacedToken? shown = new PlacedToken(golani, new AnchorSpot(0, 0, 0, 0, false));+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(), selectedUnit: () => shown);+ using var toast = new ToastPresenter(ui.Root, bridge, Text) { Units = Units };+ var syrian = bridge.State.Units.Values.First(u => u.Side == "syria" && MapActions.Distance(u.Q, u.R, bridge.State.Units[0].Q, bridge.State.Units[0].R) == 1);+ var arms = bridge.State.Arms;+ Assert.IsNull(bridge.Queue(new UnitOrder(0, Combat.Attack, syrian.Q, syrian.R)));+ Assert.AreEqual(arms - 1, bridge.State.Arms, "paid at once (arms_per_attack 1)");+ var line = ui.Q<Label>("toast").text;+ StringAssert.StartsWith("The attack on hex", line);+ StringAssert.DoesNotContain("unit 0", line);+ StringAssert.Contains(golani.Unit.Name, line);+ info.ShowUnit();+ if (bridge.State.Units.ContainsKey(0))+ {+ var full = C.UnitTypes.Single(t => t.Id == bridge.State.Units[0].Type).MovementPoints;+ StringAssert.Contains(Text.Format("unit.points", 0, full), ui.Q<Label>("info-settlements").text);+ }+ else+ Assert.IsFalse(info.ShowsUnit, "a unit its own attack destroyed has no card");+ info.Dispose();+ }+/// <summary>The overlay draws one band per hex given (two rings of MapBuilder.RingVertices each) and hides when given/// none, or only hexes off the map.</summary>[Test]@@ -479,6 +567,151 @@ public class UnitOrdersTestsfinally { Object.DestroyImmediate(map.gameObject); }}+ /// <summary>Spec 8.1: every route hex has one band, and the last hex of each turn carries that turn's number.</summary>+ [Test]+ public void TheRouteOverlayShowsTurnNumbers()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ using var labels = new MapLabelsPresenter(ui.Root, map, Camera.main);+ var hexes = C.Hexes.Where(h => h.Land).Take(3).ToList();+ var route = new[] { (hexes[0].Q, hexes[0].R, 1), (hexes[1].Q, hexes[1].R, 1), (hexes[2].Q, hexes[2].R, 2) };+ map.ShowRoute(route);+ labels.Refresh();+ var go = map.Terrain.transform.Find(MapScene.RouteName);+ Assert.IsTrue(go.GetComponent<MeshRenderer>().enabled);+ Assert.AreEqual(3 * 2 * MapBuilder.RingVertices, go.GetComponent<MeshFilter>().sharedMesh.vertexCount);+ CollectionAssert.AreEqual(new[] { "1", "2" }, ui.Root.Query<Label>(className: MapLabelsPresenter.RouteTurnClass).ToList().Select(x => x.text).ToList());+ map.ShowRoute(System.Array.Empty<(int, int, int)>());+ labels.Refresh();+ Assert.IsFalse(go.GetComponent<MeshRenderer>().enabled);+ Assert.IsEmpty(ui.Root.Query<Label>(className: MapLabelsPresenter.RouteTurnClass).ToList());+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>R-MOVE-008 on screen: in Move's pick, a click on an unlit hex a route reaches gives the go-to, and the card+ /// says how many turns remain after this one.</summary>+ [Test]+ public void AClickBeyondTheLitHexesGivesAGoTo()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ layer.Show(bridge.Content, bridge.State);+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(),+ selectedUnit: () => layer.Selected is string sel ? layer.Tokens.First(p => p.Token.Unit.Id == sel) : (PlacedToken?)null,+ showReachable: map.ShowReachable, showRoute: map.ShowRoute);+ var golani = layer.Tokens.Single(p => p.Token.Unit.Id == "golani");+ var id = UnitCard.SimUnit(C, bridge.State, golani.Token.Unit)!.Value;+ var lit = Movement.Reachable(C, bridge.State, id).Keys.ToHashSet();+ var none = new Dictionary<int, int>();+ var far = C.Hexes.Where(h => h.Land && !lit.Contains((h.Q, h.R)) && (h.Q, h.R) != (golani.Q, golani.R))+ .Select(h => (h.Q, h.R)).First(h => Movement.Route(C, bridge.State, id, h.Q, h.R, none).LastOrDefault().Turn == 2);+ GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);+ UiTestKit.Press(ui.Q<Button>("info-move"));+ GameRoot.OnHexClicked(map, layer, info, far.Q, far.R);+ Assert.AreEqual((Movement.GoTo, $"{far.Q},{far.R}"), (bridge.State.Units[id].Order, bridge.State.Units[id].OrderTarget));+ StringAssert.Contains(Text.Format("unit.go_to_given", 1), ui.Q<Label>("info-settlements").text);+ info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Spec 8.1: on touch, the first tap on an unlit reachable route previews it and the second gives the go-to.</summary>+ [Test]+ public void AGoToNeedsASecondTapOnTouch()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ layer.Show(bridge.Content, bridge.State);+ var shown = new List<IReadOnlyList<(int q, int r, int turn)>>();+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(),+ selectedUnit: () => layer.Selected is string sel ? layer.Tokens.First(p => p.Token.Unit.Id == sel) : (PlacedToken?)null,+ showReachable: map.ShowReachable, showRoute: route => shown.Add(route));+ var golani = layer.Tokens.Single(p => p.Token.Unit.Id == "golani");+ var id = UnitCard.SimUnit(C, bridge.State, golani.Token.Unit)!.Value;+ var lit = Movement.Reachable(C, bridge.State, id).Keys.ToHashSet();+ var far = C.Hexes.Where(h => h.Land && !lit.Contains((h.Q, h.R)) && (h.Q, h.R) != (golani.Q, golani.R))+ .Select(h => (h.Q, h.R)).First(h => Movement.Route(C, bridge.State, id, h.Q, h.R, new Dictionary<int, int>()).Count > 0);+ GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);+ UiTestKit.Press(ui.Q<Button>("info-move"));+ GameRoot.OnHexClicked(map, layer, info, far.Q, far.R, touch: true);+ Assert.IsEmpty(bridge.Session.Committed, "the first tap only previews");+ Assert.IsNotEmpty(shown.Last(), "the route is visible after the first tap");+ GameRoot.OnHexClicked(map, layer, info, far.Q, far.R, touch: true);+ Assert.AreEqual(Movement.GoTo, bridge.State.Units[id].Order);+ info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Spec 8.1: a hovered route hides when the mouse leaves the map, and the same hex shows it again on return+ /// (the hover's cache is cleared with it, not only the map's overlay).</summary>+ [Test]+ public void AHoveredRouteShowsAgainAfterTheMouseLeavesTheMap()+ {+ var map = BuildMap();+ using var ui = new UiTestKit();+ try+ {+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ layer.Show(bridge.Content, bridge.State);+ var shown = new List<IReadOnlyList<(int q, int r, int turn)>>();+ var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(),+ selectedUnit: () => layer.Selected is string sel ? layer.Tokens.First(p => p.Token.Unit.Id == sel) : (PlacedToken?)null,+ showReachable: map.ShowReachable, showRoute: route => shown.Add(route));+ var golani = layer.Tokens.Single(p => p.Token.Unit.Id == "golani");+ var id = UnitCard.SimUnit(C, bridge.State, golani.Token.Unit)!.Value;+ var lit = Movement.Reachable(C, bridge.State, id).Keys.ToHashSet();+ var far = C.Hexes.Where(h => h.Land && !lit.Contains((h.Q, h.R)) && (h.Q, h.R) != (golani.Q, golani.R))+ .Select(h => (h.Q, h.R)).First(h => Movement.Route(C, bridge.State, id, h.Q, h.R, new Dictionary<int, int>()).Count > 0);+ GameRoot.OnHexClicked(map, layer, info, golani.Q, golani.R);+ UiTestKit.Press(ui.Q<Button>("info-move"));+ info.ShowRouteTo(far.Q, far.R);+ Assert.IsNotEmpty(shown.Last(), "precondition: the hover shows the route");+ info.HideRoute();+ Assert.IsEmpty(shown.Last(), "the mouse left the map");+ var calls = shown.Count;+ info.HideRoute();+ Assert.AreEqual(calls, shown.Count, "hiding again redraws nothing");+ info.ShowRouteTo(far.Q, far.R);+ Assert.IsNotEmpty(shown.Last(), "back on the same hex, the route shows again");+ info.Dispose();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>R-MOVE-009 on screen: a go-to that arrives at the next turn's start says so in the toast, by the unit's name.</summary>+ [Test]+ public void ARouteThatArrivesSaysSo()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);+ using var toast = new ToastPresenter(ui.Root, bridge, Text) { Units = Units };+ var none = new Dictionary<int, int>();+ var lit = Movement.Reachable(C, bridge.State, 0).Keys.ToHashSet();+ var far = C.Hexes.Where(h => h.Land && !lit.Contains((h.Q, h.R)))+ .Select(h => (h.Q, h.R)).First(h => Movement.Route(C, bridge.State, 0, h.Q, h.R, none).LastOrDefault().Turn == 2);+ Assert.IsNull(bridge.Queue(new UnitOrder(0, Movement.GoTo, far.Q, far.R)));+ bridge.EndTurn();+ Assert.IsEmpty(bridge.Session.Committed, "route work happens before this turn has a player order");+ Assert.AreEqual(bridge.Session.Now.State.Hash(), bridge.State.Hash(), "spec6.3/8.1: the map shows the route-start preview");+ Assert.AreEqual((far.Q, far.R), (bridge.State.Units[0].Q, bridge.State.Units[0].R));+ var golaniName = Units.Single(u => u.Id == C.StartingForces[0].Row).Name;+ StringAssert.Contains(golaniName, ui.Q<Label>("toast").text);+ }+/// <summary>The smoke-orders golden (slice 4): GameRoot.SmokeOrders hides turn 1's event card, gives GoldenRun.SmokeMove/// through the unit card (a click on the unit, Move, a click on the lit hex), ends the turn with End Turn, and ends on the state the sim's/// PlaySmokeOrders pins in the golden manifest.</summary>@@ -491,7 +724,8 @@ public class UnitOrdersTests{var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);using var toast = new ToastPresenter(ui.Root, bridge, Text);- using var hud = new HudPresenter(ui.Root, bridge, Text); // wires End Turn+ System.Action<int>? select = null;+ using var hud = new HudPresenter(ui.Root, bridge, Text, id => select?.Invoke(id)); // wires End Turn and the unit cycleusing var card = new EventCardPresenter(ui.Root, bridge, Text, null);Assert.IsTrue(ui.Root.Q("root").ClassListContains(EventCardPresenter.OpenClass), "precondition: turn 1's card is open, as in the player");var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);@@ -499,6 +733,11 @@ public class UnitOrdersTestsusing var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(),selectedUnit: () => layer.Selected is string sel ? layer.Tokens.First(p => p.Token.Unit.Id == sel) : (PlacedToken?)null,showReachable: map.ShowReachable);+ select = id =>+ {+ var row = layer.Tokens.Single(p => UnitCard.SimUnit(C, bridge.State, p.Token.Unit) == id).Token.Unit.Id;+ layer.Select(row); info.ShowUnit();+ };var log = new List<string>();var run = GameRoot.SmokeOrders(ui.Root, bridge, layer, (q, r) => GameRoot.OnHexClicked(map, layer, info, q, r), log.Add);while (run.MoveNext()) { }@@ -520,11 +759,17 @@ public class UnitOrdersTeststry{var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);- using var hud = new HudPresenter(ui.Root, bridge, Text);+ System.Action<int>? select = null;+ using var hud = new HudPresenter(ui.Root, bridge, Text, id => select?.Invoke(id));var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);layer.Show(bridge.Content, bridge.State);using var info = new InfoPanelPresenter(ui.Root, bridge, Text, new Dictionary<string, string>(),selectedUnit: () => layer.Selected is string sel ? layer.Tokens.First(p => p.Token.Unit.Id == sel) : (PlacedToken?)null);+ select = id =>+ {+ var row = layer.Tokens.Single(p => UnitCard.SimUnit(C, bridge.State, p.Token.Unit) == id).Token.Unit.Id;+ layer.Select(row); info.ShowUnit();+ };int clicks = 0, turn = bridge.State.Turn;var log = new List<string>();var run = GameRoot.SmokeOrders(ui.Root, bridge, layer, (q, r) => { if (clicks++ == 0) GameRoot.OnHexClicked(map, layer, info, q, r); }, log.Add);diff --git a/unity/Assets/Tests/EditMode/UnitsFromStateTests.cs b/unity/Assets/Tests/EditMode/UnitsFromStateTests.csindex e34fdfdcf..c2cc42fd8 100644--- a/unity/Assets/Tests/EditMode/UnitsFromStateTests.cs+++ b/unity/Assets/Tests/EditMode/UnitsFromStateTests.cs@@ -224,8 +224,10 @@ public class UnitsFromStateTestsinfo.ShowUnit();Assert.AreEqual(Text["city.track_recruit"], ui.Q<Label>("info-title").text);Assert.AreEqual(Text["unit.service.army"], ui.Q<Label>("info-subtitle").text);- Assert.AreEqual(Text.Format("unit.strength", raised.Strength) + "\n" + Text.Format("unit.home_city", C.SettlementNames[raised.HomeCity]),- ui.Q<Label>("info-settlements").text, "strength and home city, and no empty sector line");+ var points = C.UnitTypes.Single(t => t.Id == raised.Type).MovementPoints;+ Assert.AreEqual(Text.Format("unit.strength", raised.Strength) + "\n" + Text.Format("unit.home_city", C.SettlementNames[raised.HomeCity])+ + "\n" + Text.Format("unit.points", points, points), // #1398 (U1): the card shows the movement points left+ ui.Q<Label>("info-settlements").text, "strength, home city and movement points, and no empty sector line");Assert.AreEqual(DisplayStyle.Flex, ui.Q<Button>("info-move").style.display.value);Assert.AreEqual(Text["unit.order.move"], ui.Q<Button>("info-move").text);info.Dispose();diff --git a/unity/Assets/Tests/EditMode/WhyScreenTests.cs b/unity/Assets/Tests/EditMode/WhyScreenTests.csindex a704dfc79..a617fbcd3 100644--- a/unity/Assets/Tests/EditMode/WhyScreenTests.cs+++ b/unity/Assets/Tests/EditMode/WhyScreenTests.cs@@ -1,6 +1,9 @@+using System.Collections.Generic;+using System.IO;using System.Linq;using NUnit.Framework;using Statecraft.Game;+using Statecraft.Game.Map.Units;using Statecraft.Game.UI;using Statecraft.Sim;using UnityEditor;@@ -10,6 +13,7 @@ using UnityEngine.UIElements;public class WhyScreenTests{static readonly Content C = ContentLoader.Load(Paths.Content);+ static List<UnitEntry> Rows => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);[Test]@@ -36,9 +40,9 @@ public class WhyScreenTests{using var ui = new UiTestKit();var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text);- new WhyPresenter(ui.Root, bridge, Text);+ new WhyPresenter(ui.Root, bridge, Text) { Units = Rows };var r = bridge.EndTurn();- var expected = WhyPresenter.Order.SelectMany(sys => r.Why.Where(w => w.System == sys).Select(w => w.Message)).ToList();+ var expected = WhyPresenter.Order.SelectMany(sys => r.Why.Where(w => w.System == sys).Select(w => UnitNames.Line(w, C, Rows, Text))).ToList();var shown = ui.Q<ScrollView>("why-rows").Query<Label>(className: "why-line").ToList().Select(l => l.text).ToList();Assert.AreEqual(expected, shown);}diff --git a/unity/Assets/Tests/EditMode/WhyUnitNamesTests.cs b/unity/Assets/Tests/EditMode/WhyUnitNamesTests.csnew file mode 100644index 000000000..0eec1b257--- /dev/null+++ b/unity/Assets/Tests/EditMode/WhyUnitNamesTests.cs@@ -0,0 +1,56 @@+#nullable enable+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map.Units;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor;+using UnityEngine;++/// <summary>#1399: the Why lines name units by their names, in English and Hebrew, never by the sim's number.</summary>+public class WhyUnitNamesTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static List<UnitEntry> Rows => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);+ static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");++ [Test]+ public void EveryKeyHasALineInBothLanguages()+ {+ foreach (var key in WhyKeys.All)+ {+ Assert.IsTrue(En.Has("why.line." + key), key);+ Assert.IsTrue(He.Has("why.line." + key), key);+ }+ }++ [Test]+ public void AStartingUnitIsNamedByItsRowAndARaisedUnitByItsTypeAndHome()+ {+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);+ var golani = Rows.Single(r => r.Id == C.StartingForces[0].Row);+ Assert.AreEqual(golani.Name, UnitNames.Of(new UnitRef(s.Units[0]), C, Rows, En));+ var raised = new UnitRef(new Unit(s.NextId, "recruit", 0, 0, side: "israel", strength: 2, homeCity: "tel_aviv"));+ var name = UnitNames.Of(raised, C, Rows, En);+ StringAssert.Contains("Tel Aviv", name);+ StringAssert.DoesNotContain(raised.Id.ToString(), name);+ }++ [Test]+ public void AMoveLineHasNoSimNumberInEitherLanguage()+ {+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical);+ var move = GoldenRun.SmokeMove(C, s);+ var line = Simulation.Preview(C, s, new Command[] { move }).Why.Single(w => w.Key == WhyKeys.UnitMoved);+ foreach (var text in new[] { En, He })+ {+ var shown = UnitNames.Line(line, C, Rows, text);+ StringAssert.DoesNotContain("Unit 0", shown);+ StringAssert.DoesNotMatch(@"\bunit \d", shown);+ }+ }+}diff --git a/unity/Assets/Tests/EditMode/WhyUnitNamesTests.cs.meta b/unity/Assets/Tests/EditMode/WhyUnitNamesTests.cs.metanew file mode 100644index 000000000..78aa55912--- /dev/null+++ b/unity/Assets/Tests/EditMode/WhyUnitNamesTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 459813e9fa3243889078a3b2c47f8b43diff --git a/unity/Assets/UI/Game.uxml b/unity/Assets/UI/Game.uxmlindex e015605ff..33d6ca733 100644--- a/unity/Assets/UI/Game.uxml+++ b/unity/Assets/UI/Game.uxml@@ -96,7 +96,7 @@</ui:VisualElement><ui:VisualElement class="turn-box"><ui:Label name="attention" class="muted" />- <ui:Button name="end-turn" text="End turn" class="end-turn" />+ <ui:Button name="end-turn" text="A unit needs orders" class="end-turn" /></ui:VisualElement></ui:VisualElement><!-- The map's keyboard stop (#41 B1b, #1116): after End Turn in the Tab order, before the minimap's buttons and the@@ -154,6 +154,9 @@<!-- Fortify and Hold (#754): each shown only when the sim's Orders.Check takes it; else its reason shows. --><ui:Button name="info-fortify" /><ui:Button name="info-hold" />+ <!-- Skip is UI-only: it drops this unit from the needs-orders cycle for this turn. Hidden until the unit card+ shows it (InfoPanelPresenter sets its display on every render). -->+ <ui:Button name="info-skip" style="display: none;" /><!-- Attack (#754): shown only when the sim's Combat.Check takes some hex; the pick shows each hex's odds. --><ui:Button name="info-attack" /><!-- Send home (#1309): shown only when the sim's Demobilization.Check takes the unit. -->diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.ussindex de5d35067..19f133ca2 100644--- a/unity/Assets/UI/Statecraft.uss+++ b/unity/Assets/UI/Statecraft.uss@@ -199,6 +199,7 @@ Button:disabled { color: var(--ink-dim); border-color: rgba(120, 120, 120, 0.4);the window's foot (padding, so its backdrop still reaches it, DecisionCardTests.TheBackdropReachesTheWindowsEdgesAtEveryTier). */.hud-three-row .event-layer { justify-content: flex-start; padding-left: 72px; padding-bottom: 88px; }.turn-box { width: 150px; flex-shrink: 1; min-width: 150px; align-items: flex-end; }+.turn-box.needs-orders { width: 230px; min-width: 230px; } /* the blocked End turn label and its hourglass, EN and HE */#attention { font-size: 15px; } /* the audit's floor (H4): 15 px in the stylesheet */.end-turn {-unity-font-definition: url("project://database/Assets/UI/Fonts/EBGaramond-SemiBold.ttf"); font-size: 20px;@@ -818,6 +819,16 @@ Button.settings-choice-selected { -unity-font-definition: url("project://databas-unity-text-align: middle-center;white-space: nowrap;}+/* The last hex of each turn in a multi-turn go-to: a compact number centred on the route, not a settlement name. */+.map-route-turn {+ width: 26px;+ height: 26px;+ translate: -50% -50%;+ padding: 0;+ border-radius: 13px;+ font-size: 17px;+ background-color: rgba(14, 22, 38, 0.92);+}.map-label-city { font-size: 23px; color: rgb(250, 242, 224); }.map-label-town, .map-label-arab_town { font-size: 19px; }/* #1063: the city under the pointer (its hexes or its pill) lights its pill, ivory like the map's selected-hex outline, to saydiff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex 191a4ecfc..015fd43b4 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -47,6 +47,7 @@ hud.nav.objectives: "Objectives"hud.nav.settings: "Settings"hud.new_game: "New game"hud.end_turn: "End turn"+hud.end_turn_needs_orders: "A unit needs orders"# The screens' titles and buttons, the decision card's draft mark, the start screen and the loading line (GameRoot).budget.title: "Budget"budget.reset: "Reset"@@ -63,7 +64,7 @@ how_to_play.city: "Select a city on the map to review its housing and jobs. Choohow_to_play.training: "Train civilians without work as recruits at a military camp, or as halutzim (pioneers) at a Hakhshara (pioneer training camp). Each button shows the cost and training time."how_to_play.events: "An event card asks for a decision. Answering it costs Attention, and your choice takes effect when you end the turn."how_to_play.top_bar: "The top bar shows the date, your Attention, Money and the country's main indicators."-how_to_play.end_turn: "End turn carries out your orders and moves to the next month. A card you leave unanswered, or have no Attention left to answer, goes to the responsible minister, who decides it for you."+how_to_play.end_turn: "End turn moves to the next month. While one of your units still needs orders, the button selects it instead: move it, fortify it, hold or skip it. A card you leave unanswered, or have no Attention left to answer, goes to the responsible minister, who decides it for you."how_to_play.why: "After a turn, open Why? to see each change and its cause."# The Objectives screen (#1189): every objective in objectives.yaml, done or not, the player's date beside the historical# one, and no score (owner, 20 October 2026). The objective card's wording (#380). {0} the player's date,@@ -219,6 +220,7 @@ start.recording_failed: "The recording could not be played."outcome.order: "Your order: {0}"outcome.skip: "Click, Enter or Space to skip · Esc skips all"order.game_over: "The game is over"+order.going_home: "That unit is going home when the turn ends"order.no_attention: "Not enough attention (need {0:0.0}, have {1:0.0})"order.unknown: "Unknown {0}"# The kind of thing a refused order names in order.unknown (SimBridge.Validate; #595), one key per kind.@@ -290,6 +292,27 @@ why.effects: "Ongoing effects"why.situations: "Situations"why.other: "Other"why.nothing: "Nothing notable happened this turn."+# Structured Why lines that name units (#1399).+why.line.unit_moved: "{0} moved to hex {1} for {2} movement points"+why.line.fortify_lost: "{0} left hex {1} and is no longer fortified"+why.line.fortifying: "{0} is fortifying hex {1}; it is fortified from the end of the turn"+why.line.holds: "{0} holds hex {1}"+why.line.attack_ended_truce: "{0}'s attack on hex {1} ends: a truce is on"+why.line.attack_ordered: "{0} will attack hex {1}"+why.line.attack_ended: "{0}'s attack on hex {1} ends: no enemy unit is there"+why.line.holds_fire: "{0} holds its fire: no attack on hex {1} to support"+why.line.attack_called_off: "{0}'s attack on hex {1} is called off: it needs {2} Arms and the stock has {3}"+why.line.engagement: "The attack on hex {2} ({0} against {1}, strength ratio {3}%): the attackers lost {4:N0} people and the defenders lost {5:N0} people"+why.line.destroyed: "{0} was destroyed"+why.line.retreated: "{0} retreated to hex {1}"+why.line.surrendered_prisoners: "{0} surrendered with {1:N0} people: it had no hex to retreat to. They are held as prisoners"+why.line.surrendered_held: "{0} surrendered with {1:N0} people: it had no hex to retreat to. They are held by the enemy"+why.line.sent_home: "{0} is sent home: its {1:N0} people are civilians in {2} now"+why.line.withdrew: "{0} withdrew from {1} to hex {2}"+why.line.on_its_way: "{0} is on its way to hex {1}"+why.line.stopped_no_route: "{0} stopped: no route reaches hex {1}"+why.line.stopped_full: "{0} stopped: hex {1} is full"+why.line.arrived: "{0} arrived at hex {1}"# The turn report (#1037, TurnReportPresenter): a line is a top-bar caption and the change the bar shows.report.title: "What happened this turn"report.intro: "What changed in the top bar, and the main causes:"@@ -481,15 +504,19 @@ unit.sources: "Sources: {0}"unit.draft_wikipedia: "Draft: from Wikipedia only, not yet checked against a published history"unit.draft: "Draft: not yet checked by a historian"unit.defence: "Open the Defence screen"+unit.raised_name: "{0}, {1}"# The unit card's Move order (GDD Phase 5 PR 15, #754): the order's name is Q-UI-2's, approved by the owner (#375).unit.order.move: "Move"-unit.move_pick: "Choose a lit hex to move to"-unit.move_queued: "Move ordered: the unit moves when you end the turn"+unit.move_pick: "Choose a lit hex to move to now, or another hex to send the unit there over several turns"+unit.points: "Movement points: {0} of {1}"+# A unit with a go-to (#1398, spec 8.1): {0} the turns after this one until it arrives.+unit.go_to_given: "On its way to the chosen hex. Turns to arrive: {0}"# Fortify and Hold (#754): the names are Q-UI-2's, approved by the owner (#375). Fortify is set at the end of the turn (R-ORDER-002).unit.order.fortify: "Fortify"unit.order.hold: "Hold"+unit.order.skip: "Skip this turn"unit.fortify_queued: "Fortify ordered: the unit is fortified from the end of the turn"-unit.hold_queued: "Hold ordered: the unit holds its hex when you end the turn"+unit.hold_queued: "Holding its hex"# Attack (#754): the name is Q-UI-2's, approved by the owner (#375). The odds are Q-UI-1's: Combat.Preview's strength ratio# ({0} the defenders' names, or the hex's coordinates; {1} the percent), then each of Combat.Outcomes' bands ({0} of {1} faces; {2} and {3} people lost).unit.order.attack: "Attack"@@ -498,7 +525,6 @@ unit.attack_pick: "Choose a lit hex to attack"unit.attack_odds: "{0}: strength ratio {1:0'%'}"unit.attack_band: "{0} in {1}: you lose {2:N0} people, they lose {3:N0}"unit.attack_band_retreat: "{0} in {1}: you lose {2:N0} people, they lose {3:N0} and retreat"-unit.attack_queued: "Attack ordered: the unit attacks when you end the turn"# The unit card's player-triggered demobilisation order (R-UNIT-005, #1309).unit.order.send_home: "Send home"unit.send_home_queued: "Send home ordered: the unit goes home when you end the turn"diff --git a/unity/Assets/UI/strings.he.yaml b/unity/Assets/UI/strings.he.yamlindex af23cc651..02ccdeff5 100644--- a/unity/Assets/UI/strings.he.yaml+++ b/unity/Assets/UI/strings.he.yaml@@ -42,6 +42,8 @@ hud.nav.objectives: "יעדים"hud.nav.settings: "הגדרות"hud.new_game: "משחק חדש"hud.end_turn: "סיום התור"+# Civ movement U4: agent-drafted Hebrew; native review pending (#564).+hud.end_turn_needs_orders: "יחידה ממתינה להוראות"budget.title: "תקציב"budget.reset: "איפוס"budget.submit: "הגשת התקציב"@@ -57,7 +59,8 @@ how_to_play.city: "בחרו עיר במפה כדי לראות את הדיור וhow_to_play.training: "בעיר שיש בה מחנה צבאי או מחנה הכשרה אפשר לאמן אזרחים ללא עבודה כמגויסים או להכשיר אותם כחלוצים. הכפתור מראה כמה עולה האימון וכמה תורות הוא נמשך."how_to_play.events: "כרטיס אירוע מבקש מכם החלטה. מענה עליו עולה תשומת לב, והבחירה שלכם נכנסת לתוקף בסיום התור."how_to_play.top_bar: "הסרגל העליון מציג את התאריך, את תשומת הלב שלכם, את הכסף ואת המדדים העיקריים של המדינה."-how_to_play.end_turn: "סיום התור מבצע את ההוראות שלכם ומעביר לחודש הבא. כרטיס שלא עניתם עליו, או שלא נשארה לכם תשומת לב לענות עליו, עובר לשר האחראי, והוא מחליט במקומכם."+# Civ movement U4: agent-drafted Hebrew; native review pending (#564).+how_to_play.end_turn: "סיום התור מעביר לחודש הבא. כל עוד אחת היחידות שלכם ממתינה להוראות, הכפתור בוחר בה במקום זאת: הזיזו אותה, בצרו אותה, החזיקו בה או דלגו עליה. כרטיס שלא עניתם עליו, או שלא נשארה לכם תשומת לב לענות עליו, עובר לשר האחראי, והוא מחליט במקומכם."how_to_play.why: "אחרי תור, פתחו את המסך למה? כדי לראות כל שינוי ואת הסיבה לו."# The Objectives screen (#1189). For the native reviewer (#564).objectives.title: "יעדים"@@ -221,6 +224,8 @@ start.recording_failed: "לא ניתן היה להשמיע את ההקלטה."outcome.order: "הפקודה שלך: {0}"outcome.skip: "לחיצה, Enter או רווח לדילוג · Esc מדלג על הכול"order.game_over: "המשחק הסתיים"+# Hebrew draft for #1398; native review pending (#564).+order.going_home: "היחידה חוזרת הביתה בסיום התור"order.no_attention: "אין מספיק תשומת לב (נדרש {0:0.0}, יש {1:0.0})"order.unknown: "לא ניתן לזהות {0}"# The kind of thing a refused order names in order.unknown (SimBridge.Validate; #595), one key per kind. order.unknown puts@@ -303,6 +308,27 @@ why.effects: "השפעות מתמשכות"why.situations: "מצבים"why.other: "אחר"why.nothing: "לא קרה דבר ראוי לציון בתור הזה."+# Hebrew drafts for the structured unit Why lines (#1399); native review pending (#564).+why.line.unit_moved: "{0} נעה למשושה {1} תמורת {2} נקודות תנועה"+why.line.fortify_lost: "{0} עזבה את משושה {1} ואינה מבוצרת עוד"+why.line.fortifying: "{0} מתבצרת במשושה {1}; היא תהיה מבוצרת מסוף התור"+why.line.holds: "{0} מחזיקה במשושה {1}"+why.line.attack_ended_truce: "ההתקפה של {0} על משושה {1} מסתיימת: שביתת נשק בתוקף"+why.line.attack_ordered: "{0} תתקוף את משושה {1}"+why.line.attack_ended: "ההתקפה של {0} על משושה {1} מסתיימת: אין שם יחידת אויב"+why.line.holds_fire: "{0} אינה יורה: אין התקפה על משושה {1} לתמוך בה"+why.line.attack_called_off: "ההתקפה של {0} על משושה {1} מבוטלת: נדרשים {2} כלי נשק ובמלאי יש {3}"+why.line.engagement: "ההתקפה על משושה {2} ({0} נגד {1}, יחס כוחות {3}%): התוקפים איבדו {4:N0} איש והמגינים איבדו {5:N0} איש"+why.line.destroyed: "{0} הושמדה"+why.line.retreated: "{0} נסוגה למשושה {1}"+why.line.surrendered_prisoners: "{0} נכנעה עם {1:N0} איש: לא היה לה משושה לסגת אליו. הם מוחזקים כשבויים"+why.line.surrendered_held: "{0} נכנעה עם {1:N0} איש: לא היה לה משושה לסגת אליו. הם מוחזקים בידי האויב"+why.line.sent_home: "{0} נשלחת הביתה: {1:N0} אנשיה הם כעת אזרחים ב־{2}"+why.line.withdrew: "{0} נסוגה מ־{1} למשושה {2}"+why.line.on_its_way: "{0} בדרך למשושה {1}"+why.line.stopped_no_route: "{0} נעצרה: אין מסלול שמגיע למשושה {1}"+why.line.stopped_full: "{0} נעצרה: משושה {1} מלא"+why.line.arrived: "{0} הגיעה למשושה {1}"# The turn report (#1037, TurnReportPresenter): a line is a top-bar caption and the change the bar shows.report.title: "מה קרה בתור הזה"report.intro: "מה השתנה בסרגל העליון, ומה הסיבות העיקריות:"@@ -497,19 +523,25 @@ unit.sources: "מקורות: {0}"unit.draft_wikipedia: "טיוטה: מוויקיפדיה בלבד, טרם נבדק מול מחקר שפורסם"unit.draft: "טיוטה: טרם נבדק בידי היסטוריון"unit.defence: "פתיחת מסך הביטחון"+# Hebrew draft for a raised unit's type and home city (#1399); native review pending (#564).+unit.raised_name: "{0}, {1}"# The unit card's Move order (#754): the order's name is Q-UI-2's, approved by the owner (#375).unit.order.move: "תנועה"-# Approved by Beri, a native speaker, on #1265 (21 Oct 2026). For the native reviewer (#564)-unit.move_pick: "בחרו משושה מואר שאליו היחידה תנוע"-# Approved by Beri, a native speaker, on #1265 (21 Oct 2026). For the native reviewer (#564)-unit.move_queued: "ניתנה פקודת תנועה: היחידה תנוע בסיום התור"+# Hebrew route draft for #1398; native review pending (#564).+unit.move_pick: "בחרו משושה מואר כדי לנוע אליו עכשיו, או משושה אחר כדי לשלוח אליו את היחידה במשך כמה תורות"+# Hebrew draft for #1398; native review pending (#564).+unit.points: "נקודות תנועה: {0} מתוך {1}"+# Hebrew route draft for #1398; native review pending (#564).+unit.go_to_given: "בדרך למשושה שנבחר. תורות עד ההגעה: {0}"# Fortify and Hold (#754): the names are Q-UI-2's, approved by the owner (#375).unit.order.fortify: "ביצור"unit.order.hold: "החזקה"+# Civ movement U4: agent-drafted Hebrew; native review pending (#564).+unit.order.skip: "דילוג על התור"# Approved by Beri, a native speaker, on #1269 (21 Oct 2026). For the native reviewer (#564)unit.fortify_queued: "ניתנה פקודת ביצור: היחידה תהיה מבוצרת מסוף התור"-# Approved by Beri, a native speaker, on #1269 (21 Oct 2026). For the native reviewer (#564)-unit.hold_queued: "ניתנה פקודת החזקה: היחידה תחזיק במשושה שלה בסיום התור"+# Hebrew draft for #1398; native review pending (#564).+unit.hold_queued: "מחזיקה במשושה שלה"# Attack (#754): the name is Q-UI-2's, approved by the owner (#375).unit.order.attack: "התקפה"# Approved by Beri, a native speaker, on #1277 (21 Oct 2026). For the native reviewer (#564)@@ -522,7 +554,6 @@ unit.attack_band: "{0} מתוך {1}: אתם מאבדים {2:N0} איש, הם מ# Approved by Beri, a native speaker, on #1277 (21 Oct 2026). For the native reviewer (#564)unit.attack_band_retreat: "{0} מתוך {1}: אתם מאבדים {2:N0} איש, הם מאבדים {3:N0} ונסוגים"# Approved by Beri, a native speaker, on #1277 (21 Oct 2026). For the native reviewer (#564)-unit.attack_queued: "ניתנה פקודת התקפה: היחידה תתקוף בסיום התור"# The unit card's Send home order and its queued line (R-UNIT-005, #1309), in unit.order.*'s and unit.*_queued's form.# Hebrew drafts: agent-checked; native review pending (#564).unit.order.send_home: "שליחה הביתה"