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.

43.0 KB
Raw Blame
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game;
using Statecraft.Game.Map;
using Statecraft.Game.Map.Units;
using Statecraft.Game.UI;
using Statecraft.Sim;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.TestTools.Constraints;
using UnityEngine.UIElements;
using Is = UnityEngine.TestTools.Constraints.Is;

/// <summary>GDD Phase 5 PR 14 (#753; impact plan §2.6): in the GDD loop the map's army tokens come from the sim's units
/// (GameState.Units), one per unit on its sim hex, and a token's figures follow Q-UI-3, not the call-up. The squadron and
/// the ships stay tokens drawn from their rows (Q-UNIT-5).</summary>
public class UnitsFromStateTests
{
    static readonly Content C = ContentLoader.Load(Paths.Content);
    static List<UnitEntry> Units => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
    static GameState NewGame() => Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
    static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);

    /// <summary>A moved unit's anchor as the layer makes it: the hex's centre, made once per row and hex.</summary>
    sealed class Moved
    {
        public readonly Dictionary<(string, int, int), UnitAnchor> Made = new Dictionary<(string, int, int), UnitAnchor>();
        public UnitAnchor At(UnitEntry row, UnitAnchor start, int q, int r)
        {
            if (!Made.TryGetValue((row.Id, q, r), out var a))
            {
                var h = C.HexAt(q, r)!;
                Made[(row.Id, q, r)] = a = new UnitAnchor { Lon = h.Lon, Lat = h.Lat, From = start.From, To = start.To };
            }
            return a;
        }
    }

    static List<UnitToken> Army(List<UnitToken> tokens) => tokens.Where(t => t.Unit.Service == UnitData.Army).ToList();

    /// <summary>A land hex next to (q, r) that holds no unit.</summary>
    static (int q, int r) FreeNeighbour(GameState s, int q, int r)
    {
        foreach (var (dq, dr) in new[] { (1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1) })
        {
            var h = C.HexAt(q + dq, r + dr);
            if (h != null && h.Land && !s.Units.Values.Any(u => u.Q == h.Q && u.R == h.R)) return (h.Q, h.R);
        }
        throw new InvalidOperationException($"no free land hex next to ({q},{r})");
    }

    static void MoveTo(GameState s, int id, int q, int r)
    {
        var u = s.Units[id];
        s.Units[id] = new Unit(u.Id, u.Type, q, r, u.Service, u.Side, u.Strength, u.Order, u.OrderTarget);
    }

    [Test]
    public void OneTokenPerUnitOnItsHex()
    {
        Assert.IsTrue(C.IsGdd, "the real content runs the GDD loop");
        var s = NewGame();
        var units = Units;
        var moved = new Moved();
        var drawn = s.Units.Values.Where(u => u.Side != "" && UnitRoster.OnMap(units.Single(e => e.Id == C.StartingForces[u.Id].Row))).ToList();
        Assert.Greater(drawn.Count, 0);
        var army = Army(UnitRoster.FromState(units, C, s, _ => true, moved.At));
        CollectionAssert.AreEquivalent(drawn.Select(u => C.StartingForces[u.Id].Row), army.Select(t => t.Unit.Id), "one token per drawn unit");
        Assert.AreEqual(army.Count, army.Select(t => t.Unit.Id).Distinct().Count());
        var hexes = MapBuilder.LoadHexes(Path.Combine(Paths.Content, "map", "hexes.json"));
        foreach (var u in drawn)
        {
            var t = army.Single(x => x.Unit.Id == C.StartingForces[u.Id].Row);
            var picked = HexPicker.FromLonLat(t.Anchor.Lon, t.Anchor.Lat, hexes.bounds, hexes.hex_size_km);
            // tools/unit_anchor_hexes.py moves two kinds of anchor to a land neighbour (#1183): one in a water hex (Haifa's
            // point on the 4.4 km grid, hexgrid.settlement_hex) and an enemy's on a settlement's hex (the Syrian Army's start
            // on Degania Alef's, the owner's nearest-free-neighbour rule).
            if ((u.Q, u.R) != picked)
                Assert.IsTrue((!hexes.hexes.Single(h => (h.q, h.r) == picked).land || (u.Side != "israel" && C.SettlementHexes.Any(x => (x.Q, x.R) == picked)))
                    && MapActions.Distance(u.Q, u.R, picked.q, picked.r) == 1 && hexes.hexes.Single(h => (h.q, h.r) == (u.Q, u.R)).land,
                    $"{t}: the sim hex: {(u.Q, u.R)} is a land neighbour of the anchor's water or settlement hex {picked}");
            Assert.AreEqual(C.StartingForces[u.Id].Anchor, t.Anchor.Place, $"{t}: unmoved, it stands on its starting anchor");
        }
        Assert.IsEmpty(moved.Made, "no unit moved, so no moved anchor");
        // Grouped per hex: the army tokens come in (q, r) order.
        var order = army.Select(t => drawn.Single(u => C.StartingForces[u.Id].Row == t.Unit.Id)).Select(u => (u.Q, u.R)).ToList();
        CollectionAssert.AreEqual(order.OrderBy(h => h.Q).ThenBy(h => h.R).ToList(), order);

        // A unit that moves is drawn on its new hex, once, and a halutz draws nothing.
        var first = drawn[0];
        var to = FreeNeighbour(s, first.Q, first.R);
        MoveTo(s, first.Id, to.q, to.r);
        s.Units.Add(s.NextId, new Unit(s.NextId, "halutz", first.Q, first.R)); s.NextId++;
        army = Army(UnitRoster.FromState(units, C, s, _ => true, moved.At));
        Assert.AreEqual(drawn.Count, army.Count, "still one token per unit; the halutz has none");
        var mt = army.Single(t => t.Unit.Id == C.StartingForces[first.Id].Row);
        Assert.AreSame(moved.Made.Values.Single(), mt.Anchor, "the moved unit takes its moved anchor");
        Assert.AreEqual(to, HexPicker.FromLonLat(mt.Anchor.Lon, mt.Anchor.Lat, hexes.bounds, hexes.hex_size_km));
        Assert.AreEqual("", mt.Anchor.Place, "no source names the hex it moved to");
        // The squadron and the ships are still the rows' tokens.
        var late = NewGame(); late.Date = new DateTime(1948, 6, 1);
        var rows = UnitRoster.Build(units, C, late, _ => true).Where(t => t.Unit.Service != UnitData.Army).ToList();
        Assert.IsNotEmpty(rows);
        CollectionAssert.AreEqual(rows, UnitRoster.FromState(units, C, late, _ => true, moved.At).Where(t => t.Unit.Service != UnitData.Army).ToList());
    }

    [TestCase(6, 6, 3)]
    [TestCase(4, 6, 3)]
    [TestCase(3, 6, 2)]
    [TestCase(2, 6, 2)]
    [TestCase(1, 6, 1)]
    [TestCase(1, 1, 3)]
    [TestCase(1, 2, 2)]
    [TestCase(1, 4, 1)]
    public void FiguresFollowTheAnswerAtEveryStrength(int strength, int full, int figures) =>
        Assert.AreEqual(figures, UnitRoster.FiguresForStrength(strength, full), "Q-UI-3: 3 at two thirds or more, 2 at a third or more, 1 below");

    /// <summary>Q-UI-3 on the map: a new game draws every unit at full strength with three figures whatever the call-up,
    /// and a unit that lost strength shows it.</summary>
    [Test]
    public void FiguresFollowTheAnswer()
    {
        var s = NewGame();
        s.Mobilization = 0; s.Rung = 1;   // the call-up no longer sets the figures (legacy: 1 figure here)
        var units = Units;
        var moved = new Moved();
        var army = Army(UnitRoster.FromState(units, C, s, _ => true, moved.At));
        Assert.IsNotEmpty(army);
        foreach (var t in army) Assert.AreEqual(3, t.Figures, $"{t}: full strength");
        var big = s.Units.Values.Where(u => u.Side == "israel").OrderByDescending(u => u.Strength).ThenBy(u => u.Id).First();
        Assert.AreEqual(4, big.Strength, "the largest brigades start at 4 units (docs/units.md, the starting forces; #1240)");
        var row = C.StartingForces[big.Id].Row;
        foreach (var (strength, figures) in new[] { (4, 3), (3, 3), (2, 2), (1, 1) })
        {
            var u = s.Units[big.Id];
            s.Units[big.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, strength, u.Order, u.OrderTarget);
            var t = Army(UnitRoster.FromState(units, C, s, _ => true, moved.At)).Single(x => x.Unit.Id == row);
            Assert.AreEqual(figures, t.Figures, $"{row} at {strength} of 4");
            Assert.AreEqual(figures, t.Headgear.Count, "one headgear per figure");
        }
    }

    /// <summary>A unit that moved stands on a hex no source names: its card gives no position and the row's sources.</summary>
    [Test]
    public void AMovedUnitsCardNamesNoPlaceAndGivesTheRowsSources()
    {
        var text = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
        var s = NewGame();
        var u = s.Units.Values.First(x => x.Side == "israel");
        var to = FreeNeighbour(s, u.Q, u.R);
        MoveTo(s, u.Id, to.q, to.r);
        var row = C.StartingForces[u.Id].Row;
        var t = Army(UnitRoster.FromState(Units, C, s, _ => true, new Moved().At)).Single(x => x.Unit.Id == row);
        var card = UnitCard.For(new PlacedToken(t, default), s, text);
        var start = UnitRoster.AnchorAt(t.Unit, C.Rules.Start)!;
        var position = string.IsNullOrWhiteSpace(start.Since) ? text.Format("unit.position_plain", start.Place) : text.Format("unit.position", start.Place, start.Since!);
        var home = UnitCard.For(new PlacedToken(new UnitToken(t.Unit, start, 3, t.ArtType, false), default), s, text);
        CollectionAssert.Contains(home.Body.Split('\n'), position, "on its starting anchor the card names the place");
        CollectionAssert.DoesNotContain(card.Body.Split('\n'), position, "no position line for a hex no source names");
        foreach (var host in t.Unit.AllSources().Select(x => new Uri(x.Url).Host)) StringAssert.Contains(host, card.Footer);
        // #2918 P2: a fact-checked row says a person checked it (no starting row has a source checked after its checked_on:
        // ReleaseGate.StartingForcesUnchecked, #2722); any other row keeps the draft note, by the row's sources off a sourced hex.
        Assert.AreEqual(t.Unit.Status == "fact-checked" ? text["unit.fact_checked"]
            : UnitData.IsWikipediaOnly(t.Unit) ? text["unit.draft_wikipedia"] : text["unit.draft"], card.Note, row);
    }

    static Unit Raise(GameState s, string type = "recruit", int strength = 2)
    {
        var like = s.Units.Values.First(x => x.Side == UnitData.Israel);
        var to = FreeNeighbour(s, like.Q, like.R);
        var unit = new Unit(s.NextId++, type, to.q, to.r, side: UnitData.Israel, strength: strength, homeCity: "tel_aviv");
        s.Units.Add(unit.Id, unit);
        return unit;
    }

    /// <summary>#1396: each military type raised after the starting forces gets an army token on its sim hex. Its reusable
    /// type default supplies the existing figures and vehicle, and Q-UI-3 supplies the figure count from strength.</summary>
    [TestCase("recruit", 1, 1, null)]
    [TestCase("veteran_soldier", 4, 3, null)]
    [TestCase("artillery", 2, 2, UnitFigures.Napoleonchik)]
    [TestCase("armoured_car", 4, 3, UnitFigures.SandwichArmouredCar)]
    public void ARaisedUnitDrawsItsTypeAndStrengthOnItsHex(string type, int strength, int figures, string vehicle)
    {
        var s = NewGame();
        var raised = Raise(s, type, strength);
        var tokens = UnitRoster.FromState(Units, C, s, _ => true, new Moved().At);
        var token = tokens.Single(t => t.SimId == raised.Id);
        Assert.AreEqual(UnitData.Army, token.Unit.Service);
        Assert.AreEqual(figures, token.Figures, "Q-UI-3 against the reused four-strength Israeli army default");
        Assert.AreEqual(figures, token.Headgear.Count, "one existing figure per strength band");
        if (vehicle == null) CollectionAssert.IsEmpty(token.Vehicles); else CollectionAssert.Contains(token.Vehicles, vehicle);
        var hexes = MapBuilder.LoadHexes(Path.Combine(Paths.Content, "map", "hexes.json"));
        Assert.AreEqual((raised.Q, raised.R), HexPicker.FromLonLat(token.Anchor.Lon, token.Anchor.Lat, hexes.bounds, hexes.hex_size_km));
    }

    /// <summary>#1396: the raised token has its own stable map id, so the same UnitLayer path as a starting unit selects it.</summary>
    [Test]
    public void ARaisedUnitCanBeSelected()
    {
        EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
        var map = new GameObject("MapScene").AddComponent<MapScene>();
        try
        {
            map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));
            Statecraft.Game.Map.Kits.KitPopulation.Use(Statecraft.Game.Map.Kits.KitPopulation.Parse(
                File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))));
            map.Build();
            var s = NewGame();
            var raised = Raise(s);
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            Assert.IsTrue(layer.Show(C, s));
            var token = layer.Tokens.Single(t => t.Token.SimId == raised.Id);
            Assert.AreEqual(token.Token.Unit.Id, layer.UnitToSelectAt(token.Q, token.R));
            layer.Select(token.Token.Unit.Id);
            Assert.AreEqual(token.Token.Unit.Id, layer.Selected);
        }
        finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
    }

    /// <summary>#1396: a raised formation's card names its type, strength and home city, and routes Move to its real sim id.</summary>
    [Test]
    public void ARaisedUnitShowsItsCardAndMove()
    {
        using var ui = new UiTestKit();
        var game = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
        var raised = Raise(game.State);
        var bridge = new SimBridge(game, Text);
        var token = UnitRoster.FromState(Units, C, game.State, _ => true, new Moved().At).Single(t => t.SimId == raised.Id);
        Assert.IsNotEmpty(Movement.Reachable(C, game.State, raised.Id), "precondition: the raised recruits can move");
        PlacedToken? selected = new PlacedToken(token, new AnchorSpot(raised.Q, raised.R, 0, 0, false));
        var info = new InfoPanelPresenter(ui.Root, bridge, Text, C.SettlementNames, selectedUnit: () => selected);
        info.ShowUnit();
        Assert.AreEqual(Text["city.track_recruit"], ui.Q<Label>("info-title").text);
        Assert.AreEqual(Text["unit.service.army"], ui.Q<Label>("info-subtitle").text);
        var points = C.UnitTypes.Single(t => t.Id == raised.Type).MovementPoints;
        Assert.AreEqual(Text.Format("unit.strength", raised.Strength) + "\n" + Text.Format("unit.home_city", C.SettlementNames[raised.HomeCity])
            + "\n" + Text.Format("unit.points", points, points)   // #1398 (U1): the card shows the movement points left
            + "\n" + Text["unit.move_pick"],   // owner, 25 Oct 2026: selecting a unit that can move opens its Move pick
            ui.Q<Label>("info-settlements").text, "strength, home city, movement points and the Move pick, and no empty sector line");
        Assert.AreEqual(DisplayStyle.Flex, ui.Q<Button>("info-move").style.display.value);
        Assert.AreEqual(Text["unit.order.move"], ui.Q<Button>("info-move").text);
        info.Dispose();
    }

    /// <summary>#1396 is additive: giving a raised unit a default token does not change any starting unit's row, art or anchor.</summary>
    [Test]
    public void StartingUnitsAreUnchangedWhenARaisedUnitIsDrawn()
    {
        var s = NewGame();
        var units = Units;   // one parse: a token's row is compared by reference
        var moved = new Moved();
        var before = UnitRoster.FromState(units, C, s, _ => true, moved.At);
        var raised = Raise(s);
        var after = UnitRoster.FromState(units, C, s, _ => true, moved.At);
        CollectionAssert.AreEqual(before, after.Where(t => t.SimId != raised.Id).ToList());
        Assert.AreEqual(before.Count + 1, after.Count);
    }

    /// <summary>Review point 3 on #1205: in the GDD loop the call-up no longer sets the figures, so the card's footer does not
    /// lead with it. An army token's footer gives only its sources; the squadron's keeps the security level, which still
    /// sets whether it flies. The legacy loop keeps the call-up line.</summary>
    [Test]
    public void TheGddCardDoesNotLeadWithTheCallUp()
    {
        var text = UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
        var s = NewGame(); s.Date = new DateTime(1948, 7, 1);   // the squadron at Herzliya
        var tokens = UnitRoster.FromState(Units, C, s, _ => true, new Moved().At);
        var army = tokens.First(t => t.Unit.Service == UnitData.Army && t.Unit.Side == UnitData.Israel);
        var air = tokens.First(t => t.Unit.Service == UnitData.Air);
        var national = text.Format("unit.national", PlayerText.Percent(s.Mobilization), s.Rung);
        string First(UnitToken t, bool gdd) => UnitCard.For(new PlacedToken(t, default), s, text, gdd).Footer.Split('\n')[0];
        StringAssert.StartsWith(text.Format("unit.sources", ""), First(army, true), "an army token: sources only");
        Assert.AreEqual(text.Format("unit.security", s.Rung), First(air, true), "the squadron: the security level alone");
        Assert.AreEqual(national, First(army, false), "the legacy loop still leads with the call-up");
        Assert.AreEqual(national, First(air, false));
    }

    /// <summary>#563's spot cache: a rebuild after a move places only the unit that moved; every other token keeps its spot,
    /// and a unit back on its starting hex stands on its starting spot again.</summary>
    [Test]
    public void ARebuildAfterAMoveKeepsTheSpotCache()
    {
        EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
        var map = new GameObject("MapScene").AddComponent<MapScene>();
        try
        {
            map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));
            Statecraft.Game.Map.Kits.KitPopulation.Use(Statecraft.Game.Map.Kits.KitPopulation.Parse(
                File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))));
            map.Build();
            var s = NewGame();
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            Assert.IsTrue(layer.Show(C, s));
            Assert.AreEqual(0, layer.MovedSpotsPlaced);
            var start = layer.Tokens.ToDictionary(p => p.Token.Unit.Id, p => p.Spot);
            var israel = s.Units.Values.Where(u => u.Side == "israel").Take(2).ToArray();
            string a = C.StartingForces[israel[0].Id].Row, b = C.StartingForces[israel[1].Id].Row;
            var home = (israel[0].Q, israel[0].R);

            var to = FreeNeighbour(s, israel[0].Q, israel[0].R);
            MoveTo(s, israel[0].Id, to.q, to.r);
            Assert.IsTrue(layer.Show(C, s));
            Assert.AreEqual(1, layer.MovedSpotsPlaced, "only the moved unit is placed");
            var spotA = layer.Tokens.Single(p => p.Token.Unit.Id == a).Spot;
            Assert.LessOrEqual(MapActions.Distance(spotA.Q, spotA.R, to.q, to.r), UnitPlacer.MaxShift, "within one hex of its sim hex");
            foreach (var p in layer.Tokens.Where(p => p.Token.Unit.Id != a)) Assert.AreEqual(start[p.Token.Unit.Id], p.Spot, $"{p}: kept its spot");
            Assert.IsFalse(layer.Tokens.Any(p => p.Token.Unit.Id != a && p.Q == spotA.Q && p.R == spotA.R), "off the other tokens' hexes");

            var toB = FreeNeighbour(s, israel[1].Q, israel[1].R);
            MoveTo(s, israel[1].Id, toB.q, toB.r);
            Assert.IsTrue(layer.Show(C, s));
            Assert.AreEqual(2, layer.MovedSpotsPlaced, "the second move places only the second unit");
            Assert.AreEqual(spotA, layer.Tokens.Single(p => p.Token.Unit.Id == a).Spot, "the first keeps its cached spot");
            Assert.IsFalse(layer.Show(C, s), "nothing changed, nothing rebuilt");

            MoveTo(s, israel[0].Id, home.Item1, home.Item2);
            Assert.IsTrue(layer.Show(C, s));
            Assert.AreEqual(2, layer.MovedSpotsPlaced, "back home is the starting spot, not a new placement");
            Assert.AreEqual(start[a], layer.Tokens.Single(p => p.Token.Unit.Id == a).Spot);
            Assert.AreNotEqual(start[b], layer.Tokens.Single(p => p.Token.Unit.Id == b).Spot, "the second still stands where it moved");
        }
        finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
    }

    [TestCase(false)]
    [TestCase(true)]
    public void MapOnlyArmyKeepsADistinctFixedSpotBesidePersistentStartingForces(bool delayedOriginal)
    {
        var savedSource = UnitFigures.Source;
        EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
        UnitFigures.ResetSession();
        Action answerLebanese = null!;
        bool holdLebanese = delayedOriginal;
        var map = new GameObject("MapScene").AddComponent<MapScene>();
        try
        {
            UnitFigures.Source = (id, detail, done) =>
            {
                Action answer = () => done(AssetDatabase.LoadAssetAtPath<GameObject>(
                    Statecraft.Game.Map.Collection.CollectionCatalog.PrefabPath(id, detail)));
                if (holdLebanese && id == UnitFigures.LebaneseRegular) answerLebanese = answer;
                else answer();
            };
            map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));
            Statecraft.Game.Map.Kits.KitPopulation.Use(Statecraft.Game.Map.Kits.KitPopulation.Parse(
                File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))));
            map.Build();
            var rows = map.UnitEntries;
            var sourceSpots = map.UnitSpots.ToDictionary(kv => kv.Key, kv => kv.Value);
            var windows = rows.SelectMany(u => u.Anchors.Select(a => (u.Id, a.From, a.To))).ToArray();
            var game = GameSession.New(C, GoldenRun.Seed, Mode.Historical);
            game.EndTurn(Array.Empty<Command>());
            Assert.AreEqual(new DateTime(1948, 6, 15), game.State.Date);
            var hash = game.State.Hash();
            var layer = UnitLayer.Create(map, rows, C.Hexes, still: true);
            Assert.IsTrue(layer.Show(C, NewGame()));
            Assert.IsFalse(layer.Tokens.Any(t => t.Token.Unit.Id == "lebanese_army"), "first Show precedes the dated window");
            layer.Show(C, game.State);
            if (delayedOriginal)
            {
                Assert.IsNotNull(answerLebanese, "the actual Lebanese original was requested");
                Assert.IsFalse(layer.Tokens.Any(t => t.Token.Unit.Id == "lebanese_army"), "no placeholder before the delayed original");
                holdLebanese = false; // Only the first arrival is delayed; later lease reacquisitions answer normally.
                answerLebanese!();
                layer.Show(C, game.State);
            }
            var ala = layer.Tokens.Single(t => t.Token.Unit.Id == "arab_liberation_army");
            var lebanese = layer.Tokens.Single(t => t.Token.Unit.Id == "lebanese_army");
            Assert.Less(UnitData.Day(ala.Token.Anchor.To), game.State.Date, "the ALA persists past its sourced display window");
            Assert.IsNotNull(ala.Token.StateUnit, "the existing ALA remains a real sim unit");
            Assert.IsNull(lebanese.Token.StateUnit, "the Lebanese token remains map-only");
            var alaPlinth = layer.transform.Find("Tokens/arab_liberation_army/Plinth").GetComponent<Renderer>();
            var lebanesePlinth = layer.transform.Find("Tokens/lebanese_army/Plinth").GetComponent<Renderer>();
            Assert.IsTrue(alaPlinth.enabled && alaPlinth.gameObject.activeInHierarchy && !alaPlinth.forceRenderingOff);
            Assert.IsTrue(lebanesePlinth.enabled && lebanesePlinth.gameObject.activeInHierarchy && !lebanesePlinth.forceRenderingOff);
            float separation = Vector2.Distance(new Vector2(alaPlinth.bounds.center.x, alaPlinth.bounds.center.z),
                new Vector2(lebanesePlinth.bounds.center.x, lebanesePlinth.bounds.center.z));
            float required = Mathf.Max(alaPlinth.bounds.extents.x, alaPlinth.bounds.extents.z)
                + Mathf.Max(lebanesePlinth.bounds.extents.x, lebanesePlinth.bounds.extents.z);
            Assert.GreaterOrEqual(separation, required, "Lebanese map-only token must not overlay the persistent ALA display token");
            Assert.AreEqual(layer.Spots[ala.Token.Anchor], ala.Spot, "the simulated starting force never shifts");
            Assert.AreNotEqual(layer.Spots[lebanese.Token.Anchor], lebanese.Spot, "the Lebanese token uses a separate display spot");
            Assert.IsFalse(layer.Show(C, game.State), "unchanged roster does not rebuild");
            layer.Show(C, NewGame());
            Assert.IsFalse(layer.Tokens.Any(t => t.Token.Unit.Id == "lebanese_army"), "dated map-only token is absent before its window");
            layer.Show(C, game.State);
            Assert.AreEqual(lebanese.Spot, layer.Tokens.Single(t => t.Token.Unit.Id == "lebanese_army").Spot,
                "reappearing dated token keeps its fixed display spot");
            foreach (var kv in sourceSpots) Assert.AreEqual(kv.Value, map.UnitSpots[kv.Key], "cached source spot unchanged");
            Assert.AreEqual(hash, game.State.Hash(), "presentation does not change the sim state");
            CollectionAssert.AreEqual(windows, rows.SelectMany(u => u.Anchors.Select(a => (u.Id, a.From, a.To))).ToArray(),
                "source windows remain unchanged");
        }
        finally { UnityEngine.Object.DestroyImmediate(map.gameObject); UnitFigures.Source = savedSource; }
    }

    static MapScene BuildMap()
    {
        EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
        var map = new GameObject("MapScene").AddComponent<MapScene>();
        map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));
        Statecraft.Game.Map.Kits.KitPopulation.Use(Statecraft.Game.Map.Kits.KitPopulation.Parse(
            File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))));
        map.Build();
        return map;
    }

    static Transform TokenOf(MapScene map, string row) => map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").Find(row);
    static Vector2 SpotOf(UnitLayer layer, string row)
    {
        var spot = layer.Tokens.Single(p => p.Token.Unit.Id == row).Spot;
        return new Vector2((float)spot.X, (float)spot.Z);
    }
    static Vector2 XZ(Vector3 v) => new Vector2(v.x, v.z);

    /// <summary>#1866 (design by Tal Heuberger, #1900): a moved unit's token slides from where it was drawn to its new spot
    /// and stops there; a second move mid-slide starts from where the token is drawn then; every other token stands still,
    /// with nothing running per frame. Presentation only: the state is not touched.</summary>
    [Test]
    public void AMovedTokenSlidesFromWhereItWasDrawnAndStops()
    {
        var map = BuildMap();
        try
        {
            var s = NewGame();
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            layer.AnimateMoves = true;
            layer.Show(C, s);
            var unit = s.Units.Values.First(u => u.Side == "israel");
            string row = C.StartingForces[unit.Id].Row;
            var first = SpotOf(layer, row);
            var to = FreeNeighbour(s, unit.Q, unit.R);
            MoveTo(s, unit.Id, to.q, to.r);
            Assert.IsTrue(layer.Show(C, s));
            var second = SpotOf(layer, row);
            Assert.Greater((first - second).magnitude, 1000f, "a real move, not a nudge");
            var token = TokenOf(map, row);
            var motion = token.GetComponent<UnitTokenMotion>();
            Assert.AreEqual(unit.Id, motion.SimId);
            Assert.IsTrue(motion.Moving && motion.enabled);
            Assert.Less((XZ(token.position) - (first - second)).magnitude, 1f, "it starts where it was drawn");
            foreach (var other in map.Terrain.transform.Find(UnitLayer.RootName).GetComponentsInChildren<UnitTokenMotion>(true).Where(m => m != motion))
            {
                Assert.IsFalse(other.Moving, other.name);
                Assert.IsFalse(other.enabled, other.name + ": an idle token runs nothing per frame");
                Assert.AreEqual(Vector3.zero, other.transform.position, other.name);
            }

            motion.Tick(UnitTokenMotion.Duration / 2f);
            var drawn = second + XZ(token.position);   // halfway along
            Assert.Less((drawn - (first + second) / 2f).magnitude, 1f);
            var next = FreeNeighbour(s, to.q, to.r);
            MoveTo(s, unit.Id, next.q, next.r);
            Assert.IsTrue(layer.Show(C, s));
            var third = SpotOf(layer, row);
            token = TokenOf(map, row);
            motion = token.GetComponent<UnitTokenMotion>();
            Assert.Less((XZ(token.position) - (drawn - third)).magnitude, 1f, "a second move starts from where the token is drawn");

            motion.Tick(UnitTokenMotion.Duration);
            Assert.AreEqual(Vector3.zero, token.position, "it ends on its spot");
            Assert.IsFalse(motion.Moving); Assert.IsFalse(motion.enabled);
        }
        finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
    }

    /// <summary>Another unit's order must not cut an attack short (review of #2177, 3). Since #3055 it leaves the firing
    /// unit's token as it was, so the take plays on untouched. A change to the firing unit itself (its strength) builds its
    /// pieces again, and the new figures go on firing from where the take was.</summary>
    [Test]
    public void ARebuildForAnotherUnitsOrderKeepsAnAttackPlaying()
    {
        var map = BuildMap();
        var controller = new UnityEditor.Animations.AnimatorController(); controller.AddLayer("Base Layer");
        var fire = new AnimationClip { name = "fire" };
        fire.SetCurve("", typeof(Transform), "localScale.x", AnimationCurve.Linear(0f, 1f, 1f, 1f));
        try
        {
            var machine = controller.layers[0].stateMachine;
            machine.defaultState = machine.AddState("idle"); machine.AddState("attack").motion = fire;
            var s = NewGame();
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            layer.AnimateMoves = true;
            layer.Show(C, s);
            var israel = s.Units.Values.Where(u => u.Side == "israel").Take(2).ToArray();
            string firing = C.StartingForces[israel[0].Id].Row;
            var figure = new GameObject("test figure").transform; figure.SetParent(TokenOf(map, firing), false);
            var animator = figure.gameObject.AddComponent<Animator>(); animator.runtimeAnimatorController = controller;
            animator.Rebind(); animator.Update(0f);
            Assert.IsTrue(layer.PlayAttack(israel[0].Id), "fixture: the token plays the attack");
            // An Animator takes a Play at its next update, which only enters the state (at time 0) and does not move its clock
            // (as AnAttackPlaysTheBakedTakeOnTheFigure): that update first, then 0.3 s on the figure's clock, as on the motion's.
            animator.Update(0f);
            Assert.AreEqual(UnitFigureMotion.Attack, animator.GetCurrentAnimatorStateInfo(0).fullPathHash, "fixture: the figure fires");
            TokenOf(map, firing).GetComponent<UnitTokenMotion>().Tick(0.3f);
            var attacker = TokenOf(map, firing).GetComponent<UnitTokenMotion>();
            animator.Update(0.3f);   // 0.3 s into the 1 s take
            float taken = animator.GetCurrentAnimatorStateInfo(0).normalizedTime;
            Assert.AreEqual(0.3f, taken, 0.02f, "fixture: the take has run 0.3 s");
            var to = FreeNeighbour(s, israel[1].Q, israel[1].R);
            MoveTo(s, israel[1].Id, to.q, to.r);
            Assert.IsTrue(layer.Show(C, s), "another unit's move rebuilds the tokens");
            Assert.AreSame(attacker, TokenOf(map, firing).GetComponent<UnitTokenMotion>(), "the firing unit's token is kept (#3055)");
            Assert.IsTrue(attacker.Attacking, "the attack goes on");
            animator.Update(0f);
            Assert.AreEqual(UnitFigureMotion.Attack, animator.GetCurrentAnimatorStateInfo(0).fullPathHash, "its figure still fires");
            Assert.AreEqual(taken, animator.GetCurrentAnimatorStateInfo(0).normalizedTime, 0.02f, "where it was, not restarted");
            // The firing unit's own strength changes: its pieces are built again on its root, and the attack is handed on.
            var u0 = s.Units[israel[0].Id];
            s.Units[u0.Id] = new Unit(u0.Id, u0.Type, u0.Q, u0.R, u0.Service, u0.Side, u0.Strength - 1, u0.Order, u0.OrderTarget, u0.HomeCity, u0.Full, u0.CombatXp, u0.Records);
            Assert.IsTrue(layer.Show(C, s), "the strength change rebuilds the firing token");
            var successor = TokenOf(map, firing).GetComponent<UnitTokenMotion>();
            Assert.IsTrue(figure == null, "fixture: the old pieces are gone");
            Assert.IsTrue(successor.Attacking, "the attack goes on on the rebuilt token");
            // Its near figure turns on a frame later (UnitFigureDetail) and plays on from 0.3 s, not from the start
            // (review of #2176, items 3 and 4).
            var near = new GameObject("test figure").transform; near.SetParent(TokenOf(map, firing), false);
            var b = near.gameObject.AddComponent<Animator>(); b.runtimeAnimatorController = controller; b.Rebind(); b.Update(0f);
            successor.RefreshPose(); b.Update(0f);
            Assert.AreEqual(UnitFigureMotion.Attack, b.GetCurrentAnimatorStateInfo(0).fullPathHash, "the new figure fires");
            Assert.AreEqual(0.3f, b.GetCurrentAnimatorStateInfo(0).normalizedTime, 0.02f, "from 0.3 s into the 1 s take");
        }
        finally { UnityEngine.Object.DestroyImmediate(map.gameObject); UnityEngine.Object.DestroyImmediate(controller); UnityEngine.Object.DestroyImmediate(fire); }
    }

    /// <summary>Review of #2176, item 5 (#1900's test, in our words): a slide is the one time FaceCamera's whole loop runs
    /// every frame with a still camera, and each slide frame hands the map's names the other KeepClear list. Neither
    /// allocates (per-frame garbage stutters on WebGL).</summary>
    [Test]
    public void FacingASlidingTokenDoesNotAllocate()
    {
        var map = BuildMap();
        var eye = new GameObject("SlideCamera");
        try
        {
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            layer.AnimateMoves = true;
            layer.Show(C, NewGame());
            var motion = map.Terrain.transform.Find(UnitLayer.RootName).GetComponentInChildren<UnitTokenMotion>(true);
            Assert.IsNotNull(motion, "fixture: a play build gives the tokens their motion");
            var cam = eye.AddComponent<Camera>(); cam.farClipPlane = 1e6f;
            motion.Begin(new Vector3(30000f, 0f, 0f));
            for (int k = 0; k < 5; k++) { motion.Tick(0.001f); layer.FaceCamera(cam); }   // warm up: both lists grown
            var before = layer.KeepClear;
            Assert.That(() => { for (int k = 0; k < 50; k++) { motion.Tick(0.001f); layer.FaceCamera(cam); } }, Is.Not.AllocatingGCMemory());
            Assert.IsTrue(motion.Moving, "the token slid throughout");
            motion.Tick(0.001f); layer.FaceCamera(cam);
            Assert.AreNotSame(before, layer.KeepClear, "the measured frames were slide frames that hand the names a list");
        }
        finally { UnityEngine.Object.DestroyImmediate(eye); UnityEngine.Object.DestroyImmediate(map.gameObject); }
    }

    /// <summary>New Game (SimBridge.Replace) shows another game whose sim ids are the old game's (review of #2176, H4): its
    /// tokens are drawn where they stand, with no slide from where the old game's units were.</summary>
    [Test]
    public void AnotherGamesTokensDoNotSlideFromTheOldGames()
    {
        var map = BuildMap();
        try
        {
            var s = NewGame();
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            layer.AnimateMoves = true;
            var unit = s.Units.Values.First(u => u.Side == "israel");
            var to = FreeNeighbour(s, unit.Q, unit.R);
            MoveTo(s, unit.Id, to.q, to.r);
            layer.Show(C, s);
            Assert.IsTrue(layer.Show(C, NewGame(), slide: false), "the new game's roster differs, so the tokens are rebuilt");
            var motions = map.Terrain.transform.Find(UnitLayer.RootName).GetComponentsInChildren<UnitTokenMotion>(true);
            Assert.IsNotEmpty(motions);
            foreach (var m in motions) { Assert.IsFalse(m.Moving, m.name); Assert.AreEqual(Vector3.zero, m.transform.position, m.name); }
        }
        finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
    }

    /// <summary>With the "units" toggle off, a move does not slide: the token would play its slide only when shown again,
    /// from where it stood when hidden (review of #1900).</summary>
    [Test]
    public void AMoveWhileTheUnitsAreHiddenDoesNotSlideLater()
    {
        var map = BuildMap();
        try
        {
            var s = NewGame();
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            layer.AnimateMoves = true;
            layer.Show(C, s);
            var unit = s.Units.Values.First(u => u.Side == "israel");
            string row = C.StartingForces[unit.Id].Row;
            VisualToggles.Set(UnitLayer.ToggleName, false);
            var to = FreeNeighbour(s, unit.Q, unit.R);
            MoveTo(s, unit.Id, to.q, to.r);
            Assert.IsTrue(layer.Show(C, s));
            VisualToggles.Set(UnitLayer.ToggleName, true);
            var motion = TokenOf(map, row).GetComponent<UnitTokenMotion>();
            Assert.IsFalse(motion.Moving);
            Assert.AreEqual(Vector3.zero, motion.transform.position);
        }
        finally { VisualToggles.Set(UnitLayer.ToggleName, true); UnityEngine.Object.DestroyImmediate(map.gameObject); }
    }

    /// <summary>Mid-slide, a click and the map's names find the token where it is drawn, not on its empty spot or on the path
    /// (#1900): the badge's box is the plate as drawn, at the size #2077 caps it to up close, and the box of the still pieces
    /// moves with the token, for an army token (flag and figures) and a ship (neither).</summary>
    [TestCase(UnitData.Army, false)]
    [TestCase(UnitData.Army, true)]
    [TestCase(UnitData.Navy, false)]
    public void MidSlideTheHitBoxesAreWhereTheTokenIsDrawn(string service, bool perspective)
    {
        var map = BuildMap();
        var eye = new GameObject("SlideCamera");
        var target = new RenderTexture(512, 512, 16);
        try
        {
            var s = NewGame();
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            layer.AnimateMoves = true;
            layer.Show(C, s);
            int i = layer.Tokens.ToList().FindIndex(p => p.Token.Unit.Service == service);
            Assert.GreaterOrEqual(i, 0, "the new game draws such a token");
            var token = TokenOf(map, layer.Tokens[i].Token.Unit.Id);
            var spot = SpotOf(layer, layer.Tokens[i].Token.Unit.Id);
            var slide = new Vector3(30000f, 0f, 0f);   // halfway through a slide from 60 km east of the spot
            var cam = eye.AddComponent<Camera>();
            cam.targetTexture = target; cam.farClipPlane = 1e6f;
            if (perspective)
            {
                // Close over the drawn token: #2077 caps the plate below its full size.
                cam.fieldOfView = 30f;
                cam.transform.SetPositionAndRotation(new Vector3(spot.x, 0f, spot.y) + slide + new Vector3(0f, 6000f, -6000f),
                    Quaternion.Euler(45f, 0f, 0f));
            }
            else
            {
                // Top-down over the spot and the drawn token alike, for the clicks.
                cam.orthographic = true; cam.orthographicSize = 40000f;
                cam.transform.SetPositionAndRotation(new Vector3(spot.x, 100000f, spot.y) + slide / 2f, Quaternion.Euler(90f, 0f, 0f));
            }
            layer.FaceCamera(cam);
            var rest = layer.KeepClear[i].ToArray();
            var motion = token.GetComponent<UnitTokenMotion>();
            motion.Begin(slide * 2f);
            motion.Tick(UnitTokenMotion.Duration / 2f);
            Assert.Less((token.position - slide).magnitude, 1f);
            layer.FaceCamera(cam);
            var boxes = layer.KeepClear[i];
            var badge = token.Find("Badge");
            Assert.Less((boxes[0].center - badge.position).magnitude, 1e-2f, "the badge's box is the plate as drawn");
            Assert.AreEqual(badge.localScale.x, boxes[0].size.x, 1e-3f, "at the plate's drawn size");
            if (perspective) Assert.Less(badge.localScale.x, UnitBadge.SizeM, "the close camera caps the plate (#2077)");
            Assert.Less((XZ(boxes[0].center) - XZ(rest[0].center + slide)).magnitude, UnitBadge.SizeM, "the badge moved with its token");
            Assert.Less((boxes[1].center - (rest[1].center + slide)).magnitude, rest[1].extents.magnitude / 2f, "the pieces' box moved with it");
            Assert.Less(boxes[1].size.magnitude, rest[1].size.magnitude * 1.5f, "and does not stretch along the path");
            if (perspective) return;   // the clicks below need the spot and the drawn token in one view
            var hit = layer.TokenAtScreen(cam, cam.WorldToScreenPoint(rest[1].center + slide));
            Assert.AreEqual(layer.Tokens[i].Token.Unit.Id, hit?.Token.Unit.Id, "a click on the drawn token selects it");
            var empty = layer.TokenAtScreen(cam, cam.WorldToScreenPoint(rest[1].center));
            Assert.AreNotEqual(layer.Tokens[i].Token.Unit.Id, empty?.Token.Unit.Id, "its empty spot does not");
            motion.Tick(UnitTokenMotion.Duration);
            Assert.AreEqual(layer.Tokens[i].Token.Unit.Id, layer.TokenAtScreen(cam, cam.WorldToScreenPoint(rest[1].center))?.Token.Unit.Id,
                "arrived, the spot selects it again");
            Assert.Less((layer.KeepClear[i][1].center - rest[1].center).magnitude, 1f);
        }
        finally { UnityEngine.Object.DestroyImmediate(eye); UnityEngine.Object.DestroyImmediate(target); UnityEngine.Object.DestroyImmediate(map.gameObject); }
    }

    /// <summary>An edit-mode build (promo captures) draws every token still; no token there can attack (#1867).</summary>
    [Test]
    public void AnEditModeBuildDrawsTokensStillAndAttacksNothing()
    {
        var map = BuildMap();
        try
        {
            var s = NewGame();
            var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
            Assert.IsFalse(layer.AnimateMoves, "only a playing game animates");
            layer.Show(C, s);
            var unit = s.Units.Values.First(u => u.Side == "israel");
            var to = FreeNeighbour(s, unit.Q, unit.R);
            MoveTo(s, unit.Id, to.q, to.r);
            Assert.IsTrue(layer.Show(C, s));
            Assert.IsEmpty(map.Terrain.transform.Find(UnitLayer.RootName).GetComponentsInChildren<UnitTokenMotion>(true));
            Assert.IsFalse(layer.PlayAttack(unit.Id));
            layer.AnimateMoves = true;
            MoveTo(s, unit.Id, unit.Q, unit.R);
            Assert.IsTrue(layer.Show(C, s));
            Assert.IsFalse(layer.PlayAttack(unit.Id), "no near Animator is on in an edit-mode map (nothing has rendered)");
            Assert.IsFalse(layer.PlayAttack(-5), "no such unit");
        }
        finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }
    }

    static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");
}