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.

Map: shell bursts and dust on the attacked hex, flipbook fire and smoke, dust where a unit dies (Refs #2069) (#2614)

Eyal Golan74cf30c923d3
diff --git a/changelog.d/2645.md b/changelog.d/2645.md
new file mode 100644
index 000000000..c8a007fe2
--- /dev/null
+++ b/changelog.d/2645.md
@@ -0,0 +1 @@
+- Moving units now leave a short, light ground-dust trail, and a defending group that takes losses briefly shakes and flashes.
diff --git a/changelog.d/combat-flipbook-vfx.md b/changelog.d/combat-flipbook-vfx.md
new file mode 100644
index 000000000..ebae71d80
--- /dev/null
+++ b/changelog.d/combat-flipbook-vfx.md
@@ -0,0 +1,7 @@
+- The map now shows where an attack lands and what it costs (owner, 4 November 2026: "Hit on target hex",
+ "Fire/smoke on attacked hexes" and "Dust when a unit dies"). When guns attack, a shell bursts on the defender's token
+ just after the gun's flash; small arms kick up a short volley of dust there. A unit destroyed in the fight leaves a
+ cloud of dust where its token stood. On a hex under attack the small flame cones are now animated flames and the
+ smoke columns are drawn from a smoke flipbook. All of it uses the two CC0 Unity Labs flipbooks the Dakotas brought in
+ (#2490), drawn the same way, from small pools that allocate nothing per frame. Looks only: no change to the game's
+ rules, numbers or saves.
diff --git a/changelog.d/train-steam.md b/changelog.d/train-steam.md
new file mode 100644
index 000000000..81ccb6cff
--- /dev/null
+++ b/changelog.d/train-steam.md
@@ -0,0 +1,7 @@
+- The steam train now leaves a short trail of smoke and steam while it runs (owner, 4 November 2026: "Train steam").
+ Palestine Railways had converted its locomotives from coal to oil by 1943; the game assumes they still burned oil in
+ 1950 (unsourced). The smoke leaves the chimney dark grey-black and thins to grey, with white steam puffs among it,
+ drifting back along the track; the smoke colour is a design choice. It stops when the train
+ stands at either end of its run and is never drawn while the train is hidden. It uses the CC0 smoke flipbook the
+ Dakotas brought in (#2490), from a small pool that allocates nothing per frame. Looks only: no change to the game's
+ rules, numbers or saves.
diff --git a/research_notes/Map/train-steam-oil-burning-2026-11-05.md b/research_notes/Map/train-steam-oil-burning-2026-11-05.md
new file mode 100644
index 000000000..40b5a847b
--- /dev/null
+++ b/research_notes/Map/train-steam-oil-burning-2026-11-05.md
@@ -0,0 +1,22 @@
+# The train's steam: Palestine Railways burned oil
+
+Sources for the colour of the service train's exhaust (`TrainSteam`; owner, 4 November 2026, "Train steam"). The game draws dark grey-black smoke at the chimney, thinning to grey, with white steam puffs: the look of an oil-burning locomotive rather than a coal-burning one.
+
+Tags follow the research convention (`.github/skills/statecraft-video-script/references/05-claims-quotes-and-sources.md`): [S] single or secondary source. The pages below were opened and the lines copied by an AI agent (Claude), not by a person, so none is [V].
+
+## Palestine Railways converted from coal to oil, 1942-43
+
+- English Wikipedia, "Palestine Railways", section on the Second World War (https://en.wikipedia.org/wiki/Palestine_Railways, page source checked 2026-11-05): "PR had fuelled its locomotives with Welsh coal [Hughes 1981, p. 41] but in June 1940 Italy declared war on the Allies and France surrendered to Germany and Italy, leaving the Mediterranean extremely dangerous for British merchant shipping. Early in 1942 PR belatedly began to convert its locomotives to burn oil, [Cotterell 1984, p. 77] but it did not complete the conversion programme until 1943. [Hughes 1981, p. 41]" [S]
+- English Wikipedia, "Palestine Railways P class" (https://en.wikipedia.org/wiki/Palestine_Railways_P_class, page source checked 2026-11-05):
+ - Infobox, fuel type: "originally Welsh coal; converted to oil by 1943" [Hughes 1981, p. 41]. [S]
+ - Infobox, fuel capacity: "1,193 imperial gallons" "(after conversion to oil fuel)" [Cotterell 1984, p. 130]. [S]
+ - Body: "PR therefore began converting its locomotives to burn oil, but it did not complete the conversion programme until 1943." [Hughes 1981, p. 41] [S]
+- English Wikipedia, "Palestine Railways H class" (https://en.wikipedia.org/wiki/Palestine_Railways_H_class, page source checked 2026-11-05), infobox, fuel type: "originally Welsh coal; converted to oil fuel by 1943" [Hughes 1981, p. 41]. [S]
+
+The books behind these lines are Hughes, *Middle East Railways* (1981), and Cotterell, *The Railways of Palestine and Israel* (1984). Neither was opened here.
+
+## Not checked
+
+- A web-research pass on 4 November 2026 (`.superpowers/coordination/codex-results/railfuel-web.md`, not in the repository) also reported Google Books snippets: the Palestine and Transjordan administration report for 1945, *A Survey of Palestine* (1946: "all locomotives have been converted from coal to oil burning"), Railway Gazette's *Overseas Railways* (1948), and *World Railways* (1956) on Israel Railways' steam stock "(oil burning)" with "Fuel oil, obtained locally". On 2026-11-05 Google Books answered with a robot check, so none of those was opened; they stay unconfirmed.
+- No source found says whether Israel Railways went back to coal in 1948-50. The game's train runs from 2 March 1950 and assumes it still burned oil.
+- No period description of the smoke's colour was found. Dark grey-black at the chimney thinning to grey is the general look of oil-fired exhaust, a design choice, not a sourced detail of these locomotives.
diff --git a/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs b/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs
index 10cb4c893..5bb34c0f9 100644
--- a/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs
+++ b/unity/Assets/Editor/HexTiles/Tests/HexUnderAttackTests.cs
@@ -3,12 +3,15 @@ using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Statecraft.HexTiles;
+using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
/// <summary>The "under attack" look (HexUnderAttack): presentation only, shown on one hex and hidden again. It sits on
/// the hex centre and stays inside the hex at every time, shows once however often it is shown, frees every mesh and
-/// material it made when hidden, samples the same pulse and smoke for the same time, and ships its material templates.</summary>
+/// material it made when hidden, samples the same pulse and smoke for the same time, and ships its material templates. Its
+/// smoke and flames are #2490's flipbooks (owner, 4 November 2026: "Fire/smoke on attacked hexes"), one mesh each, sampled
+/// with no allocation.</summary>
public class HexUnderAttackTests
{
const int Q = -3, R = 19;
@@ -71,9 +74,10 @@ public class HexUnderAttackTests
go.GetComponent<HexUnderAttackLook>().Time(1.5f);
var (meshes, renderers) = Parts(go);
var materials = renderers.SelectMany(r => r.sharedMaterials).ToList();
+ // The flipbooks are Resources assets the look shows, not makes: they stay.
var made = meshes.Select(m => (Object)m.sharedMesh).Concat(materials)
- .Concat(materials.Select(m => m.GetTexture("_BaseMap")).Where(t => t != null)).ToList();
- Assert.That(made.Count, Is.GreaterThanOrEqualTo(6), "three meshes and three materials at least");
+ .Concat(materials.Select(m => m.GetTexture("_BaseMap")).Where(t => t != null && !EditorUtility.IsPersistent(t))).ToList();
+ Assert.That(made.Count, Is.GreaterThanOrEqualTo(8), "four meshes and four materials at least");
Assert.That(made.All(o => o != null));
Assert.That(HexUnderAttack.Hide(root, Q, R), Is.True);
Assert.That(made.Where(o => o != null).Select(o => o.name), Is.Empty, "every mesh and material the look made is destroyed");
@@ -135,6 +139,62 @@ public class HexUnderAttackTests
}
}
+ static Mesh MeshOf(GameObject go, string part) => go.transform.Find(part).GetComponent<MeshFilter>().sharedMesh;
+ static Texture TextureOf(GameObject go, string part) => go.transform.Find(part).GetComponent<Renderer>().sharedMaterial.GetTexture("_BaseMap");
+
+ /// <summary>The smoke is the smoke flipbook, each puff on one frame of it; the flames are the explosion flipbook's
+ /// burning frames on camera-facing quads, one mesh for the hex; both move with time.</summary>
+ [Test]
+ public void TheSmokeAndTheFlamesAreFlipbookFrames()
+ {
+ var go = HexUnderAttack.Show(Root(), new FlatSurface(), Q, R);
+ var look = go.GetComponent<HexUnderAttackLook>();
+ Assert.That(TextureOf(go, "Smoke"), Is.SameAs(Flipbook.Load(Flipbook.SmokeResource)), "the smoke flipbook (#2490)");
+ Assert.That(TextureOf(go, "Fire"), Is.SameAs(Flipbook.Load(Flipbook.ExplosionResource)), "the explosion flipbook (#2490)");
+ int columns = HexUnderAttack.SmokeBases(Q, R, HexScale.HexM).Length, flames = columns * HexUnderAttack.Fire.PerColumn;
+ Assert.That(MeshOf(go, "Fire").vertexCount, Is.EqualTo(flames * 4), "a quad per flame, all in one mesh");
+ float smokeCell = 1f / Flipbook.SmokeGrid, fireCell = 1f / Flipbook.ExplosionGrid;
+ int burningRows = (Flipbook.ExplosionFireFrames + Flipbook.ExplosionGrid - 1) / Flipbook.ExplosionGrid;
+ foreach (var t in new[] { 0f, 0.31f, 1.7f, 9.2f })
+ {
+ look.Time(t);
+ var smokeUV = MeshOf(go, "Smoke").uv;
+ const int perPuff = 9; // the octagon's centre and its rim
+ for (int p = 0; p < smokeUV.Length / perPuff; p++)
+ {
+ var puff = smokeUV.Skip(p * perPuff).Take(perPuff).ToArray();
+ float x0 = Mathf.Floor(puff[0].x / smokeCell) * smokeCell, y0 = Mathf.Floor(puff[0].y / smokeCell) * smokeCell;
+ Assert.That(puff.All(uv => uv.x >= x0 - 1e-4f && uv.x <= x0 + smokeCell + 1e-4f && uv.y >= y0 - 1e-4f && uv.y <= y0 + smokeCell + 1e-4f),
+ $"puff {p} at t={t} stays on one frame");
+ }
+ var fireUV = MeshOf(go, "Fire").uv;
+ for (int f = 0; f < flames; f++)
+ {
+ var quad = fireUV.Skip(f * 4).Take(4).ToArray();
+ Assert.That(quad.Max(uv => uv.x) - quad.Min(uv => uv.x), Is.EqualTo(fireCell).Within(1e-4f), $"flame {f}: one frame wide");
+ Assert.That(quad.Min(uv => uv.y), Is.GreaterThanOrEqualTo(1f - burningRows * fireCell - 1e-4f), $"flame {f} at t={t}: a burning frame, never the smoke");
+ int frame = Mathf.RoundToInt(quad.Min(uv => uv.x) / fireCell) + Flipbook.ExplosionGrid * Mathf.RoundToInt((1f - quad.Max(uv => uv.y)) / fireCell);
+ Assert.That(frame, Is.LessThan(Flipbook.ExplosionFireFrames), $"flame {f} at t={t}: frame {frame} burns");
+ }
+ }
+ look.Time(1f); var fireA = MeshOf(go, "Fire").uv; var smokeA = MeshOf(go, "Smoke").uv;
+ look.Time(1f + HexUnderAttack.Fire.CycleS / 2f);
+ CollectionAssert.AreNotEqual(fireA, MeshOf(go, "Fire").uv, "the flames burn through the frames");
+ look.Time(4f);
+ CollectionAssert.AreNotEqual(smokeA, MeshOf(go, "Smoke").uv, "the smoke boils through the frames");
+ }
+
+ /// <summary>Per-frame garbage stutters on WebGL: sampling the look (smoke, flames, glow, border) allocates nothing.</summary>
+ [Test]
+ public void SamplingTheLookAllocatesNothing()
+ {
+ var look = HexUnderAttack.Show(Root(), new FlatSurface(), Q, R).GetComponent<HexUnderAttackLook>();
+ for (int i = 0; i < 10; i++) look.Time(i * 0.016f); // warm up
+ long before = System.GC.GetAllocatedBytesForCurrentThread();
+ for (int i = 0; i < 300; i++) look.Time(1f + i * 0.016f);
+ Assert.That(System.GC.GetAllocatedBytesForCurrentThread() - before, Is.EqualTo(0), "no allocation per frame");
+ }
+
[Test]
public void TheTemplatesShipInResources()
{
diff --git a/unity/Assets/Scripts/Map/Collection/DakotaLoop.cs b/unity/Assets/Scripts/Map/Collection/DakotaLoop.cs
index 0db89c8c3..0cb8159c7 100644
--- a/unity/Assets/Scripts/Map/Collection/DakotaLoop.cs
+++ b/unity/Assets/Scripts/Map/Collection/DakotaLoop.cs
@@ -269,39 +269,11 @@ namespace Statecraft.Game.Map.Collection
return (at.ToArray(), from.ToArray());
}
- /// <summary>One quad mesh per frame of a <paramref name="grid"/> x <paramref name="grid"/> flipbook, its UVs on that
- /// frame (frame 0 top left, then along the rows, as Unity's texture sheet animation), facing -z as the built-in quad,
- /// white (the particle shaders multiply the vertex colour).</summary>
- internal static Mesh[] Frames(MapRuntimeAssets owned, int grid)
- {
- var frames = new Mesh[grid * grid];
- float k = 1f / grid;
- var v = new[] { new Vector3(-0.5f, -0.5f, 0f), new Vector3(0.5f, -0.5f, 0f), new Vector3(-0.5f, 0.5f, 0f), new Vector3(0.5f, 0.5f, 0f) };
- var normals = new[] { Vector3.back, Vector3.back, Vector3.back, Vector3.back };
- var white = new Color32[] { new Color32(255, 255, 255, 255), new Color32(255, 255, 255, 255), new Color32(255, 255, 255, 255), new Color32(255, 255, 255, 255) };
- var tris = new[] { 0, 3, 1, 3, 0, 2 };
- for (int f = 0; f < frames.Length; f++)
- {
- float u0 = (f % grid) * k, v0 = 1f - (f / grid + 1) * k;
- var uv = new[] { new Vector2(u0, v0), new Vector2(u0 + k, v0), new Vector2(u0, v0 + k), new Vector2(u0 + k, v0 + k) };
- var m = new Mesh { name = $"dakota-frame-{grid}x{grid}-{f}", vertices = v, normals = normals, colors32 = white, uv = uv, triangles = tris };
- m.RecalculateBounds();
- frames[f] = owned.Own(m);
- }
- return frames;
- }
+ /// <summary>One quad mesh per frame of a <paramref name="grid"/> x <paramref name="grid"/> flipbook, owned by the run's
+ /// object (Flipbook.Frames, shared with the combat effects).</summary>
+ internal static Mesh[] Frames(MapRuntimeAssets owned, int grid) => Flipbook.Frames(grid, owned.Own, "dakota-frame");
- static (Transform, Renderer, MeshFilter) Part(Transform parent, string name, Mesh mesh, Material material)
- {
- var go = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer));
- go.transform.SetParent(parent, false);
- var filter = go.GetComponent<MeshFilter>(); filter.sharedMesh = mesh;
- var r = go.GetComponent<MeshRenderer>();
- r.sharedMaterial = material; r.enabled = false;
- r.shadowCastingMode = ShadowCastingMode.Off; r.receiveShadows = false;
- r.lightProbeUsage = LightProbeUsage.Off; r.reflectionProbeUsage = ReflectionProbeUsage.Off;
- return (go.transform, r, filter);
- }
+ static (Transform, Renderer, MeshFilter) Part(Transform parent, string name, Mesh mesh, Material material) => Flipbook.Part(parent, name, mesh, material);
static int Mod(int a, int n) { int m = a % n; return m < 0 ? m + n : m; }
diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/Flipbook.cs b/unity/Assets/Scripts/Map/HexTiles/Core/Flipbook.cs
new file mode 100644
index 000000000..60cc2f8d9
--- /dev/null
+++ b/unity/Assets/Scripts/Map/HexTiles/Core/Flipbook.cs
@@ -0,0 +1,226 @@
+#nullable enable
+using System;
+using UnityEngine;
+using UnityEngine.Rendering;
+using Object = UnityEngine.Object;
+
+namespace Statecraft.HexTiles
+{
+ /// <summary>The flipbook technique #2490 brought in for the Dakotas' bombs (DakotaBombRun), shared so the combat effects
+ /// draw the same way: Unity Labs' two CC0 flipbooks ("Free VFX image sequences and flipbooks", Resources/Effects;
+ /// ASSETS.yaml), each frame a quad mesh made once whose UVs cover that frame (the URP particle shaders ignore the
+ /// material's tiling), shown on an unlit camera-facing quad; the frame picked from a time, so the same time draws the
+ /// same frame. Presentation only.</summary>
+ public static class Flipbook
+ {
+ /// <summary>The explosion (5 x 5 frames: a fireball that burns out into black smoke) and the smoke (8 x 8 frames of a
+ /// boiling grey cloud), as Resources paths.</summary>
+ public const string ExplosionResource = "Effects/Explosion01_5x5", SmokeResource = "Effects/Cloud02_8x8";
+ public const int ExplosionGrid = 5, SmokeGrid = 8;
+ /// <summary>The explosion's frames that still burn (0 to 9 have open fire; from 10 it is smoke).</summary>
+ public const int ExplosionFireFrames = 10;
+
+ static readonly int BaseMap = Shader.PropertyToID("_BaseMap"), Cull = Shader.PropertyToID("_Cull");
+
+ /// <summary>The flipbook at <paramref name="resource"/>, or null when it is missing (Resources keeps it: not owned).</summary>
+ public static Texture2D? Load(string resource) => Resources.Load<Texture2D>(resource);
+
+ /// <summary>Where frame <paramref name="frame"/> of a <paramref name="grid"/> x <paramref name="grid"/> flipbook sits in
+ /// its texture (frame 0 top left, then along the rows, as Unity's texture sheet animation): its lower left UV and its
+ /// side (1 / grid).</summary>
+ public static Vector2 FrameOrigin(int frame, int grid, out float side)
+ {
+ side = 1f / grid;
+ return new Vector2((frame % grid) * side, 1f - (frame / grid + 1) * side);
+ }
+
+ /// <summary>The frame of <paramref name="frames"/> a one-shot shows <paramref name="share"/> of the way through its
+ /// life (clamped to the first and last).</summary>
+ public static int FrameAt(float share, int frames) => Mathf.Clamp((int)(share * frames), 0, frames - 1);
+
+ /// <summary>The frame of <paramref name="frames"/> a looping flipbook shows at frame clock <paramref name="clock"/>
+ /// (seconds x frames per second, plus any offset), wrapping round; never negative.</summary>
+ public static int Looping(double clock, int frames)
+ {
+ int m = (int)(Math.Floor(clock) % frames);
+ return m < 0 ? m + frames : m;
+ }
+
+ /// <summary>One quad mesh per frame of a <paramref name="grid"/> x <paramref name="grid"/> flipbook, its UVs on that
+ /// frame, facing -z as the built-in quad, white (the particle shaders multiply the vertex colour), each passed to
+ /// <paramref name="own"/> (whoever destroys it) and named <paramref name="name"/>-{grid}x{grid}-{frame}.</summary>
+ public static Mesh[] Frames(int grid, Func<Mesh, Mesh> own, string name)
+ {
+ var frames = new Mesh[grid * grid];
+ var v = new[] { new Vector3(-0.5f, -0.5f, 0f), new Vector3(0.5f, -0.5f, 0f), new Vector3(-0.5f, 0.5f, 0f), new Vector3(0.5f, 0.5f, 0f) };
+ var normals = new[] { Vector3.back, Vector3.back, Vector3.back, Vector3.back };
+ var white = new Color32[] { new Color32(255, 255, 255, 255), new Color32(255, 255, 255, 255), new Color32(255, 255, 255, 255), new Color32(255, 255, 255, 255) };
+ var tris = new[] { 0, 3, 1, 3, 0, 2 };
+ for (int f = 0; f < frames.Length; f++)
+ {
+ var o = FrameOrigin(f, grid, out float k);
+ var uv = new[] { o, new Vector2(o.x + k, o.y), new Vector2(o.x, o.y + k), new Vector2(o.x + k, o.y + k) };
+ var m = new Mesh { name = $"{name}-{grid}x{grid}-{f}", vertices = v, normals = normals, colors32 = white, uv = uv, triangles = tris };
+ m.RecalculateBounds();
+ frames[f] = own(m);
+ }
+ return frames;
+ }
+
+ /// <summary>A hidden quad renderer under <paramref name="parent"/> drawing <paramref name="mesh"/> with
+ /// <paramref name="material"/>: no shadows, no probes.</summary>
+ public static (Transform, Renderer, MeshFilter) Part(Transform parent, string name, Mesh mesh, Material material)
+ {
+ var go = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer));
+ go.transform.SetParent(parent, false);
+ var filter = go.GetComponent<MeshFilter>(); filter.sharedMesh = mesh;
+ var r = go.GetComponent<MeshRenderer>();
+ r.sharedMaterial = material; r.enabled = false;
+ r.shadowCastingMode = ShadowCastingMode.Off; r.receiveShadows = false;
+ r.lightProbeUsage = LightProbeUsage.Off; r.reflectionProbeUsage = ReflectionProbeUsage.Off;
+ return (go.transform, r, filter);
+ }
+
+ /// <summary>A copy of the under-attack template <paramref name="template"/> (HexMaterials) showing
+ /// <paramref name="texture"/>, both faces drawn.</summary>
+ public static Material NewMaterial(string template, Texture2D texture)
+ {
+ var m = HexMaterials.New(template); m.SetTexture(BaseMap, texture); m.SetFloat(Cull, (float)CullMode.Off); return m;
+ }
+ }
+
+ /// <summary>A small fixed pool of one-shot flipbook bursts (an explosion, a puff of dust): each slot one quad made once,
+ /// hidden until used, on a material of its own (its colour fades by the material, so no mesh is uploaded), and every
+ /// slot's look a pure function of the clock (<see cref="Sample"/>), so a held time repeats exactly and sampling allocates
+ /// nothing. A burst starts at a clock time (later than now for a delayed one) and plays its <see cref="Style"/>: it opens
+ /// small and swells, rises, plays the flipbook once and fades out at its end, then frees its slot. A full pool takes
+ /// the slot whose burst started first. Whoever makes it destroys what it made (<see cref="Owned"/>).</summary>
+ public sealed class FlipbookBursts
+ {
+ /// <summary>How a burst plays: its life (s), the flipbook frames it runs through (from <see cref="FirstFrame"/>,
+ /// <see cref="Frames"/> of them), its size when it opens as a share of its full size, how much more it spreads by its
+ /// end, how far its centre rises over its life as a share of its size, the share of its life it fades over at the end,
+ /// its colour fresh and at its end (alpha included), and how high its centre sits over its foot as a share of its size.</summary>
+ public readonly struct Style
+ {
+ public readonly float LifeS, OpenShare, SpreadShare, RiseShare, FadeShare, CentreShare;
+ public readonly int FirstFrame, Frames;
+ public readonly Color Fresh, Old;
+ public Style(float lifeS, int firstFrame, int frames, float openShare, float spreadShare, float riseShare, float fadeShare,
+ Color fresh, Color old, float centreShare)
+ {
+ LifeS = lifeS; FirstFrame = firstFrame; Frames = frames; OpenShare = openShare; SpreadShare = spreadShare;
+ RiseShare = riseShare; FadeShare = fadeShare; Fresh = fresh; Old = old; CentreShare = centreShare;
+ }
+ }
+
+ static readonly int BaseColor = Shader.PropertyToID("_BaseColor");
+
+ readonly Style style;
+ readonly Mesh[] frames;
+ readonly Transform[] quad; readonly Renderer[] shown; readonly MeshFilter[] filter; readonly Material[] material;
+ readonly double[] from; // each slot's start on the clock, or NaN when free
+ readonly Vector3[] foot; readonly float[] size, spin;
+ readonly Object[] owned;
+ Quaternion view = Quaternion.identity;
+
+ /// <summary>The meshes and materials this pool made (the flipbook frames and one material per slot).</summary>
+ public Object[] Owned => owned;
+ public int Capacity => quad.Length;
+ /// <summary>The slots' renderers (tests).</summary>
+ public Renderer[] Renderers => shown;
+
+ /// <summary><paramref name="capacity"/> slots under <paramref name="parent"/>, each a quad of
+ /// <paramref name="texture"/>'s <paramref name="grid"/> x <paramref name="grid"/> frames on a copy of
+ /// <paramref name="template"/>, named <paramref name="name"/>.</summary>
+ public FlipbookBursts(Transform parent, string name, int capacity, Texture2D texture, int grid, string template, Style style)
+ {
+ this.style = style;
+ var made = new System.Collections.Generic.List<Object>();
+ frames = Flipbook.Frames(grid, m => { made.Add(m); return m; }, name);
+ quad = new Transform[capacity]; shown = new Renderer[capacity]; filter = new MeshFilter[capacity]; material = new Material[capacity];
+ from = new double[capacity]; foot = new Vector3[capacity]; size = new float[capacity]; spin = new float[capacity];
+ for (int i = 0; i < capacity; i++)
+ {
+ var m = material[i] = Flipbook.NewMaterial(template, texture); made.Add(m);
+ (quad[i], shown[i], filter[i]) = Flipbook.Part(parent, name, frames[Mathf.Clamp(style.FirstFrame, 0, frames.Length - 1)], m);
+ from[i] = double.NaN;
+ }
+ owned = made.ToArray();
+ }
+
+ /// <summary>The slots playing or waiting to play.</summary>
+ public int Busy
+ {
+ get { int n = 0; for (int i = 0; i < from.Length; i++) if (!double.IsNaN(from[i])) n++; return n; }
+ }
+
+ /// <summary>Slot <paramref name="slot"/>'s burst: where its foot is and its start on the clock (NaN when free).</summary>
+ public Vector3 Foot(int slot) => foot[slot];
+ public double StartOf(int slot) => from[slot];
+ /// <summary>The flipbook frame slot <paramref name="slot"/> shows now (the index of its frame mesh).</summary>
+ public int FrameOf(int slot) => Array.IndexOf(frames, filter[slot].sharedMesh);
+
+ /// <summary>Starts a burst <paramref name="sizeM"/> across with its foot at <paramref name="at"/> (world), at clock
+ /// time <paramref name="start"/>, turned <paramref name="spinDegrees"/> on the screen. Returns its slot.</summary>
+ public int Start(Vector3 at, float sizeM, double start, float spinDegrees = 0f)
+ {
+ int slot = 0;
+ for (int i = 0; i < from.Length; i++)
+ {
+ if (double.IsNaN(from[i])) { slot = i; break; }
+ if (from[i] < from[slot]) slot = i;
+ }
+ from[slot] = start; foot[slot] = at; size[slot] = sizeM; spin[slot] = spinDegrees;
+ return slot;
+ }
+
+ /// <summary>Every slot as it is at clock time <paramref name="now"/>: hidden before its start, then playing, and freed
+ /// (hidden) at its end. The same time gives the same frame. No allocation.</summary>
+ public void Sample(double now)
+ {
+ for (int i = 0; i < from.Length; i++)
+ {
+ if (double.IsNaN(from[i])) { shown[i].enabled = false; continue; }
+ float b = (float)((now - from[i]) / style.LifeS);
+ if (b >= 1f) { from[i] = double.NaN; shown[i].enabled = false; continue; }
+ bool on = b >= 0f;
+ shown[i].enabled = on;
+ if (!on) continue;
+ filter[i].sharedMesh = frames[Mathf.Clamp(style.FirstFrame + Flipbook.FrameAt(b, style.Frames), 0, frames.Length - 1)];
+ float s = size[i] * Swell(b, style.OpenShare, style.SpreadShare);
+ quad[i].SetPositionAndRotation(foot[i] + Vector3.up * (style.CentreShare * s + style.RiseShare * size[i] * b), view * Quaternion.Euler(0f, 0f, spin[i]));
+ quad[i].localScale = Vector3.one * s;
+ var c = Color.Lerp(style.Fresh, style.Old, b); c.a *= Fade(b, style.FadeShare); material[i].SetColor(BaseColor, c);
+ }
+ }
+
+ /// <summary>Turns the bursts showing to a camera with rotation <paramref name="camera"/>, and keeps it for the next
+ /// samples.</summary>
+ public void Face(Quaternion camera)
+ {
+ view = camera;
+ for (int i = 0; i < quad.Length; i++) if (shown[i].enabled) quad[i].rotation = view * Quaternion.Euler(0f, 0f, spin[i]);
+ }
+
+ /// <summary>Frees every slot and hides it.</summary>
+ public void Clear()
+ {
+ for (int i = 0; i < from.Length; i++) { from[i] = double.NaN; shown[i].enabled = false; }
+ }
+
+ /// <summary>A burst's size over its full size at <paramref name="b"/> of its life: from <paramref name="open"/>, swelling
+ /// fast (easing out) to the full size by a quarter of its life, then spreading by <paramref name="spread"/> more, as
+ /// DakotaBombRun.BlastSwell.</summary>
+ public static float Swell(float b, float open, float spread)
+ {
+ float o = 1f - Mathf.Clamp01(b / 0.25f);
+ return Mathf.Lerp(open, 1f, 1f - o * o) + spread * Mathf.Clamp01((b - 0.25f) / 0.75f);
+ }
+
+ /// <summary>A burst's alpha at <paramref name="b"/> of its life: fading in over its first 5 per cent, whole, then fading
+ /// over the last <paramref name="fade"/> of it to nothing at its end.</summary>
+ public static float Fade(float b, float fade) =>
+ Mathf.SmoothStep(0f, 1f, b / 0.05f) * (1f - Mathf.SmoothStep(0f, 1f, (b - (1f - fade)) / fade));
+ }
+}
diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/Flipbook.cs.meta b/unity/Assets/Scripts/Map/HexTiles/Core/Flipbook.cs.meta
new file mode 100644
index 000000000..d7e8f02c0
--- /dev/null
+++ b/unity/Assets/Scripts/Map/HexTiles/Core/Flipbook.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8a28ee3642894e69b1164b32c529d560
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs
index 8385d9374..2f7b96324 100644
--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs
+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs
@@ -11,8 +11,11 @@ namespace Statecraft.HexTiles
/// the simulation can drive later (show it on a hex, hide it); nothing here reads or writes the simulation, and it is
/// never saved in a board or its overrides. Movement and combat rules are the owner's (docs/gdd/military-combat.md).
/// Kept calm, not cinematic: a few grey smoke columns drifting east on the prevailing west wind, a low warm glow
- /// where each rises, and a muted red border that pulses slowly. Three meshes and three materials, all made by and
- /// destroyed with the look's object (HexUnderAttackLook).</summary>
+ /// where each rises with small flames burning in it, and a muted red border that pulses slowly. The smoke and the
+ /// flames are Unity Labs' CC0 flipbooks (Flipbook: the smoke cloud and the explosion's burning frames, as #2490's
+ /// Dakotas draw them; owner, 4 November 2026: "Fire/smoke on attacked hexes"), each one mesh per hex, so one draw call
+ /// each. Four meshes and four materials, all made by and destroyed with the look's object (HexUnderAttackLook); the
+ /// flipbook textures are Resources assets and stay.</summary>
public static class HexUnderAttack
{
public static string Name(int q, int r) => $"under attack {q},{r}";
@@ -94,11 +97,28 @@ namespace Statecraft.HexTiles
/// <summary>Where the smoke starts: above the flames, so they show at its foot.</summary>
public const float FootShare = 0.04f;
public const float Alpha = 0.92f, GlowM = 0.11f;
+ /// <summary>DESIGN VALUE: how fast a puff's smoke boils through the flipbook (frames a second), as the Dakotas'
+ /// columns (SeaAirCollection.DakotaColumnFps).</summary>
+ public const float Fps = 6f;
+ /// <summary>DESIGN VALUE: the smoke flipbook's grey averages 0.44 where it is opaque (DakotaBombRun's measure), so
+ /// its puffs' colours are this much brighter to draw the same shade as the soft puff they replace.</summary>
+ public const float FlipbookGain = 2.2f;
+ }
+
+ /// <summary>The flames burning in each column's glow: <see cref="PerColumn"/> camera-facing quads of the explosion
+ /// flipbook's burning frames (Flipbook.ExplosionFireFrames), additive, so its black smoke adds nothing and only the
+ /// fire shows. Each flame flares and dies down over <see cref="CycleS"/>, running through those frames, offset per
+ /// flame so the fire never pulses as one. Sizes are shares of the hex size S, as the cones they replace (0.045 to
+ /// 0.075 S tall).</summary>
+ public static class Fire
+ {
+ public const int PerColumn = 3;
+ public const float CycleS = 0.9f, SizeShare = 0.07f, SizeSpread = 0.4f;
}
}
- /// <summary>Animates one shown look, in edit mode and in play: Time(t) samples the smoke, the glow's flicker and the
- /// border's pulse at t seconds, as a pure function of t and the hex (seeded by q, r), so captures and tests are
+ /// <summary>Animates one shown look, in edit mode and in play: Time(t) samples the smoke, the flames, the glow's flicker
+ /// and the border's pulse at t seconds, allocating nothing, as a pure function of t and the hex (seeded by q, r), so captures and tests are
/// deterministic. Set Hold to keep a sampled time (Update then leaves it). Destroys its meshes and materials with
/// its object.</summary>
[ExecuteAlways]
@@ -132,12 +152,24 @@ namespace Statecraft.HexTiles
}
/// <summary>The board camera's view (HexBoardCapture and the game rig: pitch 50 degrees, facing north).</summary>
static readonly Quaternion BoardView = Quaternion.Euler(50f, 0f, 0f);
- // Glow: fixed vertices (discs on the ground, small flame cones), per-vertex base colour scaled by the flicker.
- Vector3[] glowRest = Array.Empty<Vector3>(), glowV = Array.Empty<Vector3>(); Color[] glowBase = Array.Empty<Color>(); Color32[] glowC = Array.Empty<Color32>();
- int[] glowColumn = Array.Empty<int>(); bool[] glowFlameTip = Array.Empty<bool>();
+ // Smoke flipbook: each puff's octagon UVs sit in the frame it shows (Time writes them); a grid of 1 is the drawn puff.
+ Vector2[] smokeUV = Array.Empty<Vector2>(); int smokeGrid = 1; float smokeGain = 1f;
+ // The puffs of one column in height order, reused every sample (no allocation per frame).
+ (float u, int i)[] order = Array.Empty<(float, int)>();
+ // Glow: fixed vertices (discs on the ground), per-vertex base colour scaled by the flicker.
+ Vector3[] glowRest = Array.Empty<Vector3>(); Color[] glowBase = Array.Empty<Color>(); Color32[] glowC = Array.Empty<Color32>();
+ int[] glowColumn = Array.Empty<int>();
+ // Fire: one camera-facing quad per flame, its UVs on the frame it shows; Time samples, Face writes the corners.
+ Mesh fire = null!;
+ Vector3[] flameFoot = Array.Empty<Vector3>(), flameAt = Array.Empty<Vector3>(); float[] flameSize = Array.Empty<float>(), flamePhase = Array.Empty<float>(), flameHalf = Array.Empty<float>();
+ int[] flameColumn = Array.Empty<int>();
+ Vector3[] fireV = Array.Empty<Vector3>(), fireN = Array.Empty<Vector3>(); Vector2[] fireUV = Array.Empty<Vector2>(); Color32[] fireC = Array.Empty<Color32>();
+ int fireGrid = 1, fireFrames = 1;
static readonly Color SmokeLow = new Color(0.13f, 0.12f, 0.115f), SmokeHigh = new Color(0.40f, 0.395f, 0.385f);
static readonly Color GlowCore = new Color(1f, 0.34f, 0.08f), FlameCore = new Color(1f, 0.62f, 0.22f);
+ /// <summary>DESIGN VALUE: the flames keep the flipbook's own fire colours, a touch warmer; additive, so alpha is their strength.</summary>
+ static readonly Color FlameTint = new Color(1f, 0.9f, 0.78f, 0.9f);
static readonly Color BorderColour = new Color(0.78f, 0.13f, 0.10f);
const float BorderLowAlpha = 0.3f, BorderHighAlpha = 0.88f;
@@ -169,12 +201,23 @@ namespace Statecraft.HexTiles
tris[(p * PuffSides + k) * 3] = o; tris[(p * PuffSides + k) * 3 + 1] = o + 1 + (k + 1) % PuffSides; tris[(p * PuffSides + k) * 3 + 2] = o + 1 + k;
}
}
+ // The flipbooks are assets (not owned: Resources keeps them); without them the smoke falls back to the drawn
+ // puff and the flames to the puff tinted as fire, one frame each.
+ var cloud = Flipbook.Load(Flipbook.SmokeResource); var blast = Flipbook.Load(Flipbook.ExplosionResource);
+ if (cloud == null || blast == null) Debug.LogWarning("UNDER ATTACK: the smoke or explosion flipbook is missing from Resources/Effects; the drawn puff stands in.");
+ Texture2D? drawnPuff = cloud == null || blast == null ? Own(PuffTexture()) : null;
+ if (cloud != null) { smokeGrid = Flipbook.SmokeGrid; smokeGain = HexUnderAttack.Smoke.FlipbookGain; }
+ smokeUV = uv;
smoke.vertices = smokeV; smoke.normals = smokeN; smoke.colors32 = smokeC; smoke.uv = uv; smoke.triangles = tris;
- Part("Smoke", smoke, HexMaterials.AttackSmoke).SetTexture("_BaseMap", Own(PuffTexture()));
+ Part("Smoke", smoke, HexMaterials.AttackSmoke).SetTexture("_BaseMap", (cloud != null ? cloud : drawnPuff)!);
glow = Own(BuildGlow(Ground)); glow.MarkDynamic();
Part("Glow", glow, HexMaterials.AttackGlow);
+ if (blast != null) { fireGrid = Flipbook.ExplosionGrid; fireFrames = Flipbook.ExplosionFireFrames; }
+ fire = Own(BuildFire(Ground)); fire.MarkDynamic();
+ Part("Fire", fire, HexMaterials.AttackGlow).SetTexture("_BaseMap", (blast != null ? blast : drawnPuff)!);
+
var ring = Own(BuildBorder(Ground));
border = Part("Border", ring, HexMaterials.AttackBorder);
Time(0f);
@@ -201,13 +244,14 @@ namespace Statecraft.HexTiles
int P = HexUnderAttack.Smoke.Puffs;
float S = sizeM, top = HexUnderAttack.Smoke.HeightShare * S;
int slot = 0;
- var order = new (float u, int i)[P];
+ if (order.Length != P) order = new (float u, int i)[P];
for (int c = 0; c < bases.Length; c++)
{
for (int i = 0; i < P; i++) order[i] = (HexUnderAttack.Frac(t / HexUnderAttack.Smoke.LifeS + (i + phase[c]) / P), i);
- Array.Sort(order, (a, b) => a.u.CompareTo(b.u)); // low first: the camera is above, so higher puffs are nearer
- foreach (var (u, i) in order)
+ SortLowFirst(order); // low first: the camera is above, so higher puffs are nearer
+ for (int n = 0; n < P; n++)
{
+ var (u, i) = order[n];
float seed = c * 7.31f + i * 1.93f, own = HexUnderAttack.Frac(Mathf.Sin(seed * 12.9898f) * 43758.547f);
// Each puff its own size and offset, so a column reads as smoke rather than a stack of beads.
float radius = Mathf.Lerp(HexUnderAttack.Smoke.BaseRadius, HexUnderAttack.Smoke.TopRadius, Mathf.Sqrt(u)) * S * (0.8f + 0.4f * own);
@@ -217,33 +261,35 @@ namespace Statecraft.HexTiles
var wobble = new Vector3(Mathf.Sin(seed * 3.1f + u * 5f), 0f, Mathf.Cos(seed * 2.3f + u * 4f)) * (0.02f * S * Mathf.Sqrt(u));
var at = bases[c] + new Vector3(0f, HexUnderAttack.Smoke.FootShare * S + radius * 0.5f + u * top, 0f)
+ HexUnderAttack.Smoke.Wind * (HexUnderAttack.Smoke.DriftM * S * Mathf.Pow(u, 1.4f)) + wobble;
- var colour = Color.Lerp(SmokeLow, SmokeHigh, Mathf.SmoothStep(0f, 1f, u / 0.7f)); colour.a = alpha;
+ var colour = Color.Lerp(SmokeLow, SmokeHigh, Mathf.SmoothStep(0f, 1f, u / 0.7f)) * smokeGain; colour.a = alpha;
Color32 c32 = colour;
puffAt[slot] = at; puffRadius[slot] = radius; puffSpin[slot] = (own - 0.5f) * 0.7f + u * 0.6f;
for (int v = 0; v <= PuffSides; v++) smokeC[slot * (PuffSides + 1) + v] = c32;
+ // Its smoke boils through the flipbook as it rises, each puff from its own frame.
+ int frames = smokeGrid * smokeGrid;
+ PuffUVs(slot, Flipbook.Looping((double)u * HexUnderAttack.Smoke.LifeS * HexUnderAttack.Smoke.Fps + own * frames, frames));
slot++;
}
}
- smoke.colors32 = smokeC;
- Face(BoardView * Vector3.right, BoardView * Vector3.up);
+ smoke.SetColors(smokeC); smoke.SetUVs(0, smokeUV);
for (int v = 0; v < glowRest.Length; v++)
{
float f = Flicker(t, phase[glowColumn[v]]);
var col = glowBase[v]; col.a *= f;
glowC[v] = col;
- var p = glowRest[v];
- if (glowFlameTip[v]) p.y = bases[glowColumn[v]].y + (p.y - bases[glowColumn[v]].y) * (0.8f + 0.35f * Flicker(t * 1.7f, phase[glowColumn[v]] + v * 0.13f));
- glowV[v] = p;
}
- glow.vertices = glowV; glow.colors32 = glowC; glow.RecalculateBounds();
+ glow.SetColors(glowC);
+
+ SampleFire(t);
+ Face(BoardView * Vector3.right, BoardView * Vector3.up);
var b = BorderColour; b.a = Mathf.Lerp(BorderLowAlpha, BorderHighAlpha, HexUnderAttack.Pulse(t));
border.SetColor("_BaseColor", b);
}
- /// <summary>Writes the smoke puffs to face a view with these world right and up axes (the puffs are round, so
- /// only the view matters, not the time).</summary>
+ /// <summary>Writes the smoke puffs and the flames to face a view with these world right and up axes, about the
+ /// centres and sizes the last sample gave them.</summary>
void Face(Vector3 right, Vector3 up)
{
right = transform.InverseTransformDirection(right); up = transform.InverseTransformDirection(up);
@@ -258,7 +304,61 @@ namespace Statecraft.HexTiles
smokeV[o] = c; smokeN[o] = normal;
for (int k = 0; k < PuffSides; k++) { smokeV[o + 1 + k] = c + x * PuffRim[k].x + y * PuffRim[k].y; smokeN[o + 1 + k] = normal; }
}
- smoke.vertices = smokeV; smoke.normals = smokeN; smoke.RecalculateBounds();
+ smoke.SetVertices(smokeV); smoke.SetNormals(smokeN); smoke.RecalculateBounds();
+ // The flames upright on the screen (no spin), each centred where SampleFire put it.
+ for (int f = 0; f < flameAt.Length; f++)
+ {
+ Vector3 x = right * flameHalf[f], y = up * flameHalf[f], c = flameAt[f];
+ int o = f * 4;
+ fireV[o] = c - x - y; fireV[o + 1] = c + x - y; fireV[o + 2] = c - x + y; fireV[o + 3] = c + x + y;
+ for (int k = 0; k < 4; k++) fireN[o + k] = normal;
+ }
+ if (fire != null) { fire.SetVertices(fireV); fire.SetNormals(fireN); fire.RecalculateBounds(); }
+ }
+
+ /// <summary>Puff <paramref name="slot"/>'s octagon UVs on flipbook frame <paramref name="frame"/>. The octagon
+ /// circumscribes the unit disc and is inscribed in its square, so its UVs stay inside the frame.</summary>
+ void PuffUVs(int slot, int frame)
+ {
+ var o = Flipbook.FrameOrigin(frame, smokeGrid, out float k);
+ int b = slot * (PuffSides + 1);
+ smokeUV[b] = new Vector2(o.x + 0.5f * k, o.y + 0.5f * k);
+ for (int r = 0; r < PuffSides; r++)
+ smokeUV[b + 1 + r] = new Vector2(o.x + k * Mathf.Clamp01(0.5f + 0.5f * PuffRim[r].x), o.y + k * Mathf.Clamp01(0.5f + 0.5f * PuffRim[r].y));
+ }
+
+ /// <summary>The flames as they are at <paramref name="t"/>: each <see cref="HexUnderAttack.Fire.CycleS"/> a flame flares
+ /// from a little under its size, burns through the explosion's burning frames and dies down, its own phase apart from
+ /// the others, flickering with its column's glow. Writes their UVs, colours and centres; Face writes the corners.</summary>
+ void SampleFire(float t)
+ {
+ for (int f = 0; f < flameAt.Length; f++)
+ {
+ float b = HexUnderAttack.Frac(t / HexUnderAttack.Fire.CycleS + flamePhase[f]);
+ var o = Flipbook.FrameOrigin(Flipbook.FrameAt(b, fireFrames), fireGrid, out float k);
+ int v = f * 4;
+ fireUV[v] = o; fireUV[v + 1] = new Vector2(o.x + k, o.y); fireUV[v + 2] = new Vector2(o.x, o.y + k); fireUV[v + 3] = new Vector2(o.x + k, o.y + k);
+ float size = flameSize[f] * FlipbookBursts.Swell(b, 0.6f, 0.15f);
+ flameHalf[f] = 0.5f * size;
+ // Its foot on the ground: the fire fills about the middle four fifths of its frame.
+ flameAt[f] = flameFoot[f] + Vector3.up * (0.4f * size);
+ var c = fireGrid > 1 ? FlameTint : FlameCore;
+ c.a *= Mathf.SmoothStep(0f, 1f, b / 0.12f) * (1f - Mathf.SmoothStep(0f, 1f, (b - 0.55f) / 0.45f)) * Flicker(t, phase[flameColumn[f]]);
+ Color32 c32 = c;
+ for (int n = 0; n < 4; n++) fireC[v + n] = c32;
+ }
+ if (fire != null) { fire.SetUVs(0, fireUV); fire.SetColors(fireC); }
+ }
+
+ /// <summary>Sorts a column's puffs by height, low first, in place (an insertion sort: few puffs, no allocation).</summary>
+ static void SortLowFirst((float u, int i)[] a)
+ {
+ for (int j = 1; j < a.Length; j++)
+ {
+ var x = a[j]; int k = j - 1;
+ while (k >= 0 && a[k].u > x.u) { a[k + 1] = a[k]; k--; }
+ a[k + 1] = x;
+ }
}
/// <summary>A soft, slightly lumpy puff (white, alpha falling to the rim; a little darker below, as smoke
@@ -286,18 +386,19 @@ namespace Statecraft.HexTiles
void OnDisable() => RenderPipelineManager.beginCameraRendering -= FaceCamera;
void FaceCamera(ScriptableRenderContext context, Camera cam)
{
- if (smoke != null && puffAt.Length > 0) Face(cam.transform.right, cam.transform.up);
+ if (smoke != null && (puffAt.Length > 0 || flameAt.Length > 0)) Face(cam.transform.right, cam.transform.up);
}
/// <summary>A slow, irregular flicker between about 0.65 and 1 (two sines), offset per column.</summary>
static float Flicker(float t, float phase) =>
0.82f + 0.11f * Mathf.Sin(2f * Mathf.PI * (t * 0.7f + phase)) + 0.07f * Mathf.Sin(2f * Mathf.PI * (t * 1.9f + phase * 2.3f));
- /// <summary>Per column: a soft warm disc on the ground (centre bright, rim clear) and a few small flame cones.</summary>
+ /// <summary>Per column: a soft warm disc on the ground (centre bright, rim clear). The flames burning in it are the
+ /// fire mesh's (<see cref="BuildFire"/>).</summary>
Mesh BuildGlow(Func<Vector3, float> ground)
{
- const int Rim = 18, Flames = 3, Sides = 5; const float LiftM = 22f;
- var v = new List<Vector3>(); var col = new List<Color>(); var cols = new List<int>(); var tip = new List<bool>(); var tris = new List<int>();
+ const int Rim = 18; const float LiftM = 22f;
+ var v = new List<Vector3>(); var col = new List<Color>(); var cols = new List<int>(); var tris = new List<int>();
var rng = new System.Random(unchecked(Q * 19349663 ^ R * 83492791 ^ 0x6A0));
for (int c = 0; c < bases.Length; c++)
{
@@ -313,27 +414,40 @@ namespace Statecraft.HexTiles
v.Add(p); col.Add(new Color(GlowCore.r, GlowCore.g * 0.8f, GlowCore.b, 0f));
tris.AddRange(new[] { o, o + 1 + (k + 1) % Rim, o + 1 + k });
}
- for (int k = 0; k <= Rim; k++) { cols.Add(c); tip.Add(false); }
- for (int f = 0; f < Flames; f++)
- {
- float a = (float)rng.NextDouble() * 2f * Mathf.PI, d = (float)rng.NextDouble() * rad * 0.4f;
- var foot = b + new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a)) * d; foot.y = ground(foot) + LiftM * 0.5f;
- float h = sizeM * (0.045f + 0.03f * (float)rng.NextDouble()), w = sizeM * (0.016f + 0.008f * (float)rng.NextDouble());
- int o2 = v.Count;
- for (int s = 0; s < Sides; s++)
- {
- float sa = s * 2f * Mathf.PI / Sides + a;
- v.Add(foot + new Vector3(Mathf.Cos(sa), 0f, Mathf.Sin(sa)) * w); col.Add(new Color(GlowCore.r, GlowCore.g, GlowCore.b, 0.8f));
- cols.Add(c); tip.Add(false);
- }
- v.Add(foot + Vector3.up * h); col.Add(new Color(FlameCore.r, FlameCore.g, FlameCore.b, 0.15f)); cols.Add(c); tip.Add(true);
- for (int s = 0; s < Sides; s++) tris.AddRange(new[] { o2 + s, o2 + Sides, o2 + (s + 1) % Sides });
- }
+ for (int k = 0; k <= Rim; k++) cols.Add(c);
}
- glowRest = v.ToArray(); glowV = (Vector3[])glowRest.Clone(); glowBase = col.ToArray(); glowC = new Color32[glowRest.Length];
- glowColumn = cols.ToArray(); glowFlameTip = tip.ToArray();
+ glowRest = v.ToArray(); glowBase = col.ToArray(); glowC = new Color32[glowRest.Length];
+ glowColumn = cols.ToArray();
var mesh = new Mesh { name = "under-attack-glow" };
- mesh.vertices = glowV; mesh.colors32 = glowC; mesh.triangles = tris.ToArray(); mesh.RecalculateNormals();
+ mesh.vertices = glowRest; mesh.colors32 = glowC; mesh.triangles = tris.ToArray(); mesh.RecalculateNormals(); mesh.RecalculateBounds();
+ return mesh;
+ }
+
+ /// <summary>The flames: <see cref="HexUnderAttack.Fire.PerColumn"/> per column, each a quad (Face turns it to the camera)
+ /// standing in the inner part of its column's glow, its size and phase seeded by the hex.</summary>
+ Mesh BuildFire(Func<Vector3, float> ground)
+ {
+ const float LiftM = 11f;
+ int n = bases.Length * HexUnderAttack.Fire.PerColumn;
+ flameFoot = new Vector3[n]; flameAt = new Vector3[n]; flameSize = new float[n]; flamePhase = new float[n]; flameHalf = new float[n]; flameColumn = new int[n];
+ fireV = new Vector3[n * 4]; fireN = new Vector3[n * 4]; fireUV = new Vector2[n * 4]; fireC = new Color32[n * 4];
+ var tris = new int[n * 6];
+ var rng = new System.Random(unchecked(Q * 2654435 ^ R * 73856093 ^ 0xF1A3E));
+ for (int c = 0, f = 0; c < bases.Length; c++)
+ for (int k = 0; k < HexUnderAttack.Fire.PerColumn; k++, f++)
+ {
+ float a = (float)rng.NextDouble() * 2f * Mathf.PI, d = (float)rng.NextDouble() * HexUnderAttack.Smoke.GlowM * sizeM * 0.4f;
+ var foot = bases[c] + new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a)) * d; foot.y = ground(foot) + LiftM;
+ flameFoot[f] = foot; flameColumn[f] = c;
+ flameSize[f] = sizeM * HexUnderAttack.Fire.SizeShare * (1f - 0.5f * HexUnderAttack.Fire.SizeSpread + HexUnderAttack.Fire.SizeSpread * (float)rng.NextDouble());
+ // Spread over the cycle, so a column's flames take turns.
+ flamePhase[f] = (k + 0.6f * (float)rng.NextDouble()) / HexUnderAttack.Fire.PerColumn;
+ int o = f * 4, t6 = f * 6;
+ // Clockwise as the viewer sees it, as the built-in quad: 0 3 1, 3 0 2.
+ tris[t6] = o; tris[t6 + 1] = o + 3; tris[t6 + 2] = o + 1; tris[t6 + 3] = o + 3; tris[t6 + 4] = o; tris[t6 + 5] = o + 2;
+ }
+ var mesh = new Mesh { name = "under-attack-fire" };
+ mesh.vertices = fireV; mesh.normals = fireN; mesh.uv = fireUV; mesh.colors32 = fireC; mesh.triangles = tris;
return mesh;
}
diff --git a/unity/Assets/Scripts/Map/Routes/RouteTrain.cs b/unity/Assets/Scripts/Map/Routes/RouteTrain.cs
index 9c04b552f..73d404f7c 100644
--- a/unity/Assets/Scripts/Map/Routes/RouteTrain.cs
+++ b/unity/Assets/Scripts/Map/Routes/RouteTrain.cs
@@ -45,6 +45,8 @@ namespace Statecraft.Game.Map.Routes
float carHalfWidth;
TerrainData? terrain;
Vector3 terrainOrigin;
+ // The chimney's top in the locomotive car's own frame (before its scale), where the steam leaves (TrainSteam).
+ Vector3 chimneyLocal;
/// <summary>Distance along the line of the head (front of the locomotive) at time <paramref name="t"/>, and the
/// direction (+1 towards the turn point, -1 back).</summary>
@@ -62,6 +64,33 @@ namespace Statecraft.Game.Map.Routes
return (endS - length - back, -1);
}
+ /// <summary>Whether the train is running at time <paramref name="t"/>: false while it stands at either end, and
+ /// always false for a still train (and for a stretch shorter than the train, where it cannot run).</summary>
+ public bool MovingAt(float t)
+ {
+ if (still.HasValue) return false;
+ float run = endS - startS - length;
+ if (run <= 0f) return false;
+ float leg = run / SpeedMps + DwellSeconds;
+ float x = Mathf.Repeat(t, 2f * leg);
+ if (x >= leg) x -= leg;
+ return x * SpeedMps < run;
+ }
+
+ /// <summary>The locomotive's chimney top (world) with the head at <paramref name="head"/> running in direction
+ /// <paramref name="dir"/>, and the way back along the locomotive (world, unit, level): where its steam leaves and
+ /// where it drifts. As <see cref="Place"/> puts the locomotive, without the model train's few metres of lift.</summary>
+ public (Vector3 at, Vector3 back) ChimneyAt(float head, int dir)
+ {
+ if (cars.Count == 0) return (Vector3.zero, Vector3.back);
+ float c = head - dir * carOffset[0], half = carHalf[0];
+ var fwd = At(c + dir * half) - At(c - dir * half);
+ var axis = fwd.sqrMagnitude > 1e-6f ? fwd.normalized : Vector3.forward;
+ var at = At(c) + Quaternion.LookRotation(axis, Vector3.up) * Vector3.Scale(cars[0].lossyScale, chimneyLocal);
+ var back = new Vector3(-axis.x, 0f, -axis.z);
+ return (at, back.sqrMagnitude > 1e-6f ? back.normalized : Vector3.back);
+ }
+
public float? StillHead => still;
public IReadOnlyList<Transform> Cars => cars;
/// <summary>Each car's middle, metres behind the head along the line (Place puts car k at head - dir * offset).</summary>
@@ -173,11 +202,14 @@ namespace Statecraft.Game.Map.Routes
offset += 2f * half + TrainModels.GapM * Scale;
}
train.length = offset - TrainModels.GapM * Scale;
+ train.chimneyLocal = new Vector3(0f, TrainModels.ChimneyTopM, TrainModels.ChimneyZM);
float stillMiddle = train.Nearest(new Vector2(stillAt.x, stillAt.z));
float stillHead = Mathf.Clamp(stillMiddle + train.length / 2f, train.startS + train.length, train.endS);
train.still = stillTrain ? stillHead : (float?)null;
if (stillTrain) train.Place(stillHead, +1); else { var (h, d) = train.HeadAt(0f); train.Place(h, d); }
+ // A still train never runs, so it never steams: only the moving showcase carries the steam.
+ if (!stillTrain) TrainSteam.Attach(train, TrainSteam.PuffWidthShare * TrainModels.LocoWidthM * Scale * Chunk);
return go;
}
@@ -236,6 +268,9 @@ namespace Statecraft.Game.Map.Routes
body.transform.localPosition -= new Vector3(size.center.x, size.min.y, size.center.z);
loco.transform.localScale = CarScale(size.size, carLength, carWidthM);
train.AddCar(loco.transform, carLength);
+ // The model's chimney: at its top, as far behind its smokebox end as the showcase's chimney is behind the
+ // showcase locomotive's front, along the locomotive and tender together (TrainModels).
+ train.chimneyLocal = new Vector3(0f, size.size.y, size.extents.z - ChimneyShare * size.size.z);
// The coaches: the showcase's painted miniatures, one mesh per coach as the showcase's own consist.
if (cars > 1)
@@ -265,9 +300,14 @@ namespace Statecraft.Game.Map.Routes
train.carHalfWidth = carWidthM / 2f;
train.terrain = data; train.terrainOrigin = origin; train.clearGround = true;
var (h, d) = train.HeadAt(0f); train.Place(h, d);
+ TrainSteam.Attach(train, TrainSteam.PuffWidthShare * carWidthM);
return train;
}
+ /// <summary>How far the chimney stands behind the front of the locomotive and tender, as a share of their length: the
+ /// showcase's (TrainModels), about 0.06.</summary>
+ public const float ChimneyShare = (TrainModels.LocoLengthM / 2f - TrainModels.ChimneyZM) / ModelRealLengthM;
+
/// <summary>The scale that makes a shape of <paramref name="size"/> (its length along Z) <paramref name="length"/> long
/// and <paramref name="width"/> wide, its height scaled with its width.</summary>
static Vector3 CarScale(Vector3 size, float length, float width)
diff --git a/unity/Assets/Scripts/Map/Routes/TrainModels.cs b/unity/Assets/Scripts/Map/Routes/TrainModels.cs
index df29ce61e..4d98a629b 100644
--- a/unity/Assets/Scripts/Map/Routes/TrainModels.cs
+++ b/unity/Assets/Scripts/Map/Routes/TrainModels.cs
@@ -14,6 +14,9 @@ namespace Statecraft.Game.Map.Routes
{
public const float LocoLengthM = 17f, TenderLengthM = 7.5f, CoachLengthM = 20f, GapM = 1f;
public const int Coaches = 4;
+ /// <summary>The locomotive's chimney: its top's height above the rail and its place ahead of the locomotive's middle
+ /// (real metres), where the train's steam leaves it (TrainSteam); and the locomotive's width (its running board).</summary>
+ public const float ChimneyTopM = 4.5f, ChimneyZM = 6.9f, LocoWidthM = 2.9f;
/// <summary>The consist from the front: (name, mesh, length in real metres).</summary>
public static List<(string name, Mesh mesh, float lengthM)> Consist()
@@ -34,10 +37,10 @@ namespace Statecraft.Game.Map.Routes
{
var m = new MiniatureMesh();
m.Box(Box(0, 0.7f, 0, 2.2f, 1.2f, 14f), UnitPalette.Waterline); // wheels and frames, dark
- m.Box(Box(0, 1.4f, 0.4f, 2.9f, 0.3f, 16f), UnitPalette.PropBlack); // running board
+ m.Box(Box(0, 1.4f, 0.4f, LocoWidthM, 0.3f, 16f), UnitPalette.PropBlack); // running board
m.Rod(new Vector3(0, 2.7f, -3.5f), new Vector3(0, 2.7f, 6.6f), 0.95f, 0.95f, UnitPalette.PropBlack, 14, rounded: false);
m.Rod(new Vector3(0, 2.7f, 6.6f), new Vector3(0, 2.7f, 7.8f), 1.0f, 1.0f, UnitPalette.Funnel, 14, rounded: false); // smokebox
- m.Rod(new Vector3(0, 3.4f, 6.9f), new Vector3(0, 4.5f, 6.9f), 0.32f, 0.38f, UnitPalette.PropBlack, 10, rounded: false); // chimney
+ m.Rod(new Vector3(0, 3.4f, ChimneyZM), new Vector3(0, ChimneyTopM, ChimneyZM), 0.32f, 0.38f, UnitPalette.PropBlack, 10, rounded: false); // chimney
m.Ellipsoid(Matrix4x4.TRS(new Vector3(0, 3.6f, 1.8f), Quaternion.identity, new Vector3(0.5f, 0.45f, 0.65f)), UnitPalette.PropBlack, 10, 6);
m.Box(Box(0, 2.85f, -5.6f, 2.9f, 2.7f, 3.2f), UnitPalette.PropBlack); // cab
m.Box(Box(0, 4.3f, -5.6f, 3.1f, 0.25f, 3.6f), UnitPalette.Funnel); // cab roof
diff --git a/unity/Assets/Scripts/Map/Routes/TrainSteam.cs b/unity/Assets/Scripts/Map/Routes/TrainSteam.cs
new file mode 100644
index 000000000..aefeb6f26
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Routes/TrainSteam.cs
@@ -0,0 +1,177 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using Statecraft.HexTiles;
+using UnityEngine;
+using UnityEngine.Rendering;
+using Object = UnityEngine.Object;
+
+namespace Statecraft.Game.Map.Routes
+{
+ /// <summary>The steam train's exhaust (owner, 4 November 2026: "Train steam"): a short trail of smoke and steam from the
+ /// locomotive's chimney while the train runs, drifting back along the track. Palestine Railways burned oil, not coal,
+ /// from 1942-43 (research_notes/Map/train-steam-oil-burning-2026-11-05.md); the game assumes they still did in 1950
+ /// (unsourced). The smoke leaves the chimney dark grey-black and thins to grey, with white steam puffs among it; the
+ /// smoke colour is a design choice.
+ /// Drawn as #2490's Dakota bombs are: Unity Labs' CC0 smoke flipbook (Flipbook) on unlit camera-facing quads, from
+ /// <see cref="Puffs"/> slots made once. Each puff is a pure function of the clock: puff k leaves the chimney at
+ /// k x <see cref="GapS"/> from where the chimney was then (RouteTrain.ChimneyAt), swells, rises, drifts back and fades
+ /// over <see cref="LifeS"/>; so the same time draws the same trail, and sampling allocates nothing. Nothing shows while
+ /// the train stands at either end (a puff left while it stood is never drawn), and nothing while it is hidden (the
+ /// train's toggle or its date: this lives under the train, so it goes with it). Runs in play only, as the train does.
+ /// Presentation only: it reads no game state. [ExecuteAlways] only so that hiding or destroying the train in edit mode
+ /// (the EditMode tests, an edit-mode map build) drops the puffs and frees the meshes and materials too, as CombatBursts
+ /// does; the trail itself advances in play only (Update).</summary>
+ [ExecuteAlways]
+ public sealed class TrainSteam : MonoBehaviour
+ {
+ public const string Name = "Steam";
+
+ /// <summary>DESIGN VALUES: the puffs on screen at once, one leaving every <see cref="GapS"/> s, each living
+ /// <see cref="LifeS"/> (so the trail is always the same few puffs); every <see cref="SteamEvery"/>th puff is white
+ /// steam, the others smoke.</summary>
+ public const int Puffs = 10, SteamEvery = 3;
+ public const float GapS = 0.3f, LifeS = Puffs * GapS;
+
+ /// <summary>DESIGN VALUES for the sizes, as shares of a puff's size (<see cref="PuffWidthShare"/> of the locomotive's
+ /// width, so both trains steam to their own size): a puff opens at <see cref="OpenShare"/> and spreads by
+ /// <see cref="SpreadShare"/> more by its end; it drifts back along the track <see cref="DriftShare"/> and rises
+ /// <see cref="RiseShare"/> a second; its centre sits <see cref="CentreShare"/> over the chimney. A steam puff is
+ /// <see cref="SteamSizeShare"/> of a smoke puff and gone by <see cref="SteamLifeShare"/> of the life.</summary>
+ public const float PuffWidthShare = 1.6f, OpenShare = 0.45f, SpreadShare = 1.4f, DriftShare = 0.35f, RiseShare = 0.3f,
+ CentreShare = 0.4f, SteamSizeShare = 0.75f, SteamLifeShare = 0.6f, FadeShare = 0.55f;
+
+ /// <summary>DESIGN VALUES: the flipbook's frames a second (it boils as it goes, each puff from its own frame).</summary>
+ public const float FramesPerSecond = 20f;
+
+ /// <summary>DESIGN VALUES for the colours: the smoke flipbook's grey averages about 0.44 where opaque, so each tint is
+ /// about twice the shade drawn. Oil-burning smoke leaves the chimney dark grey-black (about 0.14) and thins to grey
+ /// (about 0.5); steam is white.</summary>
+ public static readonly Color SmokeFresh = new Color(0.32f, 0.31f, 0.3f, 0.92f), SmokeOld = new Color(1.15f, 1.15f, 1.15f, 0.55f),
+ SteamFresh = new Color(2.2f, 2.2f, 2.2f, 0.85f), SteamOld = new Color(2.25f, 2.25f, 2.25f, 0.5f);
+
+ /// <summary>The clock (s), the train's own (RouteTrain runs on Time.time). Test seam (internal; the tests see it
+ /// through InternalsVisibleTo).</summary>
+ internal static Func<float> Clock = () => Time.time;
+
+ static readonly int BaseColor = Shader.PropertyToID("_BaseColor");
+
+ RouteTrain train = null!;
+ float sizeM;
+ Mesh[] frames = Array.Empty<Mesh>();
+ Transform[] quad = Array.Empty<Transform>();
+ Renderer[] shown = Array.Empty<Renderer>();
+ MeshFilter[] filter = Array.Empty<MeshFilter>();
+ Material[] material = Array.Empty<Material>();
+ float[] spin = Array.Empty<float>(); // each slot's puff's turn on the screen
+ readonly List<Object> owned = new List<Object>();
+ Quaternion view = Quaternion.identity;
+
+ /// <summary>The meshes and materials this made (tests: freed with the train).</summary>
+ internal IReadOnlyList<Object> Owned => owned;
+ /// <summary>The puffs' renderers, one per slot (tests).</summary>
+ internal Renderer[] Renderers => shown;
+ public float SizeM => sizeM;
+
+ /// <summary>Adds the steam to <paramref name="train"/>, its puffs <paramref name="sizeM"/> across. Null when the smoke
+ /// flipbook is missing from Resources (a warning says so): the train runs without steam.</summary>
+ public static TrainSteam? Attach(RouteTrain train, float sizeM)
+ {
+ var cloud = Flipbook.Load(Flipbook.SmokeResource);
+ if (cloud == null)
+ {
+ Debug.LogWarning("TRAIN: the smoke flipbook is missing from Resources/Effects; the train runs without steam.");
+ return null;
+ }
+ var go = new GameObject(Name);
+ go.transform.SetParent(train.transform, false);
+ var s = go.AddComponent<TrainSteam>();
+ s.train = train; s.sizeM = sizeM;
+ s.frames = Flipbook.Frames(Flipbook.SmokeGrid, m => { s.owned.Add(m); return m; }, "TrainSteam");
+ s.quad = new Transform[Puffs]; s.shown = new Renderer[Puffs]; s.filter = new MeshFilter[Puffs]; s.material = new Material[Puffs]; s.spin = new float[Puffs];
+ for (int i = 0; i < Puffs; i++)
+ {
+ var m = s.material[i] = Flipbook.NewMaterial(HexMaterials.AttackBorder, cloud); s.owned.Add(m);
+ (s.quad[i], s.shown[i], s.filter[i]) = Flipbook.Part(go.transform, "Puff", s.frames[0], m);
+ }
+ var cam = Camera.main;
+ if (cam != null) s.view = cam.transform.rotation;
+ return s;
+ }
+
+ /// <summary>The slot puff <paramref name="k"/> draws in (each puff keeps its slot for its whole life).</summary>
+ public static int SlotOf(long k) { int m = (int)(k % Puffs); return m < 0 ? m + Puffs : m; }
+
+ /// <summary>Whether puff <paramref name="k"/> is white steam rather than smoke.</summary>
+ public static bool IsSteam(long k) => k % SteamEvery == 0;
+
+ /// <summary>The trail as it is at clock time <paramref name="now"/>: nothing while the train stands; else the last
+ /// <see cref="Puffs"/> puffs, each from where the chimney was when it left (none for a puff that left while the train
+ /// stood). The same time gives the same trail. No allocation.</summary>
+ internal void Sample(float now)
+ {
+ if (train == null) return;
+ if (!train.MovingAt(now)) { Hide(); return; }
+ long newest = (long)Math.Floor(now / (double)GapS);
+ for (int j = 0; j < Puffs; j++)
+ {
+ long k = newest - j;
+ int i = SlotOf(k);
+ float born = (float)(k * (double)GapS), age = now - born, b = age / LifeS;
+ if (b < 0f || b >= 1f || !train.MovingAt(born)) { shown[i].enabled = false; continue; }
+ var (head, dir) = train.HeadAt(born);
+ var (chimney, back) = train.ChimneyAt(head, dir);
+ bool steam = IsSteam(k);
+ float size = sizeM * (steam ? SteamSizeShare : 1f);
+ float s = size * FlipbookBursts.Swell(b, OpenShare, SpreadShare);
+ var centre = chimney + back * (DriftShare * size * age) + Vector3.up * (CentreShare * s + RiseShare * size * age);
+ spin[i] = Spin(k);
+ quad[i].SetPositionAndRotation(centre, view * Quaternion.Euler(0f, 0f, spin[i]));
+ quad[i].localScale = Vector3.one * s;
+ filter[i].sharedMesh = frames[Flipbook.Looping(age * FramesPerSecond + SlotOf(k * 7) * 6, frames.Length)];
+ Color c;
+ if (steam)
+ {
+ float sb = Mathf.Clamp01(b / SteamLifeShare);
+ c = Color.Lerp(SteamFresh, SteamOld, sb); c.a *= sb >= 1f ? 0f : FlipbookBursts.Fade(sb, FadeShare);
+ }
+ else { c = Color.Lerp(SmokeFresh, SmokeOld, b); c.a *= FlipbookBursts.Fade(b, FadeShare); }
+ material[i].SetColor(BaseColor, c);
+ shown[i].enabled = c.a > 0f;
+ }
+ }
+
+ /// <summary>Puff <paramref name="k"/>'s turn on the screen (degrees, within 25 either way so the flipbook's lit side
+ /// stays up).</summary>
+ static float Spin(long k) { int m = (int)((k * 37) % 51); return (m < 0 ? m + 51 : m) - 25; }
+
+ void Hide() { for (int i = 0; i < shown.Length; i++) shown[i].enabled = false; }
+
+ void Update() { if (Application.isPlaying) Sample(Clock()); }
+
+ void OnEnable() => RenderPipelineManager.beginCameraRendering += Face;
+
+ /// <summary>Hidden (the train's toggle, its date) or stopped: every puff goes, so none is left over when it shows
+ /// again.</summary>
+ void OnDisable()
+ {
+ RenderPipelineManager.beginCameraRendering -= Face;
+ Hide();
+ }
+
+ /// <summary>Turns the puffs to the camera about to render, as CombatBursts does.</summary>
+ void Face(ScriptableRenderContext _, Camera cam)
+ {
+ if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;
+ view = cam.transform.rotation;
+ for (int i = 0; i < quad.Length; i++)
+ if (shown[i].enabled) quad[i].rotation = view * Quaternion.Euler(0f, 0f, spin[i]);
+ }
+
+ void OnDestroy()
+ {
+ foreach (var o in owned) if (o != null) { if (Application.isPlaying) Destroy(o); else DestroyImmediate(o); }
+ owned.Clear();
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Routes/TrainSteam.cs.meta b/unity/Assets/Scripts/Map/Routes/TrainSteam.cs.meta
new file mode 100644
index 000000000..c5f7d7141
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Routes/TrainSteam.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: da9ebdf2f0804709bdaf332ba1d7b359
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/CombatBursts.cs b/unity/Assets/Scripts/Map/Units/CombatBursts.cs
new file mode 100644
index 000000000..0cca0563d
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/CombatBursts.cs
@@ -0,0 +1,196 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using Statecraft.HexTiles;
+using UnityEngine;
+using UnityEngine.Rendering;
+using Object = UnityEngine.Object;
+
+namespace Statecraft.Game.Map.Units
+{
+ /// <summary>What an attack hits (owner, 4 November 2026: "Hit on target hex"), from an engagement's structured line
+ /// (UnitAttackPresenter.HitOf): the hex it hit, whether guns fired (a shell bursts there) and whether other units did
+ /// (small-arms fire kicks up dust), and the defenders by sim id, whose tokens the hit lands on.</summary>
+ public readonly struct CombatHit
+ {
+ public readonly int Q, R;
+ public readonly bool Guns, SmallArms;
+ /// <summary>The engagement's aggregate defender loss, or zero when the structured value is absent or malformed.</summary>
+ public readonly int DefenderLoss;
+ public readonly IReadOnlyList<int> Defenders;
+ public CombatHit(int q, int r, bool guns, bool smallArms, IReadOnlyList<int> defenders)
+ : this(q, r, guns, smallArms, 0, defenders) { }
+ public CombatHit(int q, int r, bool guns, bool smallArms, int defenderLoss, IReadOnlyList<int> defenders)
+ { Q = q; R = r; Guns = guns; SmallArms = smallArms; DefenderLoss = defenderLoss; Defenders = defenders; }
+ }
+
+ /// <summary>The combat effects on the map's ground (owner, 4 November 2026: "Hit on target hex" and "Dust when a unit
+ /// dies"): a shell's burst where the guns' fire lands, a few puffs of dust where small arms hit, and a cloud of dust where
+ /// a destroyed unit's token stood, and a lighter trail behind a moving token. All are drawn as #2490's Dakota bombs are:
+ /// Unity Labs' CC0 flipbooks (Flipbook) on unlit camera-facing quads, from three small pools made once
+ /// (<see cref="FlipbookBursts"/>), each burst a pure function of the
+ /// clock, so sampling allocates nothing. Presentation only: it reads no state and writes none. It lives under the unit
+ /// layer, so the units' toggle hides it (and drops what plays), and it goes with the layer. It runs only while a burst
+ /// plays (in play: an edit-mode build, such as the promo captures, never advances it).</summary>
+ [ExecuteAlways]
+ public sealed class CombatBursts : MonoBehaviour
+ {
+ public const string Name = "Combat effects";
+
+ /// <summary>DESIGN VALUES for the timing, from the attack's start (UnitTokenMotion.PlayAttack, the gun's flash at 0,
+ /// UnitGunFire): the shell bursts on the target <see cref="ShellFlightS"/> after the flash; the first puff of the
+ /// small-arms volley rises <see cref="VolleyS"/> after the figures' fire take starts, then <see cref="VolleyPuffs"/>
+ /// in all, <see cref="VolleyGapS"/> apart. A destroyed unit's dust rises with the hit that destroyed it
+ /// (<see cref="ImpactS"/>), in <see cref="DeathPuffs"/> puffs <see cref="DeathGapS"/> apart.</summary>
+ public const float ShellFlightS = 0.3f, VolleyS = 0.12f, VolleyGapS = 0.22f, DeathGapS = 0.15f;
+ public const int VolleyPuffs = 3, DeathPuffs = 3;
+
+ /// <summary>When <paramref name="h"/>'s first hit shows on its target, from the fire take's start: the small-arms
+ /// volley's first puff (<see cref="VolleyS"/>) when any small arms fired, else the shell's burst
+ /// (<see cref="ShellFlightS"/>); 0 for neither. The defenders' shake and flash and the dust of the units it destroyed
+ /// start then, so they land with it (e21's capture of #2614, 5 November 2026: they came with the shot, before it).</summary>
+ public static float ImpactS(CombatHit h) => h.SmallArms ? VolleyS : h.Guns ? ShellFlightS : 0f;
+
+ /// <summary>DESIGN VALUES for the sizes (m across), beside a 4.4 km hex and the Dakotas' 2.2 km bomb blast
+ /// (SeaAirCollection.DakotaBlastM): a field gun's shell is smaller than an aerial bomb; small arms raise small puffs;
+ /// a unit's end raises a cloud about as wide as its token's base. Each puff stands <see cref="SpreadShare"/> of its
+ /// size from the spot, each its own way, so the puffs read as several.</summary>
+ public const float BlastM = 1400f, HitDustM = 800f, DeathDustM = 1500f, MoveDustM = 520f, SpreadShare = 0.45f;
+
+ /// <summary>DESIGN VALUES: the pools' sizes, as many as can show at once with a few attacks in one turn (an older burst
+ /// gives up its slot to a newer one).</summary>
+ public const int BlastSlots = 4, DustSlots = 12, MoveDustSlots = 8;
+
+ /// <summary>DESIGN VALUES: the shell's burst plays the whole explosion flipbook (fire, then black smoke) over 1.8 s,
+ /// opening at 0.45 of its size and swelling, as the Dakotas' blast does (BlastTint, DakotaBlastOpenShare and
+ /// DakotaBlastFadeShare). The dust is the smoke flipbook in a dusty brown (its grey averages 0.44 where opaque, so
+ /// the tint is about twice the shade drawn), puffing out from a third of its size, rising and thinning paler.</summary>
+ public static readonly FlipbookBursts.Style BlastStyle = new FlipbookBursts.Style(1.8f, 0, Flipbook.ExplosionGrid * Flipbook.ExplosionGrid,
+ 0.45f, 0.12f, 0.1f, 0.35f, new Color(1f, 0.95f, 0.88f, 1f), new Color(1f, 0.95f, 0.88f, 1f), 0.4f);
+ public static readonly FlipbookBursts.Style DustStyle = new FlipbookBursts.Style(1.6f, 0, 24,
+ 0.35f, 0.5f, 0.35f, 0.6f, new Color(1.25f, 1.1f, 0.88f, 0.85f), new Color(1.6f, 1.5f, 1.35f, 0.6f), 0.4f);
+ public static readonly FlipbookBursts.Style MoveDustStyle = new FlipbookBursts.Style(0.7f, 0, 18,
+ 0.25f, 0.3f, 0.12f, 0.55f, new Color(1.18f, 1.05f, 0.84f, 0.48f), new Color(1.45f, 1.35f, 1.18f, 0f), 0.3f);
+
+ /// <summary>Each puff's direction from the spot (x east, z north) and its turn on the screen (degrees, within 25 either
+ /// way so the flipbook's lit side stays up).</summary>
+ static readonly Vector2[] PuffSide = { new Vector2(-0.8f, 0.2f), new Vector2(0.7f, -0.3f), new Vector2(0.1f, 0.9f) };
+ static readonly float[] PuffSpin = { -18f, 12f, 24f };
+
+ /// <summary>The clock (s). Test seam (internal; the tests see it through InternalsVisibleTo): an EditMode test has no
+ /// frame clock.</summary>
+ internal static Func<double> Clock = () => Time.timeAsDouble;
+
+ FlipbookBursts? blasts, dust, moveDust;
+ readonly List<Object> owned = new List<Object>();
+
+ /// <summary>The pools (tests): the shells' bursts, combat dust and movement dust.</summary>
+ internal FlipbookBursts? Blasts => blasts;
+ internal FlipbookBursts? Dust => dust;
+ internal FlipbookBursts? MoveDust => moveDust;
+
+ /// <summary>Makes the effects under <paramref name="parent"/>, hidden until a burst. Null when the flipbooks are
+ /// missing from Resources (a warning says so): nothing plays then.</summary>
+ public static CombatBursts? Create(Transform parent)
+ {
+ var blast = Flipbook.Load(Flipbook.ExplosionResource); var cloud = Flipbook.Load(Flipbook.SmokeResource);
+ if (blast == null || cloud == null)
+ {
+ Debug.LogWarning("UNITS: the explosion or smoke flipbook is missing from Resources/Effects; attacks and losses play no burst.");
+ return null;
+ }
+ var go = new GameObject(Name);
+ go.transform.SetParent(parent, false);
+ var c = go.AddComponent<CombatBursts>();
+ c.blasts = new FlipbookBursts(go.transform, "ShellBurst", BlastSlots, blast, Flipbook.ExplosionGrid, HexMaterials.AttackBorder, BlastStyle);
+ c.dust = new FlipbookBursts(go.transform, "Dust", DustSlots, cloud, Flipbook.SmokeGrid, HexMaterials.AttackBorder, DustStyle);
+ c.moveDust = new FlipbookBursts(go.transform, "MoveDust", MoveDustSlots, cloud, Flipbook.SmokeGrid, HexMaterials.AttackBorder, MoveDustStyle);
+ c.owned.AddRange(c.blasts.Owned); c.owned.AddRange(c.dust.Owned); c.owned.AddRange(c.moveDust.Owned);
+ var cam = Camera.main;
+ if (cam != null) c.Face(cam.transform.rotation);
+ c.enabled = false; // runs only while a burst plays
+ // Keep the already-created callback registered for this short-lived map child. Re-subscribing on every first
+ // emission would allocate on that frame; OnDestroy removes it, and Face returns immediately while hidden.
+ RenderPipelineManager.beginCameraRendering += c.Face;
+ return c;
+ }
+
+ /// <summary>Plays an attack's hit on the spot <paramref name="at"/> (world, on the ground), from now: a shell's burst
+ /// when <paramref name="guns"/> fired, the small-arms volley's dust when <paramref name="smallArms"/> did. False when
+ /// neither, or the effects are hidden.</summary>
+ public bool Hit(Vector3 at, bool guns, bool smallArms)
+ {
+ if (!gameObject.activeInHierarchy || blasts == null || dust == null || !(guns || smallArms)) return false;
+ double now = Clock();
+ if (guns) blasts.Start(at, BlastM, now + ShellFlightS);
+ if (smallArms) Puffs(at, HitDustM, now + VolleyS, VolleyPuffs, VolleyGapS);
+ Run(now);
+ return true;
+ }
+
+ /// <summary>Raises the dust of a destroyed unit where its token stood, <paramref name="at"/> (world, on the ground),
+ /// <paramref name="delayS"/> from now (the hit's <see cref="ImpactS"/>). False when the effects are hidden.</summary>
+ public bool Destroyed(Vector3 at, float delayS = 0f)
+ {
+ if (!gameObject.activeInHierarchy || dust == null) return false;
+ double now = Clock();
+ Puffs(at, DeathDustM, now + Mathf.Max(0f, delayS), DeathPuffs, DeathGapS);
+ Run(now);
+ return true;
+ }
+
+ /// <summary>Raises one light ground-dust puff behind a moving token. False while the unit layer is hidden.</summary>
+ public bool March(Vector3 at)
+ {
+ if (!gameObject.activeInHierarchy || moveDust == null) return false;
+ double now = Clock();
+ moveDust.Start(at, MoveDustM, now);
+ Run(now);
+ return true;
+ }
+
+ void Puffs(Vector3 at, float size, double start, int count, float gap)
+ {
+ for (int i = 0; i < count; i++)
+ {
+ var side = PuffSide[i % PuffSide.Length] * (SpreadShare * size * (i == 0 ? 0.4f : 1f));
+ dust!.Start(at + new Vector3(side.x, 0f, side.y), size, start + i * gap, PuffSpin[i % PuffSpin.Length]);
+ }
+ }
+
+ void Run(double now) { enabled = true; Sample(now); }
+
+ /// <summary>Every burst as it is at clock time <paramref name="now"/>; the component stops when none is left. No
+ /// allocation.</summary>
+ internal void Sample(double now)
+ {
+ if (blasts == null || dust == null || moveDust == null) return;
+ blasts.Sample(now); dust.Sample(now); moveDust.Sample(now);
+ if (blasts.Busy == 0 && dust.Busy == 0 && moveDust.Busy == 0) enabled = false;
+ }
+
+ void Update() { if (Application.isPlaying) Sample(Clock()); }
+
+ /// <summary>Hidden (the units' toggle) or stopped: whatever played is dropped, as a gun drops its shot.</summary>
+ void OnDisable()
+ {
+ blasts?.Clear(); dust?.Clear(); moveDust?.Clear();
+ }
+
+ /// <summary>Turns the bursts to the camera about to render, as UnitGunFire.Face does the gun's.</summary>
+ void Face(ScriptableRenderContext _, Camera cam)
+ {
+ if (!enabled || !gameObject.activeInHierarchy || cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;
+ Face(cam.transform.rotation);
+ }
+
+ void Face(Quaternion view) { blasts?.Face(view); dust?.Face(view); moveDust?.Face(view); }
+
+ void OnDestroy()
+ {
+ RenderPipelineManager.beginCameraRendering -= Face;
+ foreach (var o in owned) if (o != null) { if (Application.isPlaying) Destroy(o); else DestroyImmediate(o); }
+ owned.Clear();
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Units/CombatBursts.cs.meta b/unity/Assets/Scripts/Map/Units/CombatBursts.cs.meta
new file mode 100644
index 000000000..9dce62621
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Units/CombatBursts.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: ffb87413fe12441e9969fc643da461cf
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
index 3bd46d972..1f09d2310 100644
--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
@@ -34,7 +34,7 @@ namespace Statecraft.Game.Map.Units
UnitGround ground = null!;
IReadOnlyDictionary<UnitAnchor, AnchorSpot> spots = new Dictionary<UnitAnchor, AnchorSpot>();
MapRuntimeAssets assets = null!;
- Material paint = null!, ringTemplate = null!, badgePlate = null!, badgeGlyph = null!, rim = 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 the tokens drawn now (each base's draped top, lip and ring follow its own ground):
@@ -153,6 +153,14 @@ namespace Statecraft.Game.Map.Units
/// <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>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;
@@ -231,9 +239,12 @@ namespace Statecraft.Game.Map.Units
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)>()));
@@ -668,13 +679,20 @@ namespace Statecraft.Game.Map.Units
// 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;
- drawnAt[Key(m.SimId, m.name)] = trios[i].centre + m.transform.position;
+ // 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);
var outgoing = new List<GameObject>();
for (int i = tokensRoot.childCount - 1; i >= 0; i--)
{
@@ -688,18 +706,26 @@ namespace Statecraft.Game.Map.Units
// 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); }
+ try { BuildTokens(drawnAt, firing, hits); }
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> firing,
+ IReadOnlyDictionary<(int sim, string row), (float left, float delay)> hits)
{
pickVersion++;
FreeTokenMeshes();
motions.Clear();
+ drawnSims.Clear();
+ foreach (var p in placed) drawnSims.Add(p.Token.StateUnit?.Id ?? -1);
badges.Clear(); badgeHomes.Clear(); facedFor = null;
trios.Clear(); turnedFor = null; // the new figures stand as at yaw 0
treeHoles.Clear();
@@ -806,6 +832,9 @@ namespace Statecraft.Game.Map.Units
badges.Add(badge.transform); badgeHomes.Add((home, back, pole, flag, standing));
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;
AddRenderer(badge.transform, "Glyph", MeshFor("badge-" + t.Unit.Service, () => UnitBadge.GlyphMesh(t.Unit.Service)), 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;
@@ -823,11 +852,15 @@ namespace Statecraft.Game.Map.Units
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))
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);
}
}
@@ -840,6 +873,61 @@ namespace Statecraft.Game.Map.Units
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>
@@ -875,7 +963,7 @@ namespace Statecraft.Game.Map.Units
return piece;
}
- static void AddRenderer(Transform parent, string name, Mesh mesh, Material mat, float z)
+ static Renderer AddRenderer(Transform parent, string name, Mesh mesh, Material mat, float z)
{
var go = new GameObject(name);
go.transform.SetParent(parent, false);
@@ -885,6 +973,7 @@ namespace Statecraft.Game.Map.Units
r.sharedMaterial = mat;
r.shadowCastingMode = ShadowCastingMode.Off;
r.receiveShadows = false;
+ return r;
}
void BuildAircraft(Transform parent, UnitToken t, Vector3 baseCentre)
diff --git a/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs b/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
index 9c635f818..be0730977 100644
--- a/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs
@@ -10,8 +10,8 @@ namespace Statecraft.Game.Map.Units
/// stand at their map places under it, so the root's position is an offset from where the unit now is. A move slides
/// that offset from the old place to zero over <see cref="Duration"/>; the figures walk meanwhile and stand idle after.
/// An attack plays the figures' fire take once, then they walk or stand again; a 65 mm gun on the token fires with
- /// them (UnitGunFire, #2373). The component runs its LateUpdate only
- /// while a move or an attack is under way. Disabling it (the token hidden or rebuilt) puts the token where the unit is.
+ /// them (UnitGunFire, #2373). A hit reaction composes a short shake with that slide. The component runs its LateUpdate
+ /// only while a move, attack or reaction is under way. Disabling it (the token hidden or rebuilt) clears every motion.
/// A figure that turns near mid-move or mid-attack (UnitFigureDetail) or arrives then (UnitFigures) joins in at once.</summary>
public sealed class UnitTokenMotion : MonoBehaviour
{
@@ -21,14 +21,24 @@ namespace Statecraft.Game.Map.Units
/// <summary>How long an attack waits for a figure that can play it. An engagement usually changes strengths, so the
/// tokens are rebuilt just before it plays, and the new ones turn their near figures on at the next render.</summary>
public const float AttackWaitS = 0.25f;
+ public const float HitDurationS = 0.28f, HitFlashS = 0.12f, HitShakeM = 160f;
+ public const int MoveDustPuffs = 3;
/// <summary>The sim unit this token draws, or -1 for a row with no sim unit (the legacy loop).</summary>
public int SimId { get; internal set; } = -1;
/// <summary>Raised when the token's place changes, so UnitLayer redraws its badge and hit boxes there.</summary>
internal Action? Changed;
+ internal CombatBursts? Effects;
+ internal Vector3 GroundHome;
+ internal Renderer? HitFlash;
- Vector3 from;
- float elapsed = Duration, attackLeft;
+ Vector3 from, moveOffset;
+
+ /// <summary>The slide under way (world offset from the token's place), without the hit's shake: where the token is,
+ /// as the hit's burst and a destroyed unit's dust read it (UnitLayer.DrawnAt).</summary>
+ internal Vector3 SlideOffset => moveOffset;
+ float elapsed = Duration, attackLeft, hitLeft, hitDelay;
+ int nextMoveDust;
bool firing; // a figure plays the attack (else it waits for one, up to AttackWaitS)
bool fired; // an attack just ended: its figures go back to walking or standing
float attackLength, resumeAt; // the playing take's length; where a continued attack picks up
@@ -36,17 +46,21 @@ namespace Statecraft.Game.Map.Units
readonly List<Animator> animators = new List<Animator>();
readonly List<UnitFigurePointFire> aims = new List<UnitFigurePointFire>();
readonly List<UnitGunFire> guns = new List<UnitGunFire>();
+ Action? attackStarted, attackMissed;
public bool Moving => elapsed < Duration;
/// <summary>An attack plays, or waits for a figure to play it.</summary>
public bool Attacking => attackLeft > 0f;
+ public bool Reacting => hitLeft > 0f;
+ /// <summary>A shake and flash wait to start (<see cref="PlayHit"/> with a delay).</summary>
+ public bool HitPending => hitDelay > 0f;
/// <summary>Starts a slide from <paramref name="offset"/> (the old place less the new) to the unit's place.</summary>
public void Begin(Vector3 offset)
{
- if (offset.sqrMagnitude < MinMoveM * MinMoveM) { if (Moving || Attacking) Snap(); return; }
- from = offset; elapsed = 0f;
- transform.position = from;
+ if (offset.sqrMagnitude < MinMoveM * MinMoveM) { if (Moving || Attacking || Reacting || HitPending) Snap(); return; }
+ from = moveOffset = offset; elapsed = 0f; nextMoveDust = 0;
+ ApplyPosition();
enabled = true;
Pose();
Changed?.Invoke();
@@ -55,9 +69,15 @@ namespace Statecraft.Game.Map.Units
/// <summary>Plays the figures' attack take once from its start (again, if one is playing). True when a figure
/// plays it now; else it waits <see cref="AttackWaitS"/> for one to turn near, and then is dropped. A hidden token
/// does nothing. Nothing is kept to play later.</summary>
- public bool PlayAttack()
+ public bool PlayAttack() => PlayAttack(null, null);
+
+ /// <summary>As <see cref="PlayAttack()"/>, reporting when a visible take actually starts, or when its short wait
+ /// ends without one. The callbacks let the defender react to the take rather than merely to its request.</summary>
+ internal bool PlayAttack(Action? started, Action? missed)
{
- if (!gameObject.activeInHierarchy) return false;
+ if (!gameObject.activeInHierarchy) { missed?.Invoke(); return false; }
+ DropAttackCue();
+ attackStarted = started; attackMissed = missed;
attackLeft = AttackWaitS; firing = false; resumeAt = 0f;
enabled = true;
return Fire();
@@ -108,9 +128,72 @@ namespace Statecraft.Game.Map.Units
attackLength = longest; attackLeft = longest - resumeAt; resumeAt = 0f; firing = true;
foreach (var aim in aims) aim.Hold();
foreach (var gun in guns) if (gun.Ready) gun.Fire(from);
+ var started = attackStarted; attackStarted = null; attackMissed = null;
+ started?.Invoke();
+ return true;
+ }
+
+ /// <summary>Starts the defender's short presentation-only shake and badge flash, <paramref name="delayS"/> from now
+ /// (when the hit lands on it, CombatBursts.ImpactS), or at once.</summary>
+ public bool PlayHit(float delayS = 0f)
+ {
+ if (!gameObject.activeInHierarchy) return false;
+ enabled = true;
+ if (delayS > 0f) { hitDelay = delayS; return true; }
+ StartHit(0f);
return true;
}
+ /// <summary>The hit the token shows or waits to show: the shake's time left and the delay before it lands (both 0 when
+ /// none). A rebuild hands it to the unit's new token (<see cref="ContinueHit"/>).</summary>
+ internal (float left, float delay) HitState => (hitLeft, hitDelay);
+
+ /// <summary>Goes on with the hit the unit's previous token was showing (<paramref name="left"/> of its shake) or
+ /// waiting for (<paramref name="delay"/> until it lands), so a rebuild for another unit's loss cuts neither short.</summary>
+ internal void ContinueHit(float left, float delay)
+ {
+ if (!gameObject.activeInHierarchy || (left <= 0f && delay <= 0f)) return;
+ enabled = true;
+ if (delay > 0f) { hitDelay = delay; return; }
+ hitLeft = Mathf.Min(left, HitDurationS);
+ ApplyPosition();
+ Changed?.Invoke();
+ }
+
+ void StartHit(float late)
+ {
+ hitDelay = 0f;
+ hitLeft = Mathf.Max(0f, HitDurationS - late);
+ ApplyPosition();
+ Changed?.Invoke();
+ }
+
+ void EmitMoveDustThrough(float share)
+ {
+ while (nextMoveDust < MoveDustPuffs)
+ {
+ float mark = (nextMoveDust + 1f) / (MoveDustPuffs + 1f);
+ if (share < mark) break;
+ Effects?.March(GroundHome + Vector3.Lerp(from, Vector3.zero, mark));
+ nextMoveDust++;
+ }
+ }
+
+ void ApplyPosition()
+ {
+ float age = HitDurationS - hitLeft;
+ float falloff = Reacting ? hitLeft / HitDurationS : 0f;
+ float wave = Reacting ? Mathf.Sin(age * 4f * Mathf.PI / HitDurationS) : 0f;
+ transform.position = moveOffset + new Vector3(wave, 0f, -wave * 0.35f) * (HitShakeM * falloff);
+ if (HitFlash != null) HitFlash.enabled = hitLeft > HitDurationS - HitFlashS;
+ }
+
+ void DropAttackCue()
+ {
+ var missed = attackMissed; attackStarted = null; attackMissed = null;
+ missed?.Invoke();
+ }
+
/// <summary>The longest fire take on <paramref name="animator"/>'s controller (reading its clips allocates).</summary>
internal static float FireLength(Animator animator)
{
@@ -157,35 +240,50 @@ namespace Statecraft.Game.Map.Units
internal void Tick(float seconds)
{
seconds = Mathf.Max(0f, seconds);
- bool wasMoving = Moving, wasFiring = firing;
+ bool wasMoving = Moving, wasFiring = firing, wasReacting = Reacting;
if (Moving)
{
elapsed = Mathf.Min(Duration, elapsed + seconds);
- transform.position = Vector3.Lerp(from, Vector3.zero, elapsed / Duration);
- Changed?.Invoke();
+ float share = elapsed / Duration;
+ moveOffset = Vector3.Lerp(from, Vector3.zero, share);
+ EmitMoveDustThrough(share);
+ }
+ if (Reacting) hitLeft = Mathf.Max(0f, hitLeft - seconds);
+ if (HitPending)
+ {
+ // The hit lands within this step: the shake starts then, already as old as the rest of the step.
+ if (seconds < hitDelay) hitDelay -= seconds; else { StartHit(seconds - hitDelay); wasReacting = false; }
}
+ if (wasMoving || wasReacting) { ApplyPosition(); Changed?.Invoke(); }
if (Attacking)
{
attackLeft = Mathf.Max(0f, attackLeft - seconds);
- if (!Attacking) { fired = firing; firing = false; resumeAt = 0f; }
+ if (!Attacking)
+ {
+ fired = firing; firing = false; resumeAt = 0f;
+ if (!fired) DropAttackCue();
+ }
}
if (wasMoving != Moving || wasFiring != firing) Pose();
- if (!Moving && !Attacking) enabled = false; // an idle token costs nothing per frame
+ if (!Moving && !Attacking && !Reacting && !HitPending) enabled = false; // an idle token costs nothing per frame
}
void LateUpdate() => Tick(Time.deltaTime);
void OnDisable()
{
- if (Moving || Attacking) Snap();
+ if (Moving || Attacking || Reacting || HitPending) Snap();
}
void Snap()
{
bool moved = transform.position != Vector3.zero;
fired = firing;
- elapsed = Duration; attackLeft = 0f; firing = false; resumeAt = 0f; from = Vector3.zero;
+ elapsed = Duration; attackLeft = hitLeft = hitDelay = 0f; firing = false; resumeAt = 0f;
+ from = moveOffset = Vector3.zero; nextMoveDust = 0;
+ DropAttackCue();
transform.position = Vector3.zero;
+ if (HitFlash != null) HitFlash.enabled = false;
Pose();
if (moved) Changed?.Invoke();
}
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index fc654949e..82a0258ef 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -486,7 +486,8 @@ namespace Statecraft.Game.UI
bridge.Changed += showUnits;
owned.Add(new Undo(() => bridge.Changed -= showUnits));
showUnits();
- owned.Add(new UnitAttackPresenter(bridge, unitLayer.PlayAttack)); // after showUnits: the map is redrawn first
+ owned.Add(new UnitAttackPresenter(bridge, unitLayer.PlayAttack, unitLayer.PlayHit, unitLayer.PlayDestroyed,
+ unitLayer.PlayDefenderHit, unitLayer.PlayAttack)); // after showUnits: the map is redrawn first
DiagLog.BootPhase("units layer built");
// #1878: the turn report is up, the hexes the turn attacked show the under-attack look; closing it clears them.
var underAttack = new Statecraft.Game.Map.UnderAttackLayer(map);
diff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.cs
index ea76b55f3..5de812a59 100644
--- a/unity/Assets/Scripts/UI/SimBridge.cs
+++ b/unity/Assets/Scripts/UI/SimBridge.cs
@@ -48,9 +48,10 @@ namespace Statecraft.Game.UI
public event Action<IReadOnlyList<Rejection>>? TurnEnded;
/// <summary>Raised after a move or unit order is committed, with the Why lines it added (an attack's result).</summary>
public event Action<IReadOnlyList<Cause>>? Committed;
- /// <summary>The engagements the player has just seen resolve, raised after <see cref="Changed"/> has redrawn the map
- /// (UnitAttackPresenter plays them, #1867): an attack order's at once, and at End Turn only the turn's new ones, not
- /// the open turn's attack orders, which the turn runs again first. Never on a load or a refused turn.</summary>
+ /// <summary>The engagements the player has just seen resolve, with the lines of the units they destroyed, raised after
+ /// <see cref="Changed"/> has redrawn the map (UnitAttackPresenter plays them, #1867): an attack order's at once, and at
+ /// End Turn only the turn's new ones, not the open turn's attack orders, which the turn runs again first. Never on a
+ /// load or a refused turn.</summary>
public event Action<IReadOnlyList<Cause>>? CombatResolved;
/// <summary>Raised when Queue refuses an order, with the player-facing reason.</summary>
public event Action<string>? Refused;
@@ -336,7 +337,7 @@ namespace Statecraft.Game.UI
string? Refuse(string reason) { reason = ReasonText(text, reason, Content, TownNamesHe); Refused?.Invoke(reason); return reason; }
- static IReadOnlyList<Cause> Engagements(IEnumerable<Cause> why) => why.Where(x => x.Key == WhyKeys.Engagement).ToList();
+ static IReadOnlyList<Cause> Engagements(IEnumerable<Cause> why) => why.Where(x => x.Key == WhyKeys.Engagement || x.Key == WhyKeys.Destroyed).ToList();
static void Notify(Action? handlers)
{
diff --git a/unity/Assets/Scripts/UI/UnitAttackPresenter.cs b/unity/Assets/Scripts/UI/UnitAttackPresenter.cs
index 6ceb9b52f..483795134 100644
--- a/unity/Assets/Scripts/UI/UnitAttackPresenter.cs
+++ b/unity/Assets/Scripts/UI/UnitAttackPresenter.cs
@@ -2,43 +2,146 @@
using System;
using System.Collections.Generic;
using System.Globalization;
+using System.Linq;
+using Statecraft.Game.Map.Units;
using Statecraft.Sim;
namespace Statecraft.Game.UI
{
/// <summary>Plays each fresh engagement's attackers' fire take on the map (#1867; design by Tal Heuberger, #2078): the
- /// attacking units' figures, supporting guns included, never the defenders'. Presentation only. A unit whose token cannot
- /// play now (destroyed, hidden, far, or no fire take) is skipped and nothing is kept to play later. GameRoot owns it.</summary>
+ /// attacking units' figures, supporting guns included, never the defenders'. With it, the hit on the hex it attacked
+ /// (owner, 4 November 2026: "Hit on target hex": a shell's burst when guns fired, dust when other units did) and the dust
+ /// of each unit it destroyed ("Dust when a unit dies"). On the production path the hit, the defenders' reaction and the
+ /// dust of the units the engagement destroyed wait for the attackers' first fire take that really starts (or, if none can,
+ /// the last one's wait), so nothing lands before the shot; the reaction and the dust then start when the hit lands on the
+ /// target (CombatBursts.ImpactS), with the volley's first puff or the shell's burst. Presentation only. A unit whose token cannot play now (destroyed, hidden, far, or no
+ /// fire take) is skipped and nothing is kept to play later. GameRoot owns it.</summary>
public sealed class UnitAttackPresenter : IDisposable
{
readonly SimBridge bridge;
readonly Func<int, bool> play;
+ readonly Func<CombatHit, bool>? hit;
+ readonly Func<int, float, bool>? destroyed;
+ readonly Func<CombatHit, bool>? defenderHit;
+ readonly Func<int, Action, Action, bool>? timedPlay;
/// <param name="play">Plays a sim unit's attack (UnitLayer.PlayAttack); false when its token cannot.</param>
- public UnitAttackPresenter(SimBridge bridge, Func<int, bool> play)
+ /// <param name="hit">Plays an engagement's hit on the hex it attacked (UnitLayer.PlayHit), or null.</param>
+ /// <param name="destroyed">Raises a destroyed sim unit's dust (UnitLayer.PlayDestroyed), the given seconds from now
+ /// (when the hit that destroyed it lands, CombatBursts.ImpactS), or null.</param>
+ /// <param name="defenderHit">Shakes and flashes the drawn defenders after positive aggregate loss, or null.</param>
+ /// <param name="timedPlay">Production attack path that reports the actual fire-take start or its missed wait.</param>
+ public UnitAttackPresenter(SimBridge bridge, Func<int, bool> play, Func<CombatHit, bool>? hit = null,
+ Func<int, float, bool>? destroyed = null, Func<CombatHit, bool>? defenderHit = null,
+ Func<int, Action, Action, bool>? timedPlay = null)
{
this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));
this.play = play ?? throw new ArgumentNullException(nameof(play));
+ this.hit = hit; this.destroyed = destroyed; this.defenderHit = defenderHit; this.timedPlay = timedPlay;
bridge.CombatResolved += Resolved;
}
- void Resolved(IReadOnlyList<Cause> engagements)
+ void Resolved(IReadOnlyList<Cause> lines)
{
- foreach (var engagement in engagements)
- foreach (int id in Attackers(engagement)) play(id);
+ FireCue? cue = null; // the timed engagement just before: Combat.Engage adds its Destroyed lines right after it
+ float impactS = 0f; // and when its hit lands after its fire take starts
+ foreach (var line in lines)
+ {
+ if (line.Key == WhyKeys.Destroyed)
+ {
+ if (destroyed is Func<int, float, bool> dust && line.Units.Count > 0)
+ {
+ int dead = line.Units[0].Id; float delay = impactS;
+ if (cue != null) cue.Then(() => dust(dead, delay)); else dust(dead, delay);
+ }
+ continue;
+ }
+ cue = null; impactS = 0f;
+ var parsed = HitOf(line, IsGuns);
+ if (parsed is CombatHit h && timedPlay != null && Count(line, out int attackerCount))
+ {
+ // The production path: the defenders react (on a loss) and the hit lands with the first real fire take.
+ cue = new FireCue(attackerCount, () => Impact(h));
+ impactS = CombatBursts.ImpactS(h);
+ foreach (int id in Attackers(line)) timedPlay(id, cue.Started, cue.Missed);
+ }
+ else
+ {
+ foreach (int id in Attackers(line)) play(id);
+ if (parsed is CombatHit immediate) { Impact(immediate); impactS = CombatBursts.ImpactS(immediate); }
+ }
+ }
}
+ /// <summary>The defenders' reaction when the engagement records a loss, then the hit on the hex it attacked.</summary>
+ void Impact(CombatHit h)
+ {
+ if (h.DefenderLoss > 0) defenderHit?.Invoke(h);
+ hit?.Invoke(h);
+ }
+
+ /// <summary>One engagement's group cue: the first actual fire take plays the impact once; if none can show, the last
+ /// miss does. UnitLayer's timed PlayAttack always reports one of the two (a hidden or rebuilt token reports a miss).
+ /// <see cref="Then"/> adds to the impact (a destroyed unit's dust): it plays with it, or at once if it already has,
+ /// since a take that starts at once reports during the engagement's own line.</summary>
+ sealed class FireCue
+ {
+ int left;
+ bool shown;
+ readonly List<Action> impacts = new List<Action>();
+
+ internal FireCue(int attackers, Action impact) { left = attackers; impacts.Add(impact); }
+
+ internal void Then(Action more) { if (shown) more(); else impacts.Add(more); }
+ internal void Started() { if (!shown) Play(); }
+ internal void Missed() { if (left > 0) left--; if (!shown && left == 0) Play(); }
+
+ void Play()
+ {
+ shown = true;
+ foreach (var impact in impacts) impact();
+ impacts.Clear();
+ }
+ }
+
+ /// <summary>True for a unit type of the guns' class (Combat.ArtilleryClass), as the sim's R-COMBAT-007 reads it.</summary>
+ bool IsGuns(string type) => bridge.Content.UnitTypes.Any(t => t.Id == type && t.Class == Combat.ArtilleryClass);
+
/// <summary>An engagement's attackers, from its structured line (Combat.Engage): the units are the attackers by id,
/// supporting guns included, then the defenders, and the fifth argument counts the attackers. Never the report's
/// text. None for another line or a malformed count.</summary>
internal static IEnumerable<int> Attackers(Cause engagement)
{
- if (engagement.Key != WhyKeys.Engagement || engagement.Args.Count < 5
- || !int.TryParse(engagement.Args[4], NumberStyles.None, CultureInfo.InvariantCulture, out int count)
- || count < 1 || count > engagement.Units.Count) yield break;
+ if (!Count(engagement, out int count)) yield break;
for (int i = 0; i < count; i++) yield return engagement.Units[i].Id;
}
+ /// <summary>An engagement's hit, from its structured line: the hex it hit (the first argument, "q,r"), whether any
+ /// attacker is a gun (<paramref name="isGuns"/> of its type) and whether any is not, and the defenders by id. Null for
+ /// another line, a malformed count or a malformed hex.</summary>
+ internal static CombatHit? HitOf(Cause engagement, Func<string, bool> isGuns)
+ {
+ if (!Count(engagement, out int count)) return null;
+ var hex = engagement.Args[0].Split(',');
+ if (hex.Length != 2 || !int.TryParse(hex[0], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int q)
+ || !int.TryParse(hex[1], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int r)) return null;
+ bool guns = false, smallArms = false;
+ for (int i = 0; i < count; i++) { if (isGuns(engagement.Units[i].Type)) guns = true; else smallArms = true; }
+ var defenders = new int[engagement.Units.Count - count];
+ for (int i = count; i < engagement.Units.Count; i++) defenders[i - count] = engagement.Units[i].Id;
+ int defenderLoss = int.TryParse(engagement.Args[3], NumberStyles.None, CultureInfo.InvariantCulture, out int loss)
+ && loss > 0 ? loss : 0;
+ return new CombatHit(q, r, guns, smallArms, defenderLoss, defenders);
+ }
+
+ static bool Count(Cause engagement, out int count)
+ {
+ count = 0;
+ return engagement.Key == WhyKeys.Engagement && engagement.Args.Count >= 5
+ && int.TryParse(engagement.Args[4], NumberStyles.None, CultureInfo.InvariantCulture, out count)
+ && count >= 1 && count <= engagement.Units.Count;
+ }
+
public void Dispose() => bridge.CombatResolved -= Resolved;
}
}
diff --git a/unity/Assets/Tests/EditMode/CombatEffectsTests.cs b/unity/Assets/Tests/EditMode/CombatEffectsTests.cs
new file mode 100644
index 000000000..b325d4604
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/CombatEffectsTests.cs
@@ -0,0 +1,467 @@
+#nullable enable
+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.HexTiles;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+/// <summary>The combat effects the owner chose on 4 November 2026 ("Hit on target hex", "Dust when a unit dies"), drawn with
+/// #2490's flipbook technique (Flipbook, FlipbookBursts): each burst starts where and when it should, plays on the clock
+/// alone, ends and frees its slot, allocates nothing per frame, and reads nothing but the engagement's structured lines.</summary>
+public class CombatEffectsTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
+ static GameSession NewSession() => GameSession.New(C, GoldenRun.Seed, Mode.Historical);
+ static List<UnitEntry> Units => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
+
+ readonly List<Object> made = new List<Object>();
+ double now;
+
+ [SetUp] public void HoldTheClock() { now = 100.0; CombatBursts.Clock = () => now; }
+
+ [TearDown]
+ public void Restore()
+ {
+ CombatBursts.Clock = () => Time.timeAsDouble;
+ foreach (var o in made) if (o != null) Object.DestroyImmediate(o);
+ made.Clear();
+ }
+
+ CombatBursts Bursts(out GameObject parent)
+ {
+ parent = new GameObject("test parent"); made.Add(parent);
+ var c = CombatBursts.Create(parent.transform);
+ Assert.IsNotNull(c, "the two flipbooks ship in Resources/Effects (#2490)");
+ return c!;
+ }
+
+ static Vector2 XZ(Vector3 v) => new Vector2(v.x, v.z);
+ static int Shown(FlipbookBursts pool) => pool.Renderers.Count(r => r.enabled);
+
+ [Test]
+ public void TheFlipbookFramesRunAlongTheRowsFromTheTopLeft()
+ {
+ var meshes = new List<Mesh>();
+ var frames = Flipbook.Frames(Flipbook.ExplosionGrid, m => { meshes.Add(m); return m; }, "test-frame");
+ try
+ {
+ Assert.AreEqual(25, frames.Length); CollectionAssert.AreEqual(frames, meshes, "each frame is handed to its owner");
+ Assert.AreEqual("test-frame-5x5-0", frames[0].name);
+ Rect UVs(Mesh m) { var uv = m.uv; return Rect.MinMaxRect(uv.Min(p => p.x), uv.Min(p => p.y), uv.Max(p => p.x), uv.Max(p => p.y)); }
+ Assert.AreEqual(Rect.MinMaxRect(0f, 0.8f, 0.2f, 1f).ToString("F4"), UVs(frames[0]).ToString("F4"), "frame 0 top left");
+ Assert.AreEqual(Rect.MinMaxRect(0.2f, 0.8f, 0.4f, 1f).ToString("F4"), UVs(frames[1]).ToString("F4"), "then along the row");
+ Assert.AreEqual(Rect.MinMaxRect(0.8f, 0f, 1f, 0.2f).ToString("F4"), UVs(frames[24]).ToString("F4"), "the last bottom right");
+ Assert.AreEqual(0, Flipbook.FrameAt(-0.5f, 25)); Assert.AreEqual(24, Flipbook.FrameAt(1.5f, 25)); Assert.AreEqual(12, Flipbook.FrameAt(0.5f, 25));
+ Assert.AreEqual(63, Flipbook.Looping(-0.5, 64), "a looping clock wraps below zero");
+ Assert.AreEqual(1, Flipbook.Looping(65.2, 64));
+ }
+ finally { foreach (var m in meshes) Object.DestroyImmediate(m); }
+ }
+
+ /// <summary>"Hit on target hex", the guns: the shell bursts on the spot ShellFlightS after the gun's flash, plays the
+ /// explosion flipbook through, then ends, frees its slot and stops the component.</summary>
+ [Test]
+ public void AGunsHitBurstsOnTheSpotAfterTheShellsFlightThenEnds()
+ {
+ var c = Bursts(out _);
+ var spot = new Vector3(1000f, 50f, -2000f);
+ Assert.IsTrue(c.Hit(spot, guns: true, smallArms: false));
+ Assert.AreEqual(1, c.Blasts!.Busy); Assert.AreEqual(0, c.Dust!.Busy, "no small arms, no dust");
+ Assert.IsTrue(c.enabled, "it runs while a burst plays");
+ c.Sample(now + CombatBursts.ShellFlightS - 0.01);
+ Assert.AreEqual(0, Shown(c.Blasts), "the shell is still in flight");
+ c.Sample(now + CombatBursts.ShellFlightS + 0.1);
+ var r = c.Blasts.Renderers.Single(x => x.enabled);
+ Assert.Less((XZ(r.transform.position) - XZ(spot)).magnitude, 1f, "on the spot");
+ Assert.Greater(r.transform.position.y, spot.y, "its foot on the ground, its centre above");
+ int first = c.Blasts.FrameOf(Array.IndexOf(c.Blasts.Renderers, r));
+ c.Sample(now + CombatBursts.ShellFlightS + 0.9 * CombatBursts.BlastStyle.LifeS);
+ Assert.Greater(c.Blasts.FrameOf(Array.IndexOf(c.Blasts.Renderers, r)), first, "it plays the flipbook through");
+ c.Sample(now + CombatBursts.ShellFlightS + CombatBursts.BlastStyle.LifeS + 0.01);
+ Assert.AreEqual(0, Shown(c.Blasts)); Assert.AreEqual(0, c.Blasts.Busy, "its slot is free again");
+ Assert.IsFalse(c.enabled, "nothing runs per frame once it ends");
+ }
+
+ /// <summary>"Hit on target hex", small arms: a volley of dust puffs round the spot, VolleyGapS apart from VolleyS on.</summary>
+ [Test]
+ public void SmallArmsRaiseAVolleyOfDustRoundTheSpot()
+ {
+ var c = Bursts(out _);
+ var spot = new Vector3(-300f, 10f, 700f);
+ Assert.IsTrue(c.Hit(spot, guns: false, smallArms: true));
+ Assert.AreEqual(0, c.Blasts!.Busy, "no guns, no shell");
+ Assert.AreEqual(CombatBursts.VolleyPuffs, c.Dust!.Busy);
+ c.Sample(now + CombatBursts.VolleyS - 0.01);
+ Assert.AreEqual(0, Shown(c.Dust), "nothing before the volley");
+ c.Sample(now + CombatBursts.VolleyS + 0.01);
+ Assert.AreEqual(1, Shown(c.Dust), "the first puff");
+ c.Sample(now + CombatBursts.VolleyS + (CombatBursts.VolleyPuffs - 1) * CombatBursts.VolleyGapS + 0.01);
+ Assert.AreEqual(CombatBursts.VolleyPuffs, Shown(c.Dust), "then the others");
+ for (int i = 0; i < c.Dust.Capacity; i++)
+ if (!double.IsNaN(c.Dust.StartOf(i)))
+ Assert.LessOrEqual((XZ(c.Dust.Foot(i)) - XZ(spot)).magnitude, CombatBursts.SpreadShare * CombatBursts.HitDustM + 1f, "round the spot");
+ c.Sample(now + CombatBursts.VolleyS + (CombatBursts.VolleyPuffs - 1) * CombatBursts.VolleyGapS + CombatBursts.DustStyle.LifeS + 0.01);
+ Assert.AreEqual(0, c.Dust.Busy); Assert.AreEqual(0, Shown(c.Dust)); Assert.IsFalse(c.enabled);
+ }
+
+ /// <summary>The hit's first sight on its target, from the fire take (e21's capture of #2614): the volley's first puff when
+ /// any small arms fired, else the shell's burst. A destroyed unit's dust and the defenders' shake start then.</summary>
+ [Test]
+ public void TheImpactTimeIsTheFirstHitSeen()
+ {
+ Assert.AreEqual(CombatBursts.ShellFlightS, CombatBursts.ImpactS(new CombatHit(0, 0, true, false, new int[0])));
+ Assert.AreEqual(CombatBursts.VolleyS, CombatBursts.ImpactS(new CombatHit(0, 0, false, true, new int[0])));
+ Assert.AreEqual(CombatBursts.VolleyS, CombatBursts.ImpactS(new CombatHit(0, 0, true, true, new int[0])), "the volley's puff shows first");
+ Assert.AreEqual(0f, CombatBursts.ImpactS(new CombatHit(0, 0, false, false, new int[0])));
+ }
+
+ /// <summary>A destroyed unit's dust given a delay (the hit's impact time) shows nothing before it and rises then.</summary>
+ [Test]
+ public void ADestroyedUnitsDustWaitsForItsDelay()
+ {
+ var c = Bursts(out _);
+ Assert.IsTrue(c.Destroyed(new Vector3(4000f, 120f, 900f), CombatBursts.ShellFlightS));
+ c.Sample(now + CombatBursts.ShellFlightS - 0.01);
+ Assert.AreEqual(0, Shown(c.Dust!), "nothing before the hit lands");
+ c.Sample(now + CombatBursts.ShellFlightS + 0.01);
+ Assert.Greater(Shown(c.Dust!), 0, "the cloud rises with the hit");
+ }
+
+ /// <summary>"Dust when a unit dies": the cloud rises at once where the token stood, then ends.</summary>
+ [Test]
+ public void ADestroyedUnitsDustRisesAtOnceAndEnds()
+ {
+ var c = Bursts(out _);
+ var spot = new Vector3(4000f, 120f, 900f);
+ Assert.IsTrue(c.Destroyed(spot));
+ Assert.AreEqual(CombatBursts.DeathPuffs, c.Dust!.Busy);
+ c.Sample(now + 0.01);
+ var first = c.Dust.Renderers.Single(x => x.enabled);
+ Assert.Less((XZ(first.transform.position) - XZ(spot)).magnitude, CombatBursts.SpreadShare * CombatBursts.DeathDustM, "where the token stood");
+ c.Sample(now + (CombatBursts.DeathPuffs - 1) * CombatBursts.DeathGapS + CombatBursts.DustStyle.LifeS + 0.01);
+ Assert.AreEqual(0, c.Dust.Busy); Assert.IsFalse(c.enabled);
+ }
+
+ [Test]
+ public void TheSameTimeDrawsTheSameFrame()
+ {
+ var c = Bursts(out _);
+ c.Hit(Vector3.zero, guns: true, smallArms: true);
+ Assert.IsTrue(c.March(new Vector3(300f, 0f, -200f)));
+ List<object> Drawn()
+ {
+ var s = new List<object>();
+ foreach (var pool in new[] { c.Blasts!, c.Dust!, c.MoveDust! })
+ for (int i = 0; i < pool.Capacity; i++)
+ {
+ var r = pool.Renderers[i];
+ s.Add(r.enabled); s.Add(r.transform.position); s.Add(r.transform.localScale); s.Add(pool.FrameOf(i)); s.Add(r.sharedMaterial.GetColor("_BaseColor"));
+ }
+ return s;
+ }
+ c.Sample(now + 0.4);
+ Assert.AreEqual(1, c.MoveDust!.Busy, "fixture: movement dust is active in the snapshot");
+ Assert.AreEqual(1, Shown(c.MoveDust), "fixture: the movement puff is drawn, not merely reserved");
+ var a = Drawn();
+ c.Sample(now + 0.2); c.Sample(now + 0.4);
+ CollectionAssert.AreEqual(a, Drawn());
+ }
+
+ [Test]
+ public void AFullPoolGivesUpItsOldestBurst()
+ {
+ var c = Bursts(out _);
+ for (int i = 0; i <= CombatBursts.BlastSlots; i++) { now = 100.0 + i * 0.1; c.Hit(new Vector3(i * 100f, 0f, 0f), guns: true, smallArms: false); }
+ Assert.AreEqual(CombatBursts.BlastSlots, c.Blasts!.Busy, "small and fixed");
+ var feet = Enumerable.Range(0, c.Blasts.Capacity).Select(i => c.Blasts.Foot(i).x).ToList();
+ CollectionAssert.DoesNotContain(feet, 0f, "the first burst gave up its slot");
+ CollectionAssert.Contains(feet, CombatBursts.BlastSlots * 100f, "to the newest");
+ }
+
+ [Test]
+ public void MarchingDustUsesAFixedPoolAndReusesItsOldestSlot()
+ {
+ var c = Bursts(out _);
+ for (int i = 0; i <= CombatBursts.MoveDustSlots; i++)
+ {
+ now = 100.0 + i * 0.01;
+ Assert.IsTrue(c.March(new Vector3(i * 100f, 0f, 0f)));
+ }
+ Assert.AreEqual(CombatBursts.MoveDustSlots, c.MoveDust!.Busy);
+ var feet = Enumerable.Range(0, c.MoveDust.Capacity).Select(i => c.MoveDust.Foot(i).x).ToList();
+ CollectionAssert.DoesNotContain(feet, 0f, "the oldest puff gave up its slot");
+ CollectionAssert.Contains(feet, CombatBursts.MoveDustSlots * 100f);
+ c.Sample(now + CombatBursts.MoveDustStyle.LifeS + 0.01);
+ Assert.AreEqual(0, c.MoveDust.Busy);
+ Assert.IsTrue(c.March(Vector3.zero), "a freed slot is reusable");
+ }
+
+ [Test]
+ public void ATokenMoveEmitsThreeOrderedPuffsAndThresholdFramesAllocateNothing()
+ {
+ var c = Bursts(out _);
+ for (int i = 0; i < CombatBursts.MoveDustSlots; i++) c.March(Vector3.zero);
+ c.Sample(now + CombatBursts.MoveDustStyle.LifeS + 0.01); // warm every slot and return to the idle state
+ Assert.IsFalse(c.enabled, "fixture: the first measured emission wakes the idle effects");
+ var token = new GameObject("moving token"); made.Add(token);
+ var motion = token.AddComponent<UnitTokenMotion>();
+ motion.Effects = c; motion.GroundHome = new Vector3(100f, 0f, 200f); motion.enabled = false;
+ motion.Begin(Vector3.right * 4000f);
+ long betweenBefore = GC.GetAllocatedBytesForCurrentThread();
+ motion.Tick(UnitTokenMotion.Duration / 8f);
+ long betweenAllocated = GC.GetAllocatedBytesForCurrentThread() - betweenBefore;
+ Assert.AreEqual(0, betweenAllocated, "a moving frame between emission thresholds allocates nothing");
+ Assert.AreEqual(0, c.MoveDust!.Busy);
+ for (int i = 0; i < UnitTokenMotion.MoveDustPuffs; i++)
+ {
+ long before = GC.GetAllocatedBytesForCurrentThread();
+ motion.Tick(i == 0 ? UnitTokenMotion.Duration / 8f
+ : UnitTokenMotion.Duration / (UnitTokenMotion.MoveDustPuffs + 1f));
+ long allocated = GC.GetAllocatedBytesForCurrentThread() - before;
+ Assert.AreEqual(0, allocated, "emission frame " + i + " allocates nothing");
+ Assert.AreEqual(i + 1, c.MoveDust!.Busy);
+ }
+ motion.Tick(UnitTokenMotion.Duration);
+ Assert.AreEqual(UnitTokenMotion.MoveDustPuffs, c.MoveDust!.Busy, "arrival emits no extra puff");
+ Assert.AreEqual(Vector3.zero, token.transform.position);
+ var xs = Enumerable.Range(0, c.MoveDust.Capacity).Where(i => !double.IsNaN(c.MoveDust.StartOf(i)))
+ .Select(i => c.MoveDust.Foot(i).x).OrderBy(x => x).ToArray();
+ CollectionAssert.AreEqual(new[] { 1100f, 2100f, 3100f }, xs);
+ }
+
+ /// <summary>Per-frame garbage stutters on WebGL: sampling the effects, the pools full, allocates nothing.</summary>
+ [Test]
+ public void SamplingAllocatesNothing()
+ {
+ var c = Bursts(out _);
+ for (int i = 0; i < 4; i++) { c.Hit(new Vector3(i * 500f, 0f, 0f), true, true); c.Destroyed(new Vector3(0f, 0f, i * 500f)); }
+ for (int i = 0; i < 10; i++) c.Sample(now + i * 0.016); // warm up
+ long before = GC.GetAllocatedBytesForCurrentThread();
+ for (int i = 0; i < 1000; i++) c.Sample(now + 0.2 + (i % 100) * 0.016);
+ Assert.AreEqual(0, GC.GetAllocatedBytesForCurrentThread() - before, "no allocation per frame");
+ }
+
+ [Test]
+ public void HiddenItPlaysNothingAndDropsWhatPlayed()
+ {
+ var c = Bursts(out var parent);
+ c.Destroyed(Vector3.zero); c.March(Vector3.zero);
+ parent.SetActive(false);
+ Assert.IsFalse(c.Hit(Vector3.zero, true, true)); Assert.IsFalse(c.Destroyed(Vector3.zero)); Assert.IsFalse(c.March(Vector3.zero));
+ parent.SetActive(true);
+ Assert.AreEqual(0, c.Dust!.Busy, "the units' toggle dropped the dust that played");
+ Assert.AreEqual(0, c.MoveDust!.Busy, "hidden marching dust does not resume");
+ }
+
+ [Test]
+ public void DestroyedItFreesEveryMeshAndMaterialItMade()
+ {
+ var c = Bursts(out var parent);
+ var owned = c.Blasts!.Owned.Concat(c.Dust!.Owned).Concat(c.MoveDust!.Owned).ToList();
+ Assert.Greater(owned.Count, 0);
+ Assert.IsTrue(owned.All(o => o is Mesh || o is Material), "the frames and the slots' materials; the flipbooks are assets and stay");
+ Object.DestroyImmediate(parent);
+ Assert.IsTrue(owned.All(o => o == null), "every one destroyed with the effects");
+ Assert.IsNotNull(Flipbook.Load(Flipbook.ExplosionResource), "the asset itself is untouched");
+ }
+
+ static Cause Line(string key, string attackers, string hex = "9,9", string defenderLoss = "0") => new Cause("map", hex, 0, "Report text is never read",
+ key: key, units: new[] { new UnitRef(new Unit(71, "infantry", 0, 0)), new UnitRef(new Unit(72, "guns", 0, 0)),
+ new UnitRef(new Unit(73, "infantry", 0, 0)) }, args: new[] { hex, "150", "0", defenderLoss, attackers });
+
+ [Test]
+ public void AnEngagementsHitIsItsHexItsGunsAndItsDefenders()
+ {
+ Func<string, bool> guns = type => type == "guns";
+ var both = UnitAttackPresenter.HitOf(Line(WhyKeys.Engagement, "2", "-3,19"), guns)!.Value;
+ Assert.AreEqual((-3, 19), (both.Q, both.R));
+ Assert.IsTrue(both.Guns); Assert.IsTrue(both.SmallArms);
+ CollectionAssert.AreEqual(new[] { 73 }, both.Defenders);
+ var rifles = UnitAttackPresenter.HitOf(Line(WhyKeys.Engagement, "1"), guns)!.Value;
+ Assert.IsFalse(rifles.Guns); Assert.IsTrue(rifles.SmallArms);
+ CollectionAssert.AreEqual(new[] { 72, 73 }, rifles.Defenders);
+ Assert.AreEqual(7, UnitAttackPresenter.HitOf(Line(WhyKeys.Engagement, "1", defenderLoss: "7"), guns)!.Value.DefenderLoss);
+ Assert.AreEqual(0, UnitAttackPresenter.HitOf(Line(WhyKeys.Engagement, "1", defenderLoss: "lost"), guns)!.Value.DefenderLoss,
+ "a malformed loss suppresses only the reaction, not the existing impact");
+ Assert.IsNull(UnitAttackPresenter.HitOf(Line(WhyKeys.AttackOrdered, "2"), guns), "only an engagement hits");
+ Assert.IsNull(UnitAttackPresenter.HitOf(Line(WhyKeys.Engagement, "0"), guns), "a malformed count");
+ Assert.IsNull(UnitAttackPresenter.HitOf(Line(WhyKeys.Engagement, "2", "nine"), guns), "a malformed hex");
+ }
+
+ /// <summary>The real sim: an attack order plays one hit, on the hex it attacked, after the map is redrawn; End Turn's
+ /// replay of it plays none.</summary>
+ [Test]
+ public void AnAttackOrderPlaysOneHitOnTheHexItAttacked()
+ {
+ var session = NewSession();
+ var bridge = new SimBridge(session, Text);
+ var hits = new List<CombatHit>();
+ bool redrawn = false;
+ bridge.Changed += () => redrawn = true;
+ using var presenter = new UnitAttackPresenter(bridge, _ => true, h => { Assert.IsTrue(redrawn, "after Changed"); hits.Add(h); return true; }, (_, _) => true);
+ UnitOrder? order = null; Unit? target = null;
+ foreach (var u in session.Now.State.Units.Values.Where(u => u.Side == Movement.PlayerSide))
+ {
+ target = session.Now.State.Units.Values.FirstOrDefault(x => x.Side != Movement.PlayerSide && x.Side != "" && MapActions.Distance(x.Q, x.R, u.Q, u.R) == 1);
+ if (target != null) { order = new UnitOrder(u.Id, Combat.Attack, target.Q, target.R); break; }
+ }
+ Assert.IsNotNull(order, "fixture: a player unit stands next to an enemy at the start");
+ Assert.IsNull(bridge.Queue(order!));
+ Assert.AreEqual(1, hits.Count, "one engagement, one hit");
+ Assert.AreEqual((target!.Q, target.R), (hits[0].Q, hits[0].R));
+ CollectionAssert.Contains(hits[0].Defenders, target.Id);
+ bridge.EndTurn();
+ Assert.AreEqual(1, hits.Count(h => (h.Q, h.R) == (target.Q, target.R) && h.Defenders.Contains(target.Id)), "End Turn's replay plays it no second time");
+ }
+
+ [Test]
+ public void ADestroyedLineRaisesItsUnitsDust()
+ {
+ var destroyed = new List<int>();
+ var lines = new[] { Line(WhyKeys.Engagement, "2"), new Cause("map", "73", 0, "Unit 73 was destroyed", key: WhyKeys.Destroyed,
+ units: new[] { new UnitRef(new Unit(73, "infantry", 9, 9)) }) };
+ var bridge = new SimBridge(NewSession(), Text,
+ (session, orders) => new StepResult(session.State, session.Now.Why.Concat(lines).ToArray(), Array.Empty<Rejection>()));
+ using var presenter = new UnitAttackPresenter(bridge, _ => true, _ => true, (id, _) => { destroyed.Add(id); return true; });
+ bridge.EndTurn();
+ CollectionAssert.AreEqual(new[] { 73 }, destroyed);
+ bridge.Replace(NewSession());
+ CollectionAssert.AreEqual(new[] { 73 }, destroyed, "a load raises nothing");
+ }
+
+ 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 Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");
+
+ /// <summary>On the map: a hit lands on the defender's token, else on the hex's centre; a unit the rebuild dropped raises
+ /// its dust where its token stood, once; a unit still drawn raises none.</summary>
+ [Test]
+ public void OnTheMapTheHitAndTheDustFindTheTokens()
+ {
+ var map = BuildMap();
+ try
+ {
+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ layer.AnimateMoves = true;
+ layer.Show(C, s);
+ Assert.IsNotNull(layer.Combat, "the layer makes its combat effects");
+ var drawn = s.Units.Values.Where(u => u.Side == Movement.PlayerSide && layer.Tokens.Any(t => t.Token.StateUnit?.Id == u.Id)).Take(2).ToArray();
+ Assert.AreEqual(2, drawn.Length, "fixture: two player units are drawn");
+ Vector2 SpotOf(Unit u) { var spot = layer.Tokens.Single(t => t.Token.StateUnit?.Id == u.Id).Spot; return new Vector2((float)spot.X, (float)spot.Z); }
+
+ var defender = drawn[0];
+ Assert.IsFalse(layer.PlayDefenderHit(new CombatHit(defender.Q, defender.R, false, true,
+ drawn.Select(u => u.Id).ToArray())), "the five-argument caller means no recorded defender loss");
+ Assert.IsTrue(layer.PlayDefenderHit(new CombatHit(defender.Q, defender.R, false, true, 1,
+ drawn.Select(u => u.Id).ToArray())), "all drawn defenders react to the aggregate loss");
+ // They react when the volley's first puff lands (CombatBursts.ImpactS), not with the shot (e21's capture of #2614).
+ foreach (var unit in drawn)
+ {
+ var motion = layer.GetComponentsInChildren<UnitTokenMotion>().Single(m => m.SimId == unit.Id);
+ Assert.IsFalse(motion.Reacting, "no shake before the hit lands"); Assert.IsTrue(motion.HitPending);
+ if (motion.HitFlash != null) Assert.IsFalse(motion.HitFlash.enabled, "no flash before the hit lands");
+ motion.Tick(CombatBursts.VolleyS - 0.01f);
+ Assert.IsFalse(motion.Reacting, "still waiting just before it");
+ motion.Tick(0.02f);
+ Assert.IsTrue(motion.Reacting, "the shake starts as it lands");
+ }
+ Assert.IsTrue(layer.PlayHit(new CombatHit(defender.Q, defender.R, true, false, new[] { defender.Id })));
+ int slot = Enumerable.Range(0, layer.Combat!.Blasts!.Capacity).Single(i => !double.IsNaN(layer.Combat.Blasts.StartOf(i)));
+ Assert.Less((XZ(layer.Combat.Blasts.Foot(slot)) - SpotOf(defender)).magnitude, 1f, "on the defender's token");
+ Assert.AreEqual(now + CombatBursts.ShellFlightS, layer.Combat.Blasts.StartOf(slot), 1e-9, "timed to the attack");
+
+ var hex = C.HexAt(defender.Q, defender.R)!;
+ var centre = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);
+ layer.Combat.Blasts.Clear();
+ Assert.IsTrue(layer.PlayHit(new CombatHit(hex.Q, hex.R, true, false, Array.Empty<int>())));
+ slot = Enumerable.Range(0, layer.Combat.Blasts.Capacity).Single(i => !double.IsNaN(layer.Combat.Blasts.StartOf(i)));
+ Assert.Less((XZ(layer.Combat.Blasts.Foot(slot)) - XZ(centre)).magnitude, 1f, "no defender drawn: the hex's centre");
+
+ var lost = drawn[1]; var was = SpotOf(lost);
+ s.Units.Remove(lost.Id);
+ Assert.IsTrue(layer.Show(C, s), "fixture: the roster changed");
+ Assert.IsFalse(layer.PlayDestroyed(defender.Id), "a unit still drawn raises no dust");
+ Assert.IsTrue(layer.PlayDestroyed(lost.Id, CombatBursts.ShellFlightS));
+ var dust = layer.Combat.Dust!;
+ Assert.AreEqual(CombatBursts.DeathPuffs, dust.Busy);
+ var starts = Enumerable.Range(0, dust.Capacity).Select(dust.StartOf).Where(t => !double.IsNaN(t)).ToList();
+ Assert.AreEqual(now + CombatBursts.ShellFlightS, starts.Min(), 1e-9, "the dust rises with the shell's burst, not the shot");
+ for (int i = 0; i < dust.Capacity; i++)
+ if (!double.IsNaN(dust.StartOf(i)))
+ Assert.LessOrEqual((XZ(dust.Foot(i)) - was).magnitude, CombatBursts.SpreadShare * CombatBursts.DeathDustM + 1f, "where its token stood");
+ // Exactly where: the same puffs as a cloud raised on the token's spot itself. The lost unit was shaking from the hit
+ // when the rebuild dropped it, so this fails if the spot takes the shake (HitShakeM) as well as the slide.
+ var raised = Enumerable.Range(0, dust.Capacity).Where(i => !double.IsNaN(dust.StartOf(i)))
+ .Select(i => (dust.StartOf(i), XZ(dust.Foot(i)))).OrderBy(x => x.Item1).ToList();
+ dust.Clear();
+ Assert.IsTrue(layer.Combat.Destroyed(new Vector3(was.x, 0f, was.y), CombatBursts.ShellFlightS));
+ var onSpot = Enumerable.Range(0, dust.Capacity).Where(i => !double.IsNaN(dust.StartOf(i)))
+ .Select(i => (dust.StartOf(i), XZ(dust.Foot(i)))).OrderBy(x => x.Item1).ToList();
+ Assert.AreEqual(onSpot.Count, raised.Count);
+ for (int i = 0; i < raised.Count; i++)
+ Assert.Less((raised[i].Item2 - onSpot[i].Item2).magnitude, 1f, $"puff {i} on the token's spot, not where the shake put it");
+ Assert.IsFalse(layer.PlayDestroyed(lost.Id), "once");
+ }
+ finally { Object.DestroyImmediate(map.gameObject); }
+ }
+
+ /// <summary>A rebuild while a defender shakes from a hit (another unit destroyed by the same attack) hands the shake to
+ /// the defender's new token, as an attack is handed on (ContinueAttack): the survivor never moved, so it does not slide
+ /// from where the shake had put it and raises no march dust, and the shake plays on to its end. A hit still on its way
+ /// (HitPending) is handed on too.</summary>
+ [Test]
+ public void ARebuildMidShakeKeepsTheShakeAndSlidesNothing()
+ {
+ var map = BuildMap();
+ try
+ {
+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ layer.AnimateMoves = true;
+ layer.Show(C, s);
+ var drawn = s.Units.Values.Where(u => u.Side == Movement.PlayerSide && layer.Tokens.Any(t => t.Token.StateUnit?.Id == u.Id)).Take(3).ToArray();
+ Assert.AreEqual(3, drawn.Length, "fixture: three player units are drawn");
+ UnitTokenMotion MotionOf(Unit u) => layer.GetComponentsInChildren<UnitTokenMotion>().Single(m => m.SimId == u.Id);
+ var (shaking, waiting, lost) = (drawn[0], drawn[1], drawn[2]);
+ Assert.IsTrue(layer.PlayDefenderHit(new CombatHit(shaking.Q, shaking.R, false, true, 1, new[] { shaking.Id, waiting.Id })));
+ MotionOf(shaking).Tick(CombatBursts.VolleyS + 0.01f); // the hit lands on the first: it shakes, ~70 m off its spot
+ Assert.IsTrue(MotionOf(shaking).Reacting, "fixture: the first defender shakes");
+ Assert.Greater(MotionOf(shaking).transform.position.magnitude, UnitTokenMotion.MinMoveM, "fixture: off its spot");
+ Assert.IsTrue(MotionOf(waiting).HitPending, "fixture: the second still waits for the hit");
+
+ s.Units.Remove(lost.Id);
+ Assert.IsTrue(layer.Show(C, s), "fixture: the roster changed, so the tokens are rebuilt");
+ var after = MotionOf(shaking);
+ Assert.IsFalse(after.Moving, "the shaking defender never moved, so its new token does not slide");
+ Assert.IsTrue(after.Reacting, "its shake goes on in the new token");
+ Assert.IsTrue(MotionOf(waiting).HitPending, "and the hit still on its way to the second lands on its new token");
+ int dust = layer.Combat!.MoveDust!.Busy;
+ for (int i = 0; i < 30; i++) { after.Tick(0.05f); MotionOf(waiting).Tick(0.05f); }
+ Assert.AreEqual(dust, layer.Combat.MoveDust.Busy, "no march dust from a unit that did not march");
+ Assert.IsFalse(after.Reacting, "the shake ends");
+ Assert.AreEqual(Vector3.zero, after.transform.position, "back on its spot");
+ }
+ finally { Object.DestroyImmediate(map.gameObject); }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/CombatEffectsTests.cs.meta b/unity/Assets/Tests/EditMode/CombatEffectsTests.cs.meta
new file mode 100644
index 000000000..4828191cb
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/CombatEffectsTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 880fb355cb3a4fd6a17a8c344544576f
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/GameSceneTests.cs b/unity/Assets/Tests/EditMode/GameSceneTests.cs
index 8bb5ea51a..069daca59 100644
--- a/unity/Assets/Tests/EditMode/GameSceneTests.cs
+++ b/unity/Assets/Tests/EditMode/GameSceneTests.cs
@@ -70,6 +70,14 @@ public class GameSceneTests
var play = (Func<int, bool>)typeof(UnitAttackPresenter).GetField("play", flags)!.GetValue(presenters[0])!;
Assert.AreSame(root.Units, play.Target, "it plays on the game's unit layer");
Assert.AreEqual(nameof(Statecraft.Game.Map.Units.UnitLayer.PlayAttack), play.Method.Name);
+ var defenderHit = (Func<Statecraft.Game.Map.Units.CombatHit, bool>)typeof(UnitAttackPresenter)
+ .GetField("defenderHit", flags)!.GetValue(presenters[0])!;
+ Assert.AreSame(root.Units, defenderHit.Target, "the defender reaction uses the game's unit layer");
+ Assert.AreEqual(nameof(Statecraft.Game.Map.Units.UnitLayer.PlayDefenderHit), defenderHit.Method.Name);
+ var timedPlay = (Func<int, Action, Action, bool>)typeof(UnitAttackPresenter)
+ .GetField("timedPlay", flags)!.GetValue(presenters[0])!;
+ Assert.AreSame(root.Units, timedPlay.Target, "the reaction is timed through the game's attack path");
+ Assert.AreEqual(nameof(Statecraft.Game.Map.Units.UnitLayer.PlayAttack), timedPlay.Method.Name);
}
[Test]
diff --git a/unity/Assets/Tests/EditMode/TrainSteamTests.cs b/unity/Assets/Tests/EditMode/TrainSteamTests.cs
new file mode 100644
index 000000000..f8436af1f
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/TrainSteamTests.cs
@@ -0,0 +1,172 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using Statecraft.Game.Map.Routes;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+/// <summary>The train's steam (owner, 4 November 2026: "Train steam"; TrainSteam): a few pooled flipbook puffs from the
+/// locomotive's chimney only while the train runs, each drawn from where the chimney was when it left and drifting back
+/// along the track, the same at the same time, nothing per frame allocated, nothing while hidden, and freed with the train.
+/// The train here is the moving showcase (RouteTrain.Spawn) on a straight line east over flat ground.</summary>
+public class TrainSteamTests
+{
+ const float LineM = 60000f, TurnM = 50000f;
+
+ readonly List<Object> made = new List<Object>();
+
+ [TearDown]
+ public void Restore()
+ {
+ TrainSteam.Clock = () => Time.time;
+ foreach (var o in made) if (o != null) Object.DestroyImmediate(o);
+ made.Clear();
+ }
+
+ RouteTrain Train(bool still = false)
+ {
+ var data = new TerrainData { heightmapResolution = 33, size = new Vector3(LineM + 2000f, 100f, 4000f) };
+ made.Add(data);
+ var root = new GameObject("test map"); made.Add(root);
+ var assets = root.AddComponent<MapRuntimeAssets>();
+ var line = new List<Vector2> { new Vector2(0f, 0f), new Vector2(LineM, 0f) };
+ var origin = new Vector3(-1000f, 0f, -2000f);
+ var go = RouteTrain.Spawn(root.transform, assets, line, data, origin, new Vector3(TurnM, 0f, 0f), new Vector3(20000f, 0f, 0f), still);
+ return go.GetComponent<RouteTrain>();
+ }
+
+ static TrainSteam SteamOf(RouteTrain train)
+ {
+ var s = train.GetComponentInChildren<TrainSteam>(true);
+ Assert.IsNotNull(s, "the moving train carries its steam (the smoke flipbook ships in Resources/Effects, #2490)");
+ return s!;
+ }
+
+ static int Shown(TrainSteam s) => s.Renderers.Count(r => r.enabled);
+
+ /// <summary>The puffs a train running since long before <paramref name="now"/> shows: the last Puffs, less the steam
+ /// puffs already gone (a steam puff thins away by SteamLifeShare of the life).</summary>
+ static int Trail(float now)
+ {
+ long newest = (long)Math.Floor(now / (double)TrainSteam.GapS);
+ int n = 0;
+ for (long k = newest - TrainSteam.Puffs + 1; k <= newest; k++)
+ if (!TrainSteam.IsSteam(k) || now - k * (double)TrainSteam.GapS < TrainSteam.SteamLifeShare * TrainSteam.LifeS) n++;
+ return n;
+ }
+
+ /// <summary>The first moment of the first stop: the head reaches the turn point (HeadAt's run, from the line's start).</summary>
+ static float FirstStop(RouteTrain t) => (t.Stretch.end - t.Stretch.start - t.Length) / RouteTrain.SpeedMps;
+
+ [Test]
+ public void ItSteamsOnlyWhileTheTrainRuns()
+ {
+ var train = Train(); var steam = SteamOf(train);
+ Assert.AreEqual(TrainSteam.Puffs, steam.Renderers.Length, "a small fixed pool");
+ Assert.AreEqual(0, Shown(steam), "nothing before the first sample");
+ Assert.IsTrue(train.MovingAt(10f));
+ steam.Sample(10f);
+ Assert.AreEqual(Trail(10f), Shown(steam), "running for 10 s: the whole trail");
+ Assert.GreaterOrEqual(Shown(steam), TrainSteam.Puffs - 3, "nearly every slot");
+ float stop = FirstStop(train);
+ Assert.IsFalse(train.MovingAt(stop + 1f)); Assert.IsFalse(train.MovingAt(stop + RouteTrain.DwellSeconds - 0.1f));
+ steam.Sample(stop + 1f);
+ Assert.AreEqual(0, Shown(steam), "standing at the end: no steam");
+ float leave = stop + RouteTrain.DwellSeconds + 0.05f;
+ Assert.IsTrue(train.MovingAt(leave));
+ steam.Sample(leave);
+ Assert.LessOrEqual(Shown(steam), 1, "off again: only a puff left since it moved, none from the stop");
+ steam.Sample(leave + TrainSteam.LifeS);
+ Assert.AreEqual(Trail(leave + TrainSteam.LifeS), Shown(steam), "and the trail grows back");
+ }
+
+ [Test]
+ public void AStillTrainHasNoSteam()
+ {
+ var train = Train(still: true);
+ Assert.IsNull(train.GetComponentInChildren<TrainSteam>(true), "a still train (screenshots, editor renders) never runs");
+ Assert.IsFalse(train.MovingAt(10f));
+ }
+
+ [Test]
+ public void ThePuffsTrailBackFromTheChimney()
+ {
+ var train = Train(); var steam = SteamOf(train);
+ const float now = 20f;
+ var (head, dir) = train.HeadAt(now);
+ Assert.AreEqual(+1, dir, "heading east, to the turn point");
+ var (chimney, back) = train.ChimneyAt(head, dir);
+ Assert.AreEqual(-1f, back.x, 1e-4f, "back is west along the line");
+ train.Place(head, dir);
+ var loco = train.Cars[0];
+ Assert.Greater(chimney.x, loco.position.x, "the chimney is ahead of the locomotive's middle");
+ Assert.Less(chimney.x, loco.position.x + train.CarOffsets[0], "and on the locomotive, behind the head");
+ steam.Sample(now);
+ var puffs = steam.Renderers.Where(r => r.enabled).Select(r => r.transform.position).OrderByDescending(p => p.x).ToList();
+ Assert.AreEqual(Trail(now), puffs.Count);
+ foreach (var p in puffs)
+ {
+ Assert.LessOrEqual(p.x, chimney.x + 1f, "every puff is behind the chimney");
+ Assert.Greater(p.y, chimney.y, "and above it");
+ Assert.AreEqual(0f, p.z, 1f, "over the track");
+ }
+ Assert.Less(chimney.x - puffs[0].x, RouteTrain.SpeedMps * TrainSteam.GapS + TrainSteam.DriftShare * steam.SizeM, "the newest puff is at the chimney");
+ Assert.Greater(chimney.x - puffs[puffs.Count - 1].x, RouteTrain.SpeedMps * (TrainSteam.LifeS - 2f * TrainSteam.GapS),
+ "the oldest drifted back along the track as far as the train ran since");
+ }
+
+ [Test]
+ public void TheSameTimeDrawsTheSameTrail()
+ {
+ var train = Train(); var steam = SteamOf(train);
+ steam.Sample(31.7f);
+ var first = steam.Renderers.Select(r => (r.enabled, r.transform.position, r.transform.localScale.x, r.GetComponent<MeshFilter>().sharedMesh)).ToList();
+ steam.Sample(5f); steam.Sample(44.2f);
+ steam.Sample(31.7f);
+ var again = steam.Renderers.Select(r => (r.enabled, r.transform.position, r.transform.localScale.x, r.GetComponent<MeshFilter>().sharedMesh)).ToList();
+ CollectionAssert.AreEqual(first, again);
+ Assert.IsTrue(Enumerable.Range(0, 6).Any(k => TrainSteam.IsSteam(k)) && Enumerable.Range(0, 6).Any(k => !TrainSteam.IsSteam(k)),
+ "white steam among the smoke");
+ }
+
+ [Test]
+ public void AHiddenTrainShowsNoSteamAndKeepsNoneForLater()
+ {
+ var train = Train(); var steam = SteamOf(train);
+ steam.Sample(10f);
+ Assert.Greater(Shown(steam), 0);
+ train.gameObject.SetActive(false); // the train's toggle, or a date before its service
+ Assert.IsFalse(steam.isActiveAndEnabled, "it goes with the train: no Update runs");
+ Assert.AreEqual(0, Shown(steam), "and every puff went");
+ train.gameObject.SetActive(true);
+ Assert.AreEqual(0, Shown(steam), "none left over when it shows again");
+ }
+
+ [Test]
+ public void DestroyingTheTrainFreesItsSteam()
+ {
+ var train = Train(); var steam = SteamOf(train);
+ var owned = steam.Owned.ToList();
+ Assert.AreEqual(Statecraft.HexTiles.Flipbook.SmokeGrid * Statecraft.HexTiles.Flipbook.SmokeGrid + TrainSteam.Puffs, owned.Count,
+ "the flipbook's frames and one material per puff");
+ Assert.IsTrue(owned.All(o => o != null));
+ Object.DestroyImmediate(train.gameObject);
+ Assert.IsTrue(owned.All(o => o == null), "freed with the train");
+ }
+
+ /// <summary>Per-frame garbage stutters on WebGL: sampling the steam allocates nothing.</summary>
+ [Test]
+ public void SamplingAllocatesNothing()
+ {
+ var train = Train(); var steam = SteamOf(train);
+ float stop = FirstStop(train);
+ for (int i = 0; i < 10; i++) steam.Sample(10f + i * 0.016f); // warm up
+ long before = GC.GetAllocatedBytesForCurrentThread();
+ for (int i = 0; i < 1000; i++) steam.Sample(10f + (i % 200) * 0.016f);
+ for (int i = 0; i < 100; i++) steam.Sample(stop + 1f + i * 0.016f);
+ Assert.AreEqual(0, GC.GetAllocatedBytesForCurrentThread() - before, "no allocation per frame");
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/TrainSteamTests.cs.meta b/unity/Assets/Tests/EditMode/TrainSteamTests.cs.meta
new file mode 100644
index 000000000..b1cab6361
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/TrainSteamTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1c6cf9121097458f89ca80b6f24ffde2
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs b/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs
index 4a5badf09..070bec973 100644
--- a/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs
+++ b/unity/Assets/Tests/EditMode/UnitAttackPresenterTests.cs
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game;
+using Statecraft.Game.Map.Units;
using Statecraft.Game.UI;
using Statecraft.Sim;
using UnityEditor;
@@ -18,9 +19,9 @@ public class UnitAttackPresenterTests
static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
static GameSession NewSession() => GameSession.New(C, GoldenRun.Seed, Mode.Historical);
- static Cause Line(string key, string attackers) => new Cause("map", "9,9", 0, "Report text is never read",
+ static Cause Line(string key, string attackers, string defenderLoss = "0") => new Cause("map", "9,9", 0, "Report text is never read",
key: key, units: new[] { new UnitRef(new Unit(71, "infantry", 0, 0)), new UnitRef(new Unit(72, "guns", 0, 0)),
- new UnitRef(new Unit(73, "infantry", 0, 0)) }, args: new[] { "9,9", "150", "0", "0", attackers });
+ new UnitRef(new Unit(73, "infantry", 0, 0)) }, args: new[] { "9,9", "150", "0", defenderLoss, attackers });
/// <summary>The first player unit's attack on an enemy next to it at the start of the game.</summary>
static UnitOrder AttackNextTo(GameSession session, out int attacker)
@@ -59,6 +60,121 @@ public class UnitAttackPresenterTests
Assert.IsEmpty(UnitAttackPresenter.Attackers(Line(WhyKeys.AttackOrdered, "2")));
}
+ /// <summary>The production presenter path gives every attacker one shared defender cue. It reacts with the first fire
+ /// take that really starts, or, if none starts, only when the last attack has finished waiting.</summary>
+ [TestCase(true)]
+ [TestCase(false)]
+ public void SeveralAttackersShareOneTimedDefenderReaction(bool aTakeStarts)
+ {
+ var engagement = Line(WhyKeys.Engagement, "3", defenderLoss: "2");
+ var bridge = new SimBridge(NewSession(), Text,
+ (session, orders) => new StepResult(session.State, session.Now.Why.Append(engagement).ToArray(), Array.Empty<Rejection>()));
+ var immediate = new List<int>();
+ var cues = new Dictionary<int, (Action Started, Action Missed)>();
+ var reactions = new List<Statecraft.Game.Map.Units.CombatHit>();
+ using var presenter = new UnitAttackPresenter(bridge,
+ id => { immediate.Add(id); return true; }, _ => true, (_, _) => true,
+ hit => { reactions.Add(hit); return true; },
+ (id, started, missed) => { cues.Add(id, (started, missed)); return true; });
+
+ bridge.EndTurn();
+ CollectionAssert.AreEquivalent(new[] { 71, 72, 73 }, cues.Keys);
+ Assert.IsEmpty(immediate, "positive loss uses the production timed attack path");
+ Assert.IsEmpty(reactions, "the reaction waits for an actual fire take or for every miss");
+
+ cues[71].Missed();
+ Assert.IsEmpty(reactions, "the first miss is not the fallback while attackers remain");
+ if (aTakeStarts)
+ {
+ cues[72].Started();
+ Assert.AreEqual(1, reactions.Count, "the first actual fire take starts the shared reaction");
+ cues[73].Started();
+ Assert.AreEqual(1, reactions.Count, "another actual fire take does not repeat the shared reaction");
+ }
+ else
+ {
+ cues[72].Missed();
+ Assert.IsEmpty(reactions, "the next-to-last miss is still not the fallback");
+ cues[73].Missed();
+ Assert.AreEqual(1, reactions.Count, "only the last miss starts the fallback reaction");
+ }
+ Assert.AreEqual(2, reactions[0].DefenderLoss);
+ }
+
+ /// <summary>#2614 review: on the production path the hit on the hex waits for the attackers' fire as the defenders'
+ /// reaction does (a shell or dust that lands before the shot reads wrong), with or without a defender loss; if no take
+ /// can start, the last miss plays it. Red at bcff7b8e5: the hit played at once, on resolution.</summary>
+ [TestCase("0", true)]
+ [TestCase("0", false)]
+ [TestCase("2", true)]
+ [TestCase("2", false)]
+ public void TheHitOnTheHexWaitsForTheAttackersFire(string defenderLoss, bool aTakeStarts)
+ {
+ var engagement = Line(WhyKeys.Engagement, "2", defenderLoss);
+ var bridge = new SimBridge(NewSession(), Text,
+ (session, orders) => new StepResult(session.State, session.Now.Why.Append(engagement).ToArray(), Array.Empty<Rejection>()));
+ var immediate = new List<int>();
+ var cues = new Dictionary<int, (Action Started, Action Missed)>();
+ var hits = new List<Statecraft.Game.Map.Units.CombatHit>();
+ var reactions = new List<Statecraft.Game.Map.Units.CombatHit>();
+ using var presenter = new UnitAttackPresenter(bridge,
+ id => { immediate.Add(id); return true; }, h => { hits.Add(h); return true; }, (_, _) => true,
+ h => { reactions.Add(h); return true; },
+ (id, started, missed) => { cues.Add(id, (started, missed)); return true; });
+
+ bridge.EndTurn();
+ CollectionAssert.AreEquivalent(new[] { 71, 72 }, cues.Keys);
+ Assert.IsEmpty(immediate, "the production path times every attack");
+ Assert.IsEmpty(hits, "no hit before an attacker's fire");
+
+ if (aTakeStarts) cues[72].Started();
+ else { cues[71].Missed(); Assert.IsEmpty(hits, "not while an attacker may still fire"); cues[72].Missed(); }
+ Assert.AreEqual(1, hits.Count, aTakeStarts ? "the hit lands with the first fire take" : "the last miss plays the hit");
+ Assert.AreEqual((9, 9), (hits[0].Q, hits[0].R));
+ Assert.AreEqual(defenderLoss == "2" ? 1 : 0, reactions.Count, "the defenders react only to a loss, at the same moment");
+ cues[71].Started();
+ Assert.AreEqual(1, hits.Count, "a later take does not repeat the hit");
+ }
+
+ /// <summary>#2614: the dust of a unit the engagement destroyed (its Destroyed line right after it, as Combat.Engage adds
+ /// it) waits for the attackers' fire too; a take that starts at once plays it at once. Red at 917ebf2e9: the dust played
+ /// on resolution. It rises when the hit lands, CombatBursts.ImpactS of the engagement's hit after the fire, not with the
+ /// shot (e21's capture of 423678c01: the dust came 0.12 s before the first volley puff).</summary>
+ [TestCase(false)]
+ [TestCase(true)]
+ public void ADestroyedUnitsDustWaitsForTheAttackersFire(bool takeStartsAtOnce)
+ {
+ var engagement = Line(WhyKeys.Engagement, "2", defenderLoss: "2");
+ var dead = new Cause("map", "9,9", 0, "Report text is never read", key: WhyKeys.Destroyed,
+ units: new[] { new UnitRef(new Unit(73, "infantry", 0, 0)) });
+ var bridge = new SimBridge(NewSession(), Text,
+ (session, orders) => new StepResult(session.State, session.Now.Why.Append(engagement).Append(dead).ToArray(), Array.Empty<Rejection>()));
+ var cues = new Dictionary<int, (Action Started, Action Missed)>();
+ var order = new List<string>();
+ CombatHit? seen = null; float dustDelay = -1f;
+ using var presenter = new UnitAttackPresenter(bridge,
+ _ => true, h => { order.Add("hit"); seen = h; return true; }, (id, delay) => { order.Add("dust " + id); dustDelay = delay; return true; }, _ => true,
+ (id, started, missed) =>
+ {
+ cues.Add(id, (started, missed));
+ if (takeStartsAtOnce && id == 71) started();
+ return true;
+ });
+
+ bridge.EndTurn();
+ if (!takeStartsAtOnce)
+ {
+ Assert.IsEmpty(order, "no hit and no dust before an attacker's fire");
+ cues[72].Started();
+ }
+ CollectionAssert.AreEqual(new[] { "hit", "dust 73" }, order, "the dust lands with the hit, after the fire");
+ Assert.IsTrue(seen.HasValue);
+ Assert.Greater(dustDelay, 0f, "after the fire, when the hit lands");
+ Assert.AreEqual(CombatBursts.ImpactS(seen!.Value), dustDelay, "when the engagement's hit lands");
+ cues[71].Started(); cues[72].Missed();
+ CollectionAssert.AreEqual(new[] { "hit", "dust 73" }, order, "and only once");
+ }
+
/// <summary>An attack order plays at once, after the map is redrawn for it; End Turn runs it again inside the sim (its
/// first causes are the open turn's), and that replay does not play it twice.</summary>
[Test]
diff --git a/unity/Assets/Tests/EditMode/UnitTokenMotionTests.cs b/unity/Assets/Tests/EditMode/UnitTokenMotionTests.cs
index f790e2894..56803f67e 100644
--- a/unity/Assets/Tests/EditMode/UnitTokenMotionTests.cs
+++ b/unity/Assets/Tests/EditMode/UnitTokenMotionTests.cs
@@ -285,6 +285,118 @@ public class UnitTokenMotionTests
Assert.IsTrue(In(a, UnitFigureMotion.Idle), "a figure that turns near later does not play an old attack");
}
+ [Test]
+ public void TheFireCueStartsWithTheActualTakeAndReportsWhenNoneAppears()
+ {
+ var a = Figure();
+ a.enabled = false;
+ var motion = token.AddComponent<UnitTokenMotion>();
+ motion.enabled = false;
+ int started = 0, missed = 0;
+ Assert.IsFalse(motion.PlayAttack(() => started++, () => missed++));
+ Assert.AreEqual((0, 0), (started, missed), "a waiting attack has made neither decision");
+ motion.Tick(0.05f);
+ a.enabled = true; motion.RefreshPose();
+ Assert.AreEqual((1, 0), (started, missed), "the cue starts when the delayed take becomes visible");
+ motion.Tick(1f);
+ Assert.AreEqual((1, 0), (started, missed), "the completed take reports once");
+
+ a.enabled = false;
+ Assert.IsFalse(motion.PlayAttack(() => started++, () => missed++));
+ motion.Tick(UnitTokenMotion.AttackWaitS);
+ Assert.AreEqual((1, 1), (started, missed), "the cue falls back only after the wait finds no take");
+ }
+
+ [Test]
+ public void ADefenderReactionComposesWithItsSlideAndIsDroppedWhenHidden()
+ {
+ var motion = token.AddComponent<UnitTokenMotion>();
+ var flash = new GameObject("hit flash").AddComponent<MeshRenderer>();
+ flash.transform.SetParent(token.transform, false); flash.enabled = false;
+ motion.HitFlash = flash;
+ motion.enabled = false;
+ var from = Vector3.right * 1000f;
+ motion.Begin(from);
+ motion.Tick(UnitTokenMotion.Duration * 0.25f);
+ var slide = Vector3.Lerp(from, Vector3.zero, 0.25f);
+ Assert.IsTrue(motion.PlayHit()); Assert.IsTrue(motion.Reacting); Assert.IsTrue(flash.enabled);
+ motion.Tick(0.04f);
+ slide = Vector3.Lerp(from, Vector3.zero, 0.25f + 0.04f / UnitTokenMotion.Duration);
+ Assert.Greater(Vector3.Distance(slide, token.transform.position), 1f, "the shake is added to the slide");
+ motion.Tick(UnitTokenMotion.HitFlashS);
+ Assert.IsFalse(flash.enabled, "the plate flash is brief");
+ motion.Tick(UnitTokenMotion.HitDurationS - 0.04f - UnitTokenMotion.HitFlashS);
+ slide = Vector3.Lerp(from, Vector3.zero,
+ 0.25f + UnitTokenMotion.HitDurationS / UnitTokenMotion.Duration);
+ Assert.IsFalse(motion.Reacting);
+ Assert.Less(Vector3.Distance(slide, token.transform.position), 1e-3f, "the shake returns exactly to the slide");
+
+ Assert.IsTrue(motion.PlayHit()); motion.Tick(0.04f);
+ token.SetActive(false);
+ typeof(UnitTokenMotion).GetMethod("OnDisable", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(motion, null);
+ Assert.IsFalse(motion.Reacting); Assert.IsFalse(motion.Moving);
+ Assert.IsFalse(flash.enabled); Assert.AreEqual(Vector3.zero, token.transform.position);
+ token.SetActive(true);
+ motion.Tick(0f);
+ Assert.IsFalse(motion.Reacting, "shown again, the hidden reaction does not resume");
+ }
+
+ /// <summary>e21's capture of #2614: the shake and flash start when the hit lands (a delay), not with the shot; a token
+ /// hidden while it waits drops the reaction.</summary>
+ [Test]
+ public void ADelayedDefenderReactionStartsWhenTheHitLandsAndIsDroppedWhenHidden()
+ {
+ var motion = token.AddComponent<UnitTokenMotion>();
+ var flash = new GameObject("hit flash").AddComponent<MeshRenderer>();
+ flash.transform.SetParent(token.transform, false); flash.enabled = false;
+ motion.HitFlash = flash;
+ motion.enabled = false;
+ Assert.IsTrue(motion.PlayHit(0.3f));
+ Assert.IsTrue(motion.enabled, "it ticks while it waits");
+ Assert.IsTrue(motion.HitPending); Assert.IsFalse(motion.Reacting); Assert.IsFalse(flash.enabled);
+ Assert.AreEqual(Vector3.zero, token.transform.position, "no shake yet");
+ motion.Tick(0.29f);
+ Assert.IsFalse(motion.Reacting); Assert.IsFalse(flash.enabled); Assert.IsTrue(motion.enabled);
+ motion.Tick(0.02f);
+ Assert.IsFalse(motion.HitPending); Assert.IsTrue(motion.Reacting); Assert.IsTrue(flash.enabled, "the flash starts with the shake");
+ motion.Tick(UnitTokenMotion.HitDurationS);
+ Assert.IsFalse(motion.Reacting); Assert.IsFalse(motion.enabled, "idle again");
+
+ Assert.IsTrue(motion.PlayHit(0.3f)); motion.Tick(0.1f);
+ token.SetActive(false);
+ typeof(UnitTokenMotion).GetMethod("OnDisable", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(motion, null);
+ Assert.IsFalse(motion.HitPending, "hidden while it waits: dropped");
+ token.SetActive(true);
+ motion.Tick(0.5f);
+ Assert.IsFalse(motion.Reacting, "shown again, it does not shake late"); Assert.IsFalse(flash.enabled);
+ }
+
+ [Test]
+ public void AStationaryDefenderReactionIsDroppedWhenHidden()
+ {
+ var motion = token.AddComponent<UnitTokenMotion>();
+ var flash = new GameObject("hit flash").AddComponent<MeshRenderer>();
+ flash.transform.SetParent(token.transform, false); flash.enabled = false;
+ motion.HitFlash = flash;
+ motion.enabled = false;
+ Assert.IsFalse(motion.Moving); Assert.IsFalse(motion.Attacking);
+
+ Assert.IsTrue(motion.PlayHit()); motion.Tick(0.04f);
+ Assert.IsTrue(motion.Reacting); Assert.IsTrue(flash.enabled);
+ Assert.IsFalse(motion.Moving); Assert.IsFalse(motion.Attacking);
+ token.SetActive(false);
+ // EditMode sends no OnDisable to a script without ExecuteAlways: call it as the player would.
+ typeof(UnitTokenMotion).GetMethod("OnDisable", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(motion, null);
+ Assert.IsFalse(motion.Reacting); Assert.IsFalse(flash.enabled);
+ Assert.AreEqual(Vector3.zero, token.transform.position);
+
+ token.SetActive(true);
+ motion.Tick(0f);
+ Assert.IsFalse(motion.Reacting, "shown again, the hidden reaction does not resume");
+ Assert.IsFalse(flash.enabled, "shown again, the hidden flash does not resume");
+ Assert.AreEqual(Vector3.zero, token.transform.position);
+ }
+
[Test]
public void AHiddenTokensAttackIsDroppedNotKept()
{
diff --git a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs
index 392151ba1..72033ba53 100644
--- a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs
+++ b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs
@@ -921,7 +921,13 @@ public class UnitsInPlayTests
Assert.AreEqual(3, kiryati.Cast<Transform>().Count(t => t.name.StartsWith("Rifleman")), "three riflemen at full strength (Q-UI-3)");
var badge = kiryati.Find("Badge");
Assert.IsNotNull(badge, "the promo's badge over every token");
- Assert.AreEqual(2, badge.GetComponentsInChildren<MeshRenderer>().Length, "a plate and a glyph");
+ // A plate and a glyph show; the hit's flash plate (#2614) is there but off until a hit lands, and nothing else is.
+ var badgeRenderers = badge.GetComponentsInChildren<MeshRenderer>();
+ CollectionAssert.AreEqual(new[] { "Plate", "Glyph" }, badgeRenderers.Where(r => r.enabled).Select(r => r.name).ToArray(), "a plate and a glyph");
+ var hitFlash = badge.Find("HitFlash");
+ Assert.IsNotNull(hitFlash, "the hit's flash plate");
+ Assert.IsFalse(hitFlash.GetComponent<MeshRenderer>().enabled, "the hit's flash is off until a hit lands");
+ Assert.AreEqual(3, badgeRenderers.Length, "the plate, the glyph and the flash, nothing else");
Assert.Greater(badge.position.y, kiryati.Find("Rifleman0").position.y + UnitBadge.FigureHeightM * UnitShowcase.FigureScale, "above the figures");
for (int i = 0; i < 3; i++)
{