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.

83.6 KB
Raw Blame
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Statecraft.Sim;
using UnityEngine;
using UnityEngine.Rendering;

namespace Statecraft.Game.Map.Units
{
    /// <summary>The units in normal play (docs/units.md, "Units in play"): one token per unit that the sourced unit data
    /// (units_1948.yaml) and the sim's state give now (<see cref="UnitRoster"/>), each on its anchor's spot
    /// (<see cref="UnitPlacer"/>, computed once from the data), with the #139 models (and the authored-prefab hook):
    /// riflemen for a brigade, the squadron's aircraft flying a loop over its base or parked on it, a corvette at sea, and
    /// over each token the promo's badge (a dark plate with the unit's glyph, <see cref="UnitBadge"/>). Selecting a token
    /// draws the promo's white ring round it (selection only). Presentation only: it reads the state and never writes it
    /// (UnitsInPlayTests), so the goldens cannot move. Built under the map's terrain, so a map rebuild destroys it; its
    /// meshes, palette and materials are owned by its own MapRuntimeAssets, which also unregisters its "units" visual
    /// toggle (the frame profile prices it).</summary>
    public sealed class UnitLayer : MonoBehaviour
    {
        public const string RootName = "Units", ToggleName = "units";
        /// <summary>A player unit with no movement points left this turn has its badge drawn at this share of its colours
        /// (plate and glyph alike, so the glyph keeps its contrast on the plate).</summary>
        public const float DimShade = 0.5f;
        /// <summary>A parked aircraft's centre of gravity above the ground, in real metres (on its undercarriage).</summary>
        public const float ParkedHeightM = 1.4f;
        public const float ParkedHeadingDegrees = 200f;

        MapScene map = null!;
        IReadOnlyList<UnitEntry> units = Array.Empty<UnitEntry>();
        /// <summary>The unit data the layer draws from (read only; MapScene.UnitEntries when it read the same file).</summary>
        public IReadOnlyList<UnitEntry> Units => units;
        UnitGround ground = null!;
        IReadOnlyDictionary<UnitAnchor, AnchorSpot> spots = new Dictionary<UnitAnchor, AnchorSpot>();
        MapRuntimeAssets assets = null!;
        Material paint = null!, ringTemplate = null!, badgePlate = null!, badgeGlyph = null!, hitPlate = null!, rim = null!;
        readonly Dictionary<string, Material[]> flagCloth = new Dictionary<string, Material[]>();   // per side, made on first use
        readonly Dictionary<string, Mesh> meshes = new Dictionary<string, Mesh>();
        /// <summary>The meshes built for each token drawn now (each base's draped top, lip and ring follow its own ground), in
        /// the order of <see cref="badges"/>: destroyed when that token is built again or dropped and with the layer, so no
        /// roster change leaks them (review of #559, M1).</summary>
        readonly List<List<Mesh>> tokenMeshes = new List<List<Mesh>>();
        List<Mesh>? buildingMeshes;   // the token being built's
        List<UnitToken>? roster;
        readonly Dictionary<string, UnitFigureResidency> figurePrefetch = new Dictionary<string, UnitFigureResidency>();
        readonly HashSet<string> wantedFigurePrefetch = new HashSet<string>(StringComparer.Ordinal);
        internal int FigurePrefetchCount => figurePrefetch.Count;
        bool updatingPrefetch, prefetchRetirementDirty;
        string? prefetchRetirementId;
        int seenAvailability = -1;
        int seenGeometry = -1;
        static readonly Predicate<MeshFilter> MissingMesh = mesh => mesh == null;
        void PrefetchFigures(IReadOnlyList<UnitToken> candidates)
        {
            updatingPrefetch = true;
            try
            {
                var rosterGateModels = new HashSet<string>(candidates.Where(token => token.Unit.Side != UnitData.Israel)
                    .Select(token => UnitFigures.SideFigure(token.Unit.Side)).Where(id => id != null)
                    .Select(id => id!), StringComparer.Ordinal);
                wantedFigurePrefetch.Clear(); wantedFigurePrefetch.UnionWith(rosterGateModels);
                foreach (var id in rosterGateModels)
                {
                    // A foreign token cannot create its own figure holders until this side model passes Show's roster
                    // gate. Keep one temporary owner per missing side model, never N+1 permanent owners beside the
                    // roster figures; RetireSatisfiedPrefetch transfers ownership after Rebuild has drawn the token.
                    if (!UnitFigures.Arrived(id) && !figurePrefetch.TryGetValue(id, out var owner))
                    {
                        var holder = new GameObject("Roster gate demand " + id); holder.transform.SetParent(transform, false);
                        owner = holder.AddComponent<UnitFigureResidency>(); figurePrefetch[id] = owner;
                        owner.Initialize(id, map.Residency.Units, null, draw: false, retainFar: true);
                    }
                }
                if (figurePrefetch.Keys.Any(key => !rosterGateModels.Contains(key))) ScheduleSatisfiedPrefetchRetirement();
            }
            finally { updatingPrefetch = false; }
        }
        internal void ScheduleSatisfiedPrefetchRetirement(string id)
        {
            if (figurePrefetch.Count == 0 || !figurePrefetch.ContainsKey(id)) return;
            if (!prefetchRetirementDirty) prefetchRetirementId = id;
            else if (prefetchRetirementId != id) prefetchRetirementId = null;
            prefetchRetirementDirty = true;
        }
        void ScheduleSatisfiedPrefetchRetirement()
        {
            if (figurePrefetch.Count == 0) return;
            prefetchRetirementId = null; prefetchRetirementDirty = true;
        }
        void RetireSatisfiedPrefetch(string? onlyId = null)
        {
            if (figurePrefetch.Count == 0) { prefetchRetirementDirty = false; prefetchRetirementId = null; return; }
            if (onlyId != null && !figurePrefetch.ContainsKey(onlyId))
            { prefetchRetirementDirty = false; prefetchRetirementId = null; return; }
            var heldByFigures = new HashSet<string>(tokensRoot.GetComponentsInChildren<UnitFigureResidency>(true)
                .Where(owner => owner.ActiveAnsweredFar).Select(owner => owner.ModelId), StringComparer.Ordinal);
            var candidates = onlyId == null ? figurePrefetch.Keys.ToArray() : new[] { onlyId };
            foreach (string id in candidates.Where(id => !wantedFigurePrefetch.Contains(id) || heldByFigures.Contains(id)))
            {
                var old = figurePrefetch[id]; figurePrefetch.Remove(id);
                old.gameObject.SetActive(false);
                if (Application.isPlaying) Destroy(old.gameObject); else DestroyImmediate(old.gameObject);
            }
            prefetchRetirementDirty = false; prefetchRetirementId = null;
        }
        /// <summary>Runs the deferred roster-gate ownership handoff. Production calls it from <see cref="LateUpdate"/>;
        /// EditMode tests call it explicitly because they do not advance a player frame.</summary>
        internal void FlushPrefetchRetirement()
        { if (prefetchRetirementDirty) RetireSatisfiedPrefetch(prefetchRetirementId); }
        void LateUpdate() => FlushPrefetchRetirement();
        /// <summary>What <see cref="Show"/> last drew from, so a Collection model's arrival can draw the tokens that waited for
        /// it (an Arab force's, issue #665).</summary>
        Content? shownContent;
        GameState? shownState;
        List<PlacedToken> placed = new List<PlacedToken>();
        Transform tokensRoot = null!;
        readonly List<Transform> badges = new List<Transform>();
        /// <summary>Each badge's home (over the highest figure's feet, at the figures' height and the badge's lift) and how
        /// far behind the trio it sits, away from the camera (review of #559: the badge keeps off the figures' heads from
        /// any view, the camera's yaw and steepness alike), its flag's pole from the middle (zero for none), the flag (null for
        /// none) and the box of the token's pieces that neither turn nor move (null for a flying aircraft alone). In the order
        /// of <see cref="badges"/> and <see cref="keepClear"/>.</summary>
        readonly List<(Vector3 home, float back, Vector3 pole, MeshFilter? flag, Bounds? standing, bool parkedAircraft)> badgeHomes =
            new List<(Vector3, float, Vector3, MeshFilter?, Bounds?, bool)>();
        /// <summary>Each token's figures as laid out for camera yaw 0 (their place round the base's middle and their heading),
        /// the base's middle and radius, the badge's lift over the highest figure and the figures' meshes (none for an aircraft
        /// or a ship), in the order of <see cref="badges"/>. <see cref="FaceCamera"/> turns the figures and the flag's pole
        /// about the middle with the camera's yaw (issue #644): laid out for yaw 0 alone, at yaw 90 or 270 the trio stood in a
        /// column and from about yaw 180 the pole stood in front of it.</summary>
        readonly List<(Vector3 centre, float radius, float lift, (Transform figure, Vector3 offset, float heading)[] figures, MeshFilter[] meshes)> trios =
            new List<(Vector3, float, float, (Transform, Vector3, float)[], MeshFilter[])>();
        /// <summary>The camera yaw the trios were last turned to: a pan or a zoom keeps the yaw, so it moves no figure.</summary>
        float? turnedFor;
        /// <summary>The figures' and flags' share of their scale now (<see cref="UnitShowcase.ZoomScale"/>, #2430): only the game
        /// camera sets it, as it turns them, and only a new value touches them.</summary>
        float zoomShown = 1f;
        /// <summary>A rebuild built new figures at their own scale beside kept ones at <see cref="zoomShown"/>: the next
        /// <see cref="FaceCamera"/> scales them all.</summary>
        bool rescaleDue;
        /// <summary>A badge sits this share of its token's base radius behind the trio, seen from the camera, and
        /// <see cref="BadgeAsideM"/> to the side away from its flag's pole on screen (a compact token's pole cannot stand
        /// further out than its base's edge).</summary>
        public const float BadgeBackShare = 0.6f, BadgeAsideM = 400f, BadgeOverFlagM = 150f;
        /// <summary>#2729: a parked aircraft's badge must not cover its tail, the rear <see cref="BadgeTailShare"/> of its
        /// length, as the camera sees it. When it would, the badge moves on screen by the least of down, left or right that
        /// clears the tail by <see cref="BadgeTailGapPixels"/>, never up, so it stays by the aircraft and under the HUD.</summary>
        public const float BadgeTailShare = 0.4f, BadgeTailGapPixels = 4f;
        readonly List<(Vector2 centre, float radius)> treeHoles = new List<(Vector2, float)>();
        List<Bounds[]> keepClear = new List<Bounds[]>();
        /// <summary>A slide moves the boxes in place, but the labels re-place only for a new list: FaceCamera then hands
        /// out this second list with the same boxes, the two taking turns (no allocation per frame). A new pair per rebuild.</summary>
        List<Bounds[]> keepClearSpare = new List<Bounds[]>();
        bool slid;   // a token's slide moved since FaceCamera last turned the boxes
        int pickVersion;
        /// <summary>Changes whenever TokenAtScreen's projected source geometry can change.</summary>
        internal long PickVersion => ((long)pickVersion << 32) | (uint)UnitFigures.GeometryVersion;
#if UNITY_EDITOR
        internal long TokenHitQueriesForTests { get; private set; }
#endif
        GameObject? ring;
        bool still;
        /// <summary>The camera pose and projection (vertical scale, orthographic) <see cref="FaceCamera"/> last turned the badges and flags to; a call from the same pose and projection
        /// changes nothing and returns at once (GameRoot calls it every frame). Cleared when the tokens are rebuilt.</summary>
        (Vector3 eye, Quaternion rotation, float m11, bool orthographic)? facedFor;
        /// <summary>Each token's move and attack (#1866, #1867), in the order of <see cref="badges"/>; null where the layer
        /// does not animate (an edit-mode build, such as the promo captures, whose tokens stand still at their places).</summary>
        readonly List<UnitTokenMotion?> motions = new List<UnitTokenMotion?>();
        /// <summary>Each token's sim unit (-1 for a row with no sim unit), in the order of <see cref="badges"/>.</summary>
        readonly List<int> drawnSims = new List<int>();
        /// <summary>Each token's root, what it was built from and its kit-tree hole (if any), in the order of
        /// <see cref="badges"/>: a rebuild keeps a token whose unit did not change (#3055).</summary>
        readonly List<Transform> tokenRoots = new List<Transform>();
        List<PlacedToken> drawnPlaced = new List<PlacedToken>();
        readonly List<(Vector2 centre, float radius)?> tokenHoles = new List<(Vector2, float)?>();
        /// <summary>The sim units whose tokens the last rebuild dropped, and where each was drawn then: a destroyed unit's
        /// dust rises there (<see cref="PlayDestroyed"/>).</summary>
        readonly Dictionary<int, Vector3> gone = new Dictionary<int, Vector3>();
        /// <summary>The attacks' hits and the losses' dust (owner, 4 November 2026), or null without the flipbooks.</summary>
        CombatBursts? combat;
        internal CombatBursts? Combat => combat;
        /// <summary>A rebuild slides a moved unit's token from where it was drawn (true in play; tests set it).</summary>
        internal bool AnimateMoves;
        /// <summary>The sim units whose tokens wait where they were drawn until <see cref="Release"/> (#2202): a rebuild
        /// stands a held unit's token at its old place instead of sliding it.</summary>
        readonly HashSet<int> held = new HashSet<int>();

