A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Units: the 65 mm gun recoils, flashes and smokes when it fires; C05 idles (lean and breath) (#2396)
Eyal Golan32a806d4f0e4
diff --git a/changelog.d/anim-gun-c05.md b/changelog.d/anim-gun-c05.mdnew file mode 100644index 000000000..714be6f7a--- /dev/null+++ b/changelog.d/anim-gun-c05.md@@ -0,0 +1,5 @@+- The 65 mm gun fires when its unit attacks: the tube recoils and runs out again, the carriage hops and noses up, a+ muzzle flash burns for a few frames and three puffs of smoke roll forward and thin out, all in code on the model the+ token already draws, with no new art (Refs #2373, #1867).+- C05, the pioneer veteran, idles close up like the other figures: his held pose breathes and leans a little from the+ feet, each figure at its own point in the cycle, so a trio never moves in step (Refs #2374, #2007).diff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.csindex 8c012ed47..9feb7f870 100644--- a/unity/Assets/Editor/MapCapture.cs+++ b/unity/Assets/Editor/MapCapture.cs@@ -349,7 +349,7 @@ public static class MapCapture/// <summary>The units in play as a new game starts (golden seed unless the trailer passes its -seed, historical mode): what/// the player draws on turn 1, or, with -unitsDate, on that day.</summary>- static void ShowStartUnits(MapScene map, ulong seed = Statecraft.Sim.GoldenRun.Seed)+ static (Statecraft.Game.Map.Units.UnitLayer layer, Statecraft.Sim.GameState state) ShowStartUnits(MapScene map, ulong seed = Statecraft.Sim.GoldenRun.Seed){var content = Statecraft.Sim.ContentLoader.Load(Paths.Content);var units = Statecraft.Game.Map.Units.UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Units.UnitData.DefaultFileName)));@@ -364,6 +364,118 @@ public static class MapCapturestate.Date = Statecraft.Game.Map.Units.UnitData.Day(args[at + 1]);}layer.Show(content, state);+ return (layer, state);+ }++ /// <summary>#2373 and #2374's evidence: Givati's token on -unitsDate (1948-07-11 or later: the day its 65 mm gun joins it;+ /// its third figure is C05) at close zoom, with the game's camera on the WebGL tier, into -captureDir (default+ /// captures/anim-gun-c05). Every model the token asks for is answered from the AssetDatabase, as the player's stream+ /// would, and the renders warm up until the close-zoom switch has settled. Then, from the same camera and state: the+ /// token and the gun at rest (before), the gun's shot at the flash, at the end of the recoil and with the smoke rolling+ /// (UnitGunFire.Sample), and C05 at rest (before) and at the two far ends of its sway (UnitFigureIdle.Sample), with a+ /// README of the camera. Nothing is saved to the scene or the content.</summary>+ public static void GunAndC05()+ {+ var args = System.Environment.GetCommandLineArgs();+ int at = System.Array.IndexOf(args, "-captureDir");+ var dir = at >= 0 && at + 1 < args.Length ? args[at + 1] : Path.Combine(CaptureDir, "anim-gun-c05");+ Directory.CreateDirectory(dir);+ var pending = new List<(string id, System.Action<GameObject> done)>();+ var weapons = new List<(string id, System.Action<GameObject> done)>();+ Statecraft.Game.Map.Units.UnitFigures.Forget();+ Statecraft.Game.Map.Units.UnitFigures.Source = (id, detail, done) => pending.Add((id, done));+ Statecraft.Game.Map.Units.UnitWeapons.Source = (id, done) => weapons.Add((id, done));+ int saved = QualitySettings.GetQualityLevel();+ try+ {+ var map = OpenAndBuild();+ var (layer, state) = ShowStartUnits(map);+ void Answer()+ {+ for (int round = 0; round < 4 && (pending.Count > 0 || weapons.Count > 0); round++)+ {+ var figures = pending.ToArray(); pending.Clear();+ foreach (var request in figures)+ request.done(AssetDatabase.LoadAssetAtPath<GameObject>(Statecraft.Game.Map.Collection.CollectionCatalog.PrefabPath(request.id, Statecraft.Game.Map.Collection.CollectionDetail.Far)));+ var held = weapons.ToArray(); weapons.Clear();+ foreach (var request in held)+ request.done(AssetDatabase.LoadAssetAtPath<GameObject>(Statecraft.Game.Map.Collection.CollectionCatalog.PrefabPath(request.id, Statecraft.Game.Map.Collection.CollectionDetail.Far)));+ }+ }+ Answer();+ QualitySettings.SetQualityLevel(0, true); // the WebGL tier+ var camera = Camera.main; var rig = camera.GetComponent<CameraRig>();+ camera.aspect = 16f / 9f;+ string day = state.Date.ToString("yyyy-MM-dd");+ var token = layer.transform.Find("Tokens/givati");+ if (token == null) throw new System.InvalidOperationException("no givati token on " + day);+ // The gun's piece (Givati's second vehicle slot: its armoured car came on 12 June, its gun on 11 July).+ var gun = token.GetComponentInChildren<Statecraft.Game.Map.Units.UnitGunFire>(true);+ if (gun == null) throw new System.InvalidOperationException("givati has no 65 mm gun on " + day + " (pass -unitsDate 1948-07-11 or later)");+ var gunPiece = gun.transform;+ var c05Piece = token.Find("Rifleman2");+ if (c05Piece == null) throw new System.InvalidOperationException("givati has no third figure on " + day);+ float man = Statecraft.Game.Map.Units.UnitBadge.FigureHeightM * Statecraft.Game.Map.Units.UnitShowcase.FigureScale;+ var records = new List<string>();+ void View(string name, Vector3 lookAt, float distance)+ {+ rig.LookAt = lookAt; rig.Distance = distance; rig.Yaw = 0f; rig.TopInset = 0f; rig.Apply();+ Statecraft.Game.Map.Units.UnitFlagFacing.FaceAll(camera.transform.position);+ layer.FaceCamera(camera);+ records.Add($"{name}: lookAt={lookAt}; distance={distance}; yaw=0; pitch={CameraRig.Pitch}; fov={camera.fieldOfView}; tier={QualitySettings.names[0]}");+ }+ void Shot(string name) => Save(camera, 1920, 1080, Path.Combine(dir, name + ".png"));+ var tokenAt = token.Find(Statecraft.Game.Map.Units.UnitPlinth.PlinthName).position;+ // Warm up: the first close render flips the zoom switch, which asks for the near models; answer them and render+ // again, so every frame below shows the same settled token.+ View("warmup", tokenAt + Vector3.up * (0.35f * man), 9000f);+ for (int i = 0; i < 3; i++) { Shot("warmup"); Answer(); }+ File.Delete(Path.Combine(dir, "warmup.png"));+ records.Clear();++ View("token", tokenAt + Vector3.up * (0.35f * man), 9000f);+ Shot("token-before");+ gun.Fire(); gun.Sample(0.08f);+ Shot("token-after");+ gun.Sample(Statecraft.Game.Map.Units.UnitGunFire.TotalS);++ View("gun", gunPiece.position + gunPiece.forward * (0.15f * man) + Vector3.up * (0.3f * man), 3200f); // a little towards the muzzle, where the smoke goes+ Shot("gun-before");+ gun.Fire(); gun.Sample(0.02f); Shot("gun-flash");+ gun.Sample(0.08f); Shot("gun-recoil");+ gun.Sample(0.5f); Shot("gun-smoke");+ gun.Sample(Statecraft.Game.Map.Units.UnitGunFire.TotalS);++ var idle = c05Piece.GetComponentInChildren<Statecraft.Game.Map.Units.UnitFigureIdle>(true);+ if (idle == null) throw new System.InvalidOperationException("Rifleman2 has no code-driven idle (is it C05, with his bones?)");+ if (!idle.enabled) throw new System.InvalidOperationException("the zoom switch did not turn C05's idle on at " + rig.Distance + " m");+ View("c05", c05Piece.position + Vector3.up * (0.5f * man), 3200f);+ Shot("c05-before");+ // The far ends of the cycle: where the hips' lean and the chest's pitch are both largest, each way.+ float tLeft = 0f, tRight = 0f, mostLeft = 0f, mostRight = 0f;+ for (float t = 0f; t < 60f; t += 0.02f)+ {+ Statecraft.Game.Map.Units.UnitFigureIdle.Evaluate(t, idle.Offset, out float breath, out float sway);+ if (sway + breath > mostRight) { mostRight = sway + breath; tRight = t; }+ if (-(sway + breath) > mostLeft) { mostLeft = -(sway + breath); tLeft = t; }+ }+ idle.Sample(tLeft); Shot("c05-after-lean-a");+ idle.Sample(tRight); Shot("c05-after-lean-b");+ idle.enabled = false; idle.enabled = true; // back at rest (OnDisable), still on+ records.Add($"gun frames: flash at 0.02 s, recoil at 0.08 s, smoke at 0.5 s of the shot; C05 frames at {tLeft:F2} s and {tRight:F2} s of the session (offset {idle.Offset:F4})");+ File.WriteAllText(Path.Combine(dir, "README.txt"),+ $"Unity editor renders of Givati's token on {state.Date:yyyy-MM-dd} (historical start, golden seed, the units as on that day), 1920x1080, " ++ "the game's camera, the WebGL quality tier, every model answered from the AssetDatabase. Same camera, state and lighting " ++ "within each before/after set; the only change is the gun's shot (UnitGunFire.Sample) or C05's idle (UnitFigureIdle.Sample). " ++ "No UI. Nothing in the scene or the content was modified.\n" + string.Join("\n", records) + "\n");+ }+ finally+ {+ QualitySettings.SetQualityLevel(saved, true);+ Statecraft.Game.Map.Units.UnitFigures.Source = null;+ Statecraft.Game.Map.Units.UnitWeapons.Source = null;+ Statecraft.Game.Map.Units.UnitFigures.Forget();+ }}/// <summary>PromoPose.All, plus any "-extraPose name:lon:lat:distanceM:yaw" given (close looks while tuning the art, fordiff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.csindex a04c73caa..8385d9374 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexUnderAttack.cs@@ -262,8 +262,8 @@ namespace Statecraft.HexTiles}/// <summary>A soft, slightly lumpy puff (white, alpha falling to the rim; a little darker below, as smoke- /// shades itself). Pure arithmetic, so every look draws the same texture.</summary>- static Texture2D PuffTexture()+ /// shades itself). Pure arithmetic, so every look draws the same texture. The gun's muzzle smoke draws it too (UnitGunFire).</summary>+ internal static Texture2D PuffTexture(){const int N = 64;var t = new Texture2D(N, N, TextureFormat.RGBA32, true) { name = "under-attack-puff", wrapMode = TextureWrapMode.Clamp };diff --git a/unity/Assets/Scripts/Map/Units/UnitFigureDetail.cs b/unity/Assets/Scripts/Map/Units/UnitFigureDetail.csindex 95ed425bc..74ef390c7 100644--- a/unity/Assets/Scripts/Map/Units/UnitFigureDetail.cs+++ b/unity/Assets/Scripts/Map/Units/UnitFigureDetail.cs@@ -16,7 +16,8 @@ namespace Statecraft.Game.Map.Units/// The near prefabs are asked for only once a camera first comes close, through the same stream, after the first frame./// It fails open: until a near prefab arrives, and for good when it is missing or damaged, the far model stays. C05, the/// pioneer veteran, has no idle clip (walk and run only), so he keeps his still far model close up (owner, 18 October- /// 2026, #665: "Keep its still model"). One per unit layer or showcase; nothing is allocated while the zoom band holds.</summary>+ /// 2026, #665: "Keep its still model"); the switch turns his code-driven idle (UnitFigureIdle, #2374) on and off with the+ /// zoom instead, and asks for no near model. One per unit layer or showcase; nothing is allocated while the zoom band holds.</summary>[ExecuteAlways]public sealed class UnitFigureDetail : MonoBehaviour{@@ -29,6 +30,8 @@ namespace Statecraft.Game.Map.Unitspublic string Id = "";public Renderer[] FarRenderers = Array.Empty<Renderer>(), NearRenderers = Array.Empty<Renderer>();public Animator[] Animators = Array.Empty<Animator>();+ /// <summary>A figure that idles in code on its far model (C05): it has no near model to ask for.</summary>+ public UnitFigureIdle? Idle;}readonly List<Figure> figures = new List<Figure>();@@ -57,13 +60,14 @@ namespace Statecraft.Game.Map.Unitsreturn assets != null ? assets.gameObject : piece.root.gameObject;}- /// <summary>A figure whose far model <paramref name="holder"/> now holds (its first child), with an idle clip.</summary>+ /// <summary>A figure whose far model <paramref name="holder"/> now holds (its first child), with an idle clip, or with+ /// a code-driven idle on the far model itself (UnitFigureIdle).</summary>internal void Add(Transform holder, string id){var far = holder.GetChild(0);- var f = new Figure { Holder = holder, Far = far, Id = id, FarRenderers = far.GetComponentsInChildren<Renderer>(true) };+ var f = new Figure { Holder = holder, Far = far, Id = id, FarRenderers = far.GetComponentsInChildren<Renderer>(true), Idle = far.GetComponent<UnitFigureIdle>() };figures.Add(f);- if (LastClose) { Ask(f); Attach(f); }+ if (LastClose && f.Idle == null) { Ask(f); Attach(f); }Show(f);}@@ -79,7 +83,7 @@ namespace Statecraft.Game.Map.Unitsif (close == LastClose) return;LastClose = close;figures.RemoveAll(Gone);- foreach (var f in figures) { if (close) { Ask(f); Attach(f); } Show(f); }+ foreach (var f in figures) { if (close && f.Idle == null) { Ask(f); Attach(f); } Show(f); }}internal CollectionResidencyMetrics.Category ResidencySnapshot()@@ -141,7 +145,7 @@ namespace Statecraft.Game.Map.Units/// feet, casting shadows as it does, with the probes off as on the far model.</summary>void Attach(Figure f){- if (f.NearRenderers.Length > 0 || f.Holder == null) return;+ if (f.NearRenderers.Length > 0 || f.Holder == null || f.Idle != null) return;var prefab = UnitFigures.Near(f.Id);if (prefab == null) return;var near = Instantiate(prefab, f.Holder, false).transform; // the prefab's own root rotation (the FBX axis turn) kept@@ -188,6 +192,7 @@ namespace Statecraft.Game.Map.Unitsforeach (var r in f.FarRenderers) if (r != null) r.forceRenderingOff = near;foreach (var r in f.NearRenderers) if (r != null) r.forceRenderingOff = !near;foreach (var a in f.Animators) if (a != null) a.enabled = near;+ if (f.Idle != null) f.Idle.enabled = LastClose; // C05's code-driven idle runs close up, on his far model (#2374)// A figure that turns near mid-move or mid-attack takes up its token's walk or fire at once (#1866).var motion = near && f.Holder != null ? f.Holder.GetComponentInParent<UnitTokenMotion>() : null;if (motion != null && (motion.Moving || motion.Attacking)) motion.RefreshPose();diff --git a/unity/Assets/Scripts/Map/Units/UnitFigureIdle.cs b/unity/Assets/Scripts/Map/Units/UnitFigureIdle.csnew file mode 100644index 000000000..320824757--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitFigureIdle.cs@@ -0,0 +1,108 @@+#nullable enable+using UnityEngine;++namespace Statecraft.Game.Map.Units+{+ /// <summary>C05's idle, in code (#2374, part of #2007; owner, 3 November 2026: "do everything with the 0$ and make it as+ /// high quality as possible"). C05, the pioneer veteran, is the one token figure whose only idle take is a walk, so the+ /// token draws Tal Heuberger's original held still at the walk's first frame (OriginalModelPose; owner, 18 October 2026,+ /// #665: "Keep its still model"). Close up, where the other figures play their idle clips, this moves that held pose by+ /// small, slow turns, as the rigged idles do: the chest rises and sinks (breathing), the whole figure leans a little from+ /// side to side from its feet (a shift of weight, with the feet planted) and the head stays nearer level. Calmer than+ /// Tal's idle clips (their heads travel 3 to 4 percent of the figure's height; this about 2). Each figure starts at its own point in the+ /// cycle, from a hash of its token and place (<see cref="Phase"/>), so a trio never breathes in step, and the same figure+ /// gets the same offset after every rebuild. No clip, no file and no Animator: the Animator stays off, the bones' rest+ /// turns are kept and put back exactly when the figure turns far or is hidden. Sampling allocates nothing.</summary>+ [ExecuteAlways]+ public sealed class UnitFigureIdle : MonoBehaviour+ {+ /// <summary>The figure that idles this way: C05 only.</summary>+ public static bool Wanted(string? id) => id == UnitFigures.PioneerVeteran;++ /// <summary>A breath's period and a weight shift's, incommensurate so the two never line up for long.</summary>+ public const float BreathS = 3.7f, SwayS = 6.3f;+ /// <summary>The chest's pitch, the figure's lean and the head's counter-lean, in degrees, at the most.</summary>+ public const float BreathDeg = 2.5f, SwayDeg = 1.5f, HeadDeg = 0.6f;+ internal const string ArmatureNode = "Armature", ChestBone = "Chest", NeckBone = "Neck";++ Transform? chest, neck, frame;+ Transform? chestParent, neckParent;+ Quaternion rest, chestRest, neckRest; // the model root's turn under its holder, and the bones' under their parents+ float phase;++ /// <summary>Where in the cycle this figure starts, 0 to 1.</summary>+ public float Offset => phase;++ /// <summary>The key a figure's offset is hashed from: its token and its place on it ("givati/Figure2").</summary>+ internal static string KeyOf(Transform piece) => piece.parent != null ? piece.parent.name + "/" + piece.name : piece.name;++ /// <summary>A figure's point in the cycle, 0 to 1, from its key (FNV-1a over the characters): the same key gives the+ /// same offset on every platform and after every rebuild.</summary>+ public static float Phase(string key)+ {+ uint hash = 2166136261u;+ foreach (char c in key) { hash ^= c; hash *= 16777619u; }+ return (hash % 10007u) / 10007f;+ }++ /// <summary>Gives <paramref name="model"/> (C05's streamed original, posed and under its holder) the idle, keyed by+ /// <paramref name="key"/>, off until the zoom switch turns it on. Null when the model lacks the chest or the neck: the+ /// figure then stands still, as before.</summary>+ internal static UnitFigureIdle? Equip(Transform model, string key)+ {+ if (model == null || model.parent == null || model.TryGetComponent<UnitFigureIdle>(out _)) return null;+ var armature = UnitWeapons.FindDeep(model, ArmatureNode);+ if (armature == null) return null;+ var chest = UnitWeapons.FindDeep(armature, ChestBone);+ var neck = UnitWeapons.FindDeep(armature, NeckBone);+ if (chest == null || neck == null) return null;+ var idle = model.gameObject.AddComponent<UnitFigureIdle>();+ idle.enabled = false;+ idle.chest = chest; idle.neck = neck; idle.frame = model.parent;+ idle.chestParent = chest.parent; idle.neckParent = neck.parent;+ idle.rest = model.localRotation; idle.chestRest = chest.localRotation; idle.neckRest = neck.localRotation;+ idle.phase = Phase(key);+ return idle;+ }++ /// <summary>The turns at <paramref name="t"/> seconds for a figure at <paramref name="phase"/>: the chest's pitch+ /// (breathing) and the figure's lean (weight) in degrees; the head leans back by <see cref="HeadDeg"/> over <see cref="SwayDeg"/>+ /// of the lean.</summary>+ public static void Evaluate(float t, float phase, out float breathDeg, out float swayDeg)+ {+ breathDeg = BreathDeg * Mathf.Sin(2f * Mathf.PI * (t / BreathS + phase));+ swayDeg = SwayDeg * Mathf.Sin(2f * Mathf.PI * (t / SwayS + phase * 3.3f + 0.37f));+ }++ /// <summary>Poses the figure as it stands <paramref name="t"/> seconds into the session: the same t gives the same+ /// pose. The lean is about the holder's forward axis through the model's root, which stands on the figure's feet+ /// (UnitFigures.Swap), so the feet stay planted and the held rifle leans with him; the chest's and the neck's turns+ /// are about the figure's own axes (its holder's right and forward), whatever the bones' frames. No allocation. A+ /// retired model (its bones gone) is left alone.</summary>+ public void Sample(float t)+ {+ if (chest == null || neck == null || frame == null) return;+ Evaluate(t, phase, out float breath, out float sway);+ transform.localRotation = Quaternion.AngleAxis(sway, Vector3.forward) * rest;+ var right = frame.right; var forward = frame.forward;+ chest.localRotation = Turn(chestParent!, right, breath) * chestRest;+ neck.localRotation = Turn(neckParent!, forward, -HeadDeg / SwayDeg * sway) * neckRest;+ }++ /// <summary>A turn of <paramref name="deg"/> about world axis <paramref name="axis"/>, as a bone under <paramref name="parent"/> applies it.</summary>+ static Quaternion Turn(Transform parent, Vector3 axis, float deg) => Quaternion.AngleAxis(deg, parent.InverseTransformDirection(axis));++ /// <summary>The bones back at rest, exactly.</summary>+ void Rest()+ {+ if (frame != null) transform.localRotation = rest; // equipped: the rest turns were read+ if (chest != null) chest.localRotation = chestRest;+ if (neck != null) neck.localRotation = neckRest;+ }++ void LateUpdate() { if (Application.isPlaying) Sample(Time.time); }++ /// <summary>Turned off (far again, or the units hidden): the figure stands as it was held.</summary>+ void OnDisable() => Rest();+ }+}diff --git a/unity/Assets/Scripts/Map/Units/UnitFigureIdle.cs.meta b/unity/Assets/Scripts/Map/Units/UnitFigureIdle.cs.metanew file mode 100644index 000000000..552a6f18e--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitFigureIdle.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 6e5b72d49f8743ca97d1a9252c9017db\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Units/UnitFigures.cs b/unity/Assets/Scripts/Map/Units/UnitFigures.csindex 7c2d52051..a456d55eb 100644--- a/unity/Assets/Scripts/Map/Units/UnitFigures.cs+++ b/unity/Assets/Scripts/Map/Units/UnitFigures.cs@@ -394,7 +394,10 @@ namespace Statecraft.Game.Map.Unitsif (code != null) code.enabled = false;UnitFigureWeapon.Refresh(piece); // its sourced weapon in the hand (#2083), before the detail switch reads the renderersUnitFigurePointFire.Refresh(piece); // a held point-fire aim takes the new model too (#2084)- if (CollectionCatalog.Animated.Contains(id) && !CollectionCatalog.IsFullQualityGeneratedInfantry(id)) UnitFigureDetail.Of(piece).Add(holder, id); // C05 has no idle: he stays far+ // C05 has no idle clip: he stays far, and close up his held pose breathes in code instead (#2374). The switch is told+ // only once the idle took (fail open: a model without the bones stands still, and no near model is asked for).+ if (UnitFigureIdle.Wanted(id)) { if (UnitFigureIdle.Equip(model.transform, UnitFigureIdle.KeyOf(piece)) != null) UnitFigureDetail.Of(piece).Add(holder, id); }+ else if (CollectionCatalog.Animated.Contains(id) && !CollectionCatalog.IsFullQualityGeneratedInfantry(id)) UnitFigureDetail.Of(piece).Add(holder, id);// A model that arrives mid-move walks with its token at once (#1866).var motion = piece.GetComponentInParent<UnitTokenMotion>();if (motion != null && (motion.Moving || motion.Attacking)) motion.RefreshPose();diff --git a/unity/Assets/Scripts/Map/Units/UnitGunFire.cs b/unity/Assets/Scripts/Map/Units/UnitGunFire.csnew file mode 100644index 000000000..bda9ec8d9--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitGunFire.cs@@ -0,0 +1,297 @@+#nullable enable+using System.Collections.Generic;+using Statecraft.HexTiles;+using UnityEngine;+using UnityEngine.Rendering;+using Object = UnityEngine.Object;++namespace Statecraft.Game.Map.Units+{+ /// <summary>The 65 mm gun's shot on an attacking token (#2373, part of #1867; owner, 3 November 2026: "do everything with+ /// the 0$ and make it as high quality as possible"). No new art: everything is code on the model the token already draws,+ /// Tal Heuberger's "Napoleonchik" (H02), streamed as one prefab for both details; no file of theirs changes. When the+ /// token's attack plays (UnitTokenMotion.Fire, the same event the figures' fire takes answer), the tube slides back along+ /// its own axis and runs out again on a smooth return, as its hydro-pneumatic recoil did; the carriage hops back a little+ /// and noses up with a damped bounce; a muzzle flash burns for a few frames; and three puffs of grey smoke roll forward+ /// and up, thinning as they go. The whole shot is a pure function of the time since the trigger (<see cref="Sample"/>),+ /// so a rebuilt token goes on from where its predecessor was (UnitTokenMotion.ContinueAttack) and a capture can hold any+ /// frame of it. The muzzle and the recoil axis are read from the model's own barrel node (its mesh bounds' long axis, the+ /// end farther from the body), never from a hand-pinned number, and fail open to the gun's front when the model has no+ /// barrel node. The quads, materials and textures are made on the first shot and destroyed with the piece; sampling a+ /// frame allocates nothing. The gun's share of the attack's length is its recoil (<see cref="RecoilS"/>); the smoke+ /// outlasts the attack on the gun's own clock. A hidden gun (the units' toggle) drops its shot, as a figure drops its take.</summary>+ [ExecuteAlways]+ public sealed class UnitGunFire : MonoBehaviour+ {+ /// <summary>The recoil and return, the gun's share of the attack's length.</summary>+ public const float RecoilS = 0.45f;+ /// <summary>How long the muzzle flash shows.</summary>+ public const float FlashS = 0.12f;+ public const int Puffs = 3;+ /// <summary>When the first puff leaves the muzzle, the gap to the next, and each puff's life.</summary>+ public const float FirstPuffS = 0.02f, PuffGapS = 0.06f, PuffLifeS = 1.3f;+ /// <summary>The whole shot: the last puff has faded.</summary>+ public const float TotalS = FirstPuffS + (Puffs - 1) * PuffGapS + PuffLifeS;+ /// <summary>The tube's recoil as a share of its length, and how fast it goes back before the slow return.</summary>+ public const float TubeTravel = 0.22f, TubeBackS = 0.07f;+ /// <summary>The carriage's hop as a share of the gun's length, its nose-up in degrees, and how fast it goes back.</summary>+ public const float HopShare = 0.035f, NoseUpDeg = 1.6f, HopBackS = 0.05f;+ /// <summary>The flash's width and the puffs' size and travel, as shares of the gun's length.</summary>+ public const float FlashShare = 0.5f, PuffRadiusShare = 0.06f, PuffGrowShare = 0.16f, PuffForwardShare = 0.3f, PuffRiseShare = 0.3f;+ public const float PuffAlpha = 0.85f;+ internal const string BarrelNode = "barrel", BodyNode = "body";++ static readonly int BaseColor = Shader.PropertyToID("_BaseColor"), BaseMap = Shader.PropertyToID("_BaseMap"), Cull = Shader.PropertyToID("_Cull");+ static readonly Color FlashColour = new Color(1f, 0.85f, 0.5f), SmokeFresh = new Color(0.9f, 0.88f, 0.85f), SmokeThin = new Color(0.72f, 0.72f, 0.72f);+ static readonly float[] PuffSide = { -0.07f, 0.03f, 0.08f }, PuffSpin = { 20f, 140f, 260f };++ // The model's tube and the frame it recoils in, bound on the first shot after the model arrives.+ Transform? model, barrel, holder;+ Vector3 barrelRest, barrelBack, muzzleInBarrel; // the tube's rest, one holder unit of recoil in its own local units, and its muzzle+ Vector3 holderRest; Quaternion holderRestTurn;+ Vector3 dir, muzzle, noseAxis; // holder-local: the tube's axis towards the muzzle, the muzzle, the nose-up axis+ float tubeLength, length; // holder-local: the tube's length and the gun's+ Vector3 pieceDir, pieceMuzzle, pieceRight; float pieceLength; // the same in the piece's frame, where the effects live+ // The effects, made on the first shot.+ bool built;+ Transform? flashT; Renderer? flash; Material? flashMat;+ readonly Transform?[] puffT = new Transform?[Puffs]; readonly Renderer?[] puff = new Renderer?[Puffs]; readonly Material?[] puffMat = new Material?[Puffs];+ readonly List<Object> owned = new List<Object>();+ float t = -1f;++ /// <summary>A shot is under way (the smoke may still be fading after the attack ended).</summary>+ public bool Playing => t >= 0f;+ /// <summary>Seconds into the shot, or -1 at rest.</summary>+ public float Time => t;+ /// <summary>The tube's axis towards the muzzle and the muzzle, in the model holder's frame (tests).</summary>+ internal Vector3 Direction => dir;+ internal Vector3 Muzzle => muzzle;++ /// <summary>Gives vehicle piece <paramref name="piece"/>, dressed as <paramref name="vehicle"/>, its shot: only the gun.</summary>+ internal static void Equip(Transform piece, string? vehicle)+ {+ if (vehicle != UnitFigures.Napoleonchik || piece == null || piece.TryGetComponent<UnitGunFire>(out _)) return;+ var gun = piece.gameObject.AddComponent<UnitGunFire>();+ gun.enabled = false; // runs only while a shot plays+ }++ /// <summary>True when the gun's model is there to fire (binding it the first time, which allocates once).</summary>+ public bool Ready => Bind();++ /// <summary>Starts the shot <paramref name="from"/> seconds in (0: the trigger; a continued attack passes what its+ /// predecessor had played). Nothing happens until the model has arrived.</summary>+ public void Fire(float from = 0f)+ {+ if (!Bind()) return;+ if (!built) Build();+ enabled = true;+ Sample(from);+ }++ /// <summary>Advances the shot by <paramref name="seconds"/>; LateUpdate passes the frame's time in a player.</summary>+ internal void Tick(float seconds) { if (t >= 0f) Sample(t + Mathf.Max(0f, seconds)); }++ /// <summary>Puts the gun and its effects as they are <paramref name="seconds"/> into the shot: the same time gives the+ /// same frame. At or past <see cref="TotalS"/> everything is back at rest and the component stops. No allocation.</summary>+ public void Sample(float seconds)+ {+ if (!Bind()) { Stop(); return; } // the model was retired meanwhile: nothing to move+ t = seconds;+ if (t >= TotalS) { Stop(); return; }+ float tube = Tube(t), hop = Hop(t);+ if (barrel != null) barrel.localPosition = barrelRest + barrelBack * (TubeTravel * tubeLength * tube);+ holder!.localPosition = holderRest - pieceDir * (HopShare * pieceLength * hop);+ holder.localRotation = holderRestTurn * Quaternion.AngleAxis(NoseUpDeg * hop, noseAxis);+ float flashAlpha = Flash(t);+ if (flash != null && flashT != null && flashMat != null)+ {+ flash.enabled = flashAlpha > 0f;+ if (flash.enabled)+ {+ float grow = 0.7f + 0.3f * Mathf.Clamp01(t / 0.03f);+ // On the tube's own muzzle, so it rides the recoil; a little ahead of the bore.+ if (barrel != null) flashT.position = barrel.TransformPoint(muzzleInBarrel); else flashT.localPosition = pieceMuzzle;+ flashT.localPosition += pieceDir * (0.03f * pieceLength);+ flashT.localScale = Vector3.one * (FlashShare * pieceLength * grow);+ var c = FlashColour; c.a = flashAlpha; flashMat.SetColor(BaseColor, c);+ }+ }+ for (int i = 0; i < Puffs; i++)+ {+ var r = puff[i]; var pt = puffT[i]; var m = puffMat[i];+ if (r == null || pt == null || m == null) continue;+ float u = (t - FirstPuffS - i * PuffGapS) / PuffLifeS;+ r.enabled = u > 0f && u < 1f;+ if (!r.enabled) continue;+ Puff(u, out float forward, out float rise, out float radius, out float alpha);+ pt.localPosition = pieceMuzzle + pieceDir * (forward * pieceLength) + Vector3.up * (rise * pieceLength) + pieceRight * (PuffSide[i] * u * pieceLength);+ pt.localScale = Vector3.one * (2.6f * radius * pieceLength);+ var c = Color.Lerp(SmokeFresh, SmokeThin, u); c.a = alpha; m.SetColor(BaseColor, c);+ }+ }++ /// <summary>The tube's recoil at <paramref name="t"/> (0 at rest, 1 fully back): a sharp kick, then a smooth run-out.</summary>+ public static float Tube(float t)+ {+ if (t <= 0f || t >= RecoilS) return 0f;+ if (t < TubeBackS) { float k = 1f - t / TubeBackS; return 1f - k * k; }+ return 1f - Mathf.SmoothStep(0f, 1f, (t - TubeBackS) / (RecoilS - TubeBackS));+ }++ /// <summary>The carriage's hop at <paramref name="t"/> (1 fully back): a kick, then a damped bounce that settles+ /// through a small forward overshoot and is exactly 0 at <see cref="RecoilS"/>.</summary>+ public static float Hop(float t)+ {+ if (t <= 0f || t >= RecoilS) return 0f;+ if (t < HopBackS) { float k = 1f - t / HopBackS; return 1f - k * k; }+ float u = (t - HopBackS) / (RecoilS - HopBackS);+ return Mathf.Exp(-5f * u) * Mathf.Cos(1.5f * Mathf.PI * u);+ }++ /// <summary>The flash's strength at <paramref name="t"/>: full at the shot, gone by <see cref="FlashS"/>.</summary>+ public static float Flash(float t) => t < 0f || t >= FlashS ? 0f : 1f - Mathf.SmoothStep(0f, 1f, t / FlashS);++ /// <summary>A puff <paramref name="u"/> of the way through its life: how far forward of the muzzle and how high it is+ /// and how big, as shares of the gun's length, and how opaque. It leaves the bore fast, slows, rises and thins.</summary>+ public static void Puff(float u, out float forward, out float rise, out float radius, out float alpha)+ {+ float s = Mathf.Sqrt(Mathf.Clamp01(u));+ forward = 0.02f + PuffForwardShare * s;+ radius = PuffRadiusShare + PuffGrowShare * s;+ rise = PuffRiseShare * u + radius * 0.5f;+ alpha = PuffAlpha * Mathf.SmoothStep(0f, 1f, u / 0.08f) * (1f - Mathf.SmoothStep(0f, 1f, (u - 0.4f) / 0.6f));+ }++ /// <summary>Finds the model under the piece and its tube, once: where the muzzle is and which way the recoil goes, from+ /// the barrel node's mesh bounds (its long horizontal axis, up its elevation; the muzzle is the end farther from the+ /// body). A model without a barrel node recoils whole, level along the gun's own length, its muzzle at the front.</summary>+ bool Bind()+ {+ if (model != null) return true;+ var h = transform.Find(UnitFigures.ModelName);+ if (h == null || h.childCount == 0) return false;+ var m = h.GetChild(0);+ if (!(UnitFigures.BoxIn(h, m) is Bounds whole) || whole.size.y <= 1e-6f) return false;+ var barrelNode = UnitWeapons.FindDeep(m, BarrelNode);+ var bodyNode = UnitWeapons.FindDeep(m, BodyNode);+ var tube = barrelNode != null && UnitFigures.BoxIn(h, barrelNode) is Bounds tb ? tb : whole;+ var body = bodyNode != null && UnitFigures.BoxIn(h, bodyNode) is Bounds bb ? bb : whole;+ int axis = tube.size.x > tube.size.z ? 0 : 2, across = axis == 0 ? 2 : 0; // the tube lies near level: its long axis is never up+ float sign = Mathf.Sign(tube.center[axis] - body.center[axis]); // Sign(0) is 1: a whole model fires forward+ // An elevated tube's box is taller than the tube is wide by the rise from breech to muzzle; the muzzle is the high+ // end (a gun elevates, never depresses, at rest). A whole model's box is wider than tall, so it fires level.+ float rise = Mathf.Max(0f, tube.size.y - tube.size[across]);+ dir = Vector3.zero; dir[axis] = sign * tube.size[axis]; dir.y = rise; dir.Normalize();+ muzzle = tube.center + dir * (0.5f * tube.size[axis] / Mathf.Abs(dir[axis])); // the box's far face, up the incline+ tubeLength = Mathf.Sqrt(tube.size[axis] * tube.size[axis] + rise * rise); length = Mathf.Max(whole.size.x, whole.size.z);+ noseAxis = Vector3.Cross(dir, Vector3.up);+ holder = h; model = m; barrel = barrelNode;+ holderRest = h.localPosition; holderRestTurn = h.localRotation;+ if (barrelNode != null)+ {+ barrelRest = barrelNode.localPosition;+ barrelBack = barrelNode.parent.InverseTransformVector(h.TransformVector(-dir));+ muzzleInBarrel = barrelNode.InverseTransformPoint(h.TransformPoint(muzzle));+ }+ pieceDir = holderRestTurn * dir; pieceRight = Vector3.Cross(Vector3.up, pieceDir).normalized;+ pieceMuzzle = holderRest + holderRestTurn * Vector3.Scale(muzzle, h.localScale);+ pieceLength = Vector3.Scale(dir * length, h.localScale).magnitude;+ return true;+ }++ /// <summary>The flash and the puffs: camera-facing quads under the piece (so they turn with the token, not with the+ /// recoiling gun), on the under-attack look's materials (HexMaterials: the additive glow for the flash, the lit smoke+ /// for the puffs, with its soft puff texture) and a flash texture drawn in code. Hidden until a shot.</summary>+ void Build()+ {+ built = true;+ flashMat = Own(HexMaterials.New(HexMaterials.AttackGlow)); flashMat.SetTexture(BaseMap, Own(FlashTexture()));+ (flashT, flash) = Quad("MuzzleFlash", flashMat);+ var puffTexture = Own(HexUnderAttackLook.PuffTexture());+ for (int i = 0; i < Puffs; i++)+ {+ var m = puffMat[i] = Own(HexMaterials.New(HexMaterials.AttackSmoke));+ m.SetTexture(BaseMap, puffTexture); m.SetFloat(Cull, (float)CullMode.Off);+ (puffT[i], puff[i]) = Quad("MuzzleSmoke" + i, m);+ }+ }++ (Transform, Renderer) Quad(string name, Material material)+ {+ var go = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer));+ go.transform.SetParent(transform, false);+ go.GetComponent<MeshFilter>().sharedMesh = Resources.GetBuiltinResource<Mesh>("Quad.fbx");+ 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);+ }++ T Own<T>(T o) where T : Object { owned.Add(o); return o; }++ /// <summary>A muzzle flash: a hot core, eight short rays and a soft warm halo, white at the centre and orange at the rim.+ /// Pure arithmetic, so every gun draws the same texture.</summary>+ internal static Texture2D FlashTexture()+ {+ const int N = 64;+ var tex = new Texture2D(N, N, TextureFormat.RGBA32, true) { name = "muzzle-flash", wrapMode = TextureWrapMode.Clamp };+ var px = new Color32[N * N];+ for (int j = 0; j < N; j++)+ for (int i = 0; i < N; i++)+ {+ float x = (i + 0.5f) / N * 2f - 1f, y = (j + 0.5f) / N * 2f - 1f;+ float r = Mathf.Sqrt(x * x + y * y), a = Mathf.Atan2(y, x);+ float core = Mathf.Exp(-(r * r) / 0.14f);+ float rays = Mathf.Pow(Mathf.Abs(Mathf.Cos(4f * a + 0.4f)), 16f) * Mathf.Clamp01(1f - r / 0.95f);+ float halo = 0.5f * Mathf.Pow(Mathf.Clamp01(1f - r / 0.75f), 2f);+ float alpha = Mathf.Clamp01(core + 0.9f * rays + halo);+ var colour = Color.Lerp(Color.white, new Color(1f, 0.55f, 0.15f), Mathf.Clamp01(r / 0.5f));+ px[j * N + i] = new Color(colour.r, colour.g, colour.b, alpha);+ }+ tex.SetPixels32(px); tex.Apply(true, false);+ return tex;+ }++ /// <summary>Turns the flash and the puffs to face the camera about to render (every camera in turn, as the badges).</summary>+ internal void Face(ScriptableRenderContext _, Camera cam)+ {+ if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;+ var view = cam.transform.rotation;+ if (flash != null && flash.enabled && flashT != null) flashT.rotation = view * Quaternion.Euler(0f, 0f, 37f);+ for (int i = 0; i < Puffs; i++)+ {+ var r = puff[i]; var pt = puffT[i];+ if (r != null && r.enabled && pt != null) pt.rotation = view * Quaternion.Euler(0f, 0f, PuffSpin[i]);+ }+ }++ /// <summary>Everything back at rest and hidden; the component stops.</summary>+ void Stop()+ {+ t = -1f;+ if (barrel != null) barrel.localPosition = barrelRest;+ if (holder != null) { holder.localPosition = holderRest; holder.localRotation = holderRestTurn; }+ if (flash != null) flash.enabled = false;+ for (int i = 0; i < Puffs; i++) if (puff[i] != null) puff[i]!.enabled = false;+ enabled = false;+ }++ void LateUpdate() { if (Application.isPlaying) Tick(UnityEngine.Time.deltaTime); }++ void OnEnable() => RenderPipelineManager.beginCameraRendering += Face;++ /// <summary>A gun hidden mid-shot (the units' toggle deactivates the layer) drops it, as a figure drops its take.</summary>+ void OnDisable()+ {+ RenderPipelineManager.beginCameraRendering -= Face;+ if (t >= 0f) Stop();+ }++ 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/Units/UnitGunFire.cs.meta b/unity/Assets/Scripts/Map/Units/UnitGunFire.cs.metanew file mode 100644index 000000000..66c4a49ee--- /dev/null+++ b/unity/Assets/Scripts/Map/Units/UnitGunFire.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 0d35933ad4304b20816e96ea225c3e1a\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.csindex 60ff140d0..d1bf9f30b 100644--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs@@ -760,6 +760,7 @@ namespace Statecraft.Game.Map.Unitsvar vehicle = EmptyPiece(go.transform, $"Vehicle{j}", at, heading);UnitFigures.Dress(vehicle, t.Vehicles[j], map.Residency.Units,retainFar: true); // the gun or the jeep: held while its roster token lives (#665)+ UnitGunFire.Equip(vehicle, t.Vehicles[j]); // the 65 mm gun fires when the token attacks (#2373)figures[offsets.Length + j] = (vehicle, offset, heading);}foot.y = highest;diff --git a/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs b/unity/Assets/Scripts/Map/Units/UnitTokenMotion.csindex b8996daf8..9c635f818 100644--- a/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs+++ b/unity/Assets/Scripts/Map/Units/UnitTokenMotion.cs@@ -9,7 +9,8 @@ namespace Statecraft.Game.Map.Units/// Presentation only: the sim has already moved the unit. A token's root stands at the world origin and its pieces/// 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. The component runs its LateUpdate only+ /// 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./// 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@@ -34,6 +35,7 @@ namespace Statecraft.Game.Map.Unitsint posed; // the walk or idle the figures were last asked forreadonly List<Animator> animators = new List<Animator>();readonly List<UnitFigurePointFire> aims = new List<UnitFigurePointFire>();+ readonly List<UnitGunFire> guns = new List<UnitGunFire>();public bool Moving => elapsed < Duration;/// <summary>An attack plays, or waits for a figure to play it.</summary>@@ -79,18 +81,23 @@ namespace Statecraft.Game.Map.Units/// continued attack, from where it was; the attack then lasts as long as the longest take has left. A take that had/// finished plays nothing, so the figures keep their walk or idle (review of #2176, item 8). A C06 figure holds Tal/// Heuberger's point-fire aim instead, near or far, for the whole attack; its own fire take counts toward the attack's- /// length (#2084, UnitFigurePointFire).</summary>+ /// length (#2084, UnitFigurePointFire). A 65 mm gun whose model has arrived fires too, near or far, from the same+ /// point in its shot; its recoil counts toward the attack's length (#2373, UnitGunFire).</summary>bool Fire(){float longest = 0f;animators.Clear(); GetComponentsInChildren(false, animators);aims.Clear(); GetComponentsInChildren(false, aims);+ guns.Clear(); GetComponentsInChildren(false, guns);foreach (var animator in animators)if (UnitFigureMotion.CanPlay(animator, UnitFigureMotion.Attack)) longest = Mathf.Max(longest, FireLength(animator));foreach (var aim in aims)if (aim.Ready) longest = Mathf.Max(longest, aim.FireLength);+ foreach (var gun in guns)+ if (gun.Ready) longest = Mathf.Max(longest, UnitGunFire.RecoilS);if (longest <= 0f) return false; // no live figure has a fire take yet: keep waitingif (longest <= resumeAt) { attackLeft = 0f; resumeAt = 0f; return false; } // the take had finished+ float from = resumeAt;foreach (var animator in animators){if (!UnitFigureMotion.CanPlay(animator, UnitFigureMotion.Attack)) continue;@@ -100,6 +107,7 @@ 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);return true;}diff --git a/unity/Assets/Tests/EditMode/UnitFigureIdleTests.cs b/unity/Assets/Tests/EditMode/UnitFigureIdleTests.csnew file mode 100644index 000000000..722fc9706--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitFigureIdleTests.cs@@ -0,0 +1,134 @@+using NUnit.Framework;+using Statecraft.Game.Map.Units;+using UnityEngine;+using UnityEngine.TestTools.Constraints;+using Is = UnityEngine.TestTools.Constraints.Is;+using Object = UnityEngine.Object;++/// <summary>#2374: C05's code-driven idle leans his held pose from the feet and breathes with the chest by small, slow turns,+/// starts each figure at its own deterministic point in the cycle, puts everything back exactly when turned off, and+/// allocates nothing per frame.</summary>+public sealed class UnitFigureIdleTests+{+ GameObject token = null!;++ [SetUp] public void Make() => token = new GameObject("givati");+ [TearDown] public void Free() => Object.DestroyImmediate(token);++ /// <summary>A figure piece as UnitLayer builds one, with the model holder UnitFigures.Swap makes and a rig of the bones the+ /// idle reads (under the FBX axis turn, at rest turns of their own, as Tal Heuberger's held pose has).</summary>+ (Transform piece, Transform model, Transform hips, Transform chest, Transform neck) Figure(string name = "Figure2", bool chestBone = true)+ {+ var piece = new GameObject(name).transform;+ piece.SetParent(token.transform, false);+ piece.localRotation = Quaternion.Euler(0f, 30f, 0f); piece.localScale = Vector3.one * UnitShowcase.FigureScale;+ var holder = new GameObject(UnitFigures.ModelName).transform;+ holder.SetParent(piece, false); holder.localScale = Vector3.one * 0.9f;+ var model = new GameObject("c05").transform;+ model.SetParent(holder, false); model.localRotation = Quaternion.Euler(-90f, 0f, 0f);+ Transform Bone(Transform parent, string bone, Quaternion rest)+ {+ var t = new GameObject(bone).transform;+ t.SetParent(parent, false); t.localRotation = rest; t.localPosition = Vector3.up * 0.3f;+ return t;+ }+ var armature = Bone(model, UnitFigureIdle.ArmatureNode, Quaternion.identity);+ var hips = Bone(armature, "Hips", Quaternion.Euler(3f, 170f, -2f));+ var chest = Bone(hips, chestBone ? UnitFigureIdle.ChestBone : "Spine", Quaternion.Euler(-4f, 1f, 2f));+ var neck = Bone(chest, UnitFigureIdle.NeckBone, Quaternion.Euler(6f, -3f, 0f));+ Bone(neck, "Head", Quaternion.Euler(2f, 0f, 0f));+ return (piece, model, hips, chest, neck);+ }++ [Test]+ public void TheOffsetIsDeterministicBoundedAndDiffersBetweenFigures()+ {+ Assert.AreEqual(UnitFigureIdle.Phase("givati/Figure2"), UnitFigureIdle.Phase("givati/Figure2"));+ var keys = new[] { "givati/Figure2", "carmeli/Figure2", "givati/Rifleman2", "alexandroni/Figure2", "etzioni/Figure2" };+ for (int i = 0; i < keys.Length; i++)+ {+ Assert.That(UnitFigureIdle.Phase(keys[i]), Is.InRange(0f, 0.9999f), keys[i]);+ for (int j = 0; j < i; j++)+ Assert.Greater(Mathf.Abs(UnitFigureIdle.Phase(keys[i]) - UnitFigureIdle.Phase(keys[j])), 0.02f, keys[i] + " vs " + keys[j]);+ }+ Assert.AreEqual(0.6592f, UnitFigureIdle.Phase("givati/Figure2"), 1e-4f, "pinned: the same offset on every platform and after every rebuild");++ var (piece, model, _, _, _) = Figure();+ var idle = UnitFigureIdle.Equip(model, UnitFigureIdle.KeyOf(piece));+ Assert.IsNotNull(idle);+ Assert.AreEqual("givati/Figure2", UnitFigureIdle.KeyOf(piece), "keyed by the token and the place on it");+ Assert.AreEqual(UnitFigureIdle.Phase("givati/Figure2"), idle!.Offset);+ Assert.IsFalse(idle.enabled, "off until the zoom switch turns it on");++ // Two figures at the same moment are out of step: at some point in a breath their chests differ clearly.+ float other = UnitFigureIdle.Phase("carmeli/Figure2"), apart = 0f;+ for (float t = 0f; t < UnitFigureIdle.BreathS; t += 0.05f)+ {+ UnitFigureIdle.Evaluate(t, idle.Offset, out float a, out _);+ UnitFigureIdle.Evaluate(t, other, out float b, out _);+ apart = Mathf.Max(apart, Mathf.Abs(a - b));+ }+ Assert.Greater(apart, 0.3f, "degrees apart at the most");+ }++ [Test]+ public void TheIdleLeansFromTheFeetAndBreathesAboutTheFiguresOwnAxesAndPutsEverythingBackExactly()+ {+ var (piece, model, hips, chest, neck) = Figure();+ var rest = model.localRotation; var feet = model.localPosition;+ var hipsRest = hips.localRotation; var chestRest = chest.localRotation; var neckRest = neck.localRotation;+ var headRest = neck.GetChild(0).localRotation;+ var idle = UnitFigureIdle.Equip(model, UnitFigureIdle.KeyOf(piece))!;+ idle.enabled = true;+ float breathMost = 0f, swayMost = 0f;+ for (float t = 0f; t < 2f * UnitFigureIdle.SwayS; t += 0.05f)+ {+ idle.Sample(t);+ float breath = Quaternion.Angle(chestRest, chest.localRotation), sway = Quaternion.Angle(rest, model.localRotation);+ Assert.LessOrEqual(breath, UnitFigureIdle.BreathDeg + 0.01f, "chest at " + t);+ Assert.LessOrEqual(sway, UnitFigureIdle.SwayDeg + 0.01f, "lean at " + t);+ Assert.LessOrEqual(Quaternion.Angle(neckRest, neck.localRotation), UnitFigureIdle.HeadDeg + 0.01f, "neck at " + t);+ breathMost = Mathf.Max(breathMost, breath); swayMost = Mathf.Max(swayMost, sway);+ Assert.AreEqual(feet, model.localPosition, "the feet stay planted: the lean pivots on the model's root");+ Assert.IsTrue(hipsRest.Equals(hips.localRotation), "the hips are not turned (a hip roll would drag the feet)");+ // The chest pitches about the figure's right axis and the figure leans about its forward axis, whatever the bones'+ // frames (read at the larger turns, with the axis normalized: ToAngleAxis is coarse under a quarter of a degree).+ var pitch = chest.localRotation * Quaternion.Inverse(chestRest);+ pitch.ToAngleAxis(out float pitchDeg, out var pitchAxis);+ if (pitchDeg > 0.5f * UnitFigureIdle.BreathDeg) Assert.Greater(Mathf.Abs(Vector3.Dot(chest.parent.TransformDirection(pitchAxis).normalized, piece.right)), 0.999f, "chest axis at " + t);+ var lean = model.localRotation * Quaternion.Inverse(rest);+ lean.ToAngleAxis(out float leanDeg, out var leanAxis);+ if (leanDeg > 0.5f * UnitFigureIdle.SwayDeg) Assert.Greater(Mathf.Abs(Vector3.Dot(model.parent.TransformDirection(leanAxis).normalized, piece.forward)), 0.999f, "lean axis at " + t);+ }+ Assert.Greater(breathMost, 0.9f * UnitFigureIdle.BreathDeg, "it breathes");+ Assert.Greater(swayMost, 0.9f * UnitFigureIdle.SwayDeg, "and shifts its weight");+ Assert.IsTrue(headRest.Equals(neck.GetChild(0).localRotation), "the head's own turn is untouched");+ idle.enabled = false;+ Assert.IsTrue(rest.Equals(model.localRotation), "the figure stands as it did, exactly");+ Assert.IsTrue(chestRest.Equals(chest.localRotation), "chest back at rest, exactly");+ Assert.IsTrue(neckRest.Equals(neck.localRotation), "neck back at rest, exactly");+ }++ [Test]+ public void AModelWithoutTheBonesStandsStill()+ {+ var (piece, model, _, _, _) = Figure(chestBone: false);+ Assert.IsNull(UnitFigureIdle.Equip(model, UnitFigureIdle.KeyOf(piece)), "no chest: fail open");+ Assert.IsFalse(model.TryGetComponent<UnitFigureIdle>(out _));+ Assert.IsTrue(UnitFigureIdle.Wanted(UnitFigures.PioneerVeteran));+ Assert.IsFalse(UnitFigureIdle.Wanted(UnitFigures.SabraPioneer)); Assert.IsFalse(UnitFigureIdle.Wanted(null));+ }++ [Test]+ public void SamplingAFrameAllocatesNothing()+ {+ var (piece, model, _, _, _) = Figure();+ var idle = UnitFigureIdle.Equip(model, UnitFigureIdle.KeyOf(piece))!;+ idle.enabled = true;+ float t = 0f;+ TestDelegate frames = () => { for (int i = 0; i < 100; i++) { t += 1f / 60f; idle.Sample(t); } };+ frames(); // the delegate's first call JIT-compiles it (PR 2351); the measured call below still samples 100 frames+ Assert.That(frames, Is.Not.AllocatingGCMemory());+ Assert.Greater(t, 3f);+ }+}diff --git a/unity/Assets/Tests/EditMode/UnitFigureIdleTests.cs.meta b/unity/Assets/Tests/EditMode/UnitFigureIdleTests.cs.metanew file mode 100644index 000000000..2752abf74--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitFigureIdleTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 06b7c204e0c945eea7cc16ee6580255f\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/UnitFiguresTests.cs b/unity/Assets/Tests/EditMode/UnitFiguresTests.csindex 9a1806718..7c88bbe83 100644--- a/unity/Assets/Tests/EditMode/UnitFiguresTests.cs+++ b/unity/Assets/Tests/EditMode/UnitFiguresTests.cs@@ -427,7 +427,8 @@ public class UnitFiguresTests/// <summary>Close up, a near model that never comes (null: a missing or damaged bundle) leaves the far mesh drawing (fail/// open); and C05, the pioneer veteran, has no idle clip (walk and run only), so his near model is never asked for and he- /// keeps his still far model (owner, 18 October 2026, #665: "Keep its still model"), while the figures beside him swap.</summary>+ /// keeps his still far model (owner, 18 October 2026, #665: "Keep its still model"), while the figures beside him swap.+ /// Close up that still model breathes in code (UnitFigureIdle, #2374), and stands still again far off.</summary>[Test]public void AMissingNearModelKeepsTheFarMeshAndC05KeepsHisStillModel(){@@ -453,6 +454,13 @@ public class UnitFiguresTestsAssert.IsTrue(FarOf(c05).All(r => !r.forceRenderingOff), "C05 keeps his still far model close up");Assert.IsNotNull(NearOf(c06), "C06 swaps beside him");Assert.IsTrue(FarOf(c06).All(r => r.forceRenderingOff));+ var idle = c05.Find(UnitFigures.ModelName).GetChild(0).GetComponent<UnitFigureIdle>();+ Assert.IsNotNull(idle, "C05's held pose has its code-driven idle (#2374), on the model the token draws");+ Assert.IsTrue(idle.enabled, "close up it breathes");+ Assert.IsTrue(c05.GetComponentsInChildren<Animator>(true).All(a => !a.enabled), "with his Animator still off");+ View(root.GetComponent<UnitFigureDetail>(), camera, TownModelLayer.CloseExitM + 1f);+ Assert.IsFalse(idle.enabled, "far off he stands still again");+ Assert.AreEqual(2, asked.Count(a => a.detail == CollectionDetail.Near), "and his near model was never asked for");}finally { UnityEngine.Object.DestroyImmediate(camera.gameObject); UnityEngine.Object.DestroyImmediate(root); }}diff --git a/unity/Assets/Tests/EditMode/UnitGunFireTests.cs b/unity/Assets/Tests/EditMode/UnitGunFireTests.csnew file mode 100644index 000000000..5bcd69165--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitGunFireTests.cs@@ -0,0 +1,262 @@+using NUnit.Framework;+using Statecraft.Game.Map.Units;+using UnityEngine;+using UnityEngine.TestTools.Constraints;+using Is = UnityEngine.TestTools.Constraints.Is;+using Object = UnityEngine.Object;++/// <summary>#2373: the 65 mm gun fires in code when its token attacks (recoil, flash, smoke), from the same event as the+/// figures' fire takes, and comes back to rest exactly; the muzzle and the recoil axis are read from the model's own+/// barrel node, whichever way it points; a hidden gun drops its shot; sampling a frame allocates nothing.</summary>+public sealed class UnitGunFireTests+{+ GameObject token = null!;++ [SetUp] public void Make() => token = new GameObject("givati");+ [TearDown] public void Free() => Object.DestroyImmediate(token);++ /// <summary>A vehicle piece as UnitLayer builds one (scaled, headed west), with the model holder UnitFigures.Swap makes and+ /// a gun of three cubes under the FBX axis turn: a tube long along the gun's front, a body behind its middle, a trail+ /// behind that. With <paramref name="sideways"/> the gun is built along its own -X instead, to prove the barrel is+ /// found by its shape and not by a hand-pinned axis; with <paramref name="barrelNode"/> false it is one merged node.</summary>+ (Transform piece, Transform holder, Transform barrel) Gun(bool sideways = false, bool barrelNode = true, float elevationDeg = 0f)+ {+ var piece = new GameObject("Vehicle0").transform;+ piece.SetParent(token.transform, false);+ piece.localRotation = Quaternion.Euler(0f, 270f, 0f); piece.localScale = Vector3.one * UnitShowcase.FigureScale;+ var holder = new GameObject(UnitFigures.ModelName).transform;+ holder.SetParent(piece, false); holder.localScale = Vector3.one * 0.5f;+ var model = new GameObject("gun").transform;+ model.SetParent(holder, false); model.localRotation = Quaternion.Euler(-90f, 0f, 0f); // the FBX axis turn: local -Y is the holder's +Z, local +Z its +Y+ // In the holder's frame: the tube centred at z = 1 (or x = -1), 1 long and 0.1 across, 0.5 up; the body at 0.2; the trail at -0.8.+ Transform Cube(string name, Vector3 atHolder, Vector3 sizeHolder)+ {+ var go = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer));+ go.GetComponent<MeshFilter>().sharedMesh = Resources.GetBuiltinResource<Mesh>("Cube.fbx");+ go.transform.SetParent(model, false);+ go.transform.localPosition = new Vector3(atHolder.x, -atHolder.z, atHolder.y);+ go.transform.localScale = new Vector3(sizeHolder.x, sizeHolder.z, sizeHolder.y);+ return go.transform;+ }+ Vector3 Along(float d) => sideways ? new Vector3(-d, 0f, 0f) : new Vector3(0f, 0f, d);+ Vector3 Size(float along, float across, float up) => sideways ? new Vector3(along, up, across) : new Vector3(across, up, along);+ var barrel = Cube(barrelNode ? UnitGunFire.BarrelNode : "gun-merged", Along(1f) + Vector3.up * 0.5f, Size(1f, 0.1f, 0.1f));+ if (elevationDeg != 0f)+ {+ // Elevated about the holder's X through the tube's centre: the muzzle end rises (the tube still points along the front).+ var centre = barrel.position;+ barrel.RotateAround(centre, holder.TransformDirection(Vector3.right), -elevationDeg);+ }+ if (barrelNode)+ {+ Cube(UnitGunFire.BodyNode, Along(0.2f) + Vector3.up * 0.35f, Size(0.5f, 0.5f, 0.7f));+ Cube("wheel_tail", Along(-0.8f) + Vector3.up * 0.1f, Size(0.8f, 0.1f, 0.1f));+ }+ return (piece, holder, barrel);+ }++ [Test]+ public void OnlyTheGunGetsAShot()+ {+ var (piece, _, _) = Gun();+ UnitGunFire.Equip(piece, UnitFigures.WillysJeep);+ Assert.IsFalse(piece.TryGetComponent<UnitGunFire>(out _), "the jeep does not fire");+ UnitGunFire.Equip(piece, UnitFigures.Napoleonchik);+ Assert.IsTrue(piece.TryGetComponent<UnitGunFire>(out var gun), "the 65 mm gun does");+ Assert.IsFalse(gun.enabled, "and runs nothing until it fires");+ UnitGunFire.Equip(piece, UnitFigures.Napoleonchik);+ Assert.AreEqual(1, piece.GetComponents<UnitGunFire>().Length, "equipped once");+ }++ [Test]+ public void TheMuzzleAndTheRecoilAxisComeFromTheBarrelNodeWhicheverWayItPoints()+ {+ var (piece, _, _) = Gun();+ UnitGunFire.Equip(piece, UnitFigures.Napoleonchik);+ var gun = piece.GetComponent<UnitGunFire>();+ Assert.IsTrue(gun.Ready);+ Assert.Less(Vector3.Angle(Vector3.forward, gun.Direction), 0.01f, "the tube's long axis, towards the end farther from the body");+ Assert.That(Vector3.Distance(new Vector3(0f, 0.5f, 1.5f), gun.Muzzle), Is.LessThan(1e-3f), "the muzzle: the tube's far end");++ var (side, _, _) = Gun(sideways: true);+ UnitGunFire.Equip(side, UnitFigures.Napoleonchik);+ var sideGun = side.GetComponent<UnitGunFire>();+ Assert.IsTrue(sideGun.Ready);+ Assert.Less(Vector3.Angle(Vector3.left, sideGun.Direction), 0.01f, "a gun built along -X recoils along +X");+ Assert.That(Vector3.Distance(new Vector3(-1.5f, 0.5f, 0f), sideGun.Muzzle), Is.LessThan(1e-3f));++ var (raised, _, _) = Gun(elevationDeg: 15f);+ UnitGunFire.Equip(raised, UnitFigures.Napoleonchik);+ var raisedGun = raised.GetComponent<UnitGunFire>();+ Assert.IsTrue(raisedGun.Ready);+ Assert.Less(Vector3.Angle(raisedGun.Direction, new Vector3(0f, Mathf.Sin(15f * Mathf.Deg2Rad), Mathf.Cos(15f * Mathf.Deg2Rad))), 2f,+ "an elevated tube recoils up its own incline, read from its box (taller than the tube is wide by the rise)");+ var trueMuzzle = new Vector3(0f, 0.5f + 0.5f * Mathf.Sin(15f * Mathf.Deg2Rad), 1f + 0.5f * Mathf.Cos(15f * Mathf.Deg2Rad));+ Assert.That(Vector3.Distance(trueMuzzle, raisedGun.Muzzle), Is.LessThan(0.03f), "the muzzle at the high end of the tube");++ var (merged, _, _) = Gun(barrelNode: false);+ UnitGunFire.Equip(merged, UnitFigures.Napoleonchik);+ var mergedGun = merged.GetComponent<UnitGunFire>();+ Assert.IsTrue(mergedGun.Ready, "a model with no barrel node still fires");+ Assert.Less(Vector3.Angle(Vector3.forward, mergedGun.Direction), 0.01f, "whole, level, towards its front");+ Assert.That(Vector3.Distance(new Vector3(0f, 0.5f, 1.5f), mergedGun.Muzzle), Is.LessThan(1e-3f), "its front end");+ }++ [Test]+ public void AnAttackFiresTheGunAndItReturnsToRest()+ {+ var (piece, holder, barrel) = Gun();+ UnitGunFire.Equip(piece, UnitFigures.Napoleonchik);+ var gun = piece.GetComponent<UnitGunFire>();+ var barrelRest = barrel.localPosition;+ float Along() => Vector3.Dot(holder.InverseTransformPoint(barrel.position) - new Vector3(0f, 0.5f, 1f), gun.Direction);+ float MuzzleHeight() => piece.InverseTransformPoint(holder.TransformPoint(gun.Muzzle)).y;+ float restHeight = MuzzleHeight();+ var motion = token.AddComponent<UnitTokenMotion>();+ motion.enabled = false;+ Assert.IsTrue(motion.PlayAttack(), "the gun alone plays the token's attack");+ Assert.IsTrue(motion.Attacking); Assert.IsTrue(gun.Playing); Assert.IsTrue(gun.enabled);+ Assert.AreEqual(0f, gun.Time);+ var flash = piece.Find("MuzzleFlash").GetComponent<Renderer>();+ Assert.IsTrue(flash.enabled, "the flash shows from the shot");+ Assert.AreEqual(0f, Along(), 1e-4f, "the tube has not moved yet");++ gun.Tick(0.05f);+ Assert.Less(Along(), -0.1f, "the tube is kicked back along its axis");+ Assert.Less(Vector3.Dot(holder.localPosition, gun.Direction), 0f, "the carriage hops back");+ Assert.Greater(MuzzleHeight(), restHeight, "and noses up");+ Assert.IsTrue(flash.enabled);++ gun.Tick(0.1f);+ Assert.IsFalse(flash.enabled, "the flash is gone after a few frames");+ int shown = 0;+ for (int i = 0; i < UnitGunFire.Puffs; i++) if (piece.Find("MuzzleSmoke" + i).GetComponent<Renderer>().enabled) shown++;+ Assert.AreEqual(UnitGunFire.Puffs, shown, "every puff is in the air");+ var first = piece.Find("MuzzleSmoke0"); var firstAt = first.localPosition; var firstSize = first.localScale.x;+ gun.Tick(0.3f);+ Assert.Greater(Vector3.Dot(first.localPosition - firstAt, Vector3.forward), 0f, "the smoke rolls forward of the muzzle");+ Assert.Greater(first.localPosition.y, firstAt.y, "and rises");+ Assert.Greater(first.localScale.x, firstSize, "and spreads");++ motion.Tick(UnitGunFire.RecoilS - 0.01f);+ Assert.IsTrue(motion.Attacking, "the attack lasts the recoil");+ motion.Tick(0.02f);+ Assert.IsFalse(motion.Attacking); Assert.IsFalse(motion.enabled);+ gun.Tick(UnitGunFire.RecoilS);+ Assert.AreEqual(0f, Along(), 1e-4f, "the tube is back at rest after the recoil");+ Assert.AreEqual(Vector3.zero, holder.localPosition); Assert.AreEqual(Quaternion.identity, holder.localRotation);+ Assert.IsTrue(gun.Playing, "the smoke outlasts the attack");++ gun.Tick(UnitGunFire.TotalS);+ Assert.IsFalse(gun.Playing); Assert.IsFalse(gun.enabled, "the shot is over and the gun runs nothing");+ Assert.AreEqual(barrelRest, barrel.localPosition, "the tube is exactly where it was");+ Assert.AreEqual(Vector3.zero, holder.localPosition); Assert.AreEqual(Quaternion.identity, holder.localRotation);+ Assert.IsFalse(flash.enabled);+ for (int i = 0; i < UnitGunFire.Puffs; i++) Assert.IsFalse(piece.Find("MuzzleSmoke" + i).GetComponent<Renderer>().enabled, "puff " + i);+ }++ /// <summary>The envelopes behind the shot: the tube and the carriage start and end at rest and never leave their bounds;+ /// the carriage settles through a small forward overshoot; the flash fades to nothing by FlashS.</summary>+ [Test]+ public void TheRecoilEnvelopesStartAndEndAtRestAndStayBounded()+ {+ Assert.AreEqual(0f, UnitGunFire.Tube(0f)); Assert.AreEqual(0f, UnitGunFire.Tube(UnitGunFire.RecoilS));+ Assert.AreEqual(0f, UnitGunFire.Hop(0f)); Assert.AreEqual(0f, UnitGunFire.Hop(UnitGunFire.RecoilS));+ Assert.AreEqual(1f, UnitGunFire.Tube(UnitGunFire.TubeBackS), 1e-5f, "fully back at the end of the kick");+ float minHop = 1f;+ for (float t = 0f; t <= UnitGunFire.RecoilS; t += 0.001f)+ {+ Assert.That(UnitGunFire.Tube(t), Is.InRange(0f, 1f), "tube at " + t);+ Assert.That(UnitGunFire.Hop(t), Is.InRange(-0.1f, 1f), "hop at " + t);+ Assert.That(UnitGunFire.Flash(t), Is.InRange(0f, 1f));+ minHop = Mathf.Min(minHop, UnitGunFire.Hop(t));+ }+ Assert.Less(minHop, -0.02f, "the carriage settles through a forward overshoot");+ Assert.AreEqual(1f, UnitGunFire.Flash(0f)); Assert.AreEqual(0f, UnitGunFire.Flash(UnitGunFire.FlashS));+ UnitGunFire.Puff(0.5f, out float forward, out float rise, out float radius, out float alpha);+ Assert.Greater(forward, 0f); Assert.Greater(rise, 0f); Assert.Greater(radius, 0f); Assert.That(alpha, Is.InRange(0f, UnitGunFire.PuffAlpha));+ UnitGunFire.Puff(1f, out _, out _, out _, out float gone);+ Assert.AreEqual(0f, gone, 1e-5f, "a puff has faded by the end of its life");+ }++ /// <summary>A rebuild hands a playing attack to the unit's new token from where it was (UnitTokenMotion.ContinueAttack):+ /// the shot is a pure function of its time, so the new gun shows the same frame the old one did.</summary>+ [Test]+ public void AContinuedShotShowsTheSameFrame()+ {+ var (piece, holder, barrel) = Gun();+ UnitGunFire.Equip(piece, UnitFigures.Napoleonchik);+ var gun = piece.GetComponent<UnitGunFire>();+ gun.Fire();+ gun.Sample(0.3f);+ var tube = barrel.localPosition; var hop = holder.localPosition; var smoke = piece.Find("MuzzleSmoke1").localPosition;+ gun.Sample(UnitGunFire.TotalS);+ Assert.IsFalse(gun.Playing);+ var motion = token.AddComponent<UnitTokenMotion>();+ motion.enabled = false;+ motion.ContinueAttack(0.3f);+ Assert.IsTrue(gun.Playing); Assert.AreEqual(0.3f, gun.Time, 1e-5f);+ Assert.AreEqual(tube, barrel.localPosition); Assert.AreEqual(hop, holder.localPosition);+ Assert.AreEqual(smoke, piece.Find("MuzzleSmoke1").localPosition);+ motion.ContinueAttack(UnitGunFire.RecoilS + 0.1f);+ Assert.IsFalse(motion.Attacking, "past the recoil the attack had finished");+ }++ [Test]+ public void AHiddenGunDropsItsShotAtRest()+ {+ var (piece, holder, barrel) = Gun();+ UnitGunFire.Equip(piece, UnitFigures.Napoleonchik);+ var gun = piece.GetComponent<UnitGunFire>();+ var rest = barrel.localPosition;+ gun.Fire(); gun.Sample(0.1f);+ Assert.AreNotEqual(rest, barrel.localPosition);+ token.SetActive(false); // the units toggled off mid-shot+ Assert.IsFalse(gun.Playing); Assert.IsFalse(gun.enabled);+ Assert.AreEqual(rest, barrel.localPosition); Assert.AreEqual(Vector3.zero, holder.localPosition);+ token.SetActive(true);+ Assert.IsFalse(gun.Playing, "shown again, it does not go on with the shot it dropped");+ Assert.IsFalse(piece.Find("MuzzleFlash").GetComponent<Renderer>().enabled);+ }++ [Test]+ public void AGunWhoseModelHasNotArrivedDoesNotFire()+ {+ var piece = new GameObject("Vehicle0").transform;+ piece.SetParent(token.transform, false);+ UnitGunFire.Equip(piece, UnitFigures.Napoleonchik);+ var gun = piece.GetComponent<UnitGunFire>();+ Assert.IsFalse(gun.Ready);+ var motion = token.AddComponent<UnitTokenMotion>();+ motion.enabled = false;+ Assert.IsFalse(motion.PlayAttack(), "nothing on the token can play it");+ Assert.IsFalse(gun.Playing); Assert.IsFalse(gun.enabled);+ Assert.IsNull(piece.Find("MuzzleFlash"), "nothing is built for a shot that never came");+ }++ [Test]+ public void SamplingAFrameAndFacingACameraAllocateNothing()+ {+ var (piece, _, _) = Gun();+ UnitGunFire.Equip(piece, UnitFigures.Napoleonchik);+ var gun = piece.GetComponent<UnitGunFire>();+ var camera = new GameObject("camera").AddComponent<Camera>();+ try+ {+ camera.transform.SetPositionAndRotation(new Vector3(0f, 2000f, -3000f), Quaternion.Euler(40f, 0f, 0f));+ gun.Fire();+ float t = 0f;+ TestDelegate frames = () =>+ {+ for (int i = 0; i < 100; i++) { t += 0.01f; gun.Sample(t); gun.Face(default, camera); }+ };+ // The exact measured delegate runs once first: Mono JIT-compiles it on its first call, and that one-time cost+ // belongs to the test, not to the shot (as CollectionResidencyViewAllocationTests does, PR 2351).+ frames();+ gun.Fire(); t = 0f;+ Assert.That(frames, Is.Not.AllocatingGCMemory());+ Assert.IsTrue(gun.Playing, "the measured frames were real: a second into the shot, the smoke is still fading");+ }+ finally { Object.DestroyImmediate(camera.gameObject); }+ }+}diff --git a/unity/Assets/Tests/EditMode/UnitGunFireTests.cs.meta b/unity/Assets/Tests/EditMode/UnitGunFireTests.cs.metanew file mode 100644index 000000000..9f0514f1b--- /dev/null+++ b/unity/Assets/Tests/EditMode/UnitGunFireTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ffc96c9bcdf549568138faec207f0639\ No newline at end of file