A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: show the under-attack look on attacked cities and units (Refs #1878) (#1923)
Beridf39f502681b
diff --git a/changelog.d/1878.md b/changelog.d/1878.mdnew file mode 100644index 000000000..669b3b725--- /dev/null+++ b/changelog.d/1878.md@@ -0,0 +1,3 @@+- The default map shows the calm "under attack" look (grey smoke, a low fire glow, a slowly pulsing red border) on every+ hex the turn's attacks hit, for as long as the turn report is open (#1878). It reads the sim's engagement lines and+ changes nothing in the rules.diff --git a/unity/Assets/Scripts/Map/UnderAttackLayer.cs b/unity/Assets/Scripts/Map/UnderAttackLayer.csnew file mode 100644index 000000000..9c6b2e9a5--- /dev/null+++ b/unity/Assets/Scripts/Map/UnderAttackLayer.cs@@ -0,0 +1,92 @@+#nullable enable+using System.Collections.Generic;+using System.Globalization;+using System.Linq;+using Statecraft.Game.Map.Units;+using Statecraft.HexTiles;+using Statecraft.Sim;+using UnityEngine;++namespace Statecraft.Game.Map+{+ /// <summary>#1878: the "under attack" look (HexUnderAttack: smoke, fire glow, pulsing border) on the default diorama map.+ /// HexUnderAttack builds on a hex board; this lays the same lattice over the terrain (a root at the map's north-west+ /// corner, as HexRealMap does) so the look sits on the attacked hex and follows the ground. Presentation only: it reads+ /// the turn's Why lines (an engagement's Target is the hex it hit) and writes nothing to the simulation or a save.</summary>+ public sealed class UnderAttackLayer+ {+ public const string RootName = "UnderAttack";++ readonly MapScene map;+ readonly Transform root;+ readonly float sizeM;+ readonly TerrainSurface surface;+ readonly List<(int q, int r)> shown = new List<(int, int)>();++ public IReadOnlyCollection<(int q, int r)> Shown => shown;++ /// <summary>The hexes the turn's engagements hit, each once, in the turn's order.</summary>+ public static IReadOnlyList<(int q, int r)> AttackedHexes(StepResult? turn)+ {+ var hexes = new List<(int q, int r)>();+ if (turn == null) return hexes;+ foreach (var cause in turn.Why)+ {+ if (cause.Key != WhyKeys.Engagement) continue;+ var parts = cause.Target.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)) continue;+ if (!hexes.Contains((q, r))) hexes.Add((q, r));+ }+ return hexes;+ }++ public UnderAttackLayer(MapScene map)+ {+ this.map = map;+ sizeM = map.Hexes.hex_size_km * 1000f;+ var old = map.Terrain.transform.Find(RootName);+ if (old != null) { old.SetParent(null, false); if (Application.isPlaying) Object.Destroy(old.gameObject); else Object.DestroyImmediate(old.gameObject); }+ var go = new GameObject(RootName);+ go.transform.SetParent(map.Terrain.transform, false);+ // Lattice (x east, z = -south of the north-west corner) becomes world by this shift, as HexRealMap's Origin.+ go.transform.position = new Vector3(0f, 0f, map.Frame.LengthM);+ root = go.transform;+ surface = new TerrainSurface(map, root.position);+ }++ /// <summary>Shows the look on every hex of the map the turn attacked, in place of an earlier turn's; none when the+ /// turn is null or attacked nothing. A hex the map does not have shows nothing.</summary>+ public void Show(StepResult? turn)+ {+ Clear();+ if (root == null) return; // the terrain, and the root under it, went with the scene+ var onMap = new HashSet<(int, int)>(map.Hexes.hexes.Select(h => (h.q, h.r)));+ foreach (var (q, r) in AttackedHexes(turn))+ {+ if (!onMap.Contains((q, r))) continue;+ HexUnderAttack.Show(root, surface, q, r, sizeM);+ shown.Add((q, r));+ }+ }++ public void Clear()+ {+ if (root == null) { shown.Clear(); return; } // GameRoot's teardown may run after the terrain is gone+ foreach (var (q, r) in shown) HexUnderAttack.Hide(root, q, r);+ shown.Clear();+ }++ /// <summary>The terrain's ground in the root's space (lattice x/z). Heights are world y, which is the root's local y+ /// because the root sits at y = 0 (HexRealMap's board is sunk and sea-based; this layer is not).</summary>+ sealed class TerrainSurface : IHexSurface+ {+ readonly MapScene map; readonly Vector3 origin;+ public TerrainSurface(MapScene map, Vector3 origin) { this.map = map; this.origin = origin; }+ public float Height(Vector3 p) => UnitShowcase.Ground(map, new Vector3(p.x + origin.x, 0f, p.z + origin.z)).y;+ // The look reads only Height; slope and water are for tile placement, which this layer does not do.+ public float SlopeDeg(Vector3 p) => 0f;+ public bool IsWater(Vector3 p) => false;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/UnderAttackLayer.cs.meta b/unity/Assets/Scripts/Map/UnderAttackLayer.cs.metanew file mode 100644index 000000000..eb06ec099--- /dev/null+++ b/unity/Assets/Scripts/Map/UnderAttackLayer.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: dc2667d266076bc52869b3ffc80f8cd2\ No newline at end of filediff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 546675991..b4dd9ce1e 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -374,6 +374,11 @@ namespace Statecraft.Game.UIowned.Add(new Undo(() => bridge.Changed -= showUnits));showUnits();DiagLog.BootPhase("units layer built");+ // #1878: the turn report is up, the hexes the turn attacked show the under-attack look; closing it clears them.+ var underAttack = new Statecraft.Game.Map.UnderAttackLayer(map);+ var turnReport = report!;+ turnReport.Showing += underAttack.Show;+ owned.Add(new Undo(() => { turnReport.Showing -= underAttack.Show; underAttack.Clear(); }));var localitiesAt = LocalitiesAt(map);var townNamesHe = map.SettlementsFor(inputs.Map.SettlementsYaml).ToDictionary(s => s.Id, s => s.NameHe);var info = this.info = Own(new InfoPanelPresenter(root, bridge, text, names, nav: nav,diff --git a/unity/Assets/Scripts/UI/TurnReportPresenter.cs b/unity/Assets/Scripts/UI/TurnReportPresenter.csindex e74f20ecc..b6ffc3fd2 100644--- a/unity/Assets/Scripts/UI/TurnReportPresenter.cs+++ b/unity/Assets/Scripts/UI/TurnReportPresenter.cs@@ -79,6 +79,10 @@ namespace Statecraft.Game.UIHide();}+ /// <summary>Raised with the turn being reported when the report opens, and with null when it closes (#1878: the map+ /// shows the under-attack look on the hexes the turn attacked for as long as the report is up).</summary>+ public event Action<StepResult?>? Showing;+/// <summary>True while the report shows.</summary>public bool IsOpen => hudRoot.ClassListContains(OpenClass);@@ -195,6 +199,7 @@ namespace Statecraft.Game.UIreport.style.display = DisplayStyle.Flex;hudRoot.AddToClassList(OpenClass);ScreenNav.DisableCovered(hudRoot); // the report comes out uncovered (or under an outcome clip) and takes the focus then+ Showing?.Invoke(seen);}void OnClose() => Close();@@ -209,10 +214,12 @@ namespace Statecraft.Game.UIvoid Hide(){- if (IsOpen) closedAt = UnityEngine.Time.frameCount;+ bool wasOpen = IsOpen;+ if (wasOpen) closedAt = UnityEngine.Time.frameCount;report.style.display = DisplayStyle.None;hudRoot.RemoveFromClassList(OpenClass);ScreenNav.DisableCovered(hudRoot); // the decision layer comes back: an open card takes the focus (OnUncovered)+ if (wasOpen) Showing?.Invoke(null);}void SeeAll()diff --git a/unity/Assets/Tests/EditMode/UnderAttackLayerTests.cs b/unity/Assets/Tests/EditMode/UnderAttackLayerTests.csnew file mode 100644index 000000000..5e1743b93--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnderAttackLayerTests.cs@@ -0,0 +1,172 @@+#nullable enable+using System;+using System.Collections;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Map;+using Statecraft.Game.UI;+using Statecraft.HexTiles;+using Statecraft.Sim;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;+using Statecraft.Game.Map.Units;++/// <summary>#1878: the "under attack" look (HexUnderAttack: smoke, fire glow, pulsing border) on the default diorama map.+/// The hex the sim's engagement names shows it while the turn report is open and it clears when the report closes. It reads+/// the turn's Why lines and nothing else: no rule, no state, no save changes.</summary>+public class UnderAttackLayerTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);+ static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");++ static Cause Engagement(int q, int r) => new Cause("map", FormattableString.Invariant($"{q},{r}"), 0, $"The attack on hex {q},{r}", key: WhyKeys.Engagement);+ static StepResult Turn(params Cause[] why) => new StepResult(GameSession.New(C, GoldenRun.Seed, Mode.Historical).State, why, new Rejection[0]);++ MapScene? map;++ [TearDown] public void DestroyMap() { if (map != null) Object.DestroyImmediate(map.gameObject); map = null; }++ MapScene Map()+ {+ EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);+ map = new GameObject("MapScene").AddComponent<MapScene>();+ map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));+ map.Build();+ return map;+ }++ /// <summary>A land hex of the real map, so the look has ground under it.</summary>+ static (int q, int r) LandHex(MapScene m, int skip = 0)+ {+ var h = m.Hexes.hexes.Where(x => x.land).Skip(skip).First();+ return (h.q, h.r);+ }++ [Test]+ public void OnlyEngagementsNameAnAttackedHex()+ {+ var turn = Turn(Engagement(3, 4), new Cause("map", "9,9", 0, "Unit 7 moved", key: WhyKeys.UnitMoved), Engagement(3, 4), Engagement(5, 1));+ CollectionAssert.AreEqual(new[] { (3, 4), (5, 1) }, UnderAttackLayer.AttackedHexes(turn), "each attacked hex once, in the turn's order");+ Assert.IsEmpty(UnderAttackLayer.AttackedHexes(null));+ Assert.IsEmpty(UnderAttackLayer.AttackedHexes(Turn()));+ }++ [Test]+ public void ShowPutsTheLookOnTheAttackedHexOfTheMapAndClearRemovesIt()+ {+ var m = Map();+ var (q, r) = LandHex(m);+ var layer = new UnderAttackLayer(m);+ layer.Show(Turn(Engagement(q, r)));+ var root = m.Terrain.transform.Find(UnderAttackLayer.RootName);+ Assert.IsNotNull(root);+ var look = root!.Find(HexUnderAttack.Name(q, r));+ Assert.IsNotNull(look, "the attacked hex shows the look");+ CollectionAssert.AreEqual(new[] { (q, r) }, layer.Shown);+ // On the diorama the hex centre is Frame.ToWorld of the hex's lon/lat, on the ground there.+ var hex = m.Hexes.hexes.First(h => h.q == q && h.r == r);+ var want = m.Frame.ToWorld(hex.lon, hex.lat, 0);+ Assert.That(Vector2.Distance(new Vector2(look!.position.x, look.position.z), new Vector2(want.x, want.z)), Is.LessThan(5f), "the look is on the hex's centre");+ Assert.That(look.position.y, Is.EqualTo(m.Terrain.SampleHeight(new Vector3(look.position.x, 0f, look.position.z)) + m.Terrain.transform.position.y).Within(0.5f), "on the ground");+ Assert.That(look.GetComponentsInChildren<MeshRenderer>().Length, Is.GreaterThanOrEqualTo(3), "smoke, glow and border");+ layer.Clear();+ Assert.IsNull(root.Find(HexUnderAttack.Name(q, r)));+ Assert.IsEmpty(layer.Shown);+ }++ [Test]+ public void ANewTurnReplacesTheHexesAndAHexOffTheMapShowsNothing()+ {+ var m = Map();+ var a = LandHex(m); var b = LandHex(m, 40);+ var layer = new UnderAttackLayer(m);+ layer.Show(Turn(Engagement(a.q, a.r)));+ layer.Show(Turn(Engagement(b.q, b.r), Engagement(-500, -500)));+ CollectionAssert.AreEqual(new[] { b }, layer.Shown, "only the new hex, and none for a hex the map does not have");+ Assert.IsNull(m.Terrain.transform.Find(UnderAttackLayer.RootName)!.Find(HexUnderAttack.Name(a.q, a.r)));+ layer.Show(null);+ Assert.IsEmpty(layer.Shown);+ }++ /// <summary>GameRoot's teardown can run once the terrain (and the layer's root under it) is destroyed: neither call throws.</summary>+ [Test]+ public void ClearAndShowAreSafeAfterTheTerrainIsGone()+ {+ var m = Map();+ var (q, r) = LandHex(m);+ var layer = new UnderAttackLayer(m);+ layer.Show(Turn(Engagement(q, r)));+ Object.DestroyImmediate(m.Terrain.gameObject);+ Assert.DoesNotThrow(() => layer.Clear());+ Assert.DoesNotThrow(() => layer.Show(Turn(Engagement(q, r))));+ Assert.IsEmpty(layer.Shown);+ }++ [Test]+ public void TheReportSaysWhenItOpensAndCloses()+ {+ using var ui = new UiTestKit();+ var text = En;+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);+ using var nav = new ScreenNav(ui.Root);+ using var hud = new HudPresenter(ui.Root, bridge, text);+ using var report = new TurnReportPresenter(ui.Root, bridge, text, nav);+ var seen = new List<StepResult?>();+ report.Showing += seen.Add;+ var turn = bridge.EndTurn();+ Assert.IsTrue(report.IsOpen);+ Assert.AreEqual(1, seen.Count);+ Assert.AreSame(bridge.Session.Last, seen[0], "it names the turn it reports");+ UiTestKit.Press(ui.Q<Button>("turn-report-close"));+ Assert.AreEqual(2, seen.Count);+ Assert.IsNull(seen[1], "closing says null");+ report.Close();+ Assert.AreEqual(2, seen.Count, "closing it again says nothing");+ }++ /// <summary>The real game scene: an enemy attack that engages on End turn lights the attacked hex while the report is up,+ /// and closing the report puts it out. The setup is TurnReportTests' (the Arab Liberation Army attacks Golani's hex).</summary>+ [UnityTest]+ public IEnumerator InTheGameTheAttackedHexShowsTheLookUntilTheReportCloses()+ {+ VisualElement ui = null!; GameRoot root = null!; RenderTexture? rt = null; PanelSettings? ps = null;+ var dir = Path.Combine(Path.GetTempPath(), "statecraft-under-attack-" + Guid.NewGuid().ToString("N"));+ try+ {+ yield return CivMovementShots.Boot(false, dir, (t, p, u, g) => { rt = t; ps = p; ui = u; root = g; });+ var bridge = root.Bridge!;+ var gameMap = Object.FindFirstObjectByType<MapScene>();+ var layerRoot = gameMap.Terrain.transform.Find(UnderAttackLayer.RootName);+ Assert.IsNotNull(layerRoot, "the game builds the layer");+ var forces = C.StartingForces.ToList();+ int golani = forces.FindIndex(f => f.Row == "golani"), ala = forces.FindIndex(f => f.Row == "arab_liberation_army");+ var s = bridge.Session.State; var g = s.Units[golani]; var a = s.Units[ala];+ s.Units[golani] = new Unit(g.Id, g.Type, a.Q, a.R - 1, g.Service, g.Side, 1);+ s.Units[ala] = new Unit(a.Id, a.Type, a.Q, a.R, a.Service, a.Side, a.Strength, Combat.Attack, $"{a.Q},{a.R - 1}");+ foreach (var id in bridge.NeedsOrders.ToList()) bridge.Skip(id);+ UiTestKit.Press(ui.Q<Button>("end-turn"));+ yield return null;+ Assert.IsTrue(ui.Q("root").ClassListContains(TurnReportPresenter.OpenClass), "precondition: the report is up");+ Assert.IsNotNull(layerRoot!.Find(HexUnderAttack.Name(a.Q, a.R - 1)), "the attacked hex shows the look");+ Assert.AreEqual(1, layerRoot.childCount);+ UiTestKit.Press(ui.Q<Button>("turn-report-close"));+ yield return null;+ Assert.AreEqual(0, layerRoot.childCount, "closing the report clears it");+ }+ finally+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ if (ps != null) Object.DestroyImmediate(ps);+ if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }+ if (Directory.Exists(dir)) Directory.Delete(dir, true);+ }+ }+}diff --git a/unity/Assets/Tests/EditMode/UnderAttackLayerTests.cs.meta b/unity/Assets/Tests/EditMode/UnderAttackLayerTests.cs.metanew file mode 100644index 000000000..4712b9b96--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnderAttackLayerTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 2ff9633b2bcfcec5bacf24f7f9f24651\ No newline at end of file