        /// <summary>The GDD loop's anchors for units that moved off their starting hex (UnitRoster.FromState), one per row and
        /// sim hex, and their spots: placed once, the first time a unit stands there, so a rebuild after a move places only
        /// the units that moved (#563's spot cache, GDD Phase 5 PR 14). The spots drawn from are <see cref="spots"/> with these.
        /// A cached spot keeps off the hexes other tokens held when it was placed, not those they take later: two tokens can
        /// then share a hex until stacks are drawn together.</summary>
        readonly Dictionary<(string row, int q, int r), UnitAnchor> movedAnchors = new Dictionary<(string, int, int), UnitAnchor>();
        readonly Dictionary<UnitAnchor, AnchorSpot> movedSpots = new Dictionary<UnitAnchor, AnchorSpot>();
        /// <summary>Moved anchors made since the last placement (each is placed once, spot or not).</summary>
        readonly HashSet<UnitAnchor> movedNew = new HashSet<UnitAnchor>();
        Dictionary<UnitAnchor, AnchorSpot>? drawSpots;
        Dictionary<UnitAnchor, AnchorSpot>? fixedGddSpots;
        readonly List<AnchorSpot> reservedMapOnlySpots = new List<AnchorSpot>();
        IReadOnlyDictionary<UnitAnchor, AnchorSpot> DisplaySpots =>
            shownContent?.IsGdd == true && fixedGddSpots != null ? fixedGddSpots : spots;

        /// <summary>How many moved units' anchors the layer has placed (each once; the tests read it).</summary>
        public int MovedSpotsPlaced { get; private set; }

        /// <summary>The tokens drawn now, in the data's order.</summary>
        public IReadOnlyList<PlacedToken> Tokens => placed;
        /// <summary>Every anchor's spot, from the data alone.</summary>
        public IReadOnlyDictionary<UnitAnchor, AnchorSpot> Spots => spots;
        /// <summary>The ground the anchors were placed on.</summary>
        public UnitGround PlacementGround => ground;
        /// <summary>The world boxes the map's name pills keep clear of (issue #197), one entry per drawn token: its standing
        /// pieces (the figures on their bases with the flag, a parked aircraft, the ship; not a flying aircraft, which moves) and
        /// its badge, which MapLabelsPresenter projects to one screen rectangle, so no pill sits on a token or between its badge
        /// and its figures. The badge's box and the flag's part follow them as <see cref="FaceCamera"/> turns them to a camera
        /// (in place: the boxes hold the token as that camera draws it). A new list whenever the tokens are rebuilt, and empty
        /// while the "units" toggle hides the layer.</summary>
        public IReadOnlyList<Bounds[]> KeepClear => gameObject.activeInHierarchy ? keepClear : (IReadOnlyList<Bounds[]>)Array.Empty<Bounds[]>();
        /// <summary>The selected unit's id, or null.</summary>
        public string? Selected { get; private set; }

        /// <summary>Makes the layer under the map's terrain and places every anchor once; <see cref="Show"/> draws the
        /// tokens. <paramref name="still"/> holds a flying aircraft at <see cref="UnitShowcase.StillPhase"/> (screenshots
        /// repeat).</summary>
        public static UnitLayer Create(MapScene map, IReadOnlyList<UnitEntry> units, IReadOnlyList<MapHex> hexes, bool still)
        {
            if (map == null || map.Terrain == null || map.Hexes == null) throw new InvalidOperationException("UnitLayer needs a built map");
            var terrain = map.Terrain;
            var old = terrain.transform.Find(RootName);
            if (old != null)
            {
                foreach (var a in old.GetComponentsInChildren<MapRuntimeAssets>(true)) a.RunTeardown();
                old.SetParent(null);
                if (Application.isPlaying) Destroy(old.gameObject); else DestroyImmediate(old.gameObject);
            }
            var template = Resources.Load<Material>(UnitMaterials.MiniatureResource)
                ?? throw new InvalidOperationException($"Resources/{UnitMaterials.MiniatureResource}.mat is missing (run UnitMaterialAssets.Create)");
            var ringTemplate = Resources.Load<Material>(UnitMaterials.RingResource)
                ?? throw new InvalidOperationException($"Resources/{UnitMaterials.RingResource}.mat is missing (run UnitMaterialAssets.Create)");
            var root = new GameObject(RootName);
            root.transform.SetParent(terrain.transform, false);
            root.transform.position = Vector3.zero;   // children are placed in world space
            var layer = root.AddComponent<UnitLayer>();
            layer.map = map; layer.units = units; layer.still = still;
            layer.AnimateMoves = Application.isPlaying;
            // The same ground and the same placement as MapScene's (which keeps the kits off a token in a town).
            layer.ground = Ground(map, hexes);
            // The map's own spots when it placed these units on these hexes (issue #321: the same ground, so the same spots;
            // UnitSpotsOnceTests), with its skipped anchors' warnings; else placed here.
            if (map.UnitSpotsFor(units, hexes) is { } mapSpots)
            {
                layer.spots = mapSpots;
                foreach (var skip in UnitPlacer.SkipMessages(units, mapSpots)) Debug.LogWarning(skip);
            }
            else layer.spots = layer.ground.Place(units, XZ(map), Debug.LogWarning, control: map.Control);
            layer.assets = root.AddComponent<MapRuntimeAssets>();
            var palette = layer.assets.Own(UnitPalette.MakeTexture(readable: false));
            layer.paint = layer.assets.Own(new Material(template) { name = "UnitMiniature (palette)" });
            layer.paint.SetTexture("_BaseMap", palette);
            layer.ringTemplate = ringTemplate;
            layer.badgePlate = layer.assets.Own(new Material(ringTemplate) { name = "UnitBadge (plate)", color = UnitBadge.PlateColour });
            layer.badgeGlyph = layer.assets.Own(new Material(ringTemplate) { name = "UnitBadge (glyph)", color = UnitBadge.GlyphColour });
            layer.hitPlate = layer.assets.Own(new Material(ringTemplate)
                { name = "UnitBadge (hit flash)", color = new Color(0.86f, 0.12f, 0.08f, 0.92f) });
            layer.rim = layer.assets.Own(new Material(ringTemplate) { name = "UnitPlinthRim", color = UnitPlinth.RimColour });
            layer.tokensRoot = new GameObject("Tokens").transform;
            layer.tokensRoot.SetParent(root.transform, false);
            layer.combat = CombatBursts.Create(root.transform);
            // The kit trees under the figures are left out while the layer shows (issue #249), and come back with the layer
            // off: a plain screenshot run (HiddenInCaptures) keeps every tree, so its checkpoints stay comparable.
            layer.assets.OnTeardown(() => UnitShowcase.HideTrees(map, ToggleName, Array.Empty<(Vector2, float)>()));
            layer.assets.OnTeardown(layer.FreeTokenMeshes);
            // The Collection's figures (issue #665): an Arab force's token waits for its figure, so ask for each one the map
            // can draw (nothing is fetched before the frame after the request, CollectionStream), and draw again when one arrives.
            UnitFigures.ModelArrived += layer.OnModelArrived;
            layer.assets.OnTeardown(() => UnitFigures.ModelArrived -= layer.OnModelArrived);
            layer.assets.OnTeardown(VisualToggles.Register(ToggleName, on =>
            {
                if (root != null) root.SetActive(on);
                if (layer != null) layer.HideTrees();
            }));
            return layer;
        }

