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.

65.8 KB
Raw Blame
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game.Map;
using Statecraft.Game.Map.Collection;
using Statecraft.Game.Map.Kits;
using Statecraft.Game.Map.Units;
using Statecraft.Game.UI;
using Statecraft.HexTiles;
using Statecraft.Sim;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;

/// <summary>Before/after stills of Tal Heuberger's signed-off models in the real game scene (owner, 27 October 2026, #756: "Sign
/// off all 19"), in English and Hebrew: the game booted as CivMovementShots boots it, the map camera with the UI over it.
/// "Before" withholds the new models (main's map: every layer adds them last, so nothing else moves); "after" answers them.
/// The editor streams nothing, so the scenery layers are rebuilt with the geometry fixture's prefab answers. Explicit.</summary>
[Explicit("writes stills for a pull request, not a check")]
public class TalModelsShots
{
    internal static string ShotDir => Path.GetFullPath(Path.Combine(Application.dataPath, "..", "..", ".superpowers", "tal-models-shots"));
    string saveDir = "";
    RenderTexture? rt; PanelSettings? ps;
    GameRoot root = null!;
    Action<string, CollectionDetail, Action<GameObject?>>? savedRural, savedPeople, savedSpecial, savedUnits, savedLandmark;
    Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? savedTown, savedWhole;
    Action<string, Action<GameObject?>>? savedHexProps;

    [SetUp]
    public void Prepare()
    {
        saveDir = Path.Combine(Path.GetTempPath(), "statecraft-tal-shots-" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(ShotDir); Directory.CreateDirectory(CivMovementShots.ShotDir);
        savedRural = RuralLife.Request; savedPeople = CivilianPeople.Request; savedSpecial = SpecialBuildingModels.Request;
        savedUnits = UnitFigures.Source; savedTown = TownModelLayer.ModelAcquire; savedLandmark = TownLandmarks.Request;
        savedWhole = TownLandmarks.Acquire; savedHexProps = HexPropModels.Request;
    }

    [TearDown]
    public void DiscardScene()
    {
        RuralLife.Request = savedRural!; CivilianPeople.Request = savedPeople!; SpecialBuildingModels.Request = savedSpecial!;
        UnitFigures.Source = savedUnits; TownModelLayer.ModelAcquire = savedTown!; TownLandmarks.Request = savedLandmark!;
        TownLandmarks.Acquire = savedWhole!; HexPropModels.Request = savedHexProps!;
        EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
        if (ps != null) Object.DestroyImmediate(ps);
        if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }
        if (Directory.Exists(saveDir)) Directory.Delete(saveDir, true);
    }

