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.

32.7 KB
Raw Blame
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.Map;
using Statecraft.Game.UI;
using Statecraft.Sim;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;

public class MapActionUiTests
{
    // The legacy loop: the GDD loop refuses every map action and offers no Build button (R-PROJ-004).
    static readonly Content C = SimBridgeGddTests.Legacy;
    static readonly HexFile Hexes = MapBuilder.LoadHexes(Path.Combine(Paths.Content, "map", "hexes.json"));
    static readonly System.Collections.Generic.List<Settlement> Towns =
        SettlementPlacer.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", SettlementPlacer.DefaultFileName)));
    static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);

    [Test]
    public void HexPickerAgreesWithTheToolsSettlementRule()
    {
        // tools/settlement_hexes.py moves a settlement off a water hex to its nearest land neighbour (Tiberias; Haifa on the
        // 4.4 km grid, #1183); every other settlement must land on exactly the hex the C# port computes.
        foreach (var t in Towns)
        {
            var picked = HexPicker.FromLonLat(t.Lon, t.Lat, Hexes.bounds, Hexes.hex_size_km);
            var owner = C.SettlementHexes.Single(s => s.Id == t.Id);
            if (!Hexes.hexes.Single(h => (h.q, h.r) == picked).land) { Assert.AreNotEqual((owner.Q, owner.R), picked, t.Id); continue; }
            Assert.AreEqual((owner.Q, owner.R), picked, t.Id);
        }
    }

    [Test]
    public void GeoFrameRoundTripsLonLat()
    {
        var f = new GeoFrame(34.2, 35.9, 29.45, 33.35, 161530f, 431220f);
        var (lon, lat) = f.ToLonLat(f.ToWorld(34.78, 32.08, 0));
        Assert.AreEqual(34.78, lon, 1e-5); Assert.AreEqual(32.08, lat, 1e-5);
    }

    static SimBridge At(DateTime date)
    {
        var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
        while (g.State.Date < date) g.Step(HistoricalAI.Commands(C, g.State));
        return new SimBridge(g, Text);
    }

    static InfoPanelPresenter Panel(UiTestKit ui, SimBridge bridge) =>
        new InfoPanelPresenter(ui.Root, bridge, Text, Towns.ToDictionary(t => t.Id, t => t.Name));

    [Test]
    public void BeforeTheMaabarotTheButtonsSayWhy()
    {
        using var ui = new UiTestKit();
        var info = Panel(ui, At(new DateTime(1949, 6, 1)));
        Assert.AreEqual(Text["info.hint"], ui.Q<Label>("info-title").text);
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        info.Show(tlv.Q, tlv.R);
        Assert.AreEqual("Tel Aviv", ui.Q<Label>("info-title").text);
        StringAssert.StartsWith("Coastal plain · elevation ", ui.Q<Label>("info-subtitle").text);
        StringAssert.DoesNotContain("hex (", ui.Q<Label>("info-subtitle").text, "no debug coordinates in player text (playtest 2, P2-6)");
        Assert.IsFalse(ui.Q<Button>("build-camp").enabledSelf);
        Assert.AreEqual("Transit camps and housing projects can be placed from 1 January 1950", ui.Q<Label>("info-reason").text);
    }

    /// <summary>#881: the sim supplies a refusal kind and ISO date; the Hebrew UI supplies both the words and Hebrew date.</summary>
    [Test]
    public void BeforeTheMaabarotTheHebrewPanelSaysWhyInHebrew()
    {
        var he = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
        using var ui = new UiTestKit();
        var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
        var bridge = new SimBridge(g, he);
        var info = new InfoPanelPresenter(ui.Root, bridge, he, Towns.ToDictionary(t => t.Id, t => t.Name));
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        info.Show(tlv.Q, tlv.R);
        Assert.AreEqual("אפשר להקים מעברות ומיזמי דיור החל מ־1 בינואר 1950", ui.Q<Label>("info-reason").text);
    }

    [Test]
    public void ATransitCampIsOrderedAndBuiltAtEndTurn()
    {
        using var ui = new UiTestKit();
        var bridge = At(new DateTime(1950, 8, 1));                        // after the ma'abarot decision (May 1950)
        var info = Panel(ui, bridge);
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        info.Show(tlv.Q, tlv.R);
        Assert.IsTrue(ui.Q<Button>("build-camp").enabledSelf, ui.Q<Label>("info-reason").text);
        Assert.AreEqual("Place a transit camp (IL\u00A01.5m)", ui.Q<Button>("build-camp").text);
        ui.Press("build-camp");
        Assert.AreEqual("Ordered: A transit camp, at End turn", ui.Q<Label>("info-placement").text);
        bridge.EndTurn();
        Assert.AreEqual(MapActions.TransitCamp, MapActions.At(bridge.State, tlv.Q, tlv.R)!.Action);
        Assert.AreEqual("A transit camp built here in August 1950", ui.Q<Label>("info-placement").text);
    }

    // Red first on PR #2679 head 0401491db: the whole-queue preview rejected the unaffordable press for its Attention, so both
    // buttons were hidden behind one shared reason. As on origin/main 0c976fb21, an action the Attention left cannot pay for
    // keeps its button and the bridge refuses the press with order.no_attention (SimBridge.Queue).
    [Test]
    public void NoAttentionKeepsMapActionsAndTheBridgeRefusesTheirPresses()
    {
        using var ui = new UiTestKit();
        var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
        while (g.State.Date < new DateTime(1950, 8, 1)) g.Step(HistoricalAI.Commands(C, g.State));
        g.State.Attention = 0;
        var bridge = new SimBridge(g, Text);
        var refusals = new System.Collections.Generic.List<string>();
        bridge.Refused += refusals.Add;
        using var info = Panel(ui, bridge);
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        var orders = new[] { new MapAction(MapActions.TransitCamp, tlv.Q, tlv.R), new MapAction(MapActions.Housing, tlv.Q, tlv.R) };
        foreach (var order in orders)
        {
            Assert.IsNull(MapActions.CheckReason(C, bridge.State, order.Action, tlv.Q, tlv.R), order.Action + ": otherwise legal on this hex");
            Assert.IsFalse(bridge.CanPay(order), order.Action + ": precondition: no Attention left");
        }

        info.Show(tlv.Q, tlv.R);

        foreach (var name in new[] { "build-camp", "build-housing" })
        {
            Assert.IsTrue(ui.Q<Button>(name).enabledSelf, name + ": the rules allow it, so the button stays");
            ui.Press(name);
        }
        Assert.IsEmpty(bridge.Queued, "the bridge queues no order it cannot pay for");
        Assert.AreEqual(orders.Select(o => Text.Format("order.no_attention", bridge.Price(o)!.Value, 0.0)).ToArray(), refusals);
    }

    // Red first on PR #2679 head 4e25f657c: Refusal returns the current state's ma'abarot-policy reason before it previews
    // the earlier SetPolicy order, so the transit-camp button is disabled even though End turn would accept the action.
    [Test]
    public void AQueuedMaabarotPolicyEnablesATransitCampMapAction()
    {
        using var ui = new UiTestKit();
        var bridge = At(new DateTime(1950, 8, 1));
        bridge.TurnStart.Policies[MapActions.MaabarotPolicy] = 0;
        bridge.TurnStart.CoalitionStability = 1;
        Assert.IsTrue(PoliticsSystem.HasMajority(C, bridge.TurnStart.Date), "precondition: the policy vote has a majority");
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        Assert.AreEqual("maabarot_policy", MapActions.CheckReason(C, bridge.State, MapActions.TransitCamp, tlv.Q, tlv.R)?.Kind,
            "precondition: without the queued policy the current state refuses the camp");
        Assert.IsNull(bridge.Queue(new SetPolicy(MapActions.MaabarotPolicy, 1)));
        Assert.AreEqual(1.0, Simulation.Preview(C, bridge.TurnStart,
            bridge.Session.Committed.Concat(bridge.Queued).ToList()).State.Policies[MapActions.MaabarotPolicy],
            "precondition: the policy vote passes before the map action runs");

        using var info = Panel(ui, bridge);
        info.Show(tlv.Q, tlv.R);

        Assert.IsTrue(ui.Q<Button>("build-camp").enabledSelf);
        Assert.AreEqual("", ui.Q<Label>("info-reason").text);
    }

    /// <summary>#701: in the Hebrew UI the build date names its month in Hebrew (date.month_year), not "August 1950". The line
    /// is a date label with no verb (Beri, 17 October 2026), since a fixed "נבנה" is wrong for a feminine name ("מעברה").</summary>
    [Test]
    public void InHebrewTheBuildDateIsAHebrewMonth()
    {
        var he = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
        using var ui = new UiTestKit();
        var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
        while (g.State.Date < new DateTime(1950, 8, 1)) g.Step(HistoricalAI.Commands(C, g.State));
        var bridge = new SimBridge(g, he);
        var info = new InfoPanelPresenter(ui.Root, bridge, he, Towns.ToDictionary(t => t.Id, t => t.Name));
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        info.Show(tlv.Q, tlv.R);
        ui.Press("build-camp");
        bridge.EndTurn();
        var line = ui.Q<Label>("info-placement").text;
        StringAssert.EndsWith(" – תאריך הקמה: אוגוסט 1950", line);
        StringAssert.DoesNotContain("נבנה", line, "no gendered verb");
    }

    /// <summary>#929: under Hebrew the queued and built lines name the action from #924's info.map_action strings, not the
    /// content's English name. English is pinned by ATransitCampIsOrderedAndBuiltAtEndTurn.</summary>
    [Test]
    public void InHebrewTheQueuedAndBuiltLinesNameTheActionInHebrew()
    {
        var he = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
        using var ui = new UiTestKit();
        var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
        while (g.State.Date < new DateTime(1950, 8, 1)) g.Step(HistoricalAI.Commands(C, g.State));
        var bridge = new SimBridge(g, he);
        var info = new InfoPanelPresenter(ui.Root, bridge, he, Towns.ToDictionary(t => t.Id, t => t.Name));
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        info.Show(tlv.Q, tlv.R);
        ui.Press("build-camp");
        Assert.AreEqual("ניתנה פקודה: מעברה, בסיום התור", ui.Q<Label>("info-placement").text);
        bridge.EndTurn();
        Assert.AreEqual("מעברה – תאריך הקמה: אוגוסט 1950", ui.Q<Label>("info-placement").text);
    }

    /// <summary>The minimap's painted relief (tools/minimap_bake.py) is north up over the hex grid's bounds: sea off Tel Aviv
    /// and in the Gulf of Aqaba, land in the hills and the Negev. Read from the PNG itself (the imported texture is not
    /// readable on the CPU).</summary>
    [Test]
    public void TheMinimapReliefHasLandAndSeaNorthUp()
    {
        var tex = new Texture2D(2, 2);
        try
        {
            Assert.IsTrue(tex.LoadImage(File.ReadAllBytes(Path.Combine(Paths.RepoRoot, "unity", MinimapPresenter.AssetPath))), MinimapPresenter.AssetPath);
            var b = Hexes.bounds;
            Color At(double lon, double lat) =>
                tex.GetPixel((int)((lon - b.lon0) / (b.lon1 - b.lon0) * tex.width), (int)((lat - b.lat0) / (b.lat1 - b.lat0) * tex.height));
            void Sea(double lon, double lat, string where) { var c = At(lon, lat); Assert.Greater(c.b, c.r + 0.1f, $"{where} is sea: {c}"); }
            void Land(double lon, double lat, string where) { var c = At(lon, lat); Assert.Greater(c.r, c.b, $"{where} is land: {c}"); }
            Sea(34.30, 32.60, "the Mediterranean off Tel Aviv");
            Sea(34.92, 29.47, "the Gulf of Aqaba (its middle: about 34.88-34.96 E at 29.47 N)");
            Land(35.21, 31.77, "Jerusalem");
            Land(34.90, 30.50, "the Negev");
            Land(35.10, 32.95, "the Galilee");
        }
        finally { UnityEngine.Object.DestroyImmediate(tex); }
    }

    [Test]
    public void PlacementsAreDrawnOnTheirHexes()
    {
        EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
        try
        {
            new GameObject("TestMainCamera") { tag = "MainCamera" }.AddComponent<Camera>();
            var map = new GameObject("MapScene").AddComponent<MapScene>();
            map.Configure(AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Terrain.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/SettlementMarker.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/HexSelection.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Sea.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/MapFrame.mat"));
            map.Build();
            var layer = new GameObject("Placements").AddComponent<PlacementLayer>();
            var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
            layer.Render(new[] { new Placement(MapActions.TransitCamp, tlv.Q, tlv.R, new DateTime(1950, 8, 26)) }, C, map);
            layer.Render(new[] { new Placement(MapActions.Housing, tlv.Q, tlv.R, new DateTime(1950, 8, 26)) }, C, map);
            Assert.AreEqual(1, layer.transform.childCount);                 // Render replaces what it drew
            var box = layer.transform.GetChild(0);
            Assert.AreEqual($"housing_{tlv.Q}_{tlv.R}", box.name);
            var hex = C.HexAt(tlv.Q, tlv.R)!;
            var expected = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);
            Assert.AreEqual(expected.x, box.position.x, 1f); Assert.AreEqual(expected.z, box.position.z, 1f);
            Assert.AreEqual((tlv.Q, tlv.R), MapPointer.Pick(map, box.position));
        }
        finally { EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); }
    }

    // #1123: a built city project is drawn on its recorded hex as its kind's placement; one still being built, and a kind
    // with no approved art (industry), are not; the legacy placements are drawn as before.
    [Test]
    public void BuiltCityProjectsAreDrawnOnTheirHexes()
    {
        EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
        try
        {
            new GameObject("TestMainCamera") { tag = "MainCamera" }.AddComponent<Camera>();
            var map = new GameObject("MapScene").AddComponent<MapScene>();
            map.Configure(AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Terrain.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/SettlementMarker.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/HexSelection.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Sea.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/MapFrame.mat"));
            map.Build();
            var layer = new GameObject("Placements").AddComponent<PlacementLayer>();
            var hexes = C.SettlementHexes.Select(s => (s.Id, s.Q, s.R)).GroupBy(h => (h.Q, h.R)).Select(g => g.First()).Take(5).ToList();
            var built = new DateTime(1950, 9, 30);
            var legacy = new[] { new Placement(MapActions.Housing, hexes[0].Q, hexes[0].R, new DateTime(1950, 8, 26)) };
            var projects = new[]
            {
                new CityProject(1, MapActions.Housing, hexes[1].Id, hexes[1].Q, hexes[1].R, 0, built),
                new CityProject(2, MapActions.TransitCamp, hexes[2].Id, hexes[2].Q, hexes[2].R, 0, built),
                new CityProject(3, MapActions.Housing, hexes[3].Id, hexes[3].Q, hexes[3].R, 4),           // being built
                new CityProject(4, "industry", hexes[4].Id, hexes[4].Q, hexes[4].R, 0, built),            // no approved art
            };
            CollectionAssert.AreEqual(legacy, PlacementLayer.Drawn(legacy, new CityProject[0]), "no projects: the placements as they are");
            layer.Render(PlacementLayer.Drawn(legacy, projects), C, map);
            CollectionAssert.AreEquivalent(new[]
            {
                $"housing_{hexes[0].Q}_{hexes[0].R}", $"housing_{hexes[1].Q}_{hexes[1].R}", $"transit_camp_{hexes[2].Q}_{hexes[2].R}",
            }, layer.transform.Cast<Transform>().Select(t => t.name).ToList());
            var box = layer.transform.Cast<Transform>().Single(t => t.name == $"housing_{hexes[1].Q}_{hexes[1].R}");
            Assert.AreEqual((hexes[1].Q, hexes[1].R), MapPointer.Pick(map, box.position), "drawn on the project's recorded hex");
            Assert.AreEqual(built, PlacementLayer.Drawn(legacy, projects)[1].Date, "dated the day it was built");
        }
        finally { EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); }
    }

    [Test]
    public void TheInfoPanelShowsNoTileYields()
    {
        using var ui = new UiTestKit();
        var bridge = At(new DateTime(1950, 8, 1));
        var info = Panel(ui, bridge);
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        info.Show(tlv.Q, tlv.R);
        var shown = string.Join(" | ", new[] { "info-title", "info-subtitle", "info-settlements", "info-placement", "info-reason" }.Select(n => ui.Q<Label>(n).text)).ToLowerInvariant();
        foreach (var word in new[] { "yield", "food", "production", "gold", "income" }) StringAssert.DoesNotContain(word, shown);
    }

    // Red first on origin/main 0c976fb21: the third hex's buttons remain enabled because the panel checks the turn-start state,
    // so a third press enters the queue and is refused only at End turn.
    [Test]
    public void ThePerTurnCapIncludesActionsAlreadyQueuedThisTurn()
    {
        using var ui = new UiTestKit();
        var bridge = At(new DateTime(1950, 8, 1));
        using var info = Panel(ui, bridge);
        var cap = C.RulesAt(bridge.State.Date).MapActionsPerTurn;
        Assert.AreEqual(2, cap, "precondition: the legacy map-action cap");
        var hexes = C.SettlementHexes.Select(h => (h.Q, h.R)).Distinct().Take(cap + 1).ToList();
        Assert.AreEqual(cap + 1, hexes.Count, "precondition: one distinct target beyond the cap");
        foreach (var (q, r) in hexes.Take(cap)) { info.Show(q, r); ui.Press("build-housing"); }
        Assert.AreEqual(cap, bridge.Queued.OfType<MapAction>().Count());

        info.Show(hexes[cap].Q, hexes[cap].R);
        Assert.AreEqual(Text.Format("info.map_action_reason.turn_cap", cap), ui.Q<Label>("info-reason").text);
        foreach (var name in new[] { "build-camp", "build-housing" })
        {
            Assert.AreEqual(DisplayStyle.None, ui.Q<Button>(name).style.display.value, name + ": shared refusal hides the button");
            Assert.IsFalse(ui.Q<Button>(name).enabledSelf, name + ": shared refusal disables the button");
        }
        Assert.AreEqual(cap, bridge.Queued.OfType<MapAction>().Count(), "the unavailable third action was not queued");
        Assert.IsEmpty(bridge.EndTurn().Rejected);
    }

    [Test]
    public void ABuiltHexCannotBeBuiltOnAgainAndSaysWhy()
    {
        using var ui = new UiTestKit();
        var bridge = At(new DateTime(1950, 8, 1));
        var info = Panel(ui, bridge);
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        info.Show(tlv.Q, tlv.R);
        ui.Press("build-housing");
        bridge.EndTurn();
        Assert.IsFalse(ui.Q<Button>("build-housing").enabledSelf);
        Assert.AreEqual(MapActions.Check(C, bridge.State, MapActions.Housing, tlv.Q, tlv.R), ui.Q<Label>("info-reason").text);
    }

    [UnityTest]
    public System.Collections.IEnumerator AClickOnTheMinimapMapsToTheDrawnMapNotTheLetterbox()
    {
        using var ui = new UiTestKit();
        using var mini = new MinimapPresenter(ui.Root, Hexes);
        var image = ui.Q<VisualElement>("minimap-image");
        for (int i = 0; i < 30 && !(image.layout.width > 0 && Mathf.Abs(image.layout.width / image.layout.height - mini.Aspect) < 0.01f); i++) yield return null;
        Assert.Greater(image.layout.width, 0f);
        // the element is exactly as big as the picture (aspect of the texture), so there is no unused strip inside it
        Assert.AreEqual(mini.Aspect, image.layout.width / image.layout.height, 0.01f);
        (double lon, double lat)? clicked = null;
        mini.Clicked += (lon, lat) => clicked = (lon, lat);
        var b = Hexes.bounds;
        // a click a quarter of the way across and a quarter of the way down the visible map
        var local = new Vector2(image.layout.width * 0.25f, image.layout.height * 0.25f);
        using (var e = PointerDownEvent.GetPooled(new Event { type = EventType.MouseDown, button = 0, mousePosition = image.LocalToWorld(local) }))
        { e.target = image; image.SendEvent(e); }
        Assert.IsNotNull(clicked);
        Assert.AreEqual(b.lon0 + 0.25 * (b.lon1 - b.lon0), clicked!.Value.lon, 1e-6);
        Assert.AreEqual(b.lat1 - 0.25 * (b.lat1 - b.lat0), clicked.Value.lat, 1e-6);
        clicked = null;
        using (var e = PointerDownEvent.GetPooled(new Event { type = EventType.MouseDown, button = 1, mousePosition = image.LocalToWorld(local) }))
        { e.target = image; image.SendEvent(e); }
        Assert.IsNull(clicked, "only the left button clicks");
    }

    [UnityTest]
    public System.Collections.IEnumerator TheViewFrameLiesInsideTheDrawnMap()
    {
        using var ui = new UiTestKit();
        using var mini = new MinimapPresenter(ui.Root, Hexes);
        var image = ui.Q<VisualElement>("minimap-image");
        for (int i = 0; i < 30 && !(image.layout.width > 0); i++) yield return null;
        var b = Hexes.bounds;
        var f = new GeoFrame(b.lon0, b.lon1, b.lat0, b.lat1, 161530f, 431220f);
        mini.SetView(f, f.ToWorld(34.95, 31.95, 0), 20000f);
        yield return null;
        var view = ui.Q<VisualElement>("minimap-view");
        Assert.AreEqual(LengthUnit.Percent, view.style.left.value.unit);
        Assert.GreaterOrEqual(view.style.left.value.value, 0f);
        Assert.GreaterOrEqual(view.style.top.value.value, 0f);
        Assert.LessOrEqual(view.style.left.value.value + view.style.width.value.value, 100f);
        Assert.LessOrEqual(view.style.top.value.value + view.style.height.value.value, 100f);
        // a view at the very edge stays inside the picture
        foreach (var (lon, lat) in new[] { (b.lon0, b.lat0), (b.lon1, b.lat0), (b.lon0, b.lat1), (b.lon1, b.lat1) })
        {
            mini.SetView(f, f.ToWorld(lon, lat, 0), 20000f);
            yield return null;
            Assert.GreaterOrEqual(view.style.left.value.value, 0f);
            Assert.GreaterOrEqual(view.style.top.value.value, 0f);
            Assert.LessOrEqual(view.style.left.value.value + view.style.width.value.value, 100.001f, "right edge");
            Assert.LessOrEqual(view.style.top.value.value + view.style.height.value.value, 100.001f, "bottom edge");
            if (view.layout.width > 0)
            {
                Assert.LessOrEqual(view.layout.xMax, image.layout.width + 0.5f);
                Assert.LessOrEqual(view.layout.yMax, image.layout.height + 0.5f);
            }
        }
        Assert.AreSame(image, view.parent, "the frame is positioned in the picture's own coordinates");
    }

    static MapScene BuildMap()
    {
        EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
        new GameObject("TestMainCamera") { tag = "MainCamera" }.AddComponent<Camera>();
        var map = new GameObject("MapScene").AddComponent<MapScene>();
        map.Configure(AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Terrain.mat"),
            AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/SettlementMarker.mat"),
            AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/HexSelection.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Sea.mat"),
                AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/MapFrame.mat"));
        map.Build();
        Physics.SyncTransforms();
        return map;
    }

    static bool Down(MapScene map, double lon, double lat, out RaycastHit hit)
    {
        var from = map.Frame.ToWorld(lon, lat, 100_000f);
        return map.Terrain.GetComponent<TerrainCollider>().Raycast(new Ray(from, Vector3.down), out hit, 200_000f);
    }

    [Test]
    public void RaysDownOntoTheTerrainPickTheRightHexes()
    {
        var map = BuildMap();
        try
        {
            var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
            var a = C.HexAt(tlv.Q, tlv.R)!;
            Assert.IsTrue(Down(map, a.Lon, a.Lat, out var hit));
            Assert.AreEqual((tlv.Q, tlv.R), MapPointer.Pick(map, hit.point), "Tel Aviv's hex centre");

            // two points 200 m either side of the middle of the edge Tel Aviv's hex shares with its eastern neighbour
            var b = C.HexAt(tlv.Q + 1, tlv.R)!;
            var wa = map.Frame.ToWorld(a.Lon, a.Lat, 0); var wb = map.Frame.ToWorld(b.Lon, b.Lat, 0);
            var mid = (wa + wb) / 2; var dir = (wb - wa).normalized;
            foreach (var (side, expected) in new[] { (-1f, (tlv.Q, tlv.R)), (1f, (tlv.Q + 1, tlv.R)) })
            {
                var (lon, lat) = map.Frame.ToLonLat(mid + dir * 200f * side);
                Assert.IsTrue(Down(map, lon, lat, out hit));
                Assert.AreEqual(expected, MapPointer.Pick(map, hit.point), "side " + side);
            }

            Assert.IsTrue(Down(map, 34.30, 32.60, out hit));
            var seaHex = MapPointer.Pick(map, hit.point);
            Assert.IsFalse(C.HexAt(seaHex.q, seaHex.r)!.Land, "the Mediterranean");

            var f = map.Frame; const double inset = 0.005;
            foreach (var (lon, lat) in new[] { (f.Lon0 + inset, f.Lat0 + inset), (f.Lon1 - inset, f.Lat0 + inset), (f.Lon0 + inset, f.Lat1 - inset), (f.Lon1 - inset, f.Lat1 - inset) })
            {
                Assert.IsTrue(Down(map, lon, lat, out hit), $"a ray reaches the terrain at ({lon}, {lat})");
                var corner = MapPointer.Pick(map, hit.point);
                Assert.AreEqual(HexPicker.FromLonLat(lon, lat, map.Hexes.bounds, map.Hexes.hex_size_km), corner);
            }
        }
        finally { EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); }
    }

    [Test]
    public void AClickOverTheUiNeverReachesTheMapAndOtherwiseHitsTheHexUnderTheCamera()
    {
        var map = BuildMap();
        try
        {
            var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
            var hex = C.HexAt(tlv.Q, tlv.R)!;
            var ground = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);
            var cam = Camera.main!;
            cam.transform.position = new Vector3(ground.x, 50_000f, ground.z);
            cam.transform.rotation = Quaternion.Euler(90, 0, 0);
            cam.farClipPlane = 200_000f;
            var pointer = new GameObject("Pointer").AddComponent<MapPointer>();
            pointer.Map = map;
            var picked = new System.Collections.Generic.List<(int, int)>();
            pointer.HexClicked += (q, r, cityPill) => picked.Add((q, r));
            var centre = new Vector2(cam.pixelWidth / 2f, cam.pixelHeight / 2f);

            pointer.IsOverUi = _ => false;
            Assert.IsTrue(pointer.HandleClick(centre));
            Assert.AreEqual(new[] { (tlv.Q, tlv.R) }, picked);

            picked.Clear();
            pointer.IsOverUi = _ => true;
            Assert.IsFalse(pointer.HandleClick(centre));
            Assert.IsEmpty(picked);

            pointer.Map = null;                                          // the UI is asked first, even with no map
            bool asked = false; pointer.IsOverUi = _ => { asked = true; return true; };
            Assert.IsFalse(pointer.HandleClick(centre));
            Assert.IsTrue(asked);
        }
        finally { EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); }
    }

    [Test]
    public void AMissingRuleShowsNoFalseCost()
    {
        using var ui = new UiTestKit();
        var bridge = At(new DateTime(1950, 8, 1));
        var info = Panel(ui, bridge);
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        var rule = C.Rules.MapActions[MapActions.Housing];
        C.Rules.MapActions.Remove(MapActions.Housing);
        try
        {
            info.Show(tlv.Q, tlv.R);
            Assert.AreEqual("Build housing", ui.Q<Button>("build-housing").text);
            Assert.IsFalse(ui.Q<Button>("build-housing").enabledSelf);
        }
        finally { C.Rules.MapActions[MapActions.Housing] = rule; }
    }

    [Test]
    public void ADisposedMinimapLetsGoOfItsPictureAndADisposedPanelHearsNothing()
    {
        using var ui = new UiTestKit();
        var bridge = At(new DateTime(1950, 8, 1));
        var info = Panel(ui, bridge);
        var tlv = C.SettlementHexes.Single(s => s.Id == "tel_aviv");
        info.Show(tlv.Q, tlv.R);
        info.Dispose();
        ui.Q<Label>("info-title").text = "untouched";
        bridge.EndTurn();
        Assert.AreEqual("untouched", ui.Q<Label>("info-title").text);
        var mini = new MinimapPresenter(ui.Root, Hexes);
        var tex = mini.Texture;
        mini.Dispose();
        // The picture is the shared baked asset: the presenter lets go of it and does not destroy it.
        Assert.IsTrue(ui.Q<VisualElement>("minimap-image").style.backgroundImage.keyword == StyleKeyword.Null, "nothing draws the picture after Dispose");
        Assert.IsTrue(tex != null, "the baked picture is an asset and stays loaded");
    }

    [Test]
    public void AClickBeforeLayoutRaisesNothing()
    {
        using var ui = new UiTestKit();
        using var mini = new MinimapPresenter(ui.Root, Hexes);
        var image = ui.Q<VisualElement>("minimap-image");
        Assert.IsFalse(image.layout.width > 0, "no layout has run yet");
        int clicks = 0;
        mini.Clicked += (lon, lat) => clicks++;
        using (var e = PointerDownEvent.GetPooled(new Event { type = EventType.MouseDown, button = 0, mousePosition = new Vector2(10, 10) }))
        { e.target = image; image.SendEvent(e); }
        Assert.AreEqual(0, clicks);
    }

    /// <summary>R-PROJ-004: the GDD game (the real content) offers no legacy Build button and no map-action reason, before
    /// 1950 or after it: the sim refuses every map action there, and city projects replace them.</summary>
    [Test]
    public void TheGddLoopShowsNoMapActionButtons()
    {
        var gdd = ContentLoader.Load(Paths.Content);
        Assert.IsTrue(gdd.IsGdd);
        var g = GameSession.New(gdd, GoldenRun.Seed, Mode.Historical);
        using var ui = new UiTestKit();
        var info = new InfoPanelPresenter(ui.Root, new SimBridge(g, Text), Text, Towns.ToDictionary(t => t.Id, t => t.Name));
        var tlv = gdd.SettlementHexes.Single(s => s.Id == "tel_aviv");
        foreach (var date in new[] { new DateTime(1949, 6, 1), new DateTime(1950, 8, 1) })
        {
            while (g.State.Date < date) g.Step(HistoricalAI.Commands(gdd, g.State));
            info.Show(tlv.Q, tlv.R);
            foreach (var b in new[] { "build-camp", "build-housing" })
                Assert.AreEqual(DisplayStyle.None, ui.Q<Button>(b).style.display.value, $"{b} on {date:yyyy-MM-dd}");
            Assert.AreEqual("", ui.Q<Label>("info-reason").text, $"no map-action reason on {date:yyyy-MM-dd}");
        }
        info.Dispose();
    }

    /// <summary>eras.yaml systems.map_actions (#58): an action the era does not allow has no button and no reason; with
    /// both allowed both show. Played on a copy of the content, switching the list between renders.</summary>
    [Test]
    public void OnlyTheErasMapActionsHaveButtons()
    {
        var c = SimBridgeGddTests.LoadLegacy();
        var g = GameSession.New(c, GoldenRun.Seed, Mode.Historical);
        while (g.State.Date < new DateTime(1950, 8, 1)) g.Step(HistoricalAI.Commands(c, g.State));
        using var ui = new UiTestKit();
        var info = new InfoPanelPresenter(ui.Root, new SimBridge(g, Text), Text, Towns.ToDictionary(t => t.Id, t => t.Name));
        var tlv = c.SettlementHexes.Single(s => s.Id == "tel_aviv");
        void ShowWith(params string[] actions) { c.Eras[0].Systems.MapActions = actions.ToList(); info.Show(tlv.Q, tlv.R); }
        DisplayStyle Display(string name) => ui.Q<Button>(name).style.display.value;

        ShowWith(MapActions.TransitCamp, MapActions.Housing);
        Assert.AreEqual(DisplayStyle.Flex, Display("build-camp")); Assert.AreEqual(DisplayStyle.Flex, Display("build-housing"));
        Assert.IsTrue(ui.Q<Button>("build-camp").enabledSelf, ui.Q<Label>("info-reason").text);

        ShowWith(MapActions.Housing);
        Assert.AreEqual(DisplayStyle.None, Display("build-camp")); Assert.AreEqual(DisplayStyle.Flex, Display("build-housing"));
        Assert.IsFalse(ui.Q<Button>("build-camp").enabledSelf);
        StringAssert.DoesNotContain("chapter", ui.Q<Label>("info-reason").text);

        ShowWith();
        Assert.AreEqual(DisplayStyle.None, Display("build-camp")); Assert.AreEqual(DisplayStyle.None, Display("build-housing"));
        Assert.AreEqual("", ui.Q<Label>("info-reason").text);
    }
}