        /// <summary>True for a screenshot run (?shot, -shot) that does not also ask for the units (units, -units): the
        /// layer is then switched off, so plain art checkpoints stay comparable (review I5).</summary>
        public static bool HiddenInCaptures(string? url, string[] args, bool webgl) =>
            VisualShots.Requested(url, args, webgl) && !UnitShowcase.Requested(url, args, webgl);

        void OnEnable() => RenderPipelineManager.beginCameraRendering += FaceBadges;
        void OnDisable() => RenderPipelineManager.beginCameraRendering -= FaceBadges;

        /// <summary>The kit trees under drawn figure plinths and parked-aircraft footprints, left out while the layer shows.</summary>
        public IReadOnlyList<(Vector2 centre, float radius)> TreeHoles => treeHoles;

        void HideTrees() => UnitShowcase.HideTrees(map, ToggleName, gameObject.activeSelf ? treeHoles : (IReadOnlyList<(Vector2, float)>)Array.Empty<(Vector2, float)>());

        /// <summary>Turns every badge to face the camera about to render (game, editor capture or scene view alike) and sets
        /// it behind its trio as that camera sees it. No allocation.</summary>
        void FaceBadges(ScriptableRenderContext _, Camera cam) => FaceCamera(cam);

        /// <summary>As the render callback does: for a still render (the editor's promo captures, the tests), and for the map's
        /// names before they are placed (GameRoot), so the keep-clear boxes hold each badge and flag where this camera draws
        /// them: the badge's box is its own cube, not a box round every place the camera's yaw could take it (that box, about
        /// 3.7 km across, pushed Tel Aviv's name off its kit at gameplay03). No allocation while model geometry is unchanged.</summary>
        public void FaceCamera(Camera cam)
        {
            if (seenAvailability != UnitFigures.AvailabilityVersion && shownContent != null && shownState != null) Show(shownContent, shownState);
            if (cam == null) return;
            bool geometryChanged = seenGeometry != UnitFigures.GeometryVersion;
            seenGeometry = UnitFigures.GeometryVersion;
            for (int i = 0; i < trios.Count; i++)
            {
                var trio = trios[i];
                if (!geometryChanged && !Array.Exists(trio.meshes, MissingMesh)) continue;
                // The holder survives residency; its imported children do not. Never retain their old filters.
                trio.meshes = trio.figures.Where(f => f.figure != null)
                    .SelectMany(f => f.figure.GetComponentsInChildren<MeshFilter>(true)).ToArray();
                trios[i] = trio;
                facedFor = null;
            }
            var eye = cam.transform.position; var rotation = cam.transform.rotation;
            float m11 = cam.projectionMatrix[1, 1]; bool orthographic = cam.orthographic;
            if (facedFor is { } last && last.eye == eye && last.rotation == rotation && last.m11 == m11 && last.orthographic == orthographic) return;   // nothing moved since the last turn
            facedFor = (eye, rotation, m11, orthographic);
            Vector3 forward = cam.transform.forward, up = cam.transform.up;
            var away = cam.transform.forward; away.y = 0f;
            away = away.sqrMagnitude > 1e-6f ? away.normalized : Vector3.forward;
            var right = cam.transform.right; right.y = 0f;
            right = right.sqrMagnitude > 1e-6f ? right.normalized : Vector3.right;
            // The trio and its pole turn with the camera's yaw, so the camera always sees them as at yaw 0: three figures side
            // by side, the pole behind them (issue #644). Only a new yaw moves them; each is set on the draped top where it lands.
            // Only the game camera turns them: this runs for every camera (the scene view, a preview), and two cameras taking
            // turns would re-drape the figures every frame and leave them turned for whichever rendered last (review of #644).
            float yaw = Mathf.Atan2(away.x, away.z) * Mathf.Rad2Deg;
            bool turn = cam == Camera.main && turnedFor != yaw;
            if (turn) turnedFor = yaw;
            var turning = Quaternion.Euler(0f, turnedFor ?? 0f, 0f);   // as the figures stand now (yaw 0 until first turned)
            float zoom = cam == Camera.main ? UnitShowcase.ZoomScale(Kits.TownModelLayer.ViewDistance(cam)) : zoomShown;
            bool rescale = rescaleDue || zoom != zoomShown;
            zoomShown = zoom; rescaleDue = false;
            for (int i = 0; i < badges.Count; i++)
            {
                var b = badges[i]; if (b == null) continue;
                // A moving token's root stands off the origin by its slide (UnitTokenMotion); its pieces are placed in the
                // world here, so they take the same offset, and the boxes follow the token as drawn, not its destination.
                var slide = b.parent.position;
                var (home, back, pole, flag, standing, parkedAircraft) = badgeHomes[i];
                var (centre, radius, lift, figures, meshes) = trios[i];
                if (rescale && figures.Length > 0)
                {
                    foreach (var (figure, _, _) in figures) figure.localScale = Vector3.one * (UnitShowcase.FigureScale * zoom);
                    if (flag != null) flag.transform.localScale = Vector3.one * (UnitBadge.FigureHeightM * UnitShowcase.FigureScale * zoom);
                }
                if (turn && figures.Length > 0)
                {
                    float highest = float.MinValue;
                    foreach (var (figure, offset, heading) in figures)
                    {
                        var p = centre + turning * offset;
                        p.y = UnitPlinth.FigureY(map, radius, p.x, p.z);
                        highest = Mathf.Max(highest, p.y);
                        figure.SetPositionAndRotation(p + slide, Quaternion.Euler(0f, yaw + heading, 0f));
                    }
                    home.y = highest + lift;   // the badge clears the highest figure, wherever the turn set it
                    badgeHomes[i] = (home, back, pole, flag, standing, parkedAircraft);
                    if (flag != null)
                    {
                        var foot = centre + turning * pole;
                        foot.y = UnitPlinth.FigureY(map, radius, foot.x, foot.z);
                        flag.transform.position = foot + slide;
                    }
                }
                if (figures.Length > 0) pole = turning * pole;   // where the pole stands now, for the badge's side
                var aside = pole == Vector3.zero ? Vector3.zero : (Vector3.Dot(pole, right) > 0f ? -right : right) * BadgeAsideM;
                var at = home + away * back + aside + slide;
                if (figures.Length > 0 && flag != null)   // the badge stays over the flag's top as the flag grows
                    at += Vector3.up * ((zoomShown - 1f) * UnitFlags.PoleHeight * UnitBadge.FigureHeightM * UnitShowcase.FigureScale);
                // Owner, 31 October 2026 ("Shrink up close"): a near camera draws the plate no taller than a 30 km view does.
                // It shrinks about its lower edge (the plate faces the camera, so its edges run along the camera's up), which
                // stays where the full plate's is, clear of the flag and the figures; that move keeps the plate's depth.
                float size = UnitBadge.SizeFor(Vector3.Dot(at - eye, forward), m11, orthographic);
                at -= up * (0.5f * (UnitBadge.SizeM - size));
                if (parkedAircraft && b.parent.Find("Aircraft") is Transform plane && TailScreenRect(plane, cam) is Rect tail)
                    for (int k = 0; k < 3; k++)
                    {
                        float half = 0.5f * size;
                        var plate = ScreenRect(cam, at - right * half - up * half, at - right * half + up * half,
                            at + right * half - up * half, at + right * half + up * half);
                        if (!plate.Overlaps(tail)) break;
                        var c = cam.WorldToScreenPoint(at);
                        float perUp = cam.WorldToScreenPoint(at + up).y - c.y, perRight = cam.WorldToScreenPoint(at + right).x - c.x;
                        if (perUp <= 1e-5f || perRight <= 1e-5f) break;
                        float down = plate.yMax - tail.yMin + BadgeTailGapPixels;
                        float left = plate.xMax - tail.xMin + BadgeTailGapPixels, rightward = tail.xMax - plate.xMin + BadgeTailGapPixels;
                        if (down <= left && down <= rightward) at -= up * (down / perUp);
                        else if (left <= rightward) at -= right * (left / perRight);
                        else at += right * (rightward / perRight);
                    }
                b.SetPositionAndRotation(at, rotation);
                b.localScale = Vector3.one * size;
                var boxes = keepClear[i];
                boxes[0] = new Bounds(at, Vector3.one * size);   // the click and the names follow the plate as drawn
                if (standing is Bounds s)
                {
                    s.center += slide;   // the still pieces' box was taken at the unit's place; the flag and figures are where drawn
                    if (flag != null)
                    {
                        UnitFlagFacing.Face(flag.transform, eye);   // as it will turn for this camera
                        s.Encapsulate(WorldBox(flag));
                    }
                    foreach (var m in meshes) if (m != null && m.sharedMesh != null) s.Encapsulate(WorldBox(m));   // the figures as turned
                    boxes[1] = s;
                }
            }
            if (!slid) return;
            // Review of #2176: with a still camera the names kept clear of where the token started, not where it stands.
            slid = false;
            (keepClear, keepClearSpare) = (keepClearSpare, keepClear);
            keepClear.Clear();
            for (int i = 0; i < keepClearSpare.Count; i++) keepClear.Add(keepClearSpare[i]);
        }