    static GameObject? Prefab(string id, CollectionDetail detail) => AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, detail));

    internal static Action<string, CollectionDetail, Action<GameObject?>> Answer(ICollection<string> withheld) =>
        (id, detail, done) => done(withheld.Contains(id) ? null : Prefab(id, detail));

    static void Drop(MapScene map, string name)
    {
        var old = map.Terrain.transform.Find(name);
        if (old != null) Object.DestroyImmediate(old.gameObject);
    }

    internal static void Look(Vector3 at, float distance)
    {
        var rig = Camera.main.GetComponent<CameraRig>();
        rig.LookAt = at; rig.Distance = distance; rig.Yaw = 0f;
        rig.Apply();
    }

    IEnumerator Boot(bool hebrew)
    {
        yield return CivMovementShots.Boot(hebrew, saveDir, (t, p, u, g) => { rt = t; ps = p; root = g; });
    }

    IEnumerator Bedouin(bool hebrew, bool after)
    {
        yield return Boot(hebrew);
        var map = Object.FindFirstObjectByType<MapScene>();
        var state = root.Bridge!.State; var content = root.Bridge.Content;
        void Layers(ICollection<string> withheld)
        {
            RuralLife.Request = CivilianPeople.Request = Answer(withheld);
            Drop(map, RuralLife.Name); Drop(map, CivilianPeople.Name);
            // GameRoot's order and inputs: the figures first, then the rural scenes, which keep clear of them.
            CollectionGeometryFixture.People(map, state.Date, state.Placements, content, state.Settlements, state.CityProjects.Values);
            CollectionGeometryFixture.Rural(map);
        }
        // The frames come from the map with the new models, so they are the same before and after: where the tent and the
        // figure stand. Both layers add them last, so nothing else moves when they are withheld.
        Layers(Array.Empty<string>());
        var rural = map.Terrain.transform.Find(RuralLife.Name).GetComponent<RuralLife>();
        var people = map.Terrain.transform.Find(CivilianPeople.Name).GetComponent<CivilianPeople>();
        var tent = rural.Placed.First(p => p.Model == RuralLife.BedouinTent);
        var figure = people.Placed.First(p => p.Model == CivilianPeople.BedouinCivilian);
        // The tent's frame holds the tent and the nearest code-built camp (coordinator decision on #1893: the tent stands in the
        // camp area, apart from the camps' plots): the midpoint of the tent and that camp's footprint, from the closest zoom the
        // player can reach or as far as needed to hold both. Every placed tent's distance to its nearest camp is logged.
        Vector2 Flat(Vector3 v) => new Vector2(v.x, v.z);
        var camps = map.KitFootprints.Where(f => f.id.StartsWith("camp:", StringComparison.Ordinal)).ToList();
        (Vector2 centre, float radius, float edge) Nearest(Vector3 at) => camps.Select(f => (f.centre, f.radius, Vector2.Distance(Flat(at), f.centre) - f.radius)).OrderBy(c => c.Item3).First();
        foreach (var placed in rural.Placed.Where(p => p.Model == RuralLife.BedouinTent && p.Detail == CollectionDetail.Near))
            Debug.Log($"SHOT bedouin tent {placed.Key}: nearest code-built camp footprint edge {Nearest(placed.At).edge:F0} m away");
        var camp = Nearest(tent.At);
        var campAt = new Vector3(camp.centre.x, 0f, camp.centre.y);
        float span = Vector2.Distance(Flat(tent.At), camp.centre) + camp.radius;
        var frames = new[] { ("tent", tent.Key, (tent.At + campAt) * 0.5f, Mathf.Max(CameraController.MinDistance, 2.5f * span)),
                             ("figure", figure.Key, figure.At, CameraController.MinDistance) };
        if (!after)
        {
            Layers(new[] { CollectionCatalog.BedouinTent, CollectionCatalog.BedouinCivilian });
            rural = map.Terrain.transform.Find(RuralLife.Name).GetComponent<RuralLife>();
            people = map.Terrain.transform.Find(CivilianPeople.Name).GetComponent<CivilianPeople>();
        }
        Debug.Log($"SHOT bedouin {(after ? "after" : "before")}: rural tents {rural.Placed.Count(p => p.Model == RuralLife.BedouinTent)}, " +
                  $"figures {people.Placed.Count(p => p.Model == CivilianPeople.BedouinCivilian)}, tent size {RuralLife.SizeOf(RuralLife.BedouinTent)} m");
        foreach (var (what, key, flat, distance) in frames)
        {
            var at = new Vector3(flat.x, 0f, flat.z);
            at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;
            Look(at, distance);
            for (int i = 0; i < 5; i++) yield return null;
            CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"bedouin-{what}-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
            Debug.Log($"SHOT bedouin {what} at {key} {at} from {distance:F0} m");
        }
    }

    /// <summary>Degania Alef after the first turn (15 June 1948: the tank stands from 20 May), the camera on the kibbutz's own point,
    /// so the frame is the same with and without the tank.</summary>
    IEnumerator Degania(bool hebrew, bool after)
    {
        yield return Boot(hebrew);
        VisualElement card = null!;
        yield return NextTurn(c => card = c);
        var map = Object.FindFirstObjectByType<MapScene>();
        SpecialBuildingModels Layer(ICollection<string> withheld)
        {
            SpecialBuildingModels.Request = Answer(withheld);
            Drop(map, SpecialBuildingModels.Name);
            return CollectionGeometryFixture.Special(map, root.Bridge!.State.Date)!;
        }
        // The frame is where the tank stands on this date with the model answered, the same before and after.
        var layer = Layer(Array.Empty<string>());
        var tank = layer.Placed.First(p => p.Model == CollectionCatalog.SyrianR35);
        if (!after) layer = Layer(new[] { CollectionCatalog.SyrianR35 });
        var point = tank.At;
        point.y = map.Terrain.SampleHeight(point) + map.Terrain.transform.position.y;
        // The closest the player's camera comes (CameraController.MinDistance).
        Look(point, CameraController.MinDistance);
        for (int i = 0; i < 5; i++) yield return null;
        CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"degania-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
        Debug.Log($"SHOT degania on {root.Bridge!.State.Date:yyyy-MM-dd} at {point} from {CameraController.MinDistance:F0} m, event card display {card.resolvedStyle.display}: {string.Join(", ", layer.Placed.Select(p => p.Key))}");
    }

    /// <summary>Ends the turn and puts the turn report and the new turn's decision card away, as a player would, so the map is
    /// clear for the frame; hands back the card.</summary>
    IEnumerator NextTurn(Action<VisualElement> cardOut)
    {
        root.Bridge!.EndTurn();
        for (int i = 0; i < 3; i++) yield return null;
        var ui = Object.FindFirstObjectByType<UIDocument>().rootVisualElement;
        var close = ui.Q<Button>("turn-report-close");
        if (close != null && close.resolvedStyle.display == DisplayStyle.Flex) UiTestKit.Press(close);
        for (int i = 0; i < 3; i++) yield return null;
        // The new turn opens a decision card over the map; the player's Hide button puts it away, and the card shrinks away
        // (ScreenNav.Show). The frame is taken only once the card itself is undisplayed.
        var card = ui.Q("event-card");
        Assert.IsNotNull(card, "the event card");
        if (card.resolvedStyle.display == DisplayStyle.Flex) UiTestKit.Press(ui.Q<Button>("event-hide"));
        for (int i = 0; i < 120 && card.resolvedStyle.display != DisplayStyle.None; i++) yield return null;
        Assert.AreEqual(DisplayStyle.None, card.resolvedStyle.display, "the decision card is hidden before the frame");
        cardOut(card);
    }

    /// <summary>One of Tal Heuberger's four props (owner, 2 November 2026: "Place all four now") on a date in its window: the
    /// opening turn (15 May 1948) for the well, the crates and the wall, the next turn (15 June 1948, the Altalena's) for the
    /// sandbags. The camera at the closest zoom the player reaches (CameraController.MinDistance), yaw 0, aimed at the ground
    /// where the prop stands with it answered, so the frame is the same before and after; "before" withholds only the prop.</summary>
    IEnumerator Prop(bool hebrew, bool after, string key, bool nextTurn)
    {
        yield return Boot(hebrew);
        if (nextTurn) yield return NextTurn(_ => { });
        var map = Object.FindFirstObjectByType<MapScene>();
        var date = root.Bridge!.State.Date;
        SpecialBuildingModels Layer(ICollection<string> withheld)
        {
            SpecialBuildingModels.Request = Answer(withheld);
            Drop(map, SpecialBuildingModels.Name);
            return CollectionGeometryFixture.Special(map, date)!;
        }
        var layer = Layer(Array.Empty<string>());
        var prop = layer.Placed.Single(p => p.Key == key);
        if (!after) layer = Layer(new[] { prop.Model });
        var point = prop.At;
        point.y = map.Terrain.SampleHeight(point) + map.Terrain.transform.position.y;
        Look(point, CameraController.MinDistance);
        for (int i = 0; i < 5; i++) yield return null;
        CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"prop-{key}-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
        Debug.Log($"SHOT prop {key} {(after ? "after" : "before")} on {date:yyyy-MM-dd} at {point} from {CameraController.MinDistance:F0} m: {string.Join(", ", layer.Placed.Select(p => p.Key))}");
    }

    [UnityTest] public IEnumerator WellBeforeEnglish() { yield return Prop(false, false, "beersheba_abrahams_well", false); }
    [UnityTest] public IEnumerator WellBeforeHebrew() { yield return Prop(true, false, "beersheba_abrahams_well", false); }
    [UnityTest] public IEnumerator WellAfterEnglish() { yield return Prop(false, true, "beersheba_abrahams_well", false); }
    [UnityTest] public IEnumerator WellAfterHebrew() { yield return Prop(true, true, "beersheba_abrahams_well", false); }
    [UnityTest] public IEnumerator CratesBeforeEnglish() { yield return Prop(false, false, "haifa_quay_crates", false); }
    [UnityTest] public IEnumerator CratesBeforeHebrew() { yield return Prop(true, false, "haifa_quay_crates", false); }
    [UnityTest] public IEnumerator CratesAfterEnglish() { yield return Prop(false, true, "haifa_quay_crates", false); }
    [UnityTest] public IEnumerator CratesAfterHebrew() { yield return Prop(true, true, "haifa_quay_crates", false); }
    [UnityTest] public IEnumerator WallBeforeEnglish() { yield return Prop(false, false, "abu_ghosh_road_wall", false); }
    [UnityTest] public IEnumerator WallBeforeHebrew() { yield return Prop(true, false, "abu_ghosh_road_wall", false); }
    [UnityTest] public IEnumerator WallAfterEnglish() { yield return Prop(false, true, "abu_ghosh_road_wall", false); }
    [UnityTest] public IEnumerator WallAfterHebrew() { yield return Prop(true, true, "abu_ghosh_road_wall", false); }
    [UnityTest] public IEnumerator SandbagsBeforeEnglish() { yield return Prop(false, false, "tel_aviv_altalena_sandbags", true); }
    [UnityTest] public IEnumerator SandbagsBeforeHebrew() { yield return Prop(true, false, "tel_aviv_altalena_sandbags", true); }
    [UnityTest] public IEnumerator SandbagsAfterEnglish() { yield return Prop(false, true, "tel_aviv_altalena_sandbags", true); }
    [UnityTest] public IEnumerator SandbagsAfterHebrew() { yield return Prop(true, true, "tel_aviv_altalena_sandbags", true); }

    /// <summary>The Egyptian Dakota on the opening turn (15 May 1948, in its window, 15 May to 11 June 1948), at the opening
    /// distance (CameraRig.StartDistance, #2370) and at a gameplay zoom (40 km): the player's camera (yaw 0) aimed at the ground under the loop's centre
    /// and held on the map as CameraController.Step holds it. "Before" withholds the Dakota. The loop holds its start (-shot).</summary>
    IEnumerator Dakota(bool hebrew, bool after)
    {
        var savedCraft = SeaAirCollection.Request;
        try
        {
            yield return Boot(hebrew);
            var map = Object.FindFirstObjectByType<MapScene>();
            var state = root.Bridge!.State; var content = root.Bridge.Content;
            SeaAirCollection.Request = Answer(Array.Empty<string>());
            Drop(map, SeaAirCollection.Name);
            var layer = CollectionGeometryFixture.Craft(map, state.Date, state.Placements, content)!;
            // #2482: two Dakotas fly one loop, so both carry its centre; the lead's is the one to aim at.
            var plane = layer.Placed.First(p => p.Model == SeaAirCollection.Dakota);
            if (!after)
            {
                SeaAirCollection.Request = Answer(new[] { SeaAirCollection.Dakota });
                Drop(map, SeaAirCollection.Name);
                layer = CollectionGeometryFixture.Craft(map, state.Date, state.Placements, content)!;
            }
            Debug.Log($"SHOT dakota {(after ? "after" : "before")} on {state.Date:yyyy-MM-dd}: drawn {layer.Placed.Count(p => p.Model == SeaAirCollection.Dakota)}, loop centre {plane.At}, span {SeaAirCollection.SizeOf(SeaAirCollection.Dakota)} m");
            var rig = Camera.main.GetComponent<CameraRig>(); var cc = rig.GetComponent<CameraController>();
            foreach (var (what, distance) in new[] { ("gameplay", 40000f), ("opening", CameraRig.StartDistance) })
            {
                var under = new Vector3(plane.At.x, 0f, plane.At.z);
                Look(under, distance);
                CameraController.Step(rig, default, 0f, cc.Bounds, cc.Ground, cc.GroundTop, true);
                for (int i = 0; i < 5; i++) yield return null;
                UnitFlagFacing.FaceAll(Camera.main.transform.position);
                CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"dakota-{what}-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
                Debug.Log($"SHOT dakota {what} from {distance:F0} m, look-at {rig.LookAt}, camera {Camera.main.transform.position}, plane at viewport {Camera.main.WorldToViewportPoint(plane.At)}");
            }
        }
        finally { SeaAirCollection.Request = savedCraft; }
    }

    [UnityTest] public IEnumerator DakotaBeforeEnglish() { yield return Dakota(false, false); }
    [UnityTest] public IEnumerator DakotaBeforeHebrew() { yield return Dakota(true, false); }
    [UnityTest] public IEnumerator DakotaAfterEnglish() { yield return Dakota(false, true); }
    [UnityTest] public IEnumerator DakotaAfterHebrew() { yield return Dakota(true, true); }

    /// <summary>#1701 slice F: a gdd-0.3 game (every era's ruleset set on fresh inputs, as FixedNorthGameRootTests does) with
    /// one arms workshop built on Rehovot's own hex, or on Tel Aviv's or Jerusalem's among its houses (owner, 2 November 2026: "Among the
    /// houses") (a fixture state: the project is put in the state, built on the game's date),
    /// from the close zoom, framed on the workshop and the town. "Before" withholds b21 (main draws nothing there); the frame is
    /// the one the answered model gives. The load lines count the special layer's instances, drawn renderers and their
    /// triangles at the far, middle and close zooms.</summary>
    IEnumerator ArmsWorkshop(bool hebrew, bool after, string city = "rehovot")
    {
        Directory.CreateDirectory(Path.Combine(CivMovementShots.ShotDir, "..", "b21-workshop-shots"));
        // The town's houses as the player's stream answers them, so the frame shows the drawn buildings the workshop keeps clear of.
        TownModelLayer.ModelAcquire = (model, detail, done) => { done(Prefab(model, detail)); return new NoLease(); };
        var inputs = Statecraft.Game.Boot.GameInputs.FromDisk(Statecraft.Game.Paths.Content, Statecraft.Game.Paths.StreamingMap);
        foreach (var era in inputs.Content.Eras) { era.Systems.Ruleset = SaveGame.Gdd03Ruleset; era.Systems.Loop = EraSystems.Gdd; }
        EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
        ShotCamera.Configure(Camera.main, CivMovementShots.Width, CivMovementShots.Height);
        var doc = Object.FindFirstObjectByType<UIDocument>();
        rt = new RenderTexture(CivMovementShots.Width, CivMovementShots.Height, 24, RenderTextureFormat.ARGB32);
        ps = Object.Instantiate(doc.panelSettings);
        ps.targetTexture = rt; ps.clearColor = true; ps.colorClearValue = Color.clear;
        doc.panelSettings = ps;
        var map = Object.FindFirstObjectByType<MapScene>();
        map.Build(inputs.Map);
        root = Object.FindFirstObjectByType<GameRoot>();
        root.Store = new Statecraft.Game.SaveStore(saveDir);
        if (hebrew) root.Language = UiLanguage.Hebrew;
        root.Begin(inputs, 0);
        var ui = doc.rootVisualElement;
        for (int i = 0; i < 30 && !(ui.Q("top-bar").worldBound.height > 0); i++) yield return null;
        for (int i = 0; i < 5; i++) yield return null;
        GameSceneTests.HideTheOpeningCard(ui);
        if (root.Advisor != null && root.Advisor.IsOpen) UiTestKit.Press(ui.Q<Button>("advisor-close"));
        for (int i = 0; i < 3; i++) yield return null;
        var state = root.Bridge!.State; var content = root.Bridge.Content;
        Assert.AreEqual(SaveGame.Gdd03Ruleset, content.Ruleset);
        var home = content.SettlementHexes.Single(h => h.Id == city);
        int id = state.NextId++;
        state.CityProjects.Add(id, new CityProject(id, Workshops.ArmsWorkshop, city, home.Q, home.R, 0, state.Date));
        SpecialBuildingModels Layer(ICollection<string> withheld)
        {
            SpecialBuildingModels.Request = Answer(withheld);
            Drop(map, SpecialBuildingModels.Name);
            return CollectionGeometryFixture.Special(map, state.Date, content, state.CityProjects.Values)!;
        }
        var layer = Layer(Array.Empty<string>());
        var workshop = layer.Placed.Single(p => p.Key == SpecialBuildingModels.WorkshopKey(id));
        if (!after) layer = Layer(new[] { SpecialBuildingModels.Workshop });
        var town = map.KitFootprints.First(f => f.id == city);
        bool among = Vector2.Distance(new Vector2(workshop.At.x, workshop.At.z), town.centre) < town.radius;
        // Among a big town's houses (Tel Aviv, Jerusalem: "Among the houses") the frame is the workshop and its neighbours;
        // beside a town, the workshop and the whole town.
        var mid = among ? new Vector3(workshop.At.x, 0f, workshop.At.z)
            : new Vector3(0.5f * (workshop.At.x + town.centre.x), 0f, 0.5f * (workshop.At.z + town.centre.y));
        mid.y = map.Terrain.SampleHeight(mid) + map.Terrain.transform.position.y;
        float span = Vector2.Distance(new Vector2(workshop.At.x, workshop.At.z), town.centre) + town.radius;
        float close = among ? 1.5f * CameraController.MinDistance : Mathf.Clamp(2.5f * span, CameraController.MinDistance, 0.9f * TownModelLayer.CloseEnterM);
        foreach (var (zoom, distance) in new[] { ("far", 150000f), ("middle", 60000f), ("close", close) })
        {
            Look(mid, distance);
            layer.Choose(default, Camera.main);
            var drawn = layer.GetComponentsInChildren<Renderer>(true).Where(r => !r.forceRenderingOff).ToList();
            long tris = 0;
            foreach (var r in drawn)
            {
                Mesh? mesh = r is SkinnedMeshRenderer skinned ? skinned.sharedMesh : r.TryGetComponent<MeshFilter>(out var filter) ? filter.sharedMesh : null;
                if (mesh != null) tris += mesh.triangles.Length / 3;
            }
            Debug.Log($"LOAD b21 {(after ? "after" : "before")} {zoom} ({distance:F0} m): {layer.transform.childCount} instances, " +
                      $"{drawn.Count} renderers drawn, {tris} triangles drawn; placed: {string.Join(", ", layer.Placed.Select(p => p.Key))}");
        }
        Look(mid, close);
        layer.Choose(default, Camera.main);
        for (int i = 0; i < 5; i++) yield return null;
        CivMovementShots.Shot(rt!, Path.Combine("..", "b21-workshop-shots", $"{city}-workshop-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
        Debug.Log($"SHOT b21 {city} {(after ? "after" : "before")} {(hebrew ? "he" : "en")} on {state.Date:yyyy-MM-dd}: workshop at {workshop.At}, camera on {mid} from {close:F0} m");
    }

    [UnityTest] public IEnumerator ArmsWorkshopBeforeEnglish() { yield return ArmsWorkshop(false, false); }
    [UnityTest] public IEnumerator ArmsWorkshopAfterEnglish() { yield return ArmsWorkshop(false, true); }
    [UnityTest] public IEnumerator ArmsWorkshopBeforeHebrew() { yield return ArmsWorkshop(true, false); }
    [UnityTest] public IEnumerator ArmsWorkshopAfterHebrew() { yield return ArmsWorkshop(true, true); }
    [UnityTest] public IEnumerator ArmsWorkshopTelAvivBeforeEnglish() { yield return ArmsWorkshop(false, false, "tel_aviv"); }
    [UnityTest] public IEnumerator ArmsWorkshopTelAvivAfterEnglish() { yield return ArmsWorkshop(false, true, "tel_aviv"); }
    [UnityTest] public IEnumerator ArmsWorkshopTelAvivBeforeHebrew() { yield return ArmsWorkshop(true, false, "tel_aviv"); }
    [UnityTest] public IEnumerator ArmsWorkshopTelAvivAfterHebrew() { yield return ArmsWorkshop(true, true, "tel_aviv"); }
    [UnityTest] public IEnumerator ArmsWorkshopJerusalemBeforeEnglish() { yield return ArmsWorkshop(false, false, "jerusalem"); }
    [UnityTest] public IEnumerator ArmsWorkshopJerusalemAfterEnglish() { yield return ArmsWorkshop(false, true, "jerusalem"); }
    [UnityTest] public IEnumerator ArmsWorkshopJerusalemBeforeHebrew() { yield return ArmsWorkshop(true, false, "jerusalem"); }
    [UnityTest] public IEnumerator ArmsWorkshopJerusalemAfterHebrew() { yield return ArmsWorkshop(true, true, "jerusalem"); }

    sealed class NoLease : IDisposable { public void Dispose() { } }

    /// <summary>A town's houses from the closest zoom the player can reach, the camera on the centre of the town's placed
    /// houses (the plots are the same on main and on this branch: the model choice draws no random number). The town layer's
    /// building requests are answered with the editor's prefabs, as the player's stream would answer them. Run on main and on
    /// this branch for the before and after.</summary>
    IEnumerator Houses(bool hebrew, string? town)
    {
        yield return Boot(hebrew);
        TownModelLayer.ModelAcquire = (id, detail, done) => { done(Prefab(id, detail)); return new NoLease(); };
        var layer = Object.FindFirstObjectByType<TownModelLayer>();
        Assert.IsNotNull(layer, "the town layer");
        // The village: the first locality (by id) on the stone-village lattice whose houses include the plastered courtyard house.
        town ??= ((IEnumerable<(string id, Bounds bounds)>)typeof(TownModelLayer)
                .GetField("buildingPlaces", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.GetValue(layer)!)
            .Select(p => p.id).Where(id => layer.InstancesOf(id).Any(i => i.Model == TownModel.G05CourtyardHouse))
            .OrderBy(id => id, StringComparer.Ordinal).First();
        var placed = layer.InstancesOf(town);
        Assert.IsNotEmpty(placed, town);
        var map = Object.FindFirstObjectByType<MapScene>();
        var sum = Vector3.zero; foreach (var i in placed) sum += (Vector3)i.M.GetColumn(3);
        var at = sum / placed.Count;
        at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;
        Look(at, CameraController.MinDistance);
        for (int i = 0; i < 3; i++) { Camera.main.Render(); yield return null; }
        string models = string.Join(", ", placed.GroupBy(i => i.Model).OrderBy(g => g.Key).Select(g => $"{g.Key} x{g.Count()}"));
        CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"houses-{town}-{(hebrew ? "he" : "en")}"));
        Debug.Log($"SHOT houses {town} at {at} from {CameraController.MinDistance:F0} m: {models}");
    }

    /// <summary>The median time (ms) of <paramref name="n"/> renders of the map camera at the shots' size, each waited for
    /// on the GPU by a one-pixel read back, after two unmeasured renders. An editor (Metal) figure, for before and after on
    /// the same machine, not a WebGL frame time.</summary>
    static float RenderMs(int n)
    {
        var cam = Camera.main;
        var frame = new RenderTexture(CivMovementShots.Width, CivMovementShots.Height, 24, RenderTextureFormat.ARGB32);
        var pixel = new Texture2D(1, 1, TextureFormat.RGBA32, false);
        var before = cam.targetTexture; var ms = new List<float>();
        try
        {
            cam.targetTexture = frame;
            for (int i = 0; i < n + 2; i++)
            {
                var clock = System.Diagnostics.Stopwatch.StartNew();
                cam.Render();
                RenderTexture.active = frame; pixel.ReadPixels(new Rect(0, 0, 1, 1), 0, 0); pixel.Apply(); RenderTexture.active = null;
                if (i >= 2) ms.Add((float)clock.Elapsed.TotalMilliseconds);
            }
        }
        finally
        {
            cam.targetTexture = before; RenderTexture.active = null;
            frame.Release(); Object.DestroyImmediate(frame); Object.DestroyImmediate(pixel);
        }
        ms.Sort();
        return ms[ms.Count / 2];
    }

    /// <summary>Written for the owner's ruling of 2 November 2026, "Yes, small buildings at every zoom" (superseded on 6 November
    /// 2026 by "Big blocks, every zoom": these four draw their kits from 40 km out, and since 7 November 2026, "Tal's models
    /// close (Recommended)", their building models below it; MajorCityShots shows them): Tel Aviv, Jerusalem, Haifa and Jaffa from
    /// the opening view (the game's own camera, CameraRig.StartDistance), the widest zoom (diorama02, 250 km), and each city at 90 km and
    /// 30 km, with the town layers' requests (whole towns and buildings) answered with the editor's prefabs, as the player's
    /// stream would answer them. Each frame logs its draw cost: the building models' instances, triangles and instanced
    /// draws (TownModelLayer), the whole-town models in view and their triangles (TownLandmarks), and the median render time.
    /// Run on main and on this branch for the before and after.</summary>
    IEnumerator BigCities(bool hebrew)
    {
        Directory.CreateDirectory(Path.Combine(CivMovementShots.ShotDir, "..", "big-cities-shots"));
        yield return Boot(hebrew);
        string lang = hebrew ? "he" : "en";
        var map = Object.FindFirstObjectByType<MapScene>();
        TownModelLayer.ModelAcquire = (id, detail, done) => { done(Prefab(id, detail)); return new NoLease(); };
        TownLandmarks.Acquire = (id, detail, done) => { done(Prefab(id, detail)); return new NoLease(); };
        Drop(map, TownLandmarks.Name);
        var landmarks = TownLandmarks.ShowAt(map, root.Bridge!.State.Date, Array.Empty<Placement>(), root.Bridge.Content)!;
        var layer = Object.FindFirstObjectByType<TownModelLayer>();
        Assert.IsNotNull(layer, "the town layer");
        for (int i = 0; i < 3; i++) { Camera.main.Render(); yield return null; }
        IEnumerator Frame(string name)
        {
            for (int i = 0; i < 3; i++) { Camera.main.Render(); yield return null; }
            CivMovementShots.Shot(rt!, Path.Combine("..", "big-cities-shots", $"{name}-{lang}"));
            int drawn = layer.LastDrawn, draws = layer.LastDraws; long tris = layer.LastTriangles;
            var cam = Camera.main;
            landmarks.Choose(default, cam);
            var planes = GeometryUtility.CalculateFrustumPlanes(cam);
            int wholes = 0; long wholeTris = 0;
            foreach (var r in landmarks.GetComponentsInChildren<MeshRenderer>(true))
            {
                if (r.forceRenderingOff || !r.enabled || !r.gameObject.activeInHierarchy || !GeometryUtility.TestPlanesAABB(planes, r.bounds)) continue;
                var mesh = r.GetComponent<MeshFilter>()?.sharedMesh;
                if (mesh == null) continue;
                wholes++; for (int k = 0; k < mesh.subMeshCount; k++) wholeTris += mesh.GetIndexCount(k) / 3;
            }
            float ms = RenderMs(10);
            Debug.Log(FormattableString.Invariant(
                $"COST {name}-{lang} distance={TownModelLayer.ViewDistance(cam):F0} buildings={drawn} building_tris={tris} building_draws={draws} whole_towns={wholes} whole_tris={wholeTris} render_ms={ms:F2}"));
        }
        // The game's own opening view first, untouched.
        yield return Frame("opening");
        PromoPose.Diorama02.Apply(Camera.main.GetComponent<CameraRig>(), map.Frame);
        yield return Frame("widest");
        foreach (var id in new[] { "tel_aviv", "jerusalem", "haifa", "jaffa" })
        {
            var c = map.KitFootprints.First(f => f.id == id).centre;
            var at = new Vector3(c.x, 0f, c.y);
            at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;
            foreach (var km in new[] { 90, 30 })
            {
                Look(at, km * 1000f);
                yield return Frame($"{id.Replace('_', '-')}-{km}km");
            }
        }
        Debug.Log("LANDMARKS placed: " + string.Join(", ", landmarks.Placed.Select(p => p.Key + "=" + p.Model)));
    }

    [UnityTest] public IEnumerator BigCitiesEnglish() { yield return BigCities(false); }
    [UnityTest] public IEnumerator BigCitiesHebrew() { yield return BigCities(true); }

    /// <summary>#2085: a town from the far zoom (50 km, inside the 40 km+ band where whole-town models stand), the camera on the
    /// centre of the town's kit footprint, 15 May 1948. The landmarks' requests are answered with the editor's prefabs, as the
    /// player's stream would answer them. "Before" withholds Tal's four whole towns (main's map: Tiberias, Safed and Netanya
    /// have no row, so the code-built kit stands); "after" answers them. Ramla has an after frame only: since the owner's 2 November
    /// ruling Ramla's row is its own town, so withholding it leaves Ramla bare, not main's stone village. Its before frames
    /// (the stone village) were taken at cc766c04b, while Ramla still took ByType's stone village.</summary>
    IEnumerator WholeTown(bool hebrew, string town, bool after)
    {
        var towns = new[] { CollectionCatalog.TiberiasTown, CollectionCatalog.SafedTown, CollectionCatalog.NetanyaTown, CollectionCatalog.RamlaTown };
        TownLandmarks.Request = Answer(after ? Array.Empty<string>() : towns);
        yield return Boot(hebrew);
        var map = Object.FindFirstObjectByType<MapScene>();
        var foot = map.KitFootprints.First(f => f.id == town);
        var at = new Vector3(foot.centre.x, 0f, foot.centre.y);
        at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;
        const float distance = 50000f;
        Look(at, distance);
        for (int i = 0; i < 5; i++) { Camera.main.Render(); yield return null; }
        var landmarks = Object.FindFirstObjectByType<TownLandmarks>();
        string model = landmarks.Placed.Where(p => p.Key == town).Select(p => p.Model).FirstOrDefault() ?? "none";
        CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"town-{town}-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
        Debug.Log($"SHOT town {town} {(after ? "after" : "before")} at {at} from {distance:F0} m, footprint radius {foot.radius:F0} m: landmark {model}");
    }

    [UnityTest] public IEnumerator TownTiberiasBeforeEnglish() { yield return WholeTown(false, "tiberias", false); }
    [UnityTest] public IEnumerator TownTiberiasAfterEnglish() { yield return WholeTown(false, "tiberias", true); }
    [UnityTest] public IEnumerator TownTiberiasBeforeHebrew() { yield return WholeTown(true, "tiberias", false); }
    [UnityTest] public IEnumerator TownTiberiasAfterHebrew() { yield return WholeTown(true, "tiberias", true); }
    [UnityTest] public IEnumerator TownSafedBeforeEnglish() { yield return WholeTown(false, "safed", false); }
    [UnityTest] public IEnumerator TownSafedAfterEnglish() { yield return WholeTown(false, "safed", true); }
    [UnityTest] public IEnumerator TownSafedBeforeHebrew() { yield return WholeTown(true, "safed", false); }
    [UnityTest] public IEnumerator TownSafedAfterHebrew() { yield return WholeTown(true, "safed", true); }
    [UnityTest] public IEnumerator TownNetanyaBeforeEnglish() { yield return WholeTown(false, "netanya", false); }
    [UnityTest] public IEnumerator TownNetanyaAfterEnglish() { yield return WholeTown(false, "netanya", true); }
    [UnityTest] public IEnumerator TownNetanyaBeforeHebrew() { yield return WholeTown(true, "netanya", false); }
    [UnityTest] public IEnumerator TownNetanyaAfterHebrew() { yield return WholeTown(true, "netanya", true); }
    [UnityTest] public IEnumerator TownRamlaAfterEnglish() { yield return WholeTown(false, "ramla", true); }
    [UnityTest] public IEnumerator TownRamlaAfterHebrew() { yield return WholeTown(true, "ramla", true); }

    [UnityTest] public IEnumerator HousesNetanyaEnglish() { yield return Houses(false, "netanya"); }
    [UnityTest] public IEnumerator HousesNetanyaHebrew() { yield return Houses(true, "netanya"); }
    [UnityTest] public IEnumerator HousesTiberiasEnglish() { yield return Houses(false, "tiberias"); }
    [UnityTest] public IEnumerator HousesTiberiasHebrew() { yield return Houses(true, "tiberias"); }
    // Safed and Acre: the stone-village set at a named town, so the before and after frames are the same town (the village
    // picked by Houses(null) depends on the set).
    [UnityTest] public IEnumerator HousesSafedEnglish() { yield return Houses(false, "safed"); }
    [UnityTest] public IEnumerator HousesSafedHebrew() { yield return Houses(true, "safed"); }
    [UnityTest] public IEnumerator HousesAcreEnglish() { yield return Houses(false, "acre"); }
    [UnityTest] public IEnumerator HousesAcreHebrew() { yield return Houses(true, "acre"); }
    [UnityTest] public IEnumerator HousesVillageEnglish() { yield return Houses(false, null); }
    [UnityTest] public IEnumerator HousesVillageHebrew() { yield return Houses(true, null); }

    [UnityTest] public IEnumerator DeganiaBeforeEnglish() { yield return Degania(false, false); }
    [UnityTest] public IEnumerator DeganiaAfterEnglish() { yield return Degania(false, true); }
    [UnityTest] public IEnumerator DeganiaBeforeHebrew() { yield return Degania(true, false); }
    [UnityTest] public IEnumerator DeganiaAfterHebrew() { yield return Degania(true, true); }

    /// <summary>The Lebanese token's actual placed spot near Al-Malikiyya after the first turn (15 June
    /// 1948, inside the token's 6 June to 8 July window), from the unit zoom and from the closest zoom. The unit figures are
    /// answered with the editor's prefabs, as the player's stream would answer them. The admitted frame is a candidate-only diagnostic; a matched before requires this identical fixture and state.</summary>
    static void ObserveSubject(MapScene map, UnitLayer units, string stage, Vector3 target)
    {
        var camera = Camera.main;
        var policy = map.Residency.Units;
        bool ground = CollectionResidencyView.TryGroundFocus(camera, out var focus);
        var token = map.Terrain.transform.Find(UnitLayer.RootName + "/Tokens/lebanese_army");
        Debug.Log($"MODEL-OBS {stage} frame={Time.frameCount} token={token != null} active={units.gameObject.activeInHierarchy} arrived={UnitFigures.Arrived(UnitFigures.LebaneseRegular)} version={UnitFigures.AvailabilityVersion} targetVP={camera.WorldToViewportPoint(target).ToString("R")} ground={ground}:{focus.ToString("R")} view={Statecraft.Game.Map.Kits.TownModelLayer.ViewDistance(camera)} policy={policy.EnterM}/{policy.ExitM}/{policy.ViewEnterM}/{policy.ViewExitM} mask={camera.cullingMask} clip={camera.nearClipPlane}/{camera.farClipPlane}");
        foreach (var demand in units.GetComponentsInChildren<UnitFigureResidency>(true).Where(o => o.name.StartsWith("Original demand lebanese_army|", StringComparison.Ordinal)))
            Debug.Log($"MODEL-OBS {stage} prefetch={demand.name} position={demand.transform.position.ToString("R")} focusDistance={Vector2.Distance(new Vector2(focus.x, focus.z), new Vector2(demand.transform.position.x, demand.transform.position.z))} snapshot={JsonUtility.ToJson(demand.ResidencySnapshot())}");
        if (token == null) return;
        var planes = GeometryUtility.CalculateFrustumPlanes(camera);
        foreach (var owner in token.GetComponentsInChildren<UnitFigureResidency>(true))
        {
            var piece = owner.transform;
            var model = piece.Find(UnitFigures.ModelName);
            Debug.Log($"MODEL-OBS {stage} piece={piece.name} position={piece.position.ToString("R")} scale={piece.lossyScale.ToString("R")} dressed={UnitFigures.Dressed(piece)} model={model != null}");
            if (model == null) continue;
            foreach (var renderer in model.GetComponentsInChildren<Renderer>(true))
                Debug.Log($"MODEL-OBS {stage} renderer={renderer.name} enabled={renderer.enabled} off={renderer.forceRenderingOff} active={renderer.gameObject.activeInHierarchy} layer={renderer.gameObject.layer} inMask={(camera.cullingMask & (1 << renderer.gameObject.layer)) != 0} bounds={renderer.bounds.center.ToString("R")}/{renderer.bounds.size.ToString("R")} frustum={GeometryUtility.TestPlanesAABB(planes, renderer.bounds)} visible={renderer.isVisible} materials={string.Join(",", renderer.sharedMaterials.Select(m => m == null ? "null" : m.name + ":" + m.shader.name))}");
        }
    }

    IEnumerator Malikiyya(bool hebrew)
    {
        UnitFigures.Source = (id, detail, done) => done(Prefab(id, detail));
        yield return Boot(hebrew);
        root.Bridge!.EndTurn();
        for (int i = 0; i < 3; i++) yield return null;
        var ui = Object.FindFirstObjectByType<UIDocument>().rootVisualElement;
        var close = ui.Q<Button>("turn-report-close");
        if (close != null && close.resolvedStyle.display == DisplayStyle.Flex) UiTestKit.Press(close);
        // The new turn opens a decision card over the map; the player's Hide button puts it away, and the card shrinks away.
        var card = ui.Q("event-card");
        Assert.IsNotNull(card, "the event card");
        if (card.resolvedStyle.display == DisplayStyle.Flex) UiTestKit.Press(ui.Q<Button>("event-hide"));
        for (int i = 0; i < 120 && card.resolvedStyle.display != DisplayStyle.None; i++) yield return null;
        Assert.AreEqual(DisplayStyle.None, card.resolvedStyle.display, "the decision card is hidden before the frame");
        var subjects = root.Units!.Tokens.Where(t => t.Token.Unit.Id == "lebanese_army").ToArray();
        Assert.AreEqual(1, subjects.Length, "capture precondition: exactly one actual Lebanese army token");
        Assert.IsTrue(UnitFigures.Arrived(UnitFigures.LebaneseRegular), "capture precondition: the Lebanese original has arrived");
        var subject = subjects[0];
        int q = subject.Q, r = subject.R;
        var map = Object.FindFirstObjectByType<MapScene>();
        var target = new Vector3((float)subject.Spot.X, 0f, (float)subject.Spot.Z);
        target.y = map.Terrain.SampleHeight(target) + map.Terrain.transform.position.y;
        var demands = root.Units!.GetComponentsInChildren<UnitFigureResidency>(true)
            .Where(o => o.name.StartsWith("Original demand lebanese_army|", StringComparison.Ordinal)).ToArray();
        Assert.AreEqual(1, demands.Length, "capture precondition: one real Lebanese source-prefetch holder");
        var prefetch = demands[0];
        var here = root.Units!.Tokens.Where(t => t.Q == q && t.R == r).Select(t => $"{t.Token.Unit.Id} ({t.Token.ArtType})").ToList();
        foreach (var (what, distance) in new[] { ("unit", 40000f), ("admitted", 24000f), ("close", CameraController.MinDistance) })
        {
            if (what == "admitted")
            {
                var anchor = prefetch.transform.position;
                Assert.Less(Vector2.Distance(new Vector2(anchor.x, anchor.z), new Vector2(target.x, target.z)),
                    2f * map.Residency.Units.EnterM, "one real focus must be able to admit both anchors");
                var middle = new Vector3((anchor.x + target.x) * .5f, 0f, (anchor.z + target.z) * .5f);
                Look(middle, distance);
                // This south-facing admitted frame is checked against all original figure corners below the top bar.
                Camera.main.GetComponent<CameraRig>().Yaw = 180f;
                Camera.main.GetComponent<CameraRig>().Apply();
                Assert.IsTrue(CollectionResidencyView.TryGroundFocus(Camera.main, out var measured));
                var rig = Camera.main.GetComponent<CameraRig>();
                // The UI inset shifts the centre ray. Pan the real rig so its ground focus, not just LookAt, is the midpoint.
                rig.LookAt += new Vector3(middle.x - measured.x, 0f, middle.z - measured.z);
                rig.Apply();
            }
            else Look(target, distance);
            for (int i = 0; i < 5; i++) yield return null;
            if (what == "admitted")
            {
                Assert.Less(Statecraft.Game.Map.Kits.TownModelLayer.ViewDistance(Camera.main), map.Residency.Units.ViewEnterM,
                    "capture control requires a view inside the approved enter band");
                Assert.IsTrue(CollectionResidencyView.TryGroundFocus(Camera.main, out var focus));
                Assert.Less(Vector2.Distance(new Vector2(focus.x, focus.z), new Vector2(target.x, target.z)), map.Residency.Units.EnterM,
                    "capture control requires the actual placed subject inside the approved enter radius");
                Assert.Less(Vector2.Distance(new Vector2(focus.x, focus.z), new Vector2(prefetch.transform.position.x, prefetch.transform.position.z)), map.Residency.Units.EnterM,
                    "capture control requires the source-prefetch anchor inside the approved enter radius");
                var camera = Camera.main;
                var frame = new RenderTexture(CivMovementShots.Width, CivMovementShots.Height, 24, RenderTextureFormat.ARGB32);
                var previous = camera.targetTexture;
                bool Ready() => prefetch != null && prefetch.ResidencySnapshot().ownedLeases > 0
                    && UnitFigures.Arrived(UnitFigures.LebaneseRegular)
                    && map.Terrain.transform.Find(UnitLayer.RootName + "/Tokens/lebanese_army") != null;
                int renders = 0;
                try
                {
                    // Use the real render callbacks to re-admit the original after the deliberately out-of-band frame.
                    for (; renders < 30; renders++)
                    {
                        camera.targetTexture = frame; camera.Render(); camera.targetTexture = previous;
                        yield return null;
                        if (Ready()) break;
                    }
                    ObserveSubject(map, root.Units, "admitted primed", target);
                    Assert.IsTrue(Ready(), $"source, lease and token must be ready after at most 30 real renders ({renders + 1})");
                    camera.targetTexture = frame; camera.Render(); camera.targetTexture = previous;
                    yield return null;
                    Assert.IsTrue(Ready(), "admitted readiness must survive another real render");
                }
                finally { camera.targetTexture = previous; frame.Release(); Object.DestroyImmediate(frame); }
                var viewport = camera.WorldToViewportPoint(target);
                Assert.IsTrue(viewport.z > 0f && viewport.x > 0f && viewport.x < 1f && viewport.y > 0f
                    && viewport.y < 1f - Mathf.Clamp(camera.GetComponent<CameraRig>().TopInset, 0f, CameraRig.MaxTopInset),
                    "the admitted subject is inside the map viewport below the top bar");
                Assert.AreEqual((float)CivMovementShots.Width / CivMovementShots.Height, camera.aspect, 0.0001f,
                    "viewport checks and saved capture must use the same aspect ratio");
                var live = map.Terrain.transform.Find(UnitLayer.RootName + "/Tokens/lebanese_army");
                Assert.IsNotNull(live, "the admitted token remains live before whole-model projection");
                var owners = live.GetComponentsInChildren<UnitFigureResidency>(true);
                Assert.GreaterOrEqual(owners.Length, 3, "three distinct original figure owners must be framed");
                foreach (var owner in owners)
                {
                    Assert.Greater(owner.ResidencySnapshot().ownedLeases, 0, "each visible figure owns its admitted original lease");
                    var model = owner.transform.Find(UnitFigures.ModelName);
                    Assert.IsNotNull(model, "each original is dressed");
                    Assert.Greater(model.childCount, 0);
                    StringAssert.StartsWith(UnitFigures.LebaneseRegular, model.GetChild(0).name, "the actual Lebanese original");
                    Assert.IsTrue(model.GetComponentsInChildren<Renderer>(true)
                        .Any(r => r.enabled && !r.forceRenderingOff && r.gameObject.activeInHierarchy),
                        "each distinct figure has a live visible original renderer");
                }
                var visible = owners.Select(o => o.transform.Find(UnitFigures.ModelName))
                    .SelectMany(m => m.GetComponentsInChildren<Renderer>(true))
                    .Where(r => r.enabled && !r.forceRenderingOff && r.gameObject.activeInHierarchy).ToArray();
                foreach (var renderer in visible)
                {
                    var box = renderer.bounds;
                    for (int corner = 0; corner < 8; corner++)
                    {
                        var point = camera.WorldToViewportPoint(new Vector3((corner & 1) == 0 ? box.min.x : box.max.x,
                            (corner & 2) == 0 ? box.min.y : box.max.y, (corner & 4) == 0 ? box.min.z : box.max.z));
                        Assert.IsTrue(point.z > 0f && point.x > 0f && point.x < 1f && point.y > 0f
                            && point.y < 1f - Mathf.Clamp(camera.GetComponent<CameraRig>().TopInset, 0f, CameraRig.MaxTopInset),
                            $"whole original figure {renderer.name} corner {corner} must be visible below the top bar: {point}");
                    }
                }
                Debug.Log($"MODEL-OBS admitted readiness renders={renders + 2} viewport={viewport.ToString("R")}");
                Assert.IsTrue(UnitFigures.Arrived(UnitFigures.LebaneseRegular), "the admitted source is ready before the frame");
                Assert.Greater(prefetch.ResidencySnapshot().ownedLeases, 0, "the source-prefetch holder owns its admitted lease");
                Assert.IsNotNull(map.Terrain.transform.Find(UnitLayer.RootName + "/Tokens/lebanese_army"),
                    "the admitted token exists before the frame");
            }
            ObserveSubject(map, root.Units, what + " before", target);
            CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"malikiyya-{what}-{(hebrew ? "he" : "en")}"));
            ObserveSubject(map, root.Units, what + " after", target);
            if (what == "admitted")
            {
                var live = map.Terrain.transform.Find(UnitLayer.RootName + "/Tokens/lebanese_army");
                Assert.IsNotNull(live, "admitted model capture must retain its actual Lebanese token after render");
                var models = live!.GetComponentsInChildren<UnitFigureResidency>(true)
                    .Where(o => o.transform.Find(UnitFigures.ModelName) != null).ToArray();
                Assert.GreaterOrEqual(models.Length, 3, "admitted model capture must retain all three original figures after render");
            }
            Debug.Log($"SHOT malikiyya {what} on {root.Bridge.State.Date:yyyy-MM-dd} hex {q},{r} from {distance:F0} m, target {target.ToString("R")} camera {Camera.main.transform.position.ToString("R")} rotation {Camera.main.transform.rotation.ToString("R")}, event card display {card.resolvedStyle.display}: tokens [{string.Join(", ", here)}]");
        }
    }

    /// <summary>#1932 (c): the Egyptian Spitfire in flight near the western board edge (30 km in) toward el-Arish on the opening turn (15 May
    /// 1948, the first sourced Spitfire raid), close (the closest zoom), at a gameplay zoom and in an overview of the southern
    /// coast. "Before" withholds the Spitfire. Each shot is the player's camera (CameraRig.Pitch, yaw 0) aimed at the ground
    /// under the plane and held on the map as CameraController.Step holds it, so it shows what a player sees (#2014).</summary>
    IEnumerator Spitfire(bool hebrew, bool after)
    {
        var savedCraft = SeaAirCollection.Request;
        try
        {
            yield return Boot(hebrew);
            var map = Object.FindFirstObjectByType<MapScene>();
            var state = root.Bridge!.State; var content = root.Bridge.Content;
            SeaAirCollection.Request = Answer(Array.Empty<string>());
            Drop(map, SeaAirCollection.Name);
            var layer = CollectionGeometryFixture.Craft(map, state.Date, state.Placements, content)!;
            var plane = layer.Placed.Single(p => p.Model == SeaAirCollection.Spitfire);
            if (!after)
            {
                SeaAirCollection.Request = Answer(new[] { SeaAirCollection.Spitfire });
                Drop(map, SeaAirCollection.Name);
                layer = CollectionGeometryFixture.Craft(map, state.Date, state.Placements, content)!;
            }
            Debug.Log($"SHOT spitfire {(after ? "after" : "before")} on {state.Date:yyyy-MM-dd}: drawn {layer.Placed.Count(p => p.Model == SeaAirCollection.Spitfire)}, at {plane.At}, span {SeaAirCollection.SizeOf(SeaAirCollection.Spitfire)} m");
            var rig = Camera.main.GetComponent<CameraRig>(); var cc = rig.GetComponent<CameraController>();
            foreach (var (what, distance) in new[] { ("close", CameraController.MinDistance), ("gameplay", 40000f), ("overview", 150000f) })
            {
                var under = new Vector3(plane.At.x, 0f, plane.At.z);   // the player's look-at is on y = 0, lifted by Step
                Look(under, distance);
                CameraController.Step(rig, default, 0f, cc.Bounds, cc.Ground, cc.GroundTop, true);
                for (int i = 0; i < 5; i++) yield return null;
                CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"spitfire-{what}-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
                var vp = Camera.main.WorldToViewportPoint(plane.At);
                Debug.Log($"SHOT spitfire {what} from {distance:F0} m, look-at {rig.LookAt} (asked {under}), camera {Camera.main.transform.position}, plane at viewport {vp}");
            }
        }
        finally { SeaAirCollection.Request = savedCraft; }
    }

    /// <summary>#2082: Tal's papyrus at the Hula swamp (site hula, hex (16, 3)) on the opening turn, from the closest zoom the
    /// player can reach, the camera on the middle of the stands. "Before" withholds the model (#2271's map: no papyrus layer
    /// draws anything without it); "after" answers it with the editor's prefab, as the papyrus bundle would.</summary>
    IEnumerator Hula(bool hebrew, bool after)
    {
        var saved = HulaPapyrusLayer.Request;
        try
        {
            yield return Boot(hebrew);
            var map = Object.FindFirstObjectByType<MapScene>();
            var state = root.Bridge!.State; var content = root.Bridge.Content;
            HulaPapyrusLayer.Request = (id, detail, done) =>
                done(after ? AssetDatabase.LoadAssetAtPath<GameObject>(Statecraft.HexTiles.HexProps.PrefabPath(id)) : null);
            Drop(map, HulaPapyrusLayer.Name);
            var layer = HulaPapyrusLayer.ShowAt(map, content, HulaPapyrusLayer.Drained(state))!;
            var wants = HulaPapyrusLayer.Wants(map, content);
            Assert.IsNotEmpty(wants, "the Hula's clumps");
            var sum = Vector2.zero; foreach (var w in wants) sum += w.At;
            var at = new Vector3(sum.x / wants.Count, 0f, sum.y / wants.Count);
            at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;
            Look(at, CameraController.MinDistance);
            // An EditMode scene does not enable the layer's render callback, so the close-zoom switch is set as that callback
            // sets it for this camera: the view distance against the layer's own band.
            float view = TownLandmarks.ViewDistance(Camera.main);
            Assert.IsTrue(HulaPapyrusLayer.CloseAt(view, null), $"the closest zoom is close ({view:F0} m)");
            layer.SetClose(true);
            for (int i = 0; i < 5; i++) { Camera.main.Render(); yield return null; }
            CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"hula-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
            Debug.Log($"SHOT hula {(after ? "after" : "before")} on {state.Date:yyyy-MM-dd} at {at} from {CameraController.MinDistance:F0} m: wanted {layer.Wanted}, placed {layer.Placed.Count}, close {layer.LastClose}, clump {HulaPapyrusLayer.ClumpM:F1} m");
        }
        finally { HulaPapyrusLayer.Request = saved; }
    }

    [UnityTest] public IEnumerator HulaBeforeEnglish() { yield return Hula(false, false); }
    [UnityTest] public IEnumerator HulaAfterEnglish() { yield return Hula(false, true); }
    [UnityTest] public IEnumerator HulaBeforeHebrew() { yield return Hula(true, false); }
    [UnityTest] public IEnumerator HulaAfterHebrew() { yield return Hula(true, true); }

    [UnityTest] public IEnumerator SpitfireBeforeEnglish() { yield return Spitfire(false, false); }
    [UnityTest] public IEnumerator SpitfireAfterEnglish() { yield return Spitfire(false, true); }

    /// <summary>The owner's report of 2 November 2026 ("the gyptian plane's propelor isn't moving and it doesnt look fliying,
    /// also it doesnt show its an egyptian unit"): the Spitfire on the opening turn from the player's camera (CameraRig.Pitch,
    /// yaw 0), at the camera's opening distance and at 30 km, the look-at on the ground along the view ray through the plane
    /// so the plane is mid-frame. Poses come from SpitfireLoop.Place, as play draws them: 0 s (the pass in from el-Arish,
    /// straight), 10 s (the turn at the loop's east end, where the camera sees the propeller's disc face on), and each 0.02 s
    /// later (the propeller's turn between two frames). The same
    /// test on the base branch gives the "before" stills, on the PR branch the "after" ones (spitfire-flight-shots).</summary>
    IEnumerator SpitfireFlight(bool hebrew)
    {
        var savedCraft = SeaAirCollection.Request;
        try
        {
            Directory.CreateDirectory(Path.Combine(CivMovementShots.ShotDir, "..", "spitfire-flight-shots"));
            yield return Boot(hebrew);
            var map = Object.FindFirstObjectByType<MapScene>();
            var state = root.Bridge!.State; var content = root.Bridge.Content;
            SeaAirCollection.Request = Answer(Array.Empty<string>());
            Drop(map, SeaAirCollection.Name);
            var layer = CollectionGeometryFixture.Craft(map, state.Date, state.Placements, content)!;
            var plane = layer.transform.Find("el-arish-spitfire");
            var loop = plane.GetComponent<SpitfireLoop>();
            var rig = Camera.main.GetComponent<CameraRig>(); var cc = rig.GetComponent<CameraController>();
            float opening = rig.Distance;
            Debug.Log($"SHOT spitfire-flight on {state.Date:yyyy-MM-dd}: opening distance {opening:F0} m, loop centre {layer.Placed.Single(p => p.Model == SeaAirCollection.Spitfire).At}");
            var down = Quaternion.Euler(CameraRig.Pitch, 0f, 0f) * Vector3.forward;
            foreach (var (zoom, distance) in new[] { ("opening", opening), ("close", 30000f) })
                foreach (var (pose, seconds) in new[] { ("pass", 0f), ("pass-later", 0.02f), ("turn", 10f), ("turn-later", 10.02f) })
                {
                    if (zoom == "opening" && pose.EndsWith("-later")) continue;   // the propeller is a few pixels at the opening zoom
                    loop.Place(seconds);
                    var at = plane.GetComponentsInChildren<Renderer>(true).Select(r => r.bounds).Aggregate((a, b) => { a.Encapsulate(b); return a; }).center;
                    // The ground point on the view ray through the plane: the player's look-at that puts it mid-frame.
                    var ground = at + down * ((map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y - at.y) / down.y);
                    Look(new Vector3(ground.x, 0f, ground.z), distance);
                    CameraController.Step(rig, default, 0f, cc.Bounds, cc.Ground, cc.GroundTop, true);
                    UnitFlagFacing.FaceAll(Camera.main.transform.position);
                    for (int i = 0; i < 5; i++) yield return null;
                    loop.Place(seconds);   // again after the frames: nothing else moves it in edit mode, but the shot must be exact
                    CivMovementShots.Shot(rt!, Path.Combine("..", "spitfire-flight-shots", $"spitfire-{zoom}-{pose}-{(hebrew ? "he" : "en")}"));
                    Debug.Log($"SHOT spitfire-flight {zoom} {pose}: {distance:F0} m, plane at {at}, viewport {Camera.main.WorldToViewportPoint(at)}");
                    var vp = Camera.main.WorldToViewportPoint(at);
                    Assert.That(vp.x, Is.InRange(0.1f, 0.9f), $"the plane in frame across, {zoom} {pose}");
                    Assert.That(vp.y, Is.InRange(0.1f, 0.9f), $"the plane in frame up and down, {zoom} {pose}");
                }
        }
        finally { SeaAirCollection.Request = savedCraft; }
    }

    [UnityTest] public IEnumerator SpitfireFlightEnglish() { yield return SpitfireFlight(false); }
    [UnityTest] public IEnumerator SpitfireFlightHebrew() { yield return SpitfireFlight(true); }

    [UnityTest] public IEnumerator MalikiyyaEnglish() { yield return Malikiyya(false); }
    [UnityTest] public IEnumerator MalikiyyaHebrew() { yield return Malikiyya(true); }

    [UnityTest] public IEnumerator BedouinBeforeEnglish() { yield return Bedouin(false, false); }
    [UnityTest] public IEnumerator BedouinAfterEnglish() { yield return Bedouin(false, true); }
    [UnityTest] public IEnumerator BedouinBeforeHebrew() { yield return Bedouin(true, false); }
    [UnityTest] public IEnumerator BedouinAfterHebrew() { yield return Bedouin(true, true); }

    /// <summary>Tal Heuberger's hex-tile props on the main map (owner, 27 October 2026, "2+3"; 2 November 2026: his models replace
    /// the kit's minarets, belfries and clock tower, a hedge row per village, a light hill scatter). Frames: Binyamina's station,
    /// the first Bedouin camp's tent, the first village's hedge row, the first hill hex's garrigue, the first village minaret and
    /// Jaffa's clock tower, a village mosque's minaret and St Peter's belfry, each from the closest zoom, from the gameplay zoom (60 km, where the kit's far parts draw) for the
    /// landmarks, and from the opening zoom (250 km). The town models are answered, so up close the close meshes draw.
    /// "Before" is main's map: the layer withheld (the kit's own parts come back) and its tree holes given back. The frames
    /// come from the map with the props, so they are the same before and after.</summary>
    IEnumerator HexPropShots(bool hebrew, bool after)
    {
        yield return Boot(hebrew);
        var map = Object.FindFirstObjectByType<MapScene>();
        TownModelLayer.ModelAcquire = (id, detail, done) => { done(Prefab(id, detail)); return new NoLease(); };
        HexPropModels.Request = (id, done) => done(AssetDatabase.LoadAssetAtPath<GameObject>(HexProps.PrefabPath(id)));
        Drop(map, HexPropModels.Name);
        var layer = HexPropModels.ShowAt(map, root.Bridge!.State.Date)!;
        Look(layer.transform.position, CameraController.MinDistance);
        layer.Choose(default, Camera.main);
        Assert.IsTrue(layer.Requested, "the camera asked for the props");
        var parts = map.KitStats.LandmarkParts;
        var minaret = parts.First(p => p.Kind == "minaret" && p.Close != null);
        var clock = parts.Single(p => p.Kind == "clock_tower");
        // #2266 review C7: a village mosque's roof-mounted minaret and St Peter's belfry, up close.
        var villages = new HashSet<string>(map.Localities.Select(p => p.Settlement).Where(s => s.Type == "village").Select(s => s.Id));
        var village = parts.First(p => p.Kind == "minaret" && p.Close != null && villages.Contains(p.Owner));
        var belfry = parts.Single(p => p.Kind == "belfry" && p.Owner == "jaffa");
        Vector3 Up(Bounds b) => new Vector3(b.center.x, 0f, b.center.z);
        var close = CameraController.MinDistance; const float Gameplay = 60000f; var opening = CameraController.MaxDistance;
        var frames = new List<(string what, string key, Vector3 at, float[] zooms)>
        {
            ("station", "station:Binyamina railway station", layer.Placed.First(p => p.Key == "station:Binyamina railway station").At, new[] { close, opening }),
            ("tent", layer.Placed.First(p => p.Model == HexPropModels.Tent).Key, layer.Placed.First(p => p.Model == HexPropModels.Tent).At, new[] { close, opening }),
            ("hedge", layer.Placed.First(p => p.Model == HexPropModels.PricklyPear).Key, layer.Placed.First(p => p.Model == HexPropModels.PricklyPear).At, new[] { close, opening }),
            ("scatter", layer.Placed.First(p => p.Model == HexPropModels.Garrigue).Key, layer.Placed.First(p => p.Model == HexPropModels.Garrigue).At, new[] { close, opening }),
            ("minaret", minaret.Owner, Up(minaret.Near), new[] { close, Gameplay, opening }),
            ("clocktower", clock.Owner, Up(clock.Near), new[] { close, Gameplay, opening }),
            ("villagemosque", village.Owner, Up(village.Near), new[] { close }),
            ("belfry", belfry.Owner, Up(belfry.Near), new[] { close }),
        };
        Debug.Log($"SHOT hexprops {(after ? "after" : "before")}: {layer.Placed.Count} placed, {layer.Replaced.Count} landmark models: " +
                  string.Join(", ", HexPropModels.Standalone.Select(m => $"{m} {layer.Placed.Count(p => p.Model == m)}")));
        if (!after)
        {
            HexPropModels.Request = (id, done) => { };   // main streams no prop for the map
            Drop(map, HexPropModels.Name);
            UnitShowcase.HideTrees(map, HexPropModels.Name, Array.Empty<(Vector2, float)>());
        }
        foreach (var (what, key, flat, zooms) in frames)
            foreach (var distance in zooms)
            {
                string zoom = distance == close ? "close" : distance == Gameplay ? "gameplay" : "opening";
                var at = flat;
                at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;
                Look(at, distance);
                var shown = map.Terrain.transform.Find(HexPropModels.Name)?.GetComponent<HexPropModels>();
                if (shown != null) shown.Choose(default, Camera.main);
                for (int i = 0; i < 4; i++) { Camera.main.Render(); yield return null; }
                CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"hexprops-{what}-{zoom}-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));
                Debug.Log($"SHOT hexprops {what} {key} at {at} from {distance:F0} m ({zoom}), standalone drawn {shown != null && shown.LastClose}, landmark models {shown?.Replaced.Count ?? 0}");
            }
    }

    [UnityTest] public IEnumerator HexPropsBeforeEnglish() { yield return HexPropShots(false, false); }
    [UnityTest] public IEnumerator HexPropsAfterEnglish() { yield return HexPropShots(false, true); }
    [UnityTest] public IEnumerator HexPropsBeforeHebrew() { yield return HexPropShots(true, false); }
    [UnityTest] public IEnumerator HexPropsAfterHebrew() { yield return HexPropShots(true, true); }
}