A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map labels: settlement names keep clear of the unit tokens (refs #197) (#518)
Eyal Golanb9ba4e5f216e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ce24922fa..96fa376f5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -454,6 +454,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB- The art checkpoint's close checks (`hero06judea`, `hero06negev`) are shot with the settlement trees off, as the hazealready was: one tree's crown had filled `hero06judea`, so it no longer showed the ground it is there to check(audit 2026-10-13). The game itself is unchanged.+- Settlement names keep clear of the unit tokens in normal play (refs #197). The Tel Aviv name no longer sits on the+ Kiryati Brigade's badge and figures at the gameplay zoom: a token standing in a town counts as part of it, so the+ name hangs just above the brigade, and a name keeps clear of any other token as it does of a panel. Presentation+ only: no golden moves.- The Unity build has no compiler warnings again. The panel trim's corner ornament no longer uses`MeshWriteData.uvRegion`, which Unity 6000.3 marks obsolete (CS0618); the renderer now maps texture coordinates itself.The pixels are unchanged.diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.csindex 05b09efc6..de23ed49a 100644--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs@@ -36,6 +36,7 @@ namespace Statecraft.Game.Map.UnitsTransform tokensRoot = null!;readonly List<Transform> badges = new List<Transform>();readonly List<(Vector2 centre, float radius)> treeHoles = new List<(Vector2, float)>();+ List<Bounds[]> keepClear = new List<Bounds[]>();GameObject? ring;bool still;@@ -45,6 +46,11 @@ namespace Statecraft.Game.Map.Unitspublic IReadOnlyDictionary<UnitAnchor, AnchorSpot> Spots => spots;/// <summary>The ground the anchors were placed on.</summary>public UnitGround PlacementGround => ground;+ /// <summary>The world boxes the map's name pills keep clear of (issue #197), one entry per drawn token: its standing+ /// pieces (the figures on their bases, a parked aircraft, the ship; not a flying aircraft, which moves) and its+ /// badge, which MapLabelsPresenter projects to one screen rectangle, so no pill sits on a token or between its badge+ /// and its figures. A new list whenever the tokens are rebuilt, and empty while the "units" toggle hides the layer.</summary>+ public IReadOnlyList<Bounds[]> KeepClear => gameObject.activeInHierarchy ? keepClear : (IReadOnlyList<Bounds[]>)Array.Empty<Bounds[]>();/// <summary>The selected unit's id, or null.</summary>public string? Selected { get; private set; }@@ -195,6 +201,7 @@ namespace Statecraft.Game.Map.Units}badges.Clear();treeHoles.Clear();+ keepClear = new List<Bounds[]>(); // a new list, so the labels see the changefloat hex = map.Hexes.hex_size_km * 1000f;foreach (var p in placed){@@ -242,10 +249,33 @@ namespace Statecraft.Game.Map.Unitsif (cam != null) badge.transform.rotation = cam.transform.rotation;AddRenderer(badge.transform, "Plate", MeshFor("badge-plate", UnitBadge.PlateMesh), badgePlate, 0f);AddRenderer(badge.transform, "Glyph", MeshFor("badge-" + t.Unit.Service, () => UnitBadge.GlyphMesh(t.Unit.Service)), badgeGlyph, -UnitBadge.GlyphLift);+ keepClear.Add(KeepClearOf(go.transform, badge.transform.position));}HideTrees();}+ /// <summary>A token's keep-clear boxes: the bounds of its pieces that stand still (a flying aircraft is left out)+ /// and a cube of the badge's width round the badge's centre, which holds the plate however it is turned. The pieces'+ /// bounds come from their meshes and transforms, not Renderer.bounds, which is empty while the layer is inactive (the+ /// "units" toggle off when the tokens are built; review of #518).</summary>+ static Bounds[] KeepClearOf(Transform token, Vector3 badgeCentre)+ {+ var boxes = new List<Bounds> { new Bounds(badgeCentre, Vector3.one * UnitBadge.SizeM) };+ bool any = false; var pieces = default(Bounds);+ foreach (var f in token.GetComponentsInChildren<MeshFilter>(true))+ {+ if (f.sharedMesh == null || f.GetComponentInParent<UnitBadge>(true) != null || f.GetComponentInParent<ShowcaseFlight>(true) != null) continue;+ var b = f.sharedMesh.bounds; var m = f.transform.localToWorldMatrix;+ for (int c = 0; c < 8; c++)+ {+ var w = m.MultiplyPoint3x4(new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z));+ if (any) pieces.Encapsulate(w); else { pieces = new Bounds(w, Vector3.zero); any = true; }+ }+ }+ if (any) boxes.Add(pieces);+ return boxes.ToArray();+ }+static void AddRenderer(Transform parent, string name, Mesh mesh, Material mat, float z){var go = new GameObject(name);diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 685c842c1..87eeca0c8 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -224,7 +224,8 @@ namespace Statecraft.Game.UIvar mini = minimap = Own(new MinimapPresenter(root, map.Hexes));bool hebrew = text["ui.lang"] == "he"; // today's name in the UI's language (review M6)labels = Own(new MapLabelsPresenter(root, map, cameraController.GetComponent<Camera>(), null,- p => MapLabelsPresenter.TipOf(p, n => text.Format("map.today", n), text["map.mixed"], hebrew)));+ p => MapLabelsPresenter.TipOf(p, n => text.Format("map.today", n), text["map.mixed"], hebrew),+ () => unitLayer != null ? unitLayer.KeepClear : null)); // the names keep clear of the unit tokens (issue #197)mini.Clicked += (lon, lat) => { camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); cameraController.Settle(); SyncMinimap(); labels?.Refresh(); }; // the click may come after LateUpdate (review M6)Action onChanged = RenderPlacementsIfChanged;bridge.Changed += onChanged;diff --git a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs b/unity/Assets/Scripts/UI/MapLabelsPresenter.csindex c8d66b016..311f35b08 100644--- a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs+++ b/unity/Assets/Scripts/UI/MapLabelsPresenter.cs@@ -33,12 +33,23 @@ namespace Statecraft.Game.UI/// (OccluderNames: the top bar, the info panel, the minimap and its map-layer caption, the event card), does not/// overlap an already placed pill (its last laid-out size plus MarginPx), covers at most MaxKitCover of its own kit's/// rectangle and of every other visible kit's, and is more than twice as far from every other visible marker's top as- /// from its own kit, plus MarginPx, so no name reads as a neighbour's. A city whose spots all crowd a neighbour keeps- /// the first that is clear of panels, pills and its own kit. A pill hidden in the last refresh needs HysteresisPx more+ /// from its own kit (the kit alone, not the tokens on it), plus MarginPx, so no name reads as a neighbour's. A city+ /// that finds no such spot never loses its name: it takes, in this order, the first spot round its kit alone that+ /// still reads as its own (over a unit token if need be), then the first clear of panels, pills, tokens and its own+ /// kit, then the first clear of panels, pills and its own kit. A pill hidden in the last refresh needs HysteresisPx more/// room to come back, so it does not blink at a threshold. Refresh allocates nothing. The dense Tel Aviv - Lod cluster/// keeps M2's anchor classes. The kits' bounds are read once, when the presenter is created (a later MapScene.Build/// needs a new presenter; GameRoot makes one per Begin).///+ /// Units (issue #197): a pill also keeps clear of the unit tokens (UnitLayer.KeepClear, passed in as keepClear): each+ /// token's boxes (its standing figures, aircraft or ship, and its badge) are projected to one screen rectangle, and a+ /// spot that overlaps one, grown by MarginPx, does not fit, as a spot under a panel does not. A token that stands on a+ /// settlement's kit (its rectangle overlaps the kit's) counts as part of it for the spots: they are placed round the+ /// kit and that token together, so a town's name hangs just above the brigade standing in it rather than beside the+ /// whole town; how far the name is from its own town is still measured from the kit alone. A token is no settlement's marker, so it never hides a marker the way a panel does. The rectangles are+ /// re-read when the camera moves and whenever the layer hands over a new list (the tokens were rebuilt, or the "units"+ /// toggle changed).+ ////// The 1948 localities (MapScene.Localities, owner rulings 2026-10-11) get smaller pills with their 1948 names, placed/// after every game settlement by the same rules and only nearer than LocalityDistanceM (farther out they are skipped/// outright, so the overview pays nothing for them); Hover shows today's name in a tooltip under the pill the pointer@@ -78,7 +89,7 @@ namespace Statecraft.Game.UI{public Settlement Settlement = null!; public Vector3 MarkerTop; public Bounds[] Kit = null!, Marker = null!; public VisualElement Slot = null!;public Label Label = null!; public Spot First; public bool IsCity, IsLocality, TopVisible, KitInFront, ShownLast = true;- public Vector2 TopPanel; public Rect KitPanel, Placed; public string? Tip;+ public Vector2 TopPanel; public Rect KitPanel, Around, Placed; public string? Tip;}readonly VisualElement container;@@ -91,6 +102,9 @@ namespace Statecraft.Game.UIreadonly List<VisualElement> occluders = new List<VisualElement>();readonly List<Rect> occluderRects = new List<Rect>(); // in the layer's coordinatesreadonly List<Rect> placed = new List<Rect>();+ readonly Func<IReadOnlyList<Bounds[]>?>? keepClear; // the unit tokens' world boxes (UnitLayer.KeepClear), or none+ readonly List<Rect> keepClearRects = new List<Rect>(); // their screen rectangles, in the layer's coordinates+ IReadOnlyList<Bounds[]>? lastKeepClear;Rect layerRect; // the panel in the layer's coordinates: a pill stays inside itreadonly EventCallback<GeometryChangedEvent> onOccluderGeometry, onContainerGeometry;Matrix4x4 lastViewProjection; Rect lastCameraRect; Vector2 lastPanelSize, lastOrigin; float lastZoom = float.NaN;@@ -125,9 +139,11 @@ namespace Statecraft.Game.UIreturn lines.Count == 0 ? null : string.Join("\n", lines);}- public MapLabelsPresenter(VisualElement root, MapScene map, Camera camera, Func<float>? zoomDistance = null, Func<Statecraft.Game.Map.Kits.Localities.Place, string?>? tipText = null)+ public MapLabelsPresenter(VisualElement root, MapScene map, Camera camera, Func<float>? zoomDistance = null, Func<Statecraft.Game.Map.Kits.Localities.Place, string?>? tipText = null,+ Func<IReadOnlyList<Bounds[]>?>? keepClear = null){var tip = tipText ?? DefaultTip;+ this.keepClear = keepClear;container = root.Q<VisualElement>(ContainerName) ?? throw new InvalidOperationException($"Game.uxml has no '{ContainerName}' element");this.camera = camera;this.map = map;@@ -285,13 +301,16 @@ namespace Statecraft.Game.UIint 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)+ var tokens = keepClear?.Invoke();for (int i = 0; i < items.Count; i++){if (items[i].IsLocality && !localities) continue;var st = items[i].Label.resolvedStyle; if (!float.IsNaN(st.width) && !float.IsNaN(st.height)) labelSizes += st.width + st.height;}if (!force && sizesKnown && !geometryDirty && labelSizes == lastLabelSizes && viewProjection == lastViewProjection && cameraRect == lastCameraRect- && screen == lastPanelSize && origin == lastOrigin && distance == lastZoom && mask == lastOccluderMask && kitsShown == lastKitsShown) return;+ && screen == lastPanelSize && origin == lastOrigin && distance == lastZoom && mask == lastOccluderMask && kitsShown == lastKitsShown+ && tokens == lastKeepClear) return;+ lastKeepClear = tokens;lastViewProjection = viewProjection; lastCameraRect = cameraRect; lastPanelSize = screen; lastOrigin = origin;lastZoom = distance; lastOccluderMask = mask; lastKitsShown = kitsShown; lastLabelSizes = labelSizes; geometryDirty = false;sizesKnown = true;@@ -307,6 +326,10 @@ namespace Statecraft.Game.UIvar b = occluders[i].worldBound;if (!float.IsNaN(b.x) && b.width > 0f) occluderRects.Add(new Rect(b.position - origin, b.size));}+ keepClearRects.Clear();+ if (tokens != null)+ for (int i = 0; i < tokens.Count; i++)+ if (ProjectBoxes(tokens[i], viewProjection, cameraRect, screen, origin, out var r)) keepClearRects.Add(r);for (int i = 0; i < items.Count; i++){@@ -316,6 +339,10 @@ namespace Statecraft.Game.UIit.TopPanel = ToPanel(t, cameraRect, screen, origin);it.TopVisible = t.z > 0f && t.x >= 0f && t.x <= 1f && t.y >= 0f && t.y <= 1f && !UnderAPanel(it.TopPanel); // a marker under a panel is no one's neighbourit.KitInFront = ProjectBoxes(kitsShown ? it.Kit : it.Marker, viewProjection, cameraRect, screen, origin, out it.KitPanel);+ it.Around = it.KitPanel; // the kit, and every token that stands on it: the spots are placed round both+ for (int k = 0; k < keepClearRects.Count; k++)+ if (keepClearRects[k].Overlaps(it.KitPanel)) it.Around = Rect.MinMaxRect(Mathf.Min(it.Around.xMin, keepClearRects[k].xMin),+ Mathf.Min(it.Around.yMin, keepClearRects[k].yMin), Mathf.Max(it.Around.xMax, keepClearRects[k].xMax), Mathf.Max(it.Around.yMax, keepClearRects[k].yMax));}placed.Clear();@@ -338,14 +365,17 @@ namespace Statecraft.Game.UI{float extra = it.ShownLast ? 0f : HysteresisPx;var home = SpotRect(it.First, it.KitPanel, it.TopPanel, size); // where the USS anchor class draws it- bool found = TryPlace(it, size, home, it.First, extra, true, ref shift);+ bool found = TryPlace(it, size, home, it.First, extra, true, true, ref shift);for (int k = 0; !found && k < Fallbacks.Length; k++)- if (Fallbacks[k] != it.First) found = TryPlace(it, size, home, Fallbacks[k], extra, true, ref shift);- if (!found && it.IsCity)+ if (Fallbacks[k] != it.First) found = TryPlace(it, size, home, Fallbacks[k], extra, true, true, ref shift);+ // A city keeps its name (review of #518): next round its kit alone, still reading as its own but+ // over a token if need be; then clear of the tokens but not of its neighbours; last, neither.+ for (int pass = 0; !found && it.IsCity && pass < 3; pass++){- found = TryPlace(it, size, home, it.First, extra, false, ref shift);+ bool neighbours = pass == 0, avoidTokens = pass == 1;+ found = TryPlace(it, size, home, it.First, extra, neighbours, avoidTokens, ref shift);for (int k = 0; !found && k < Fallbacks.Length; k++)- if (Fallbacks[k] != it.First) found = TryPlace(it, size, home, Fallbacks[k], extra, false, ref shift);+ if (Fallbacks[k] != it.First) found = TryPlace(it, size, home, Fallbacks[k], extra, neighbours, avoidTokens, ref shift);}shown = found;}@@ -357,19 +387,21 @@ namespace Statecraft.Game.UI}/// <summary>Whether the pill fits at <paramref name="spot"/>; if so records it as placed and sets the shift from- /// its USS anchor's rectangle <paramref name="home"/>.</summary>- bool TryPlace(Item it, Vector2 size, Rect home, Spot spot, float extra, bool clearOfNeighbours, ref Vector2 shift)+ /// its USS anchor's rectangle <paramref name="home"/>. With <paramref name="clearOfTokens"/> the spot is placed+ /// round the kit and the tokens on it and keeps clear of every token; without, round the kit alone.</summary>+ bool TryPlace(Item it, Vector2 size, Rect home, Spot spot, float extra, bool clearOfNeighbours, bool clearOfTokens, ref Vector2 shift){- var r = SpotRect(spot, it.KitPanel, it.TopPanel, size);+ var r = SpotRect(spot, clearOfTokens ? it.Around : it.KitPanel, it.TopPanel, size);float m = MarginPx + extra;var grown = new Rect(r.x - m, r.y - m, r.width + 2f * m, r.height + 2f * m);if (r.xMin < layerRect.xMin || r.yMin < layerRect.yMin || r.xMax > layerRect.xMax || r.yMax > layerRect.yMax) return false;for (int i = 0; i < occluderRects.Count; i++) if (occluderRects[i].Overlaps(r)) return false;+ if (clearOfTokens) for (int i = 0; i < keepClearRects.Count; i++) if (keepClearRects[i].Overlaps(grown)) return false;for (int i = 0; i < placed.Count; i++) if (placed[i].Overlaps(grown)) return false;if (Cover(r, it.KitPanel) > MaxKitCover) return false;if (clearOfNeighbours){- float need = 2f * Gap(r, it.KitPanel) + MarginPx + extra;+ float need = 2f * Gap(r, it.KitPanel) + MarginPx + extra; // owned by the town itself, never by the tokens on itfor (int i = 0; i < items.Count; i++){var other = items[i];diff --git a/unity/Assets/Tests/EditMode/MapLabelTests.cs b/unity/Assets/Tests/EditMode/MapLabelTests.csindex 76966c041..15188aadf 100644--- a/unity/Assets/Tests/EditMode/MapLabelTests.cs+++ b/unity/Assets/Tests/EditMode/MapLabelTests.cs@@ -505,8 +505,101 @@ public class MapLabelTestsfinally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }}+ /// <summary>Issue #197 (audit 2026-10-13, webunits-gameplay03): in normal play at the gameplay03 pose (its yaw, with+ /// the game's top-bar inset) the Tel Aviv pill keeps clear of the Kiryati Brigade standing in Tel Aviv: it overlaps+ /// neither the brigade's badge nor its figures, and it still hangs above the town (over its kit's width, not beside+ /// it); no shown pill overlaps any token's badge. The rectangles are measured+ /// independently of the presenter: the badge plate's corners as it faces the camera, the figures' renderer bounds,+ /// both through the camera's pixels.</summary>+ [UnityTest]+ public IEnumerator PillsKeepClearOfTheUnitTokens()+ {+ var layer = StartUnits();+ HdPanel hd = new HdPanel(cam); // typed, not var: the local functions below capture it+ var labels = new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => layer.KeepClear);+ var inset = new TopBarInset(hd.Root, rig);+ try+ {+ var pose = PromoPose.Gameplay03;+ rig.LookAt = map.Frame.ToWorld(pose.Lon, pose.Lat, 0); rig.Distance = pose.Distance; rig.Yaw = pose.Yaw; rig.Apply();+ yield return null;+ inset.Update();+ yield return Settle(labels);+ var tokens = GameObject.Find(Statecraft.Game.Map.Units.UnitLayer.RootName).transform.Find("Tokens");+ Rect Hull(System.Collections.Generic.IEnumerable<Vector3> points)+ {+ float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;+ foreach (var w in points)+ {+ var p = hd.ToPanel(w, out bool inFront); Assert.IsTrue(inFront);+ x0 = Mathf.Min(x0, p.x); y0 = Mathf.Min(y0, p.y); x1 = Mathf.Max(x1, p.x); y1 = Mathf.Max(y1, p.y);+ }+ return Rect.MinMaxRect(x0, y0, x1, y1);+ }+ Rect BadgeRect(Transform token)+ {+ var badge = token.Find("Badge"); var turn = cam.transform.rotation; // the plate faces the camera as it renders+ float half = Statecraft.Game.Map.Units.UnitBadge.SizeM / 2f;+ return Hull(new[] { new Vector3(-half, -half, 0), new Vector3(half, -half, 0), new Vector3(-half, half, 0), new Vector3(half, half, 0) }+ .Select(c => badge.position + turn * c));+ }+ Rect FiguresRect(Transform token) => Hull(token.GetComponentsInChildren<Renderer>().Where(r => r.name.StartsWith("Rifleman"))+ .SelectMany(r => { var b = r.bounds; return Enumerable.Range(0, 8).Select(c => new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z)); }));++ var kiryati = layer.Tokens.Single(t => t.Token.Unit.Id == "kiryati");+ Assert.AreEqual("Tel Aviv", kiryati.Token.Anchor.Place, "the brigade stands in Tel Aviv on the first turn");+ var token = tokens.Find("kiryati");+ Rect badgeRect = BadgeRect(token), figuresRect = FiguresRect(token);+ var tlv = labels.Slots.Single(s => s.name == "slot-tel_aviv");+ Assert.IsTrue(Shown(tlv), "Tel Aviv is named at gameplay03");+ var pill = tlv.Q<Label>().worldBound;+ TestContext.WriteLine($"gameplay03: Tel Aviv pill {pill}, Kiryati badge {badgeRect}, figures {figuresRect}");+ Assert.IsFalse(pill.Overlaps(badgeRect), $"the Tel Aviv pill {pill} overlaps the Kiryati badge {badgeRect}");+ Assert.IsFalse(pill.Overlaps(figuresRect), $"the Tel Aviv pill {pill} overlaps the Kiryati figures {figuresRect}");+ var kit = KitRectOf(hd, "tel_aviv");+ Assert.LessOrEqual(pill.yMax, kit.yMin + 1f, $"the pill {pill} still hangs above Tel Aviv's kit {kit}");+ Assert.IsTrue(pill.center.x >= kit.xMin && pill.center.x <= kit.xMax, $"over the town, not beside it: pill {pill}, kit {kit}");+ var badges = layer.Tokens.Select(t => (id: t.Token.Unit.Id, rect: BadgeRect(tokens.Find(t.Token.Unit.Id)))).ToList();+ foreach (var slot in labels.Slots.Concat(labels.LocalitySlots).Where(Shown))+ foreach (var (id, rect) in badges)+ Assert.IsFalse(slot.Q<Label>().worldBound.Overlaps(rect), $"{slot.name} {slot.Q<Label>().worldBound} overlaps {id}'s badge {rect}");++ // The units off: with no camera move, the plain refresh re-places Tel Aviv's pill at its home above the kit.+ VisualToggles.Set(Statecraft.Game.Map.Units.UnitLayer.ToggleName, false);+ Assert.AreEqual(0, layer.KeepClear.Count, "a hidden layer asks no pill to keep clear");+ labels.Refresh(); yield return null;+ var home = tlv.Q<Label>().worldBound;+ TestContext.WriteLine($"units off: Tel Aviv pill {home}, kit {kit}");+ Assert.Greater(home.yMax, pill.yMax + 20f, $"the pill {home} came back down from {pill}");+ Assert.That(kit.yMin - home.yMax, Is.InRange(MapLabelsPresenter.LiftPx - 1f, 30f), $"back just above its kit: pill {home}, kit {kit}");+ // And on again: it goes back above the brigade.+ VisualToggles.Set(Statecraft.Game.Map.Units.UnitLayer.ToggleName, true);+ labels.Refresh(); yield return null;+ Assert.AreEqual(pill.yMax, tlv.Q<Label>().worldBound.yMax, 0.5f, "the units on again: above the brigade again");+ }+ finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }+ }+static readonly string[] Occluders = { "top-bar", "info-panel", "minimap" };+ /// <summary>The units in play as a new game starts (golden seed, historical mode), as the game draws them.</summary>+ Statecraft.Game.Map.Units.UnitLayer StartUnits()+ {+ var content = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content);+ var units = Statecraft.Game.Map.Units.UnitData.Parse(File.ReadAllText(Path.Combine(Statecraft.Game.Paths.Content, "map", Statecraft.Game.Map.Units.UnitData.DefaultFileName)));+ var layer = Statecraft.Game.Map.Units.UnitLayer.Create(map, units, content.Hexes, still: true);+ layer.Show(content, Statecraft.Sim.Simulation.NewGame(content, Statecraft.Sim.GoldenRun.Seed, Statecraft.Sim.Mode.Historical));+ return layer;+ }++ /// <summary>The presenter, keeping clear of the units in play as the game does (GameRoot), or without them.</summary>+ MapLabelsPresenter Labels(HdPanel hd, bool units)+ {+ if (!units) return new MapLabelsPresenter(hd.Root, map, cam);+ var layer = StartUnits();+ return new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => layer.KeepClear);+ }+/// <summary>Marker tops on screen and not under a panel, in panel coordinates (independent of the presenter).</summary>static System.Collections.Generic.Dictionary<string, Vector2> VisibleMarkerTops(HdPanel hd, MapScene map){@@ -529,10 +622,17 @@ public class MapLabelTests/// (well apart from any other marker), with a lower bound on the count; and at the overview a coastal town between/// Haifa and Tel Aviv is labelled. The full shown set is logged, for a new baseline.</summary>[UnityTest]- public IEnumerator ShownPillsNeverOverlapAndEachReadsAsItsOwn()+ public IEnumerator ShownPillsNeverOverlapAndEachReadsAsItsOwn() => NeverOverlapAndOwn(false);++ /// <summary>The same with the units in play on the map (review of #518): the tokens move pills, and a city with tokens+ /// on it (Tel Aviv, Jerusalem) keeps its name; each pill still reads as its own town's, measured from the kit.</summary>+ [UnityTest]+ public IEnumerator ShownPillsNeverOverlapAndEachReadsAsItsOwnWithTheUnits() => NeverOverlapAndOwn(true);++ IEnumerator NeverOverlapAndOwn(bool units){var hd = new HdPanel(cam);- var labels = new MapLabelsPresenter(hd.Root, map, cam);+ var labels = Labels(hd, units);try{foreach (var (name, lon, lat, distance, pinned, atLeast) in new[]@@ -675,10 +775,16 @@ public class MapLabelTests/// a new view, after one sweep that lets the presenter's lists reach their size). Counted by the profiler, so it does/// not depend on the machine's load (#322).</summary>[UnityTest]- public IEnumerator RefreshWhileTheCameraMovesAllocatesNothing()+ public IEnumerator RefreshWhileTheCameraMovesAllocatesNothing() => AllocatesNothing(false);++ /// <summary>The same with the unit tokens to keep clear of (the game's path).</summary>+ [UnityTest]+ public IEnumerator RefreshWhileTheCameraMovesAllocatesNothingWithTheUnits() => AllocatesNothing(true);++ IEnumerator AllocatesNothing(bool units){var hd = new HdPanel(cam);- var labels = new MapLabelsPresenter(hd.Root, map, cam);+ var labels = Labels(hd, units);try{yield return Settle(labels);@@ -735,4 +841,46 @@ public class MapLabelTests}finally { labels.Dispose(); hd.Dispose(); }}++ /// <summary>Keeping clear of the unit tokens (#197) costs little next to placing the pills: one presenter, whose+ /// keep-clear list is switched between the units in play and none, runs interleaved sweeps (off, on, off, on, ...) of+ /// 240 refreshes along the same camera path; the median refresh with the units is at most 1.25 times the median without,+ /// both taken from the same run, so the machine's load cancels out (the absolute bound stays on the test above).</summary>+ [UnityTest]+ public IEnumerator KeepingClearOfTheUnitsIsCheap()+ {+ const int Pairs = 5, Steps = 240;+ const double MaxRatio = 1.25;+ var layer = StartUnits();+ bool on = false;+ var hd = new HdPanel(cam);+ var labels = new MapLabelsPresenter(hd.Root, map, cam, keepClear: () => on ? layer.KeepClear : System.Array.Empty<Bounds[]>());+ try+ {+ yield return Settle(labels);+ var times = new double[Steps];+ var off = new System.Collections.Generic.List<double>(); var with = new System.Collections.Generic.List<double>();+ var watch = new System.Diagnostics.Stopwatch();+ for (int s = 0; s < 2 * Pairs; s++)+ {+ on = s % 2 == 1;+ for (int i = 0; i < Steps; i++)+ {+ SweepStep(i);+ watch.Restart(); labels.Refresh(); watch.Stop();+ times[i] = watch.Elapsed.TotalMilliseconds * 1000.0;+ }+ System.Array.Sort(times);+ (on ? with : off).Add((times[Steps / 2 - 1] + times[Steps / 2]) / 2.0);+ }+ Assert.Greater(layer.KeepClear.Count, 0, "the units were on the map");+ double Median(System.Collections.Generic.List<double> xs) { xs.Sort(); return xs.Count % 2 == 1 ? xs[xs.Count / 2] : (xs[xs.Count / 2 - 1] + xs[xs.Count / 2]) / 2.0; }+ double mOff = Median(off), mOn = Median(with);+ var inv = System.Globalization.CultureInfo.InvariantCulture;+ TestContext.WriteLine(System.FormattableString.Invariant(+ $"LABELS keep-clear cost off_us={mOff:0} on_us={mOn:0} ratio={mOn / mOff:0.00} off={string.Join(",", off.Select(m => m.ToString("0", inv)))} on={string.Join(",", with.Select(m => m.ToString("0", inv)))}"));+ Assert.LessOrEqual(mOn, MaxRatio * mOff, $"keeping clear of the units: {mOn:0} us against {mOff:0} us without them");+ }+ finally { labels.Dispose(); hd.Dispose(); }+ }}diff --git a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs b/unity/Assets/Tests/EditMode/UnitsInPlayTests.csindex 393cfc40b..35972919c 100644--- a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs+++ b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs@@ -393,6 +393,42 @@ public class UnitsInPlayTestsAssert.LessOrEqual(y - H(1000f, 2000f), Mathf.Sqrt(slope * slope + 0.04f) * r / Mathf.Cos(Mathf.PI / 16f) + 0.01f, "the float is bounded by the slope over the foot");}+ /// <summary>Review of #518: the tokens' keep-clear boxes (what the map's names keep clear of) are right even when the+ /// tokens are built while the "units" toggle hides the layer, as a ?shot run without &units does before the first+ /// Show: once the layer is shown again, each token's pieces box is the hull of its drawn pieces (Renderer.bounds, now+ /// that they are active), not a box stretched to the world origin; and a hidden layer hands out no boxes.</summary>+ [Test]+ public void KeepClearBoxesBuiltWhileTheLayerIsHiddenHoldTheirToken()+ {+ var map = BuildMap();+ try+ {+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ VisualToggles.Set(UnitLayer.ToggleName, false);+ layer.Show(C, Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical)); // built inactive+ Assert.AreEqual(0, layer.KeepClear.Count, "a hidden layer hands out no boxes");+ VisualToggles.Set(UnitLayer.ToggleName, true);+ Assert.AreEqual(layer.Tokens.Count, layer.KeepClear.Count, "one entry per token");+ var tokens = map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens");+ int pieces = 0;+ for (int i = 0; i < layer.Tokens.Count; i++)+ {+ var token = tokens.Find(layer.Tokens[i].Token.Unit.Id);+ var drawn = token.GetComponentsInChildren<Renderer>().Where(r => r.GetComponentInParent<UnitBadge>() == null && r.GetComponentInParent<ShowcaseFlight>() == null).ToList();+ var boxes = layer.KeepClear[i];+ if (drawn.Count == 0) { Assert.AreEqual(1, boxes.Length, $"{token.name}: only its badge"); continue; }+ Assert.AreEqual(2, boxes.Length, $"{token.name}: its badge and its pieces");+ var hull = drawn[0].bounds; foreach (var r in drawn) hull.Encapsulate(r.bounds);+ Assert.AreEqual(hull.min.x, boxes[1].min.x, 1f, token.name); Assert.AreEqual(hull.max.x, boxes[1].max.x, 1f, token.name);+ Assert.AreEqual(hull.min.y, boxes[1].min.y, 1f, token.name); Assert.AreEqual(hull.max.y, boxes[1].max.y, 1f, token.name);+ Assert.AreEqual(hull.min.z, boxes[1].min.z, 1f, token.name); Assert.AreEqual(hull.max.z, boxes[1].max.z, 1f, token.name);+ pieces++;+ }+ Assert.Greater(pieces, 5, "brigades and ships were checked");+ }+ finally { if (VisualToggles.Names.Contains(UnitLayer.ToggleName)) VisualToggles.Set(UnitLayer.ToggleName, true); UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }+/// <summary>The same on the map's real hills: every rifleman of every army anchor of the war stands no lower than the/// ground anywhere under its boots.</summary>[Test]