        /// <summary>Draws the units for <paramref name="state"/> (read only). Rebuilds the tokens only when the roster
        /// changed, and then builds or destroys only the tokens that changed (#3055); returns true when it did. A selected
        /// unit that is no longer drawn is deselected. A moved unit's token slides from where it was drawn
        /// (<see cref="AnimateMoves"/>) unless <paramref name="slide"/> is false: another game (New Game) reuses the sim ids,
        /// so its tokens are all built again, where they stand.</summary>
        public bool Show(Content content, GameState state, bool slide = true)
        {
            if (!slide) ReleaseAll(snap: true);   // another game: nothing waits from the last one
            shownContent = content; shownState = state;
            PrepareMapOnlySpots(content);
            // The GDD loop draws the army from the sim's units (GDD Phase 5 PR 14); the legacy loop keeps the rows and the call-up.
            var now = content.IsGdd
                ? UnitRoster.FromState(units, content, state, _ => true, (row, start, q, r) => MovedAnchor(content, row, start, q, r))
                : UnitRoster.Build(units, content, state, _ => true);
            PrefetchFigures(now);
            // An Arab force's token waits while its figure loads, and is drawn with the plain built-in figure if it failed.
            now = now.Where(t => t.Unit.Side == UnitData.Israel || UnitFigures.Arrived(UnitFigures.SideFigure(t.Unit.Side)!)
                || UnitFigures.Failed(UnitFigures.SideFigure(t.Unit.Side)!)).ToList();
            if (roster != null && roster.SequenceEqual(now))
            {
                seenAvailability = UnitFigures.AvailabilityVersion;
                LogDrawn(state.Turn, rebuilt: false);
                return false;
            }
            roster = now;
            PlaceMoved(now);
            placed = UnitPlacer.Place(now, drawSpots ?? DisplaySpots);
            var probe = Boot.TurnProbe.Start();   // ?turnlog (#2905): the token rebuild alone
            Rebuild(slide);
            Boot.TurnProbe.Lap("UnitLayer.Rebuild", probe);
            ScheduleSatisfiedPrefetchRetirement();
            if (Selected != null && !placed.Any(p => p.Token.Unit.Id == Selected)) Select(null); else Select(Selected);
            seenAvailability = UnitFigures.AvailabilityVersion;
            LogDrawn(state.Turn, rebuilt: true);
            return true;
        }

        /// <summary>The turn of the last "units drawn" line (null before the first).</summary>
        int? loggedTurn;

        /// <summary>Under ?navlog (DiagLog.Nav), the tokens drawn now, whenever they change and on each new turn: the state's
        /// turn, the Israeli and the enemy (every other side) totals, then each enemy side's count, e.g.
        /// "NAV f=412 t=20311 units drawn turn=0 israel=10 enemy=2 egypt=1 jordan=1". tools/web_check.py's start screen runs
        /// fail without Israeli and enemy tokens on turns 1 and 2 (owner ruling on #2056, 1 November 2026).</summary>
        void LogDrawn(int turn, bool rebuilt)
        {
            if (!Boot.DiagLog.Nav || (!rebuilt && loggedTurn == turn)) return;
            loggedTurn = turn;
            int israel = placed.Count(p => p.Token.Unit.Side == UnitData.Israel);
            var sides = placed.Where(p => p.Token.Unit.Side != UnitData.Israel).GroupBy(p => p.Token.Unit.Side)
                .OrderBy(g => g.Key, StringComparer.Ordinal)
                .Select(g => FormattableString.Invariant($" {g.Key}={g.Count()}"));
            Boot.DiagLog.NavLine(FormattableString.Invariant(
                $"units drawn turn={turn} israel={israel} enemy={placed.Count - israel}{string.Concat(sides)}"));
        }

        float DisplayReach(AnchorSpot spot) => Mathf.Max(ground.RingRadius(spot.Compact),
            UnitPlinth.Radius(UnitPlinth.TrioWidth(UnitShowcase.FigureOffsets(3),
                UnitShowcase.DrawSpread * ground.HexSizeM * Spread(spot))) * UnitPlinth.RimOuter);

        bool DisplayOverlap(AnchorSpot a, AnchorSpot b)
        {
            double dx = a.X - b.X, dz = a.Z - b.Z;
            return a.Q == b.Q && a.R == b.R || Math.Sqrt(dx * dx + dz * dz) < DisplayReach(a) + DisplayReach(b);
        }

        /// <summary>GDD starting forces keep their starting anchors after the source windows end. Reserve a fixed,
        /// clear display spot for a map-only army that would otherwise share one. Computed once from data, before
        /// date/model filtering: appearance never moves another token. The map's kit clearings and sourced spots stay intact.</summary>
        void PrepareMapOnlySpots(Content content)
        {
            if (!content.IsGdd || fixedGddSpots != null) return;
            fixedGddSpots = new Dictionary<UnitAnchor, AnchorSpot>();
            foreach (var kv in spots) fixedGddSpots[kv.Key] = kv.Value;
            var simRows = new HashSet<string>(content.StartingForces.Select(f => f.Row), StringComparer.Ordinal);
            var starts = new List<AnchorSpot>();
            foreach (var force in content.StartingForces)
            {
                var row = units.FirstOrDefault(u => u.Id == force.Row);
                if (row == null || !UnitRoster.OnMap(row) || row.Service != UnitData.Army) continue;
                var anchor = UnitRoster.AnchorAt(row, force.Arrives ?? content.Rules.Start);
                if (anchor != null && spots.TryGetValue(anchor, out var start)) starts.Add(start);
            }
            foreach (var row in units.Where(u => UnitRoster.OnMap(u) && UnitRoster.MapOnly(u, simRows)))
                foreach (var anchor in row.Anchors)
                {
                    if (!spots.TryGetValue(anchor, out var original)) continue;
                    if (starts.Any(start => DisplayOverlap(original, start)))
                    {
                        var others = fixedGddSpots.Where(kv => !ReferenceEquals(kv.Key, anchor)).Select(kv => kv.Value).ToList();
                        var taken = fixedGddSpots.Values.Select(s => (s.Q, s.R)).Distinct().ToList();
                        var entry = new UnitEntry { Id = row.Id, Side = row.Side, Service = row.Service,
                            Anchors = new List<UnitAnchor> { anchor } };
                        bool found = false;
                        int neighbourhood = 1 + 3 * UnitPlacer.MaxShift * (UnitPlacer.MaxShift + 1);
                        for (int attempt = 0; attempt < neighbourhood; attempt++)
                        {
                            var candidates = ground.Place(new[] { entry }, XZ(map), null, taken);
                            if (!candidates.TryGetValue(anchor, out var candidate)) break;
                            if (!candidate.InTown && !others.Any(other => DisplayOverlap(candidate, other)))
                            {
                                fixedGddSpots[anchor] = candidate; reservedMapOnlySpots.Add(candidate); found = true; break;
                            }
                            taken.Add((candidate.Q, candidate.R));
                        }
                        if (!found) Debug.LogWarning($"UNITS {row.Id}: no safe fixed map-only display spot; overlapping source spot retained");
                    }
                }
        }

        /// <summary>Dims the listed unit rows' badges for this turn (each badge renderer at <see cref="DimShade"/> of its
        /// material's colour); every other badge has no property override.</summary>
        public void Dim(IReadOnlyCollection<string> rowIds)
        {
            var dim = new HashSet<string>(rowIds ?? Array.Empty<string>());
            var block = new MaterialPropertyBlock();
            for (int i = 0; i < tokensRoot.childCount; i++)
            {
                var token = tokensRoot.GetChild(i);
                var badge = token.Find("Badge");
                if (badge == null) continue;
                foreach (var renderer in badge.GetComponentsInChildren<Renderer>(true))
                {
                    if (!dim.Contains(token.name)) { renderer.SetPropertyBlock(null); continue; }
                    var c = renderer.sharedMaterial.color;
                    block.SetColor("_BaseColor", new Color(c.r * DimShade, c.g * DimShade, c.b * DimShade, c.a));
                    renderer.SetPropertyBlock(block);
                }
            }
        }

        /// <summary>The anchor of <paramref name="row"/>'s unit on sim hex (<paramref name="q"/>, <paramref name="r"/>) after a
        /// move: the hex's centre, no place name and no sources (the card then gives the row's), with the starting anchor's
        /// window. The same object every time, so the roster compares equal and the spot is placed once.</summary>
        UnitAnchor MovedAnchor(Content content, UnitEntry row, UnitAnchor start, int q, int r)
        {
            if (movedAnchors.TryGetValue((row.Id, q, r), out var a)) return a;
            var hex = content.HexAt(q, r);
            if (hex == null) return start;   // the sim never moves a unit off the map; stay drawn where it started
            a = new UnitAnchor { Lon = hex.Lon, Lat = hex.Lat, From = start.From, To = start.To };
            movedAnchors[(row.Id, q, r)] = a;
            movedNew.Add(a);
            return a;
        }

        /// <summary>Places the moved units' anchors in <paramref name="tokens"/> that have no spot yet, as UnitPlacer places
        /// any anchor (within one hex, clear of the town kits and the roads), off the hexes the other drawn tokens hold.</summary>
        void PlaceMoved(List<UnitToken> tokens)
        {
            var fresh = tokens.Where(t => movedNew.Remove(t.Anchor)).ToList();
            if (fresh.Count == 0) return;
            var taken = tokens.Select(t => DisplaySpots.TryGetValue(t.Anchor, out var s) ? s : movedSpots.TryGetValue(t.Anchor, out s) ? s : (AnchorSpot?)null)
                .Where(s => s != null).Select(s => (s!.Value.Q, s.Value.R))
                .Concat(reservedMapOnlySpots.Select(s => (s.Q, s.R))).ToList();
            var entries = fresh.Select(t => new UnitEntry { Id = t.Unit.Id, Side = t.Unit.Side, Service = t.Unit.Service, Anchors = new List<UnitAnchor> { t.Anchor } }).ToList();
            foreach (var kv in ground.Place(entries, XZ(map), Debug.LogWarning, taken)) movedSpots[kv.Key] = kv.Value;
            // A sim unit with no clear spot within a hex is still drawn, compact on its own sim hex: left out, it could not
            // be seen or selected, and End turn waits for it (UnitPlacer.OnOwnHex). The spots are placed in token order.
            var toXZ = XZ(map);
            var used = tokens.Select(t => DisplaySpots.TryGetValue(t.Anchor, out var s) ? s : movedSpots.TryGetValue(t.Anchor, out s) ? s : (AnchorSpot?)null)
                .Where(s => s != null).Select(s => (s!.Value.X, s.Value.Z))
                .Concat(reservedMapOnlySpots.Select(s => (s.X, s.Z))).ToList();
            foreach (var t in fresh)
            {
                if (movedSpots.ContainsKey(t.Anchor) || t.StateUnit == null || !(shownContent?.HexAt(t.StateUnit.Q, t.StateUnit.R) is MapHex hex)) continue;
                var c = toXZ(hex.Lon, hex.Lat);
                var spot = UnitPlacer.OnOwnHex(hex.Q, hex.R, (c.x, c.y), ground.HexSizeM, used, 1.5 * ground.RingRadius(true),
                    (x, z) => ground.Clear(t.Unit.Service, new Vector2((float)x, (float)z), true, false, c));
                movedSpots[t.Anchor] = spot;
                used.Add((spot.X, spot.Z));
                Debug.Log($"UNITS {t.Unit.Id} (unit {t.StateUnit.Id}) drawn compact on its own hex ({hex.Q},{hex.R})");
            }
            MovedSpotsPlaced += fresh.Count;
            drawSpots = new Dictionary<UnitAnchor, AnchorSpot>(DisplaySpots.Count + movedSpots.Count);
            foreach (var kv in DisplaySpots) drawSpots[kv.Key] = kv.Value;
            foreach (var kv in movedSpots) drawSpots[kv.Key] = kv.Value;
        }

