Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

fix(ui): map labels avoid panels, try other anchors before hiding, refresh without allocating; ?vprofile&vmoving prices them under motion

eyalgolan9dcf5d6434ad
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 04d729210..7f2e2563b 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -95,8 +95,36 @@ Deviations from the plan text, each forced by a test:
avoid a neighbour's marker with any anchor (Rishon LeZion's pill ended 10 px under Jaffa's marker). A pill other than
a city's is now also hidden when it comes within `NeighbourClearPx` (2 x LiftPx + MarginPx = 16 px) of another
settlement's marker top. At 90 km this hides nothing (11 of 25 shown, as before); at the overview 10 of 25 are shown.
-- City pills: 20 px text and 8 px side padding (plan: 22 px and 10 px), so Tel Aviv's centred pill ends clear of Petah
- Tikva's marker at the overview.
+- City pills: 20 px text and 8 px side padding at first. Fix round 1 restores the plan's 22 px and 10 px (see below).
- `ThePillIsEbGaramondOnNavyWithAGoldEdgeAndHiddenWhileLoading` uses a 1920x1080 panel instead of `UiTestKit`'s: the
batch-mode screen gives that panel about 0.39 px per point, and UI Toolkit rounds the 1 px border up to one physical
pixel (2.57 points).
+
+### Task 9 fix round 1 (review I1-I5, M1-M7)
+
+- Panels: pills are culled against the cached rects of the top bar, the info panel, the minimap and the event card,
+ marked dirty by GeometryChangedEvent; a pill must lie wholly on screen, and a marker under a panel is no one's
+ neighbour. A container resize re-places the pills before the repaint (M4).
+- Anchors: the USS anchor class is tried first, then lower right, lower left, lower centre and centred below the marker,
+ as a pixel shift on the slot's translate. The legibility rule (more than 2 x own gap + MarginPx from every other
+ visible marker top) applies to every pill; a city whose anchors all crowd a neighbour keeps the first that is clear of
+ panels and pills. A pill hidden in the last refresh needs HysteresisPx = 2 more (M7).
+- Shown sets (MapLabelTests): 90 km: tel_aviv jaffa lod ramla petah_tikva rishon_lezion rehovot netanya (every visible
+ marker); overview: jerusalem tel_aviv lod gaza beersheba petah_tikva netanya; diorama02 with the top-bar inset also
+ labels Hadera (checkpoint).
+- City pills are back to the plan's 22 px and 10 px padding (towns 19 px), so cities read larger (M5). At the
+ overview Tel Aviv's pill takes the lower-right anchor, over the sea.
+- Refresh allocates nothing (`Is.Not.AllocatingGCMemory`). Editor Mono, 240 refreshes while turning and zooming:
+ `LABELS refresh moving avg_us=27 p95_us=38`.
+- `?vprofile&vmoving` (FrameProfile, additive): every run restarts at its pose and turns 0.5 degrees per frame.
+ Headless, DPR 1, `res=1920x1080 scale=0.80`:
+
+| Pose | all | -labels | none | all - (-labels) | budget |
+|---|---|---|---|---|---|
+| gameplay03-moving | 2.24 (spread 0.65) | 2.28 (0.78) | 2.44 (0.63) | -0.04 ms | <= 1 + 0.78 ms: within |
+| diorama02-moving | 10.21 (0.10) | 10.20 (0.16) | 10.10 (0.34) | +0.01 ms | <= 1 + 0.16 ms: within |
+| gameplay03 (still) | 2.47 (0.51) | 2.44 (0.04) | 2.35 (0.34) | +0.03 ms | within |
+| diorama02 (still) | 6.76 (0.38) | 6.53 (0.29) | 6.58 (0.41) | +0.23 ms | within |
+
+ diorama02 costs about 3.4 ms more while turning than still, with or without labels (the rest of the scene).
+
diff --git a/unity/Assets/Scripts/Map/FrameProfile.cs b/unity/Assets/Scripts/Map/FrameProfile.cs
index f319c032b..d79e6e6d5 100644
--- a/unity/Assets/Scripts/Map/FrameProfile.cs
+++ b/unity/Assets/Scripts/Map/FrameProfile.cs
@@ -21,6 +21,8 @@ namespace Statecraft.Game.Map
public static class FrameProfile
{
public const int WarmupFrames = 60, MeasuredFrames = 300, Repeats = 3;
+ /// <summary>The moving variant's turn (degrees of yaw per frame, about the look-at point).</summary>
+ public const float MovingDegreesPerFrame = 0.5f;
public static bool Requested() =>
Requested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
@@ -28,6 +30,16 @@ namespace Statecraft.Game.Map
public static bool Requested(string? url, string[] args, bool webgl) =>
webgl ? UrlFlags.Has(url, "vprofile") : args.Contains("-vprofile");
+ /// <summary>The moving variant ("vmoving" with "vprofile" in the WebGL URL, or -vmoving on desktop; Task 9 fix round 1):
+ /// every run restarts from its pose and turns the camera MovingDegreesPerFrame each frame, warm-up and measured
+ /// frames alike, so features that work only when the view changes (the map labels' placement) are priced too. Its
+ /// lines carry the pose name with "-moving".</summary>
+ public static bool MovingRequested() =>
+ MovingRequested(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
+
+ public static bool MovingRequested(string? url, string[] args, bool webgl) =>
+ webgl ? UrlFlags.Has(url, "vmoving") : args.Contains("-vmoving");
+
public static string Line(string label, string pose, string resolution, float renderScale, int rep, IReadOnlyList<float> frameMs)
{
var (avg, p95) = FrameStats.Summary(frameMs);
@@ -59,7 +71,10 @@ namespace Statecraft.Game.Map
}
}
- public static IEnumerator Run(CameraRig rig, GeoFrame frame, Action<string> log, bool quitWhenDone)
+ public static IEnumerator Run(CameraRig rig, GeoFrame frame, Action<string> log, bool quitWhenDone) =>
+ Run(rig, frame, log, quitWhenDone, MovingRequested());
+
+ public static IEnumerator Run(CameraRig rig, GeoFrame frame, Action<string> log, bool quitWhenDone, bool moving)
{
var configs = new List<(string label, string? off)> { ("all", null) };
foreach (var name in VisualToggles.Names) configs.Add(("-" + name, name));
@@ -80,6 +95,7 @@ namespace Statecraft.Game.Map
for (int f = 0; f < WarmupFrames; f++) yield return null;
}
}
+ var poseName = moving ? pose.Name + "-moving" : pose.Name;
var results = configs.ToDictionary(c => c.label, c => new List<(float avg, float p95)>());
for (int rep = 0; rep < Repeats; rep++)
foreach (var i in Order(configs.Count, rep))
@@ -87,18 +103,22 @@ namespace Statecraft.Game.Map
var (label, off) = configs[i];
VisualToggles.SetAll(off != "*");
if (off != null && off != "*") VisualToggles.Set(off, false);
- for (int f = 0; f < WarmupFrames; f++) yield return null;
+ if (moving) pose.Apply(rig, frame); // every run follows the same path
+ for (int f = 0; f < WarmupFrames; f++) { if (moving) Turn(rig); yield return null; }
var times = new List<float>(MeasuredFrames);
- for (int f = 0; f < MeasuredFrames; f++) { yield return null; times.Add(Time.unscaledDeltaTime * 1000f); }
+ for (int f = 0; f < MeasuredFrames; f++) { if (moving) Turn(rig); yield return null; times.Add(Time.unscaledDeltaTime * 1000f); }
var scale = UniversalRenderPipeline.asset != null ? UniversalRenderPipeline.asset.renderScale : 1f;
- log(Line(label, pose.Name, $"{Screen.width}x{Screen.height}", scale, rep, times));
+ log(Line(label, poseName, $"{Screen.width}x{Screen.height}", scale, rep, times));
results[label].Add(FrameStats.Summary(times));
}
- foreach (var (label, _) in configs) log(Summary(label, pose.Name, results[label]));
+ foreach (var (label, _) in configs) log(Summary(label, poseName, results[label]));
+ if (moving) pose.Apply(rig, frame);
}
VisualToggles.SetAll(true);
log("PROFILE visual done");
if (quitWhenDone) Application.Quit(0);
}
+
+ static void Turn(CameraRig rig) { rig.Yaw += MovingDegreesPerFrame; rig.Apply(); }
}
}
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 003e4548f..897d797e9 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -163,7 +163,7 @@ namespace Statecraft.Game.UI
Own(new TopBarInset(root, camRig)); // the map is framed below the top bar
var mini = minimap = Own(new MinimapPresenter(root, map.Hexes));
labels = Own(new MapLabelsPresenter(root, map, cameraController.GetComponent<Camera>()));
- mini.Clicked += (lon, lat) => { camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); camRig.Apply(); SyncMinimap(); };
+ mini.Clicked += (lon, lat) => { camRig.LookAt = map.Frame.ToWorld(lon, lat, 0); camRig.Apply(); SyncMinimap(); labels?.Refresh(); }; // the click may come after LateUpdate (review M6)
Action onChanged = RenderPlacementsIfChanged;
bridge.Changed += onChanged;
// One console line per turn, so a browser run (reload, Continue) can be checked against the hash.
diff --git a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs b/unity/Assets/Scripts/UI/MapLabelsPresenter.cs
index 743663a1f..e1604d28c 100644
--- a/unity/Assets/Scripts/UI/MapLabelsPresenter.cs
+++ b/unity/Assets/Scripts/UI/MapLabelsPresenter.cs
@@ -1,7 +1,6 @@
#nullable enable
using System;
using System.Collections.Generic;
-using System.Linq;
using Statecraft.Game.Map;
using UnityEngine;
using UnityEngine.UIElements;
@@ -11,42 +10,62 @@ namespace Statecraft.Game.UI
/// <summary>Settlement names as UI Toolkit pills (EB Garamond SemiBold on navy with a gold edge, Statecraft.uss
/// ".map-label") in the click-through "map-labels" layer under the panels. Each pill sits in a zero-size absolute slot;
/// Refresh (GameRoot.LateUpdate, after the camera has moved) moves each slot with an inline pixel translate to its
- /// marker's top as the camera sees it, LiftPx above it, so no layout pass runs per frame, and returns early when the
- /// camera's view-projection, the panel size and the zoom are unchanged. Pills are placed in priority order (city, then
- /// town and Arab town, then the rest, each in file order); a pill behind the camera or off screen, a minor place
- /// (village, kibbutz, moshav) beyond DeclutterDistanceM, or a pill that would overlap an already placed one (its last
- /// laid-out size plus MarginPx) is hidden with visibility, so it keeps its size and the choice does not flicker. A pill
- /// other than a city's is also hidden when it would come within NeighbourClearPx of another settlement's marker top, so
- /// no shown name reads as a neighbour's (the dense Tel Aviv - Lod cluster at the overview); cities always keep theirs.
- /// Screen-space, so the tilt-shift never blurs them. The dense Tel Aviv - Lod cluster keeps M2's anchors and Ramla's
- /// nudge west. The anchors are read once, when the presenter is created (a later MapScene.Build needs a new presenter;
- /// GameRoot makes one per Begin).</summary>
+ /// marker's top as the camera sees it, LiftPx above it, so no layout pass runs per frame, and returns early when
+ /// nothing it reads has changed (the camera's view-projection and rect, the panel's size, the layer's origin, the zoom,
+ /// which panels are shown, and no GeometryChangedEvent since). The mapping assumes the camera's view fills the panel,
+ /// as it does in the game (both span the canvas), so DPR, render scale and the panel's scale cancel out.
+ ///
+ /// Declutter: pills are placed in priority order (city, then town and Arab town, then the rest, each in file order). A
+ /// pill is hidden (visibility, so it keeps its size and the choice does not flicker) when its marker is behind the
+ /// camera, off screen or under a panel (the top bar, the info panel, the minimap, the event card), when it is a minor
+ /// place (village, kibbutz, moshav) beyond DeclutterDistanceM, or when no anchor fits. Its anchor class (USS) is tried
+ /// first, then the others (lower right, lower left, lower centre, then centred below the marker), applied as a pixel
+ /// shift on the slot's translate (no class change, so no style pass). An anchor fits when the pill lies wholly on
+ /// screen and clear of every panel, does not overlap an already placed pill (its last laid-out size plus MarginPx), and is more than twice
+ /// as far from every other visible marker's top as from its own, plus MarginPx, so no name reads as a neighbour's. A
+ /// city whose anchors all crowd a neighbour keeps the first that is clear of panels and pills. 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 and Ramla's nudge west. The anchors are read
+ /// once, when the presenter is created (a later MapScene.Build needs a new presenter; GameRoot makes one per Begin).</summary>
public sealed class MapLabelsPresenter : IDisposable
{
public const string ContainerName = "map-labels", SlotClass = "map-label-slot", LabelClass = "map-label";
public const float LiftPx = 6f, MarginPx = 4f, DeclutterDistanceM = 150000f;
- /// <summary>A pill's least gap to any other marker's top: twice its own gap (LiftPx) plus MarginPx.</summary>
- public const float NeighbourClearPx = 2f * LiftPx + MarginPx;
+ /// <summary>Extra room a pill hidden in the last refresh needs before it is shown again (review M7).</summary>
+ public const float HysteresisPx = 2f;
+ /// <summary>The panels a pill never sits under (Game.uxml names).</summary>
+ public static readonly string[] OccluderNames = { "top-bar", "info-panel", "minimap", "event-card" };
+ const string Centre = "anchor-lower-centre", Left = "anchor-lower-left", Right = "anchor-lower-right", Below = "below";
+ static readonly string[] Fallbacks = { Right, Left, Centre, Below };
static readonly HashSet<string> MinorTypes = new HashSet<string> { "village", "kibbutz", "moshav" };
static readonly Dictionary<string, string> AnchorClass = new Dictionary<string, string>
{
- ["jaffa"] = "anchor-lower-right", ["rishon_lezion"] = "anchor-lower-right", ["lod"] = "anchor-lower-left",
- ["petah_tikva"] = "anchor-lower-left", ["safed"] = "anchor-lower-right", ["rosh_pinna"] = "anchor-lower-left",
+ ["jaffa"] = Right, ["rishon_lezion"] = Right, ["lod"] = Left,
+ ["petah_tikva"] = Left, ["safed"] = Right, ["rosh_pinna"] = Left,
};
static readonly Dictionary<string, float> OffsetEastM = new Dictionary<string, float> { ["ramla"] = -1500f };
sealed class Item
{
- public Settlement Settlement = null!; public Vector3 Anchor, MarkerTop; public VisualElement Slot = null!; public Label Label = null!;
- public string AnchorClass = ""; public bool TopOnScreen; public Vector2 TopPanel;
+ public Settlement Settlement = null!; public Vector3 Anchor, MarkerTop, MarkerBase; public VisualElement Slot = null!;
+ public Label Label = null!; public string AnchorClass = ""; public bool IsCity, TopVisible, AnchorInFront, ShownLast = true;
+ public Vector2 TopPanel, AnchorPanel, BasePanel;
}
readonly VisualElement container;
readonly Camera camera;
- readonly Func<float> zoom;
- readonly List<Item> items = new List<Item>(); // in placing (priority) order
- Matrix4x4 lastViewProjection; Vector2 lastPanelSize; float lastZoom = float.NaN; bool sizesKnown;
+ readonly CameraRig? rig;
+ readonly Func<float>? zoomDistance;
+ readonly List<Item> items = new List<Item>(); // in placing (priority) order
+ readonly List<Item> settlementOrder = new List<Item>();
+ readonly List<VisualElement> occluders = new List<VisualElement>();
+ readonly List<Rect> occluderRects = new List<Rect>(); // in the layer's coordinates
+ readonly List<Rect> placed = new List<Rect>();
+ Rect layerRect; // the panel in the layer's coordinates: a pill stays inside it
+ readonly EventCallback<GeometryChangedEvent> onOccluderGeometry, onContainerGeometry;
+ Matrix4x4 lastViewProjection; Rect lastCameraRect; Vector2 lastPanelSize, lastOrigin; float lastZoom = float.NaN;
+ int lastOccluderMask = -1; bool sizesKnown, geometryDirty = true;
public IReadOnlyList<Label> Labels { get; }
public IReadOnlyList<VisualElement> Slots { get; }
@@ -55,14 +74,15 @@ namespace Statecraft.Game.UI
{
container = root.Q<VisualElement>(ContainerName) ?? throw new InvalidOperationException($"Game.uxml has no '{ContainerName}' element");
this.camera = camera;
- zoom = zoomDistance ?? (() => camera.TryGetComponent(out CameraRig rig) ? rig.Distance : 0f);
- container.Clear();
+ this.zoomDistance = zoomDistance;
+ rig = camera.TryGetComponent(out CameraRig r) ? r : null;
+ container.Clear(); // one layer, one owner: the newest presenter (GameRoot makes one per Begin)
var labels = new List<Label>(); var slots = new List<VisualElement>();
foreach (var s in map.Settlements)
{
var slot = new VisualElement { name = "slot-" + s.Id, pickingMode = PickingMode.Ignore };
slot.AddToClassList(SlotClass);
- var anchorClass = AnchorClass.TryGetValue(s.Id, out var a) ? a : "anchor-lower-centre";
+ var anchorClass = AnchorClass.TryGetValue(s.Id, out var a) ? a : Centre;
var label = new Label(s.Name) { name = "label-" + s.Id, pickingMode = PickingMode.Ignore };
label.AddToClassList(LabelClass);
label.AddToClassList("map-label-" + s.Type);
@@ -70,15 +90,31 @@ namespace Statecraft.Game.UI
slot.Add(label);
container.Add(slot);
labels.Add(label); slots.Add(slot);
- var anchor = Anchor(map, s); var top = map.Frame.ToWorld(s.Lon, s.Lat, 0); top.y = anchor.y;
- items.Add(new Item { Settlement = s, Anchor = anchor, MarkerTop = top, Slot = slot, Label = label, AnchorClass = anchorClass });
+ var anchor = Anchor(map, s);
+ var top = map.Frame.ToWorld(s.Lon, s.Lat, 0); top.y = anchor.y;
+ settlementOrder.Add(new Item
+ {
+ Settlement = s, Anchor = anchor, MarkerTop = top, MarkerBase = top - Vector3.up * SettlementPlacer.MarkerHeightM(s.Type),
+ Slot = slot, Label = label, AnchorClass = anchorClass, IsCity = s.Type == "city",
+ });
}
// Stable sort: priority, then file order.
- var ordered = items.Select((it, i) => (it, i)).OrderBy(x => Priority(x.it.Settlement.Type)).ThenBy(x => x.i).Select(x => x.it).ToList();
- items.Clear(); items.AddRange(ordered);
+ for (int p = 0; p <= 2; p++)
+ foreach (var it in settlementOrder) if (Priority(it.Settlement.Type) == p) items.Add(it);
Labels = labels; Slots = slots;
- removeToggle?.Invoke();
- removeToggle = VisualToggles.Register("labels", on => container.style.display = on ? DisplayStyle.Flex : DisplayStyle.None);
+
+ onOccluderGeometry = _ => geometryDirty = true;
+ onContainerGeometry = _ => { geometryDirty = true; Refresh(force: true); }; // a resize is placed before the repaint (review M4)
+ foreach (var name in OccluderNames)
+ {
+ var e = root.Q<VisualElement>(name);
+ if (e == null) continue;
+ occluders.Add(e);
+ e.RegisterCallback(onOccluderGeometry);
+ }
+ container.RegisterCallback(onContainerGeometry);
+ // On clears the inline display, so the loading rule (".loading .map-labels") still wins (review M1).
+ removeToggle = VisualToggles.Register("labels", on => container.style.display = on ? new StyleEnum<DisplayStyle>(StyleKeyword.Null) : DisplayStyle.None);
Refresh(force: true);
}
@@ -100,73 +136,152 @@ namespace Statecraft.Game.UI
/// of the pill sits there, USS translate).</summary>
public static Rect PillRect(Vector2 at, Vector2 size, string anchorClass) => anchorClass switch
{
- "anchor-lower-left" => new Rect(at.x, at.y - size.y, size.x, size.y),
- "anchor-lower-right" => new Rect(at.x - size.x, at.y - size.y, size.x, size.y),
+ Left => new Rect(at.x, at.y - size.y, size.x, size.y),
+ Right => new Rect(at.x - size.x, at.y - size.y, size.x, size.y),
_ => new Rect(at.x - size.x / 2f, at.y - size.y, size.x, size.y),
};
+ float Zoom() => zoomDistance != null ? zoomDistance() : rig != null ? rig.Distance : 0f;
+
+ int OccluderMask()
+ {
+ int mask = 0;
+ for (int i = 0; i < occluders.Count; i++)
+ {
+ var s = occluders[i].resolvedStyle;
+ if (s.display != DisplayStyle.None && s.visibility == Visibility.Visible) mask |= 1 << i;
+ }
+ return mask;
+ }
+
public void Refresh(bool force = false)
{
var panel = container.panel;
if (panel == null || camera == null) return;
var viewProjection = camera.projectionMatrix * camera.worldToCameraMatrix;
- var panelSize = container.layout.size;
- float distance = zoom();
- if (!force && sizesKnown && viewProjection == lastViewProjection && panelSize == lastPanelSize && distance == lastZoom) return;
- lastViewProjection = viewProjection; lastPanelSize = panelSize; lastZoom = distance;
+ var cameraRect = camera.rect;
+ var screen = panel.visualTree.layout.size; // the whole panel, which the camera's view fills
+ var origin = container.worldBound.position; // slots translate from the layer's top-left
+ float distance = Zoom();
+ int mask = OccluderMask();
+ if (!force && sizesKnown && !geometryDirty && viewProjection == lastViewProjection && cameraRect == lastCameraRect
+ && screen == lastPanelSize && origin == lastOrigin && distance == lastZoom && mask == lastOccluderMask) return;
+ lastViewProjection = viewProjection; lastCameraRect = cameraRect; lastPanelSize = screen; lastOrigin = origin;
+ lastZoom = distance; lastOccluderMask = mask; geometryDirty = false;
sizesKnown = true;
- var screen = panel.visualTree.layout.size; // the whole panel, which the camera's view fills
- var origin = container.worldBound.position; // slots translate from the layer's top-left
bool laidOut = !(float.IsNaN(screen.x) || screen.x <= 0f || float.IsNaN(origin.x) || float.IsNaN(origin.y));
if (!laidOut) { sizesKnown = false; origin = Vector2.zero; } // before the first layout: cull by view only, place later
- var r0 = camera.rect;
- Vector2 ToPanel(Vector3 v) => new Vector2((r0.x + v.x * r0.width) * screen.x, (1f - (r0.y + v.y * r0.height)) * screen.y) - origin;
- foreach (var it in items)
+
+ layerRect = new Rect(-origin, screen);
+ occluderRects.Clear();
+ if (laidOut)
+ for (int i = 0; i < occluders.Count; i++)
+ if ((mask & (1 << i)) != 0)
+ {
+ var b = occluders[i].worldBound;
+ if (!float.IsNaN(b.x) && b.width > 0f) occluderRects.Add(new Rect(b.position - origin, b.size));
+ }
+
+ for (int i = 0; i < items.Count; i++)
{
+ var it = items[i];
var t = camera.WorldToViewportPoint(it.MarkerTop);
- it.TopOnScreen = t.z > 0f && t.x > -0.05f && t.x < 1.05f && t.y > -0.05f && t.y < 1.05f;
- it.TopPanel = ToPanel(t);
+ it.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 neighbour
+ var v = camera.WorldToViewportPoint(it.Anchor);
+ it.AnchorInFront = OnScreen(v);
+ it.AnchorPanel = ToPanel(v, cameraRect, screen, origin);
+ it.BasePanel = ToPanel(camera.WorldToViewportPoint(it.MarkerBase), cameraRect, screen, origin);
}
- var placed = new List<Rect>();
- foreach (var it in items)
+
+ placed.Clear();
+ for (int i = 0; i < items.Count; i++)
{
- var v = camera.WorldToViewportPoint(it.Anchor);
- bool shown = v.z > 0f && v.x > -0.05f && v.x < 1.05f && v.y > -0.05f && v.y < 1.05f && !HiddenByZoom(it.Settlement.Type, distance);
- var at = Vector2.zero;
+ var it = items[i];
+ bool shown = it.AnchorInFront && it.TopVisible && !HiddenByZoom(it.Settlement.Type, distance);
+ var at = new Vector2(it.AnchorPanel.x, it.AnchorPanel.y - LiftPx);
+ var shift = Vector2.zero;
if (shown)
{
- // Viewport to panel through the camera's own rect, not RuntimePanelUtils.CameraTransformWorldToPanel: that
- // flips y with Screen.height, which is wrong whenever the camera draws to a texture (edit-mode tests,
- // captures) and the screen is a different size.
- at = ToPanel(v);
- at.y -= LiftPx;
var size = new Vector2(it.Label.resolvedStyle.width, it.Label.resolvedStyle.height);
- if (!laidOut || float.IsNaN(size.x) || size.x <= 0f) sizesKnown = false; // not laid out yet: show it, cull on a later refresh
+ if (!laidOut || float.IsNaN(size.x) || size.x <= 0f) sizesKnown = false; // not laid out yet: show it, place on a later refresh
else
{
- var r = PillRect(at, size, it.AnchorClass);
- var grown = new Rect(r.x - MarginPx, r.y - MarginPx, r.width + 2f * MarginPx, r.height + 2f * MarginPx);
- if (placed.Any(p => p.Overlaps(grown)) || it.Settlement.Type != "city" && CrowdsANeighbour(it, r)) shown = false;
- else placed.Add(r);
+ float extra = it.ShownLast ? 0f : HysteresisPx;
+ var home = PillRect(at, size, it.AnchorClass);
+ bool found = TryPlace(it, at, size, home, it.AnchorClass, extra, true, ref shift);
+ for (int k = 0; !found && k < Fallbacks.Length; k++)
+ if (Fallbacks[k] != it.AnchorClass) found = TryPlace(it, at, size, home, Fallbacks[k], extra, true, ref shift);
+ if (!found && it.IsCity)
+ {
+ found = TryPlace(it, at, size, home, it.AnchorClass, extra, false, ref shift);
+ for (int k = 0; !found && k < Fallbacks.Length; k++)
+ if (Fallbacks[k] != it.AnchorClass) found = TryPlace(it, at, size, home, Fallbacks[k], extra, false, ref shift);
+ }
+ shown = found;
}
}
+ it.ShownLast = shown;
it.Slot.style.visibility = shown ? Visibility.Visible : Visibility.Hidden;
- if (shown && laidOut) it.Slot.style.translate = new Translate(at.x, at.y);
+ if (shown && laidOut) it.Slot.style.translate = new Translate(at.x + shift.x, at.y + shift.y);
+ }
+ }
+
+ /// <summary>Whether the pill fits with <paramref name="anchor"/>; 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 at, Vector2 size, Rect home, string anchor, float extra, bool clearOfNeighbours, ref Vector2 shift)
+ {
+ var r = anchor == Below
+ ? new Rect(it.BasePanel.x - size.x / 2f, it.BasePanel.y + LiftPx, size.x, size.y)
+ : PillRect(at, size, anchor);
+ 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;
+ for (int i = 0; i < placed.Count; i++) if (placed[i].Overlaps(grown)) return false;
+ if (clearOfNeighbours)
+ {
+ float need = 2f * Gap(r, it.TopPanel) + MarginPx + extra;
+ for (int i = 0; i < items.Count; i++)
+ {
+ var other = items[i];
+ if (other != it && other.TopVisible && Gap(r, other.TopPanel) <= need) return false;
+ }
}
+ placed.Add(r);
+ shift = r.position - home.position;
+ return true;
}
- bool CrowdsANeighbour(Item it, Rect r)
+ bool UnderAPanel(Vector2 p)
{
- foreach (var other in items)
- if (other != it && other.TopOnScreen && Gap(r, other.TopPanel) <= NeighbourClearPx) return true;
+ for (int i = 0; i < occluderRects.Count; i++) if (occluderRects[i].Contains(p)) return true;
return false;
}
+ static bool OnScreen(Vector3 v) => v.z > 0f && v.x > -0.05f && v.x < 1.05f && v.y > -0.05f && v.y < 1.05f;
+
+ /// <summary>Viewport to the layer's coordinates through the camera's own rect, not
+ /// RuntimePanelUtils.CameraTransformWorldToPanel: that flips y with Screen.height, which is wrong whenever the camera
+ /// draws to a texture of another size (edit-mode tests, captures).</summary>
+ static Vector2 ToPanel(Vector3 v, Rect cameraRect, Vector2 screen, Vector2 origin) =>
+ new Vector2((cameraRect.x + v.x * cameraRect.width) * screen.x, (1f - (cameraRect.y + v.y * cameraRect.height)) * screen.y) - origin;
+
static float Gap(Rect r, Vector2 p) =>
new Vector2(Mathf.Max(0f, Mathf.Max(r.xMin - p.x, p.x - r.xMax)), Mathf.Max(0f, Mathf.Max(r.yMin - p.y, p.y - r.yMax))).magnitude;
Action? removeToggle; // the labels switch's removal token (VisualToggles.Register): a disposed presenter never removes a newer one
- public void Dispose() { removeToggle?.Invoke(); removeToggle = null; container.Clear(); items.Clear(); }
+ /// <summary>Removes only this presenter's own pills and callbacks, so an older presenter disposed after a newer one
+ /// was made leaves the newer one's pills (review M2).</summary>
+ public void Dispose()
+ {
+ removeToggle?.Invoke(); removeToggle = null;
+ foreach (var e in occluders) e.UnregisterCallback(onOccluderGeometry);
+ container.UnregisterCallback(onContainerGeometry);
+ occluders.Clear();
+ foreach (var slot in Slots) slot.RemoveFromHierarchy();
+ items.Clear(); settlementOrder.Clear();
+ }
}
}
diff --git a/unity/Assets/Tests/EditMode/FrameProfileMovingTests.cs b/unity/Assets/Tests/EditMode/FrameProfileMovingTests.cs
new file mode 100644
index 000000000..02d0e678b
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/FrameProfileMovingTests.cs
@@ -0,0 +1,51 @@
+#nullable enable
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using UnityEngine;
+
+/// <summary>Task 9 fix round 1 (review I3): "?vprofile&amp;vmoving" prices every toggle while the camera turns, so a feature
+/// that only costs when the view changes (the map labels' placement) is measured too. Additive: without the flag the
+/// profile is unchanged (VisualHarnessTests.TheProfileStartsWithOneDiscardedPassOfEveryConfiguration).</summary>
+public class FrameProfileMovingTests
+{
+ [TestCase("http://localhost/?vprofile&vmoving", true)]
+ [TestCase("http://localhost/?vprofile", false)]
+ [TestCase("http://localhost/?vmoving-x", false)]
+ public void TheMovingVariantIsAskedForByItsOwnFlag(string url, bool expected)
+ {
+ Assert.AreEqual(expected, FrameProfile.MovingRequested(url, new string[0], true));
+ Assert.AreEqual(expected, FrameProfile.MovingRequested(null, expected ? new[] { "-vmoving" } : new string[0], false));
+ }
+
+ [Test]
+ public void TheMovingVariantTurnsTheCameraHalfADegreeEveryFrameFromEachPose()
+ {
+ var go = new GameObject("cam", typeof(Camera)); var rig = go.AddComponent<CameraRig>();
+ var frame = new GeoFrame(34.2, 35.9, 29.45, 33.35, 161529f, 431223f);
+ VisualToggles.Register("grade", _ => { });
+ var log = new List<string>(); var yaws = new List<float>();
+ try
+ {
+ var run = FrameProfile.Run(rig, frame, log.Add, false, moving: true);
+ while (run.MoveNext()) yaws.Add(rig.Yaw);
+ }
+ finally { Object.DestroyImmediate(go); VisualToggles.Clear(); }
+ int configs = 3, perRun = FrameProfile.WarmupFrames + FrameProfile.MeasuredFrames;
+ Assert.AreEqual(configs * FrameProfile.WarmupFrames + PromoPose.All.Count * FrameProfile.Repeats * configs * perRun, yaws.Count);
+ // Every measured run starts at its pose's yaw and turns MovingDegreesPerFrame each frame.
+ int start = configs * FrameProfile.WarmupFrames, i = 0;
+ foreach (var pose in PromoPose.All)
+ for (int run = 0; run < FrameProfile.Repeats * configs; run++, i++)
+ for (int f = 0; f < perRun; f++)
+ Assert.AreEqual(pose.Yaw + FrameProfile.MovingDegreesPerFrame * (f + 1), yaws[start + i * perRun + f], 1e-3f, $"{pose.Name} run {run} frame {f}");
+ Assert.AreEqual(0.5f, FrameProfile.MovingDegreesPerFrame);
+ foreach (var pose in PromoPose.All)
+ {
+ Assert.AreEqual(FrameProfile.Repeats * configs, log.Count(l => l.StartsWith("PROFILE visual=") && l.Contains($" pose={pose.Name}-moving ")), pose.Name);
+ Assert.AreEqual(configs, log.Count(l => l.StartsWith("PROFILE summary") && l.Contains($" pose={pose.Name}-moving ")), pose.Name);
+ }
+ Assert.AreEqual("PROFILE visual done", log.Last());
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/FrameProfileMovingTests.cs.meta b/unity/Assets/Tests/EditMode/FrameProfileMovingTests.cs.meta
new file mode 100644
index 000000000..fd88e3e1c
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/FrameProfileMovingTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f826fe2dfd3324c9eb86ea296ecd20e1
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/MapLabelTests.cs b/unity/Assets/Tests/EditMode/MapLabelTests.cs
index de95ed7bb..c520a1626 100644
--- a/unity/Assets/Tests/EditMode/MapLabelTests.cs
+++ b/unity/Assets/Tests/EditMode/MapLabelTests.cs
@@ -9,7 +9,9 @@ using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TestTools;
+using UnityEngine.TestTools.Constraints;
using UnityEngine.UIElements;
+using Is = UnityEngine.TestTools.Constraints.Is;
/// <summary>Plan Task 9: settlement labels as UI Toolkit pills in EB Garamond, decluttered and on their markers.</summary>
public class MapLabelTests
@@ -37,6 +39,48 @@ public class MapLabelTests
static bool Shown(VisualElement slot) => slot.style.visibility.value == Visibility.Visible;
+ /// <summary>A UIDocument with Game.uxml on a panel of its own size (scale-with-screen-size against 1920x1080, so a
+ /// 2880x1620 target is a scale of 1.5), the camera drawing to a texture of the same size, "loading" removed.</summary>
+ sealed class HdPanel : System.IDisposable
+ {
+ public readonly int Width, Height; public readonly VisualElement Root;
+ readonly RenderTexture rt, camRt; readonly PanelSettings ps; readonly GameObject go; readonly Camera cam;
+
+ public HdPanel(Camera cam, int width = 1920, int height = 1080, bool loading = false)
+ {
+ this.cam = cam; Width = width; Height = height;
+ rt = new RenderTexture(width, height, 0); camRt = new RenderTexture(width, height, 24);
+ ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel)); ps.targetTexture = rt;
+ go = new GameObject("LabelPanel"); go.SetActive(false);
+ var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps; doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
+ go.SetActive(true);
+ cam.targetTexture = camRt;
+ Root = doc.rootVisualElement;
+ if (!loading) Root.Q("root")?.RemoveFromClassList("loading");
+ }
+
+ /// <summary>A world point in panel coordinates, independently of the presenter: the camera's pixels, y flipped, times
+ /// the panel's scale.</summary>
+ public Vector2 ToPanel(Vector3 world, out bool inFront)
+ {
+ var p = cam.WorldToScreenPoint(world); inFront = p.z > 0;
+ float scale = Root.worldBound.width / Width;
+ return new Vector2(p.x * scale, (Height - p.y) * scale);
+ }
+
+ public void Dispose()
+ {
+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
+ cam.targetTexture = null; camRt.Release(); Object.DestroyImmediate(camRt);
+ }
+ }
+
+ static Vector3 MarkerTopOf(string id)
+ {
+ var box = GameObject.Find("Settlements").transform.Find(id);
+ return box.position + Vector3.up * box.lossyScale.y / 2;
+ }
+
[Test]
public void EverySettlementHasOneGaramondPillThatIgnoresThePointer()
{
@@ -56,7 +100,7 @@ public class MapLabelTests
VisualToggles.Set("labels", false);
Assert.AreEqual(DisplayStyle.None, container.style.display.value, "the labels toggle hides the layer");
VisualToggles.Set("labels", true);
- Assert.AreEqual(DisplayStyle.Flex, container.style.display.value);
+ Assert.AreEqual(StyleKeyword.Null, container.style.display.keyword, "on clears the inline display, so the loading rule still wins (review M1)");
}
[Test]
@@ -111,27 +155,37 @@ public class MapLabelTests
Assert.AreEqual(map.Settlements.Count, ui.Q<VisualElement>(MapLabelsPresenter.ContainerName).childCount);
}
+ /// <summary>Review M2: an older presenter disposed after a newer one was made removes only its own pills.</summary>
+ [Test]
+ public void DisposingAnOlderPresenterLeavesTheNewerOnesPills()
+ {
+ using var ui = new UiTestKit();
+ var older = new MapLabelsPresenter(ui.Root, map, cam);
+ using var newer = new MapLabelsPresenter(ui.Root, map, cam);
+ older.Dispose();
+ var container = ui.Q<VisualElement>(MapLabelsPresenter.ContainerName);
+ Assert.AreEqual(map.Settlements.Count, container.childCount);
+ foreach (var slot in newer.Slots) Assert.AreSame(container, slot.parent, slot.name);
+ }
+
/// <summary>Behavioural, not text (review N4/N6): with the real theme, a laid-out pill resolves to EB Garamond SemiBold on
- /// the navy fill with the gold edge, and the whole layer is display:none while the root carries "loading" (the slots'
- /// inline visibility cannot override that), and back once it is removed.</summary>
+ /// the navy fill with the gold edge, and the whole layer is display:none while the root carries "loading" (neither the
+ /// slots' inline visibility nor the labels switch turned on can override that, review M1), and back once it is
+ /// removed. A 1920x1080 panel (scale 1), as in the game: UiTestKit's panel follows the batch-mode screen (about 0.39
+ /// points per pixel there), and UI Toolkit rounds a 1 px border up to one physical pixel, 2.57 points.</summary>
[UnityTest]
public IEnumerator ThePillIsEbGaramondOnNavyWithAGoldEdgeAndHiddenWhileLoading()
{
- // A 1920x1080 panel (scale 1), as in the game: UiTestKit's panel follows the batch-mode screen (about 0.39 points per
- // pixel there), and UI Toolkit rounds a 1 px border up to one physical pixel, 2.57 points.
- var rt = new RenderTexture(1920, 1080, 0);
- var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel)); ps.targetTexture = rt;
- var go = new GameObject("LabelPanel"); go.SetActive(false);
- var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps; doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
- go.SetActive(true);
- var labels = new MapLabelsPresenter(doc.rootVisualElement, map, cam);
+ var hd = new HdPanel(cam, loading: true);
+ var labels = new MapLabelsPresenter(hd.Root, map, cam);
try
{
- var root = doc.rootVisualElement.Q<VisualElement>("root");
- var container = doc.rootVisualElement.Q<VisualElement>(MapLabelsPresenter.ContainerName);
+ var root = hd.Root.Q<VisualElement>("root");
+ var container = hd.Root.Q<VisualElement>(MapLabelsPresenter.ContainerName);
Assert.IsTrue(root.ClassListContains("loading"), "Game.uxml starts loading");
+ VisualToggles.Set("labels", true);
for (int i = 0; i < 10; i++) yield return null;
- Assert.AreEqual(DisplayStyle.None, container.resolvedStyle.display, "hidden while the game loads");
+ Assert.AreEqual(DisplayStyle.None, container.resolvedStyle.display, "hidden while the game loads, the switch on or not");
root.RemoveFromClassList("loading");
for (int i = 0; i < 10; i++) yield return null;
Assert.AreEqual(DisplayStyle.Flex, container.resolvedStyle.display, "shown once ready");
@@ -145,9 +199,11 @@ public class MapLabelTests
var gold = pill.resolvedStyle.borderTopColor;
Assert.AreEqual(196f / 255f, gold.r, 0.01f); Assert.AreEqual(160f / 255f, gold.g, 0.01f); Assert.AreEqual(92f / 255f, gold.b, 0.01f);
Assert.AreEqual(1f, pill.resolvedStyle.borderTopWidth, 0.01f);
+ Assert.GreaterOrEqual(pill.resolvedStyle.fontSize, labels.Labels.Single(l => l.name == "label-petah_tikva").resolvedStyle.fontSize + 2f,
+ "a city's name is visibly larger than a town's (review M5)");
Assert.IsNull(GameObject.Find("tel_aviv_label"), "no world-space TextMesh labels remain");
}
- finally { labels.Dispose(); Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt); }
+ finally { labels.Dispose(); hd.Dispose(); }
}
static IEnumerator Settle(MapLabelsPresenter labels)
@@ -158,90 +214,162 @@ public class MapLabelTests
}
/// <summary>Independent of the presenter's own projection call: the Tel Aviv pill's bottom centre is within 2 px of its
- /// marker box's top, projected with Camera.WorldToScreenPoint and the panel's scale, LiftPx above it.</summary>
+ /// marker box's top, projected with Camera.WorldToScreenPoint and the panel's scale, LiftPx above it. Also on a 2880x1620
+ /// target (panel scale 1.5, Retina-like) with the game's top-bar inset (review I5).</summary>
[UnityTest]
- public IEnumerator APillSitsJustAboveItsMarkerTop()
- {
- var rt = new RenderTexture(1920, 1080, 0); var camRt = new RenderTexture(1920, 1080, 24);
- var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel)); ps.targetTexture = rt;
- var go = new GameObject("LabelPanel"); go.SetActive(false);
- var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps; doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
- go.SetActive(true);
- cam.targetTexture = camRt;
- var root = doc.rootVisualElement; root.Q("root")?.RemoveFromClassList("loading");
- var labels = new MapLabelsPresenter(root, map, cam);
+ public IEnumerator APillSitsJustAboveItsMarkerTop() => PillOnMarker(1920, 1080, 0f);
+
+ [UnityTest]
+ public IEnumerator APillSitsJustAboveItsMarkerTopAtScaleOneAndAHalfWithTheTopInset() => PillOnMarker(2880, 1620, 0.088f);
+
+ IEnumerator PillOnMarker(int width, int height, float topInset)
+ {
+ var hd = new HdPanel(cam, width, height);
+ rig.TopInset = topInset; rig.ApplyProjection();
+ var labels = new MapLabelsPresenter(hd.Root, map, cam);
try
{
yield return Settle(labels);
- var box = GameObject.Find("Settlements").transform.Find("tel_aviv");
- var top = box.position + Vector3.up * box.lossyScale.y / 2;
- var p = cam.WorldToScreenPoint(top); // pixels of the 1920x1080 camera target, y up
- float scale = root.worldBound.width / 1920f;
- var expected = new Vector2(p.x * scale, (1080f - p.y) * scale - MapLabelsPresenter.LiftPx);
+ var expected = hd.ToPanel(MarkerTopOf("tel_aviv"), out _) - new Vector2(0, MapLabelsPresenter.LiftPx);
var wb = labels.Labels.Single(l => l.name == "label-tel_aviv").worldBound;
- TestContext.WriteLine($"Tel Aviv pill {wb}, expected bottom centre {expected}");
+ TestContext.WriteLine($"{width}x{height} inset {topInset}: Tel Aviv pill {wb}, expected bottom centre {expected}, panel {hd.Root.worldBound.size}");
+ Assert.AreEqual(1920f, hd.Root.worldBound.width, 1f, $"the panel is 1920 points wide: a scale of {width / 1920f}");
Assert.AreEqual(expected.x, wb.center.x, 2f, "centred on the marker");
Assert.AreEqual(expected.y, wb.yMax, 2f, "LiftPx above the marker's top");
}
- finally
- {
- labels.Dispose(); Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
- cam.targetTexture = null; camRt.Release(); Object.DestroyImmediate(camRt);
- }
+ finally { labels.Dispose(); hd.Dispose(); }
}
- static readonly string[] TelAvivCluster = { "tel_aviv", "jaffa", "petah_tikva", "rishon_lezion", "lod", "ramla", "rehovot" };
-
static float Gap(Rect r, Vector2 p) => new Vector2(Mathf.Max(0, Mathf.Max(r.xMin - p.x, p.x - r.xMax)), Mathf.Max(0, Mathf.Max(r.yMin - p.y, p.y - r.yMax))).magnitude;
- /// <summary>M2's cluster test, on layout bounds (review I5): at 90 km (the flythrough's frame 120) and at the overview,
- /// no two shown pills overlap, Tel Aviv is always shown, and every shown pill of the Tel Aviv - Lod cluster is at most
- /// half as far from its own marker top as from any other cluster marker's top, so none reads as a neighbour's.</summary>
+ static readonly string[] Occluders = { "top-bar", "info-panel", "minimap" };
+
+ /// <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)
+ {
+ var panels = Occluders.Select(n => hd.Root.Q<VisualElement>(n).worldBound).ToList();
+ var size = hd.Root.worldBound.size;
+ var tops = new System.Collections.Generic.Dictionary<string, Vector2>();
+ foreach (var s in map.Settlements)
+ {
+ var p = hd.ToPanel(MarkerTopOf(s.Id), out bool inFront);
+ if (inFront && p.x >= 0 && p.x <= size.x && p.y >= 0 && p.y <= size.y && !panels.Any(r => r.Contains(p))) tops[s.Id] = p;
+ }
+ return tops;
+ }
+
+ /// <summary>M2's cluster test, on layout bounds (review I5), widened by review I2/I4: at 90 km (the flythrough's frame 120)
+ /// and at the overview no two shown pills overlap; every shown pill is at most half as far from its own marker top as
+ /// from any other visible marker's top (so none reads as a neighbour's); and the expected names are shown, among them
+ /// a coastal town between Haifa and Tel Aviv at the overview. At 90 km that is every visible marker (Hadera, Zikhron
+ /// Ya'akov and the Galilee lie under the top bar or off screen); at the overview the rest of the Tel Aviv - Lod cluster
+ /// (Jaffa, Ramla, Rishon LeZion, Rehovot, markers 10-30 px apart) and Hadera give way.</summary>
[UnityTest]
public IEnumerator ShownPillsNeverOverlapAndEachReadsAsItsOwn()
{
- var rt = new RenderTexture(1920, 1080, 0); var camRt = new RenderTexture(1920, 1080, 24);
- var ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel)); ps.targetTexture = rt;
- var go = new GameObject("LabelPanel"); go.SetActive(false);
- var doc = go.AddComponent<UIDocument>(); doc.panelSettings = ps; doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);
- go.SetActive(true);
- cam.targetTexture = camRt;
- var root = doc.rootVisualElement; root.Q("root")?.RemoveFromClassList("loading");
- var labels = new MapLabelsPresenter(root, map, cam);
+ var hd = new HdPanel(cam);
+ var labels = new MapLabelsPresenter(hd.Root, map, cam);
try
{
- foreach (var (name, lon, lat, distance) in new[] { ("90 km", 34.95, 31.3 + (32.9 - 31.3) * 120 / 239.0, 90000f), ("overview", PromoPose.Diorama02.Lon, PromoPose.Diorama02.Lat, CameraController.MaxDistance) })
+ foreach (var (name, lon, lat, distance, expected, atLeast) in new[]
+ {
+ ("90 km", 34.95, 31.3 + (32.9 - 31.3) * 120 / 239.0, 90000f, new[] { "tel_aviv", "jaffa", "petah_tikva", "lod", "ramla", "rishon_lezion", "rehovot", "netanya" }, 8),
+ ("overview", PromoPose.Diorama02.Lon, PromoPose.Diorama02.Lat, CameraController.MaxDistance, new[] { "tel_aviv", "jerusalem", "gaza", "beersheba", "petah_tikva", "lod", "netanya" }, 7),
+ })
{
Pose(lon, lat, distance);
yield return Settle(labels);
- float scale = root.worldBound.width / 1920f;
- Vector2 MarkerTop(string id)
- {
- var box = GameObject.Find("Settlements").transform.Find(id);
- var p = cam.WorldToScreenPoint(box.position + Vector3.up * box.lossyScale.y / 2);
- return new Vector2(p.x * scale, (1080f - p.y) * scale);
- }
+ var tops = VisibleMarkerTops(hd, map);
var shown = labels.Slots.Where(Shown).Select(s => (id: s.name.Substring("slot-".Length), rect: s.Q<Label>().worldBound)).ToList();
- TestContext.WriteLine($"{name}: {shown.Count} of {labels.Slots.Count} pills shown");
- Assert.IsTrue(shown.Any(s => s.id == "tel_aviv"), $"{name}: Tel Aviv is shown");
+ TestContext.WriteLine($"{name}: {shown.Count} of {labels.Slots.Count} pills shown: {string.Join(" ", shown.Select(s => s.id))}");
+ TestContext.WriteLine($"{name}: visible markers {string.Join(" ", tops.Select(t => $"{t.Key}@{t.Value.x:F0},{t.Value.y:F0}"))}");
+ foreach (var id in expected) Assert.IsTrue(shown.Any(s => s.id == id), $"{name}: {id} is shown");
+ Assert.GreaterOrEqual(shown.Count, atLeast, $"{name}: shown pills");
+ if (name == "overview") Assert.IsTrue(shown.Any(s => s.id == "hadera" || s.id == "netanya"), "overview: a coastal town between Haifa and Tel Aviv is labelled");
for (int i = 0; i < shown.Count; i++)
for (int j = i + 1; j < shown.Count; j++)
Assert.IsFalse(shown[i].rect.Overlaps(shown[j].rect), $"{name}: {shown[i].id} {shown[i].rect} overlaps {shown[j].id} {shown[j].rect}");
- foreach (var (id, rect) in shown.Where(s => TelAvivCluster.Contains(s.id)))
+ foreach (var (id, rect) in shown)
{
- float own = Gap(rect, MarkerTop(id));
- foreach (var other in TelAvivCluster.Where(o => o != id))
- Assert.Greater(Gap(rect, MarkerTop(other)), 2f * own + 4f, $"{name}: {id} pill is {own:F0} px from its marker but closer to {other}'s");
+ Assert.IsTrue(tops.ContainsKey(id), $"{name}: {id} is shown but its marker is not visible");
+ float own = Gap(rect, tops[id]);
+ foreach (var other in tops.Where(o => o.Key != id))
+ Assert.Greater(Gap(rect, other.Value), 2f * own + 4f, $"{name}: {id} pill is {own:F0} px from its marker but closer to {other.Key}'s");
}
if (distance > MapLabelsPresenter.DeclutterDistanceM)
foreach (var s in map.Settlements.Where(s => MapLabelsPresenter.HiddenByZoom(s.Type, distance)))
Assert.IsFalse(Shown(labels.Slots.Single(x => x.name == "slot-" + s.Id)), $"{name}: {s.Id} ({s.Type}) is decluttered");
}
}
- finally
+ finally { labels.Dispose(); hd.Dispose(); }
+ }
+
+ /// <summary>Review I1: with the game's top-bar inset, no shown pill reaches under the top bar, the info panel or the
+ /// minimap, at both promo poses.</summary>
+ [UnityTest]
+ public IEnumerator NoPillSitsUnderAPanel()
+ {
+ var hd = new HdPanel(cam);
+ var labels = new MapLabelsPresenter(hd.Root, map, cam);
+ var inset = new TopBarInset(hd.Root, rig);
+ try
{
- labels.Dispose(); Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);
- cam.targetTexture = null; camRt.Release(); Object.DestroyImmediate(camRt);
+ foreach (var pose in new[] { PromoPose.Diorama02, PromoPose.Gameplay03 })
+ {
+ pose.Apply(rig, map.Frame);
+ yield return null;
+ inset.Update();
+ Assert.Greater(rig.TopInset, 0.05f, "the top bar's inset applies");
+ yield return Settle(labels);
+ var bar = hd.Root.Q<VisualElement>("top-bar").worldBound;
+ var info = hd.Root.Q<VisualElement>("info-panel").worldBound;
+ var mini = hd.Root.Q<VisualElement>("minimap").worldBound;
+ int count = 0;
+ foreach (var slot in labels.Slots.Where(Shown))
+ {
+ var r = slot.Q<Label>().worldBound; count++;
+ Assert.GreaterOrEqual(r.yMin, bar.yMax - 0.5f, $"{pose.Name}: {slot.name} {r} reaches under the top bar {bar}");
+ Assert.IsFalse(r.Overlaps(info), $"{pose.Name}: {slot.name} {r} under the info panel {info}");
+ Assert.IsFalse(r.Overlaps(mini), $"{pose.Name}: {slot.name} {r} under the minimap {mini}");
+ }
+ var zikhron = labels.Slots.Single(s => s.name == "slot-zikhron_yaakov");
+ TestContext.WriteLine($"{pose.Name}: {count} shown; Zikhron Ya'akov shown={Shown(zikhron)} {zikhron.Q<Label>().worldBound}; bar {bar}");
+ Assert.Greater(count, 4, $"{pose.Name}: pills are still shown");
+ }
+ }
+ finally { inset.Dispose(); labels.Dispose(); hd.Dispose(); }
+ }
+
+ /// <summary>Review I3: a refresh allocates nothing, and placing every pill while the camera turns and zooms is cheap
+ /// (240 refreshes, each with a new view).</summary>
+ [UnityTest]
+ public IEnumerator RefreshWhileTheCameraMovesIsCheapAndAllocationFree()
+ {
+ var hd = new HdPanel(cam);
+ var labels = new MapLabelsPresenter(hd.Root, map, cam);
+ try
+ {
+ yield return Settle(labels);
+ Assert.That(() => labels.Refresh(force: true), Is.Not.AllocatingGCMemory());
+ var tlv = labels.Slots.Single(s => s.name == "slot-tel_aviv");
+ var times = new System.Collections.Generic.List<double>();
+ var watch = new System.Diagnostics.Stopwatch();
+ int moved = 0; var last = tlv.style.translate.value;
+ for (int i = 0; i < 240; i++)
+ {
+ rig.Yaw += 1.5f; rig.Distance = Mathf.Lerp(60000f, CameraController.MaxDistance, i / 239f); rig.Apply();
+ watch.Restart(); labels.Refresh(); watch.Stop();
+ times.Add(watch.Elapsed.TotalMilliseconds * 1000.0);
+ var now = tlv.style.translate.value;
+ if (now.x != last.x || now.y != last.y) moved++;
+ last = now;
+ }
+ times.Sort();
+ double avg = times.Average(), p95 = times[(int)(0.95 * (times.Count - 1))];
+ TestContext.WriteLine(System.FormattableString.Invariant($"LABELS refresh moving avg_us={avg:0} p95_us={p95:0} moved={moved}"));
+ Assert.Greater(moved, 120, "the refreshes did work: Tel Aviv's pill moved");
+ Assert.Less(avg, 200.0, "average refresh under 200 us (editor Mono)");
}
+ finally { labels.Dispose(); hd.Dispose(); }
}
}
diff --git a/unity/Assets/UI/Statecraft.uss b/unity/Assets/UI/Statecraft.uss
index 9abed170e..089b1c46b 100644
--- a/unity/Assets/UI/Statecraft.uss
+++ b/unity/Assets/UI/Statecraft.uss
@@ -149,14 +149,12 @@ Button:disabled { color: var(--ink-dim); border-color: rgba(120, 120, 120, 0.4);
border-width: 1px;
border-color: var(--gold);
border-radius: 12px;
- padding: 1px 8px 2px 8px;
+ padding: 1px 10px 2px 10px;
margin: 0;
-unity-text-align: middle-center;
white-space: nowrap;
}
-/* Tel Aviv's pill, centred on its marker, must end clear of Petah Tikva's marker 10 km east at the overview (about 61 px
- apart there; MapLabelTests.ShownPillsNeverOverlapAndEachReadsAsItsOwn): 20 px and 8 px side padding, not 22 and 10. */
-.map-label-city { font-size: 20px; }
+.map-label-city { font-size: 22px; }
.map-label-town, .map-label-arab_town { font-size: 19px; }
.anchor-lower-centre { translate: -50% -100%; }
.anchor-lower-left { translate: 0 -100%; }