        /// <summary>A Collection model arrived: draws the tokens again if it lets a new one show (an Arab force's figure).</summary>
        void OnModelArrived(string id)
        {
            if (this == null || updatingPrefetch || shownContent == null || shownState == null) return;
            Show(shownContent, shownState);
        }

        /// <summary>Where a token's vehicles stand on its base (shares of the base's radius, x east and z north, for camera
        /// yaw 0) and their headings: on the front of the base, before the trio, side-on to the camera, so the figures do
        /// not hide them (behind the trio they were hidden at 30 km; issue #665). The first on the west, a second on the east.</summary>
        internal static readonly (Vector2 at, float heading)[] VehicleSlots = { (new Vector2(-0.42f, -0.55f), 270f), (new Vector2(0.42f, -0.55f), 90f) };

        /// <summary>What a click on hex (q, r) selects: the unit standing there, unless it is already selected (a second
        /// click shows the hex, so a token never hides the hex's map actions) or the "units" toggle hides the layer; null
        /// means show the hex. Where several tokens stand on the hex (a unit drawn on its own crowded hex,
        /// UnitPlacer.OnOwnHex), each click selects the next of them in drawing order, then the hex, so every one can be
        /// clicked.</summary>
        public string? UnitToSelectAt(int q, int r)
        {
            if (!gameObject.activeInHierarchy) return null;
            var here = placed.Where(p => p.Q == q && p.R == r).Select(p => p.Token.Unit.Id).ToList();
            int i = Selected == null ? -1 : here.IndexOf(Selected);
            return i + 1 < here.Count ? here[i + 1] : null;
        }

        /// <summary>The token on hex (q, r), or null.</summary>
        public PlacedToken? At(int q, int r)
        {
            foreach (var p in placed) if (p.Q == q && p.R == r) return p;
            return null;
        }

        /// <summary>The token <paramref name="cam"/> draws under <paramref name="screen"/> (pixels, y up): its badge's or its
        /// standing pieces' box (<see cref="KeepClear"/>) as that camera projects it, the nearest to the camera when several
        /// hold the point; null off every token, behind the camera, or while the "units" toggle hides the layer. The badge
        /// floats over the figures and behind them, so the terrain under it is often the next hex (owner's report on v0.2.0:
        /// a click on a unit's badge showed the hex behind it, with no Move). No allocation.</summary>
        public PlacedToken? TokenAtScreen(Camera cam, Vector2 screen)
        {
#if UNITY_EDITOR
            TokenHitQueriesForTests++;
#endif
            if (cam == null || !gameObject.activeInHierarchy) return null;
            FaceCamera(cam);   // the boxes as this camera draws them (a no-op from the pose it last turned them to)
            PlacedToken? best = null; float nearest = float.MaxValue;
            for (int i = 0; i < placed.Count && i < keepClear.Count; i++)
                foreach (var box in keepClear[i])
                {
                    float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue; bool behind = false;
                    for (int c = 0; c < 8 && !behind; c++)
                    {
                        var p = cam.WorldToScreenPoint(new Vector3((c & 1) == 0 ? box.min.x : box.max.x, (c & 2) == 0 ? box.min.y : box.max.y, (c & 4) == 0 ? box.min.z : box.max.z));
                        behind = p.z <= 0f;
                        x0 = Mathf.Min(x0, p.x); y0 = Mathf.Min(y0, p.y); x1 = Mathf.Max(x1, p.x); y1 = Mathf.Max(y1, p.y);
                    }
                    if (behind || screen.x < x0 || screen.x > x1 || screen.y < y0 || screen.y > y1) continue;
                    float depth = (box.center - cam.transform.position).sqrMagnitude;
                    if (depth < nearest) { nearest = depth; best = placed[i]; }
                }
            return best;
        }

        /// <summary>Selects a drawn unit by id (the ring goes round it), or clears the selection (null).</summary>
        public void Select(string? id)
        {
            if (ring != null)
            {
                // Each ring has its own mesh (UnitShowcase.Ring), owned by the layer's assets until teardown: free it with
                // the ring, or every selection keeps one more alive for the session (#2043).
                var mesh = ring.GetComponent<MeshFilter>().sharedMesh;
                ring.transform.SetParent(null);
                if (Application.isPlaying) { Destroy(ring); Destroy(mesh); } else { DestroyImmediate(ring); DestroyImmediate(mesh); }
                ring = null;
            }
            var hit = placed.FirstOrDefault(p => p.Token.Unit.Id == id);
            Selected = id != null && hit.Token != null ? id : null;
            if (Selected == null) return;
            float hex = map.Hexes.hex_size_km * 1000f;
            ring = UnitShowcase.Ring(map, assets, ringTemplate, transform, Centre(hit.Spot), UnitShowcase.RingRadius * hex * Scale(hit.Spot));
        }

        static float Scale(AnchorSpot s) => s.Compact ? UnitGround.CompactScale : 1f;

        /// <summary>The share of <see cref="UnitShowcase.DrawSpread"/> a token's figures stand at.</summary>
        static float Spread(AnchorSpot s) => s.Compact ? UnitShowcase.CompactSpread : 1f;

        Vector3 Centre(AnchorSpot s) => UnitShowcase.Ground(map, new Vector3((float)s.X, 0f, (float)s.Z));

        /// <summary>The ground the units are placed on (footprints, routes, land, and the water a ship's hull must lie in) for a
        /// built map.</summary>
        public static UnitGround Ground(MapScene map, IReadOnlyList<MapHex> hexes) =>
            new UnitGround(map.SettlementFootprints, map.RouteCorridors, hexes, XZ(map), map.Hexes.hex_size_km * 1000f, Water(map));

        /// <summary>The built map's drawn water (KitGround.Water over its terrain: the sea is the heightmap's 0 m), which a ship's
        /// whole hull must lie in (issue #3038); null before the terrain is built.</summary>
        public static Func<float, float, bool>? Water(MapScene map) =>
            map.Terrain == null ? null : new Kits.KitGround(map.Terrain, map.Frame, map.Hexes, map.ElevMinM).Water;

        static Func<double, double, Vector2> XZ(MapScene map) => (lon, lat) => { var w = map.Frame.ToWorld(lon, lat, 0); return new Vector2(w.x, w.z); };

        Material? aircraftPaint, aircraftBlur;
        Mesh? aircraftBlurMesh, aircraftShadowMesh;

        /// <summary>The code-built Spitfire's glossy copy of the units' paint (UnitShowcase.Glossy), one for the layer.</summary>
        Material AircraftPaint() => aircraftPaint ??= assets.Own(UnitShowcase.Glossy(paint));

        /// <summary>The Spitfire's blur and shadow material (UnitShowcase.BlurMaterial), one for the layer.</summary>
        Material AircraftBlur() => aircraftBlur ??= assets.Own(UnitShowcase.BlurMaterial());

        Mesh MeshFor(string key, Func<Mesh> build)
        {
            if (!meshes.TryGetValue(key, out var mesh))
            {
                mesh = UnitPlinth.Upload(assets.Own(build()));   // no CPU copy kept in players
                meshes[key] = mesh;
            }
            return mesh;
        }

        /// <summary>A side's flag cloth materials, made once per side and shared by its tokens.</summary>
        Material[] FlagCloth(string side)
        {
            if (!flagCloth.TryGetValue(side, out var mats)) flagCloth[side] = mats = UnitFlags.ClothMaterials(side, ringTemplate, assets.Own);
            return mats;
        }

        /// <summary>Takes a mesh built for the token being built: freed with that token (<see cref="FreeMeshes"/>).</summary>
        Mesh TokenMesh(Mesh m) { buildingMeshes!.Add(UnitPlinth.Upload(m)); return m; }

        void FreeTokenMeshes()
        {
            foreach (var list in tokenMeshes) FreeMeshes(list);
            tokenMeshes.Clear();
        }

        static void FreeMeshes(List<Mesh> list)
        {
            foreach (var m in list) if (m != null) { if (Application.isPlaying) Destroy(m); else DestroyImmediate(m); }
            list.Clear();
        }

        static UnitModels.Headgear Hat(string headgear) => headgear switch
        {
            UnitData.SlouchHat => UnitModels.Headgear.SlouchHat,
            UnitData.SteelHelmet => UnitModels.Headgear.SteelHelmet,
            UnitData.WoolCap => UnitModels.Headgear.WoolCap,
            _ => throw new ArgumentException($"unknown headgear '{headgear}'", nameof(headgear)),
        };

        void Rebuild(bool slide)
        {
            // Where each unit's token is drawn now (its place plus any slide under way), before the old tokens go: a unit
            // drawn somewhere else after the rebuild slides from there (#1866). Keyed by the sim unit, else by the row.
            var drawnAt = new Dictionary<(int sim, string row), Vector3>();
            var firing = new Dictionary<(int sim, string row), float>();   // and how far into its fire take each attack is
            var hits = new Dictionary<(int sim, string row), (float left, float delay)>();   // and each hit it shows or awaits
            for (int i = 0; slide && i < motions.Count && i < trios.Count; i++)
            {
                var m = motions[i];
                if (m == null) continue;
                // The slide only, not a hit's shake: a defender shaking when the tokens are rebuilt has not moved (its shake is
                // handed on below instead).
                drawnAt[Key(m.SimId, m.name)] = DrawnAt(i);
                if (m.AttackPlayed > 0f) firing[Key(m.SimId, m.name)] = m.AttackPlayed;
                if (m.HitState.left > 0f || m.HitState.delay > 0f) hits[Key(m.SimId, m.name)] = m.HitState;
            }
            // Where each unit was drawn, so a unit the rebuild drops (destroyed, as the turn's lines say) raises its dust there.
            gone.Clear();
            for (int i = 0; i < drawnSims.Count && i < trios.Count; i++) if (drawnSims[i] >= 0) gone[drawnSims[i]] = DrawnAt(i);
            // #3055: each unit drawn before keeps its token's root (same key as the hand-over above). A token built from the
            // same unit, anchor, spot and looks (PlacedToken's equality) is kept whole; any other is built again on its root.
            // Another game (slide false) reuses the sim ids, so nothing of the old one is kept.
            var was = new Dictionary<(int sim, string row), int>();
            int drawn = Math.Min(Math.Min(tokenRoots.Count, drawnSims.Count), Math.Min(Math.Min(drawnPlaced.Count, motions.Count), tokenMeshes.Count));
            for (int i = 0; slide && i < drawn; i++)
                if (tokenRoots[i] != null && !was.ContainsKey(Key(drawnSims[i], tokenRoots[i].name))) was[Key(drawnSims[i], tokenRoots[i].name)] = i;
            var from = new int[placed.Count];   // the old token each one is drawn on, or -1 for a new one
            var same = new bool[placed.Count];  // and whether it is kept whole
            var taken = new bool[tokenRoots.Count];
            for (int j = 0; j < placed.Count; j++)
            {
                from[j] = -1;
                if (!was.TryGetValue(Key(placed[j].Token.StateUnit?.Id ?? -1, placed[j].Token.Unit.Id), out int i) || taken[i]) continue;
                taken[i] = true; from[j] = i;
                same[j] = drawnPlaced[i].Equals(placed[j]) && (motions[i] != null) == AnimateMoves;
            }
            var outgoing = new List<GameObject>();
            void Retire(GameObject old)
            {
                // Roster holders retain Far through deactivation and release it only on destruction. Deactivate before
                // deferred Destroy so these outgoing holders are never considered a live prefetch handoff target.
                old.SetActive(false);
                old.transform.SetParent(null);
                outgoing.Add(old);
            }
            var kept = new HashSet<Transform>();
            for (int i = 0; i < taken.Length; i++) if (taken[i]) kept.Add(tokenRoots[i]); else if (i < tokenMeshes.Count) FreeMeshes(tokenMeshes[i]);
            for (int i = tokensRoot.childCount - 1; i >= 0; i--)
                if (!kept.Contains(tokensRoot.GetChild(i))) Retire(tokensRoot.GetChild(i).gameObject);
            for (int j = 0; j < placed.Count; j++)
            {
                if (from[j] < 0 || same[j]) continue;
                var root = tokenRoots[from[j]];
                FreeMeshes(tokenMeshes[from[j]]);
                for (int c = root.childCount - 1; c >= 0; c--) Retire(root.GetChild(c).gameObject);
                if (motions[from[j]] is UnitTokenMotion m && m != null) m.Restart();   // as a new token's (the hand-over follows)
            }
            // The outgoing holders are destroyed only after the new tokens have acquired their models, as the player's
            // deferred Destroy already does: an edit-mode rebuild must not drop a model's last owner in between and ask the
            // source again for a request still in flight (or release an arrived model) only to re-acquire it.
            try { BuildTokens(drawnAt, firing, hits, from, same); }
            finally { foreach (var old in outgoing) if (Application.isPlaying) Destroy(old); else DestroyImmediate(old); }
            foreach (int id in drawnSims) gone.Remove(id);
        }

        /// <summary>Where token <paramref name="i"/> is now: its place on the ground plus any slide under way, without the hit's
        /// shake (a defender shaking from one hit still takes the next burst, or raises its dust, on its own spot).</summary>
        Vector3 DrawnAt(int i) => trios[i].centre + (i < motions.Count && motions[i] is UnitTokenMotion m && m != null ? m.SlideOffset : Vector3.zero);

        static (int sim, string row) Key(int simId, string row) => simId >= 0 ? (simId, "") : (-1, row);

        void BuildTokens(IReadOnlyDictionary<(int sim, string row), Vector3> drawnAt,
            IReadOnlyDictionary<(int sim, string row), float> firing,
            IReadOnlyDictionary<(int sim, string row), (float left, float delay)> hits, int[] from, bool[] same)
        {
            pickVersion++;
            // What each old token holds, by its old index (from): a kept token takes its own entries over unchanged.
            var oldRoots = tokenRoots.ToArray(); var oldMeshes = tokenMeshes.ToArray(); var oldHoles = tokenHoles.ToArray();
            var oldMotions = motions.ToArray(); var oldBadges = badges.ToArray(); var oldHomes = badgeHomes.ToArray();
            var oldTrios = trios.ToArray(); var oldBoxes = keepClear.ToArray();
            tokenRoots.Clear(); tokenMeshes.Clear(); tokenHoles.Clear();
            motions.Clear();
            drawnSims.Clear();
            foreach (var p in placed) drawnSims.Add(p.Token.StateUnit?.Id ?? -1);
            drawnPlaced = placed;
            badges.Clear(); badgeHomes.Clear(); facedFor = null;
            // The new figures stand as at yaw 0 and at their own scale, the kept ones as the last camera turned them: FaceCamera
            // turns and scales them all.
            trios.Clear(); turnedFor = null; rescaleDue = true;
            treeHoles.Clear();
            keepClear = new List<Bounds[]>();   // a new list, so the labels see the change
            keepClearSpare = new List<Bounds[]>(); slid = false;   // and a spare no label pass has seen
            float hex = map.Hexes.hex_size_km * 1000f;
            for (int n = 0; n < placed.Count; n++)
            {
                var p = placed[n];
                var t = p.Token;
                if (same[n])
                {
                    int i = from[n];
                    tokenRoots.Add(oldRoots[i]); tokenMeshes.Add(oldMeshes[i]); tokenHoles.Add(oldHoles[i]);
                    if (oldHoles[i] is { } kept) treeHoles.Add(kept);
                    badges.Add(oldBadges[i]); badgeHomes.Add(oldHomes[i]); trios.Add(oldTrios[i]); keepClear.Add(oldBoxes[i]);
                    continue;
                }
                GameObject go;
                if (from[n] >= 0) { go = oldRoots[from[n]].gameObject; go.name = t.Unit.Id; }   // its old pieces are gone (Rebuild)
                else
                {
                    go = new GameObject(t.Unit.Id);
                    go.transform.SetParent(tokensRoot, false);
                }
                buildingMeshes = new List<Mesh>();
                (Vector2 centre, float radius)? hole = null;
                var centre = Centre(p.Spot);
                var foot = centre;   // where the badge's height is measured from
                float top, plinth = 0f;
                var figures = Array.Empty<(Transform, Vector3, float)>();
                switch (t.Unit.Service)
                {
                    case UnitData.Army:
                        // Demo2 T29's token: the figures stand shoulder to shoulder on one earth base with a bright white
                        // rim, under the side's flag (refs #197). The base fits the full trio, whatever the call-up.
                        float k = UnitShowcase.DrawSpread * hex * Spread(p.Spot);
                        plinth = UnitPlinth.Radius(UnitPlinth.TrioWidth(UnitShowcase.FigureOffsets(3), k));
                        foot.y = UnitPlinth.Build(map, go.transform, centre, plinth, t.Unit.Side, TokenMesh, MeshFor, paint, rim, FlagCloth);
                        hole = (new Vector2(centre.x, centre.z), plinth * UnitPlinth.RimOuter);
                        var offsets = UnitShowcase.FigureOffsets(t.Figures);
                        float highest = foot.y;   // the badge clears the highest figure (on a slope the uphill one stands higher)
                        bool israel = t.Unit.Side == UnitData.Israel;
                        // Owner, 31 October 2026 ("Yes, fallback in v0.3.2"): an Arab force whose figure failed to load stands
                        // with the plain built-in rifleman (steel helmet), the Israeli fail-open figure; only for that failure.
                        bool builtIn = !israel && !UnitFigures.Arrived(UnitFigures.SideFigure(t.Unit.Side)!);
                        int vehicles = Mathf.Min(t.Vehicles.Count, VehicleSlots.Length);
                        figures = new (Transform, Vector3, float)[offsets.Length + vehicles];
                        for (int i = 0; i < offsets.Length; i++)
                        {
                            // The pose and heading are the trio position's; the headgear is the unit's (sourced, or the default).
                            var (_, _, pose, faded, heading) = UnitShowcase.Trio[i];
                            var at = centre + new Vector3(offsets[i].x, 0, offsets[i].y) * k;
                            at.y = UnitPlinth.FigureY(map, plinth, at.x, at.z);
                            highest = Mathf.Max(highest, at.y);
                            Transform figure;
                            if (israel)
                            {
                                var hat = Hat(t.Headgear[i]);
                                var type = UnitRoster.RiflemanType(t.Headgear[i]);
                                figure = UnitShowcase.Piece(go.transform, $"Rifleman{i}", type, () => MeshFor($"{type}/{pose}", () => UnitModels.Rifleman(hat, pose, faded, type)),
                                    paint, at, Quaternion.Euler(0, heading, 0), UnitShowcase.FigureScale, out _).transform;
                            }
                            else if (builtIn)
                            {
                                var type = UnitRoster.RiflemanType(UnitData.SteelHelmet);
                                figure = UnitShowcase.Piece(go.transform, $"Figure{i}", type, () => MeshFor($"{type}/{pose}",
                                    () => UnitModels.Rifleman(UnitModels.Headgear.SteelHelmet, pose, faded, type)),
                                    paint, at, Quaternion.Euler(0, heading, 0), UnitShowcase.FigureScale, out _).transform;
                            }
                            else figure = EmptyPiece(go.transform, $"Figure{i}", at, heading);   // no code-built figure for another side (#740)
                            var model = UnitFigures.FigureFor(t.Unit, i, israel ? t.Headgear[i] : null);
                            UnitFigures.Dress(figure, model, map.Residency.Units, retainFar: true);   // the Collection's figure, held while its roster token lives (#665)
                            UnitFigureWeapon.Equip(figure, t.Unit.Side, model);   // its sourced weapon, if any (#2083)
                            UnitFigurePointFire.Equip(figure, model);   // C06's point-fire aim when the token attacks (#2084)
                            figures[i] = (figure, new Vector3(offsets[i].x, 0, offsets[i].y) * k, heading);
                        }
                        for (int j = 0; j < vehicles; j++)
                        {
                            var (slot, heading) = VehicleSlots[j];
                            var offset = new Vector3(slot.x, 0f, slot.y) * plinth;
                            var at = centre + offset;
                            at.y = UnitPlinth.FigureY(map, plinth, at.x, at.z);
                            var vehicle = EmptyPiece(go.transform, $"Vehicle{j}", at, heading);
                            UnitFigures.Dress(vehicle, t.Vehicles[j], map.Residency.Units,
                                retainFar: true);   // the gun or the jeep: held while its roster token lives (#665)
                            UnitGunFire.Equip(vehicle, t.Vehicles[j]);   // the 65 mm gun fires when the token attacks (#2373)
                            figures[offsets.Length + j] = (vehicle, offset, heading);
                        }
                        foot.y = highest;
                        top = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;
                        break;
                    case UnitData.Air:
                        BuildAircraft(go.transform, t, centre);
                        if (!t.Flying && StillBox(go.transform, null, Array.Empty<MeshFilter>()) is Bounds aircraft)
                        {
                            var flat = new Vector2(aircraft.center.x, aircraft.center.z);
                            hole = (flat, new Vector2(aircraft.extents.x, aircraft.extents.z).magnitude);
                        }
                        top = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;
                        break;
                    default:
                        UnitShowcase.Piece(go.transform, "Corvette", t.ArtType, () => MeshFor(t.ArtType, () => UnitModels.Corvette(t.ArtType)),
                            paint, centre, Quaternion.Euler(0, UnitShowcase.ShipHeadingDegrees, 0), UnitShowcase.ShipScale, out _);
                        top = UnitBadge.MastHeightM * UnitShowcase.ShipScale;
                        break;
                }
                var badge = new GameObject("Badge");
                badge.transform.SetParent(go.transform, false);
                // Above the figures by the badge's lift, and above the flag's top (the cloth turns with the camera, so at some yaws it
                // stands right behind the badge): the badge's lower edge clears the pole's top by BadgeOverFlagM.
                float lift = top + UnitBadge.LiftM;
                if (t.Unit.Service == UnitData.Army && go.transform.Find(UnitPlinth.FlagName) != null)
                    lift = Mathf.Max(lift, UnitFlags.PoleHeight * UnitBadge.FigureHeightM * UnitShowcase.FigureScale + UnitBadge.SizeM / 2f + BadgeOverFlagM);
                var home = foot + Vector3.up * lift;
                float back = t.Unit.Service == UnitData.Army ? BadgeBackShare * UnitPlinth.Radius(UnitPlinth.TrioWidth(UnitShowcase.FigureOffsets(3), UnitShowcase.DrawSpread * hex * Spread(p.Spot))) : 0f;
                badge.transform.position = home + Vector3.forward * back;
                badge.transform.localScale = Vector3.one * UnitBadge.SizeM;
                badge.AddComponent<UnitBadge>();
                var flagT = go.transform.Find(UnitPlinth.FlagName);
                var flag = flagT != null ? flagT.GetComponent<MeshFilter>() : null;
                var pole = flagT != null ? new Vector3(flagT.position.x - centre.x, 0f, flagT.position.z - centre.z) : Vector3.zero;
                var meshes = figures.SelectMany(f => f.Item1.GetComponentsInChildren<MeshFilter>(true)).ToArray();
                var standing = StillBox(go.transform, flag, meshes);
                badges.Add(badge.transform); badgeHomes.Add((home, back, pole, flag, standing, t.Unit.Service == UnitData.Air && !t.Flying));
                trios.Add((centre, plinth, lift, figures, meshes));
                AddRenderer(badge.transform, "Plate", MeshFor("badge-plate", UnitBadge.PlateMesh), badgePlate, 0f);
                var hitFlash = AddRenderer(badge.transform, "HitFlash", MeshFor("badge-plate", UnitBadge.PlateMesh),
                    hitPlate, -UnitBadge.GlyphLift * 0.5f);
                hitFlash.enabled = false;
                // #2432: a military sim unit's strength in pips under a smaller glyph (UnitBadge.PipsMesh), one shared mesh per
                // strength and full strength, built here with the tokens (a change of either rebuilds them, UnitToken.Equals),
                // so nothing is done per frame; the squadron, the ships and a map-only token have no sim strength and no pips.
                bool pips = t.StateUnit != null && t.StateUnit.Side != "";
                AddRenderer(badge.transform, "Glyph", MeshFor("badge-" + t.Unit.Service + (pips ? "-pips" : ""), () => UnitBadge.GlyphMesh(t.Unit.Service, pips)),
                    badgeGlyph, -UnitBadge.GlyphLift);
                if (pips)
                {
                    int strength = t.StateUnit!.Strength, full = Mathf.Max(strength, UnitDamage.FullStrength(shownContent, t.StateUnit));
                    AddRenderer(badge.transform, "Pips", MeshFor(FormattableString.Invariant($"badge-pips-{strength}/{full}"), () => UnitBadge.PipsMesh(strength, full)),
                        badgeGlyph, -UnitBadge.GlyphLift);
                }
                // The badge's cube and the pieces (the flag and the figures as they stand now); FaceCamera moves both with the camera.
                var pieces = standing;
                if (pieces is Bounds s) { if (flag != null) s.Encapsulate(WorldBox(flag)); foreach (var m in meshes) if (m != null && m.sharedMesh != null) s.Encapsulate(WorldBox(m)); pieces = s; }
                keepClear.Add(pieces is Bounds p2 ? new[] { new Bounds(badge.transform.position, Vector3.one * UnitBadge.SizeM), p2 }
                    : new[] { new Bounds(badge.transform.position, Vector3.one * UnitBadge.SizeM) });
                tokenHoles.Add(hole);
                if (hole is { } h) treeHoles.Add(h);
                tokenMeshes.Add(buildingMeshes);
                tokenRoots.Add(go.transform);
            }
            buildingMeshes = null;
            for (int n = 0; n < tokenRoots.Count; n++) tokenRoots[n].SetSiblingIndex(n);   // the children in the tokens' order
            FaceCamera(Camera.main);   // the badges as the main camera sees them until a render turns them
            HideTrees();
            for (int i = 0; i < placed.Count; i++)
            {
                if (same[i]) { motions.Add(oldMotions[from[i]]); continue; }   // a kept token's move, attack or hit plays on
                var token = tokenRoots[i];
                var reused = from[i] >= 0 ? oldMotions[from[i]] : null;
                if (!AnimateMoves)
                {
                    if (reused != null) { if (Application.isPlaying) Destroy(reused); else DestroyImmediate(reused); }
                    motions.Add(null); continue;
                }
                var motion = reused != null ? reused : token.gameObject.AddComponent<UnitTokenMotion>();
                motion.enabled = false;   // runs only while it moves or attacks
                motion.SimId = placed[i].Token.StateUnit?.Id ?? -1;
                motion.Changed = () => { pickVersion++; facedFor = null; slid = true; };   // FaceCamera sets the badge and the boxes where the token is drawn
                motion.Effects = combat;
                motion.GroundHome = trios[i].centre;
                motion.HitFlash = badges[i].Find("HitFlash").GetComponent<Renderer>();
                motions.Add(motion);
                // With the units hidden the token cannot be seen, and it would slide only once they are shown again.
                if (tokensRoot.gameObject.activeInHierarchy && drawnAt.TryGetValue(Key(motion.SimId, token.name), out var was))
                {
                    if (motion.SimId >= 0 && held.Contains(motion.SimId)) motion.Hold(was - trios[i].centre);   // waits for its beat
                    else motion.Begin(was - trios[i].centre);
                }
                if (firing.TryGetValue(Key(motion.SimId, token.name), out var played)) motion.ContinueAttack(played);
                if (hits.TryGetValue(Key(motion.SimId, token.name), out var hit)) motion.ContinueHit(hit.left, hit.delay);
            }
        }

        /// <summary>Holds the tokens of <paramref name="simIds"/> where they are drawn now (#2202): the next rebuilds stand
        /// each at that place, its unit already moved by the sim, until <see cref="Release"/> or <see cref="ReleaseAll"/>.
        /// A token mid-slide stops where it is. Ids the layer does not draw are kept, and hold nothing.</summary>
        public void Hold(IEnumerable<int> simIds)
        {
            foreach (int id in simIds)
            {
                if (id < 0 || !held.Add(id)) continue;
                foreach (var m in motions) if (m != null && m.SimId == id) { m.Hold(m.SlideOffset); break; }
            }
        }

        /// <summary>Lets the held token of <paramref name="simId"/> slide from where it waits to its place, as any move.
        /// False when it was not held, or no token of it waits.</summary>
        public bool Release(int simId)
        {
            if (!held.Remove(simId)) return false;
            foreach (var m in motions)
                if (m != null && m.SimId == simId && m.Held) { m.Unhold(slide: true); return true; }
            return false;
        }

        /// <summary>Releases every held token: each slides (<paramref name="snap"/> false) or stands on its place at once.</summary>
        public void ReleaseAll(bool snap)
        {
            held.Clear();
            foreach (var m in motions) if (m != null && m.Held) m.Unhold(slide: !snap);
        }

        /// <summary>Whether a token draws sim unit <paramref name="simId"/> now.</summary>
        public bool Draws(int simId) => simId >= 0 && drawnSims.Contains(simId);

        /// <summary>Plays the attack take of sim unit <paramref name="simId"/>'s figures (#1867). False when no token draws
        /// that unit or none of its figures can play one now (a far zoom, the units hidden, or no fire take).</summary>
        public bool PlayAttack(int simId)
        {
            foreach (var motion in motions)
                if (motion != null && motion.SimId == simId) return motion.PlayAttack();
            return false;
        }

        /// <summary>Plays an attack and reports its actual visible fire start, or the end of its brief wait without one.</summary>
        internal bool PlayAttack(int simId, Action started, Action missed)
        {
            foreach (var motion in motions)
                if (motion != null && motion.SimId == simId) return motion.PlayAttack(started, missed);
            missed();
            return false;
        }

        /// <summary>Briefly shakes and flashes every currently drawn defender when the engagement records aggregate
        /// defender loss. The cause cannot identify an individual damaged unit, so the visible group reacts together.</summary>
        public bool PlayDefenderHit(CombatHit hit)
        {
            if (hit.DefenderLoss <= 0 || !gameObject.activeInHierarchy) return false;
            bool played = false;
            foreach (int id in hit.Defenders)
                foreach (var motion in motions)
                {
                    if (motion == null || motion.SimId != id) continue;
                    played |= motion.PlayHit(CombatBursts.ImpactS(hit));   // with the hit on it, not the shot
                    break;
                }
            return played;
        }

        /// <summary>Plays an attack's hit (owner, 4 November 2026: "Hit on target hex"): a shell's burst and the small arms'
        /// dust on the first defender drawn (where its token is drawn now, or stood if the attack destroyed it), else on the
        /// hit hex's centre. False when nothing plays (no flipbooks, the units hidden, or the hex is not on the map).</summary>
        public bool PlayHit(CombatHit hit)
        {
            if (combat == null) return false;
            Vector3? at = null;
            foreach (int id in hit.Defenders)
            {
                int i = drawnSims.IndexOf(id);
                if (i >= 0 && i < trios.Count) { at = DrawnAt(i); break; }
                if (gone.TryGetValue(id, out var was)) { at = was; break; }
            }
            if (at == null && shownContent?.HexAt(hit.Q, hit.R) is MapHex hex)
            {
                var c = XZ(map)(hex.Lon, hex.Lat);
                at = UnitShowcase.Ground(map, new Vector3(c.x, 0f, c.y));
            }
            return at is Vector3 p && combat.Hit(p, hit.Guns, hit.SmallArms);
        }

        /// <summary>Raises a destroyed sim unit's dust where its token stood when the rebuild dropped it (owner, 4 November
        /// 2026: "Dust when a unit dies"), once. False when its token was not drawn, or nothing plays.</summary>
        public bool PlayDestroyed(int simId, float delayS = 0f)
        {
            if (combat == null || !gone.TryGetValue(simId, out var at)) return false;
            gone.Remove(simId);
            return combat.Destroyed(at, delayS);
        }

        /// <summary>The world box of a mesh's bounds through its transform. From the mesh and the transform, not
        /// Renderer.bounds, which is empty while the layer is inactive (the "units" toggle off when the tokens are built;
        /// review of #518).</summary>
        static Bounds WorldBox(MeshFilter f)
        {
            var b = f.sharedMesh.bounds; var m = f.transform.localToWorldMatrix; var box = new Bounds(m.MultiplyPoint3x4(b.min), Vector3.zero);
            for (int c = 1; c < 8; c++)
                box.Encapsulate(m.MultiplyPoint3x4(new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z)));
            return box;
        }

        /// <summary>The box of a token's pieces that neither turn nor move (a flying aircraft, the badge, and the flag and the
        /// figures, which turn with the camera, are left out), or null when it has none.</summary>
        static Bounds? StillBox(Transform token, MeshFilter? flag, MeshFilter[] figures)
        {
            Bounds? box = null;
            foreach (var f in token.GetComponentsInChildren<MeshFilter>(true))
            {
                if (f.sharedMesh == null || f == flag || Array.IndexOf(figures, f) >= 0 || f.GetComponentInParent<UnitBadge>(true) != null || f.GetComponentInParent<ShowcaseFlight>(true) != null) continue;
                var w = WorldBox(f);
                if (box is Bounds b) { b.Encapsulate(w); box = b; } else box = w;
            }
            return box;
        }

        /// <summary>A piece with no code-built model (an Arab force's figure, a vehicle): the Collection's model goes under it.</summary>
        static Transform EmptyPiece(Transform parent, string name, Vector3 at, float heading)
        {
            var piece = new GameObject(name).transform;
            piece.SetParent(parent, false);
            piece.SetPositionAndRotation(at, Quaternion.Euler(0, heading, 0));
            piece.localScale = Vector3.one * UnitShowcase.FigureScale;
            return piece;
        }

        static Renderer AddRenderer(Transform parent, string name, Mesh mesh, Material mat, float z)
        {
            var go = new GameObject(name);
            go.transform.SetParent(parent, false);
            go.transform.localPosition = new Vector3(0, 0, z);
            go.AddComponent<MeshFilter>().sharedMesh = mesh;
            var r = go.AddComponent<MeshRenderer>();
            r.sharedMaterial = mat;
            r.shadowCastingMode = ShadowCastingMode.Off;
            r.receiveShadows = false;
            return r;
        }

        /// <summary>The screen box of <paramref name="plane"/>'s tail, the rear <see cref="BadgeTailShare"/> of its meshes' box
        /// along its own z axis (the way it faces), or null before any mesh has arrived.</summary>
        static Rect? TailScreenRect(Transform plane, Camera cam)
        {
            Vector3 min = Vector3.positiveInfinity, max = Vector3.negativeInfinity;
            foreach (var f in plane.GetComponentsInChildren<MeshFilter>(true))
            {
                if (f.sharedMesh == null) continue;
                var bounds = f.sharedMesh.bounds;
                for (int c = 0; c < 8; c++)
                {
                    var p = plane.InverseTransformPoint(f.transform.TransformPoint(new Vector3((c & 1) == 0 ? bounds.min.x : bounds.max.x,
                        (c & 2) == 0 ? bounds.min.y : bounds.max.y, (c & 4) == 0 ? bounds.min.z : bounds.max.z)));
                    min = Vector3.Min(min, p); max = Vector3.Max(max, p);
                }
            }
            if (min.x > max.x) return null;
            max.z = Mathf.Lerp(min.z, max.z, BadgeTailShare);
            var corners = new Vector3[8];
            for (int c = 0; c < 8; c++)
                corners[c] = plane.TransformPoint(new Vector3((c & 1) == 0 ? min.x : max.x, (c & 2) == 0 ? min.y : max.y, (c & 4) == 0 ? min.z : max.z));
            return ScreenRect(cam, corners);
        }

        /// <summary>The screen box round <paramref name="points"/> as <paramref name="cam"/> projects them.</summary>
        static Rect ScreenRect(Camera cam, params Vector3[] points)
        {
            float x0 = float.MaxValue, y0 = float.MaxValue, x1 = float.MinValue, y1 = float.MinValue;
            foreach (var p in points)
            {
                var q = cam.WorldToScreenPoint(p);
                x0 = Mathf.Min(x0, q.x); y0 = Mathf.Min(y0, q.y); x1 = Mathf.Max(x1, q.x); y1 = Mathf.Max(y1, q.y);
            }
            return Rect.MinMaxRect(x0, y0, x1, y1);
        }

        void BuildAircraft(Transform parent, UnitToken t, Vector3 baseCentre)
        {
            var plane = new GameObject("Aircraft");
            plane.transform.SetParent(parent, false);
            bool spitfire = t.ArtType == UnitShowcase.SpitfireType;
            Func<Mesh> airframe = spitfire ? (Func<Mesh>)(() => UnitModels.Spitfire(t.ArtType))
                : () => UnitModels.AviaS199(t.ArtType);
            // The code-built Spitfire's satin paint (UnitShowcase.AircraftSmoothness); the S-199 keeps the units' paint.
            var mat = spitfire ? AircraftPaint() : paint;
            var airframeGo = UnitShowcase.Piece(plane.transform, "Airframe", t.ArtType, () => MeshFor(t.ArtType, airframe), mat, Vector3.zero, Quaternion.identity, 1f, out bool authored);
            Transform? prop = null, shadow = null;
            Vector2 shadowHalf = default;
            if (!authored)
            {
                var propKey = spitfire ? "spitfire-propeller" : "avia-s199-propeller";
                var propMesh = MeshFor(propKey, spitfire ? (Func<Mesh>)(() => UnitModels.SpitfirePropeller(propKey)) : () => UnitModels.S199Propeller(propKey));
                prop = UnitShowcase.Piece(plane.transform, "Propeller", propMesh, mat, Vector3.zero, Quaternion.identity, 1f).transform;
                prop.localPosition = spitfire ? UnitModels.SpitfirePropellerHub : UnitModels.S199PropellerHub;
            }
            // A flying Spitfire's light propeller blur, soft ground shadow and no cast shadow, whichever model draws it (an
            // authored one brings its own propeller, UnitShowcase.AuthoredPropellerName).
            if (spitfire && t.Flying)
            {
                prop = UnitShowcase.FlyingSpitfire(plane.transform, airframeGo, prop, aircraftBlurMesh ??= assets.Own(UnitShowcase.PropellerBlurMesh()), AircraftBlur(),
                    aircraftShadowMesh ??= assets.Own(Collection.SeaAirCollection.SpitfireShadowDisc()), out var laid, out shadowHalf);
                shadow = laid;
            }
            plane.transform.localScale = Vector3.one * UnitShowcase.AircraftScale;
            if (t.Flying)
            {
                var flight = plane.AddComponent<ShowcaseFlight>();
                flight.Configure(baseCentre, UnitShowcase.LoopRadiusM, UnitShowcase.LoopFloor(map, baseCentre, UnitShowcase.LoopRadiusM) + UnitShowcase.AltitudeM,
                    UnitShowcase.LoopSeconds, UnitShowcase.BankDegrees, prop, still ? UnitShowcase.StillPhase : (float?)null,
                    shadow, map.Terrain, UnitShowcase.SeaLevelY(map), shadowHalf);
            }
            else
                plane.transform.SetPositionAndRotation(baseCentre + Vector3.up * ParkedHeightM * UnitShowcase.AircraftScale,
                    Quaternion.Euler(0, ParkedHeadingDegrees, 0));
        }
    }
}