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.

Units: strength pips on the map's badges (#2432, PR 2) (#2999)

Eyal Golan9f2e7d478673
diff --git a/changelog.d/2960-map-pips.md b/changelog.d/2960-map-pips.md
new file mode 100644
index 000000000..11d67d409
--- /dev/null
+++ b/changelog.d/2960-map-pips.md
@@ -0,0 +1,4 @@
+- On the map, every military unit's badge, on both sides, now shows its strength as small pips under its symbol: one pip
+ per unit of strength, filled for the strength it has and hollow for the strength it lost, five to a row, so a damaged
+ unit reads at a glance. The pips follow the unit through a loss and fill again when it is reinforced. The squadron and
+ the ships show none.
diff --git a/unity/Assets/Scripts/Map/Units/UnitBadge.cs b/unity/Assets/Scripts/Map/Units/UnitBadge.cs
index bd196eab4..72ce61b76 100644
--- a/unity/Assets/Scripts/Map/Units/UnitBadge.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitBadge.cs
@@ -7,7 +7,8 @@ namespace Statecraft.Game.Map.Units
/// <summary>The promo's unit badge (promo/final/03-gameplay-1936.png): a small dark rounded plate with a light glyph,
/// floating over a token so a player sees it is a unit and can click it. Two flat unlit meshes in the local XY plane
/// (the plate, and the glyph a little towards the camera), turned to face each camera as it renders (UnitLayer). The
- /// glyph says the service: two figures for a brigade, an aircraft for the squadron, a ship for the navy.</summary>
+ /// glyph says the service: two figures for a brigade, an aircraft for the squadron, a ship for the navy. A military sim
+ /// unit's badge also carries its strength in pips under the glyph (<see cref="PipsMesh"/>, #2432).</summary>
public sealed class UnitBadge : MonoBehaviour
{
/// <summary>The plate's width at map scale (m) from a far camera; nearer it is capped on the screen
@@ -53,10 +54,12 @@ namespace Statecraft.Game.Map.Units
return m.Build("UnitBadgePlate");
}
- /// <summary>The service's glyph inside the plate (about 0.6 across).</summary>
- public static Mesh GlyphMesh(string service)
+ /// <summary>The service's glyph inside the plate (about 0.6 across). With <paramref name="pips"/> (a badge that
+ /// carries <see cref="PipsMesh"/>) it is drawn at <see cref="PippedGlyphScale"/> and raised by
+ /// <see cref="PippedGlyphRise"/>, clear of the pips' strip.</summary>
+ public static Mesh GlyphMesh(string service, bool pips = false)
{
- var m = new Flat();
+ var m = pips ? new Flat(PippedGlyphScale, PippedGlyphRise) : new Flat();
switch (service)
{
case UnitData.Army: // two standing figures: a head and a tapered body each
@@ -77,7 +80,61 @@ namespace Statecraft.Game.Map.Units
m.Fan(Rect(-0.10f, 0.08f, 0.08f, 0.24f));
break;
}
- return m.Build("UnitBadgeGlyph-" + service);
+ return m.Build("UnitBadgeGlyph-" + service + (pips ? "-pips" : ""));
+ }
+
+ /// <summary>#2432, the damaged look (owner, 8 November 2026, "A. Pips on badge (Recommended)" and "(c) No bands, pips
+ /// (Recommended)"; 9 November 2026, "Rows of five (Recommended)", "Every military unit (Recommended)" and "All 3 as
+ /// recommended (Recommended)"): a military unit's badge carries one pip per population unit of its full strength,
+ /// a disc for each unit it has and a ring for each it lost, so a loss reads by shape, not by colour alone. Five to a
+ /// row, rows from the top, filled pips first from the left in both languages (a count, not text), in a strip inside
+ /// the plate under the glyph, which is drawn smaller and higher (<see cref="GlyphMesh"/>): the plate keeps its size.</summary>
+ public const int PipsPerRow = 5;
+ /// <summary>The pips' strip inside the plate (plate widths): its top and its bottom edge.</summary>
+ public const float PipStripTop = -0.10f, PipStripBottom = -0.43f;
+ /// <summary>The distance between neighbouring pips' centres (plate widths; less when more rows than two must fit the
+ /// strip), a pip's radius as a share of it, and a hollow pip's hole as a share of its radius. Two rows of five fit
+ /// at the full pitch: a pip about 0.11 of the plate across, 6 of its 59 pixels at the gameplay zoom.</summary>
+ public const float PipPitch = 0.16f, PipRadiusShare = 0.34f, PipHoleShare = 0.5f;
+ /// <summary>The glyph's scale and rise (plate widths) on a badge with pips.</summary>
+ public const float PippedGlyphScale = 0.7f, PippedGlyphRise = 0.12f;
+ const int PipSides = 12;
+
+ /// <summary>The pips' centre spacing for a unit of <paramref name="full"/>: <see cref="PipPitch"/>, or less so that
+ /// its rows fit the strip.</summary>
+ public static float PipSpacing(int full) =>
+ Mathf.Min(PipPitch, (PipStripTop - PipStripBottom) / Mathf.Max(1, (full + PipsPerRow - 1) / PipsPerRow));
+
+ /// <summary>Where each pip of a unit at <paramref name="strength"/> of <paramref name="full"/> stands in the plate
+ /// (plate widths, the plate's centre at the origin), in order: row by row from the top, each row centred and from the
+ /// left; the first <paramref name="strength"/> are filled. A strength above the full counts as full. None for a full
+ /// strength of 0.</summary>
+ public static List<(Vector2 centre, bool filled)> PipLayout(int strength, int full)
+ {
+ full = Mathf.Max(full, strength);
+ var pips = new List<(Vector2, bool)>(Mathf.Max(0, full));
+ if (full <= 0) return pips;
+ int rows = (full + PipsPerRow - 1) / PipsPerRow;
+ float pitch = PipSpacing(full), middle = (PipStripTop + PipStripBottom) / 2f;
+ for (int i = 0; i < full; i++)
+ {
+ int row = i / PipsPerRow, inRow = Mathf.Min(PipsPerRow, full - row * PipsPerRow);
+ float x = (i % PipsPerRow - (inRow - 1) / 2f) * pitch, y = middle + ((rows - 1) / 2f - row) * pitch;
+ pips.Add((new Vector2(x, y), i < strength));
+ }
+ return pips;
+ }
+
+ /// <summary>The pips of a unit at <paramref name="strength"/> of <paramref name="full"/> as one mesh (<see cref="PipLayout"/>):
+ /// a disc per filled pip, a ring per hollow one, drawn with the glyph's material.</summary>
+ public static Mesh PipsMesh(int strength, int full)
+ {
+ full = Mathf.Max(full, strength);
+ float r = PipRadiusShare * PipSpacing(full);
+ var m = new Flat();
+ foreach (var (centre, filled) in PipLayout(strength, full))
+ if (filled) m.Fan(Circle(centre, r, PipSides)); else m.Ring(centre, r, r * PipHoleShare, PipSides);
+ return m.Build(System.FormattableString.Invariant($"UnitBadgePips-{strength}of{full}"));
}
static List<Vector2> Rect(float cx, float cy, float w, float h) => new List<Vector2>
@@ -94,12 +151,31 @@ namespace Statecraft.Game.Map.Units
sealed class Flat
{
readonly List<Vector3> verts = new List<Vector3>(); readonly List<int> tris = new List<int>();
+ readonly float scale, rise;
+ /// <param name="scale">Every point is drawn at this scale about the origin, then raised by <paramref name="rise"/>.</param>
+ public Flat(float scale = 1f, float rise = 0f) { this.scale = scale; this.rise = rise; }
+ Vector3 At(Vector2 p) => new Vector3(p.x * scale, p.y * scale + rise, 0f);
public void Fan(List<Vector2> outline)
{
int b = verts.Count;
- foreach (var p in outline) verts.Add(new Vector3(p.x, p.y, 0f));
+ foreach (var p in outline) verts.Add(At(p));
for (int i = 1; i + 1 < outline.Count; i++) tris.AddRange(new[] { b, b + i, b + i + 1 });
}
+ /// <summary>A ring of <paramref name="n"/> quads between radii <paramref name="inner"/> and <paramref name="outer"/>.</summary>
+ public void Ring(Vector2 centre, float outer, float inner, int n)
+ {
+ int b = verts.Count;
+ for (int i = 0; i < n; i++)
+ {
+ float a = 2f * Mathf.PI * i / n; var d = new Vector2(Mathf.Cos(a), Mathf.Sin(a));
+ verts.Add(At(centre + d * outer)); verts.Add(At(centre + d * inner));
+ }
+ for (int i = 0; i < n; i++)
+ {
+ int o = b + 2 * i, o2 = b + 2 * ((i + 1) % n);
+ tris.AddRange(new[] { o, o2, o2 + 1, o, o2 + 1, o + 1 });
+ }
+ }
public Mesh Build(string name)
{
var mesh = new Mesh { name = name };
diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
index 17392fc77..12472cd8b 100644
--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs
@@ -898,7 +898,18 @@ namespace Statecraft.Game.Map.Units
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);
+ // #2432: a military sim unit's strength in pips under a smaller glyph (UnitBadge.PipsMesh), one shared mesh per
+ // strength and full strength, built here with the tokens (a change of either rebuilds them, UnitToken.Equals),
+ // so nothing is done per frame; the squadron, the ships and a map-only token have no sim strength and no pips.
+ bool pips = t.StateUnit != null && t.StateUnit.Side != "";
+ AddRenderer(badge.transform, "Glyph", MeshFor("badge-" + t.Unit.Service + (pips ? "-pips" : ""), () => UnitBadge.GlyphMesh(t.Unit.Service, pips)),
+ badgeGlyph, -UnitBadge.GlyphLift);
+ if (pips)
+ {
+ int strength = t.StateUnit!.Strength, full = Mathf.Max(strength, UnitDamage.FullStrength(shownContent, t.StateUnit));
+ AddRenderer(badge.transform, "Pips", MeshFor(FormattableString.Invariant($"badge-pips-{strength}/{full}"), () => UnitBadge.PipsMesh(strength, full)),
+ badgeGlyph, -UnitBadge.GlyphLift);
+ }
// The badge's cube and the pieces (the flag and the figures as they stand now); FaceCamera moves both with the camera.
var pieces = standing;
if (pieces is Bounds s) { if (flag != null) s.Encapsulate(WorldBox(flag)); foreach (var m in meshes) if (m != null && m.sharedMesh != null) s.Encapsulate(WorldBox(m)); pieces = s; }
diff --git a/unity/Assets/Scripts/Map/Units/UnitRoster.cs b/unity/Assets/Scripts/Map/Units/UnitRoster.cs
index 35c3cb4c3..3caaf4cfe 100644
--- a/unity/Assets/Scripts/Map/Units/UnitRoster.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitRoster.cs
@@ -43,7 +43,8 @@ namespace Statecraft.Game.Map.Units
&& Figures == o.Figures && ArtType == o.ArtType && Flying == o.Flying && Headgear.SequenceEqual(o.Headgear)
&& Vehicles.SequenceEqual(o.Vehicles) && SimId == o.SimId && Raised == o.Raised
&& (StateUnit == null && o.StateUnit == null || StateUnit != null && o.StateUnit != null
- && StateUnit.Type == o.StateUnit.Type && StateUnit.Strength == o.StateUnit.Strength && StateUnit.HomeCity == o.StateUnit.HomeCity);
+ && StateUnit.Type == o.StateUnit.Type && StateUnit.Strength == o.StateUnit.Strength && StateUnit.Full == o.StateUnit.Full
+ && StateUnit.HomeCity == o.StateUnit.HomeCity);
public override bool Equals(object? o) => Equals(o as UnitToken);
public override int GetHashCode() => HashCode.Combine(Unit.Id, Anchor.Place, Figures, ArtType, Flying);
public override string ToString() => $"{Unit.Id}@{Anchor.Place}:{ArtType}x{Figures}{(Headgear.Count > 0 ? "[" + string.Join("/", Headgear) + "]" : "")}{(Vehicles.Count > 0 ? "+" + string.Join("+", Vehicles) : "")}{(Flying ? " flying" : "")}";
diff --git a/unity/Assets/Tests/EditMode/UnitBadgePipsTests.cs b/unity/Assets/Tests/EditMode/UnitBadgePipsTests.cs
new file mode 100644
index 000000000..987954e2d
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitBadgePipsTests.cs
@@ -0,0 +1,321 @@
+#nullable enable
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Map;
+using Statecraft.Game.Map.Units;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.TestTools.Constraints;
+using Is = UnityEngine.TestTools.Constraints.Is;
+using Object = UnityEngine.Object;
+
+/// <summary>#2432, #2960 PR 2: the damaged look on the map. Owner, 8 November 2026: "A. Pips on badge (Recommended)" (one
+/// pip per population unit on the badge plate, filled for the strength left, hollow for the strength lost; not colour
+/// alone; shared meshes on the existing unlit badge material) and "(c) No bands, pips (Recommended)". Owner, 9 November
+/// 2026: "Rows of five (Recommended)", "Every military unit (Recommended)" (a full unit shows its pips too) and "All 3 as
+/// recommended (Recommended)": a row inside the plate under the glyph (the glyph smaller, the plate's size unchanged), the
+/// same order in both languages, always shown with the plate. #2432: both sides, clears on a reinforce, dims with the
+/// badge, built when the tokens are rebuilt (no per-frame work), military sim units only. The pips are read back from the
+/// badge's "Pips" mesh: one connected piece per pip, a disc when filled, a ring when hollow.</summary>
+public class UnitBadgePipsTests
+{
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+ static List<UnitEntry> Units => UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
+ const string Golani = "golani", Egypt = "egyptian_expeditionary_force";
+
+ MapScene map = null!;
+ UnitLayer? layer;
+ GameObject standIn = null!;
+ bool readable;
+
+ [OneTimeSetUp]
+ public void BuildMap()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
+ map = new GameObject("MapScene").AddComponent<MapScene>();
+ map.Configure(Load("Terrain"), Load("SettlementMarker"), Load("HexSelection"), Load("Sea"), Load("MapFrame"));
+ map.Build();
+ }
+
+ [OneTimeTearDown]
+ public void DropMap()
+ {
+ if (map != null) Object.DestroyImmediate(map.gameObject);
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ }
+
+ [SetUp]
+ public void Prepare()
+ {
+ // The meshes are read back below (a player build keeps no CPU copy).
+ readable = UnitPlinth.KeepMeshesReadable; UnitPlinth.KeepMeshesReadable = true;
+ // An Arab force's token waits for its Collection figure, which edit mode never streams: answer at once with a
+ // stand-in, as UnitBadgeScreenCapTests does (the badge does not depend on the figure's mesh).
+ standIn = GameObject.CreatePrimitive(PrimitiveType.Cube); standIn.transform.position = Vector3.one * -100000f;
+ UnitFigures.Source = (_, __, done) => done(standIn); UnitFigures.Forget();
+ layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ }
+
+ [TearDown]
+ public void Discard()
+ {
+ if (layer != null) Object.DestroyImmediate(layer.gameObject);
+ layer = null;
+ UnitFigures.Source = null; UnitFigures.Forget();
+ Object.DestroyImmediate(standIn);
+ UnitPlinth.KeepMeshesReadable = readable;
+ }
+
+ static Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");
+
+ static GameState NewGame() => Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
+
+ static int SimId(string row) => C.StartingForces.FindIndex(f => f.Row == row);
+
+ /// <summary>Sets sim unit <paramref name="id"/>'s strength and its Full (0: it has lost none).</summary>
+ static void SetStrength(GameState s, int id, int strength, int full)
+ {
+ var u = s.Units[id];
+ s.Units[id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, strength, u.Order, u.OrderTarget, u.HomeCity, full, u.CombatXp);
+ }
+
+ Transform Badge(string row) => layer!.transform.Find("Tokens/" + row + "/Badge");
+
+ struct Pip { public Vector2 Centre; public float Radius; public bool Hollow; }
+
+ /// <summary>The pips on <paramref name="badge"/>, in the plate's frame (1 x 1, centred), top row first, each row from
+ /// the left: one connected piece of the "Pips" mesh per pip; a ring (some vertices well inside its radius) is hollow.
+ /// None when the badge has no "Pips" renderer.</summary>
+ static List<Pip> PipsOn(Transform badge)
+ {
+ var holder = badge.Find("Pips");
+ if (holder == null) return new List<Pip>();
+ var mesh = holder.GetComponent<MeshFilter>().sharedMesh;
+ Assert.IsTrue(mesh.isReadable, "fixture: the pips' mesh is kept readable");
+ var v = mesh.vertices; var t = mesh.triangles;
+ var parent = Enumerable.Range(0, v.Length).ToArray();
+ int Root(int i) { while (parent[i] != i) i = parent[i] = parent[parent[i]]; return i; }
+ for (int i = 0; i < t.Length; i += 3) { parent[Root(t[i + 1])] = Root(t[i]); parent[Root(t[i + 2])] = Root(t[i]); }
+ var offset = (Vector2)holder.localPosition;
+ var pips = new List<Pip>();
+ foreach (var piece in Enumerable.Range(0, v.Length).GroupBy(Root))
+ {
+ var pts = piece.Select(i => (Vector2)v[i] + offset).ToList();
+ var centre = pts.Aggregate(Vector2.zero, (a, b) => a + b) / pts.Count;
+ float far = pts.Max(p => (p - centre).magnitude), near = pts.Min(p => (p - centre).magnitude);
+ pips.Add(new Pip { Centre = centre, Radius = far, Hollow = near < 0.8f * far });
+ }
+ return Rows(pips).SelectMany(r => r).ToList();
+ }
+
+ /// <summary>The pips' rows, top first, each from the left: a pip within 0.02 of the plate's height of the row's first
+ /// pip stands in that row.</summary>
+ static List<List<Pip>> Rows(List<Pip> pips)
+ {
+ var rows = new List<List<Pip>>();
+ foreach (var p in pips.OrderByDescending(p => p.Centre.y))
+ if (rows.Count > 0 && Mathf.Abs(rows[rows.Count - 1][0].Centre.y - p.Centre.y) < 0.02f) rows[rows.Count - 1].Add(p);
+ else rows.Add(new List<Pip> { p });
+ return rows.Select(r => r.OrderBy(p => p.Centre.x).ToList()).ToList();
+ }
+
+ static string Draw(List<Pip> pips) => string.Join(" ", Rows(pips).Select(r => string.Concat(r.Select(p => p.Hollow ? "o" : "x"))));
+
+ /// <summary>The look the rulings ask for: <paramref name="strength"/> filled pips then the lost ones hollow, five to a
+ /// row from the top, e.g. "xxxxx xxooo" for 7 of 10.</summary>
+ static string Want(int strength, int full) => string.Join(" ", Enumerable.Range(0, (full + 4) / 5)
+ .Select(r => string.Concat(Enumerable.Range(r * 5, Mathf.Min(5, full - r * 5)).Select(i => i < strength ? "x" : "o"))));
+
+ /// <summary>"Every military unit (Recommended)", both sides: at the opening every military sim unit's badge carries one
+ /// filled pip per population unit (its full strength, UnitDamage.FullStrength), the Egyptian force's 10 in two rows of
+ /// five; the squadron, the ships and a map-only token (no sim unit, no strength) carry none. Units of the same strength
+ /// share one pips mesh.</summary>
+ [Test]
+ public void EveryMilitaryUnitOnBothSidesShowsItsStrengthInPips()
+ {
+ var s = NewGame();
+ layer!.Show(C, s);
+ int israel = 0, arab = 0;
+ var meshes = new Dictionary<string, Mesh>();
+ foreach (var p in layer.Tokens)
+ {
+ var badge = Badge(p.Token.Unit.Id);
+ var u = p.Token.StateUnit;
+ if (u == null || u.Side == "")
+ {
+ Assert.IsNull(badge.Find("Pips"), $"{p.Token}: no sim strength, no pips");
+ continue;
+ }
+ int full = UnitDamage.FullStrength(C, u);
+ Assert.AreEqual(Want(u.Strength, full), Draw(PipsOn(badge)), $"{p.Token}: {u.Strength} of {full}");
+ if (u.Side == UnitData.Israel) israel++; else arab++;
+ var key = Want(u.Strength, full);
+ var mesh = badge.Find("Pips").GetComponent<MeshFilter>().sharedMesh;
+ if (meshes.TryGetValue(key, out var seen)) Assert.AreSame(seen, mesh, $"{p.Token}: the same pips share one mesh");
+ else meshes[key] = mesh;
+ }
+ Assert.Greater(israel, 2, "Israeli units carry pips");
+ Assert.Greater(arab, 0, "an Arab force carries pips");
+ Assert.IsTrue(layer.Tokens.Any(p => p.Token.StateUnit == null), "fixture: the squadron and the ships are drawn");
+ var egypt = s.Units[SimId(Egypt)];
+ Assert.AreEqual(10, UnitDamage.FullStrength(C, egypt), "fixture: the Egyptian force starts at 10 (units_1948.yaml)");
+ Assert.AreEqual("xxxxx xxxxx", Draw(PipsOn(Badge(Egypt))), "\"Rows of five (Recommended)\": 10 is two rows of five");
+ }
+
+ /// <summary>"A. Pips on badge (Recommended)": a damaged unit shows filled pips for the strength left, then hollow ones
+ /// for the strength lost (3 of 4: x x x o), by shape (a disc, a ring), not colour alone; the pips follow the sim through
+ /// another loss and clear when a reinforce refills the unit (Full back to 0). A change in Full alone redraws them too.</summary>
+ [Test]
+ public void ADamagedUnitShowsHollowPipsForItsLossesAndAReinforceClearsThem()
+ {
+ var s = NewGame();
+ int id = SimId(Golani);
+ foreach (var (strength, full, want) in new[] { (3, 4, "xxxo"), (2, 4, "xxoo"), (1, 4, "xooo"), (4, 0, "xxxx"), (3, 0, "xxx"), (3, 4, "xxxo") })
+ {
+ SetStrength(s, id, strength, full);
+ layer!.Show(C, s);
+ var pips = PipsOn(Badge(Golani));
+ Assert.AreEqual(want, Draw(pips), $"{strength} with Full {full}");
+ Assert.AreEqual(1, Rows(pips).Count, "four or fewer pips stand in one row");
+ for (int i = 1; i < pips.Count; i++) Assert.Greater(pips[i].Centre.x, pips[i - 1].Centre.x, "filled first, from the left");
+ }
+ }
+
+ /// <summary>"Rows of five (Recommended)": one pip per unit, five to a row; a unit of 10 at 7 shows a full top row and
+ /// x x o o o under it; 5 is one row; above 10 a third row.</summary>
+ [Test]
+ public void ALargeUnitShowsItsPipsInRowsOfFive()
+ {
+ var s = NewGame();
+ int id = SimId(Golani);
+ foreach (var (strength, full) in new[] { (5, 0), (6, 0), (7, 10), (10, 0), (4, 10), (12, 0) })
+ {
+ SetStrength(s, id, strength, full);
+ layer!.Show(C, s);
+ int f = full > 0 ? full : strength;
+ var pips = PipsOn(Badge(Golani));
+ Assert.AreEqual(Want(strength, f), Draw(pips), $"{strength} of {f}");
+ var rows = Rows(pips);
+ Assert.AreEqual((f + 4) / 5, rows.Count, $"{strength} of {f}: rows of five");
+ for (int r = 1; r < rows.Count; r++)
+ Assert.Less(rows[r][0].Centre.y, rows[r - 1][0].Centre.y, "each next row stands under the last");
+ }
+ }
+
+ /// <summary>"All 3 as recommended (Recommended)": the pips stand in a strip inside the plate, under the glyph, which is
+ /// drawn smaller than the 0.5-tall army glyph so they fit; the plate keeps its 1 x 1 mesh and its scale (the click box,
+ /// the label keep-clear box and the 0.055 screen cap all read the plate). The pips stay big enough to read at the
+ /// gameplay zoom: up to 10, each at least 0.09 of the plate across (about 5 of the plate's 59 pixels).</summary>
+ [Test]
+ public void ThePipsStandInsideThePlateUnderASmallerGlyph()
+ {
+ var s = NewGame();
+ int id = SimId(Golani);
+ for (int full = 1; full <= 12; full++)
+ {
+ SetStrength(s, id, full - 1 > 0 ? full - 1 : full, full);
+ layer!.Show(C, s);
+ var badge = Badge(Golani);
+ var plate = badge.Find("Plate");
+ var plateBox = plate.GetComponent<MeshFilter>().sharedMesh.bounds;
+ Assert.AreEqual(1f, plateBox.size.x, 1e-3f, "the plate is 1 wide"); Assert.AreEqual(1f, plateBox.size.y, 1e-3f, "and 1 tall");
+ Assert.AreEqual(Vector3.one, plate.localScale, "at the badge's own scale");
+ var glyph = badge.Find("Glyph");
+ var glyphBox = glyph.GetComponent<MeshFilter>().sharedMesh.bounds;
+ Assert.Less(glyphBox.size.y, 0.45f, $"{full}: the glyph is drawn smaller to make room");
+ var pips = PipsOn(badge);
+ Assert.AreEqual(full, pips.Count, $"{full}: one pip per unit");
+ foreach (var p in pips)
+ {
+ Assert.IsTrue(InsidePlate(p.Centre, p.Radius + 0.02f), $"{full}: the pip at {p.Centre} (r {p.Radius:0.000}) is inside the plate");
+ Assert.Less(p.Centre.y + p.Radius, glyphBox.min.y + glyph.localPosition.y, $"{full}: the pip at {p.Centre} is under the glyph");
+ if (full <= 10) Assert.GreaterOrEqual(2f * p.Radius, 0.09f, $"{full}: the pip reads at the gameplay zoom");
+ }
+ }
+ }
+
+ /// <summary>Whether a circle of <paramref name="r"/> at <paramref name="c"/> is inside UnitBadge.PlateMesh's rounded
+ /// square (1 x 1, corner radius 0.22).</summary>
+ static bool InsidePlate(Vector2 c, float r)
+ {
+ var q = new Vector2(Mathf.Abs(c.x), Mathf.Abs(c.y));
+ const float half = 0.5f, rad = 0.22f;
+ if (q.x <= half - rad || q.y <= half - rad) return q.x + r <= half && q.y + r <= half;
+ return (q - new Vector2(half - rad, half - rad)).magnitude + r <= rad;
+ }
+
+ /// <summary>"All 3 as recommended (Recommended)": the same order in both languages. The pips are a count, not text: with
+ /// the process in Hebrew (he-IL) every badge's pips are the ones it has in English, filled first from the left.</summary>
+ [Test]
+ public void ThePipsReadTheSameWayInHebrew()
+ {
+ var s = NewGame();
+ SetStrength(s, SimId(Golani), 3, 4);
+ string Drawn()
+ {
+ layer!.Show(C, s, slide: false);
+ return string.Join("\n", layer.Tokens.Select(p => p.Token.Unit.Id + " " + Draw(PipsOn(Badge(p.Token.Unit.Id)))
+ + " " + string.Join(",", PipsOn(Badge(p.Token.Unit.Id)).Select(x => x.Centre.x.ToString("0.000", CultureInfo.InvariantCulture)))));
+ }
+ var culture = CultureInfo.CurrentCulture; var ui = CultureInfo.CurrentUICulture;
+ string english, hebrew;
+ try
+ {
+ CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo("en-US");
+ english = Drawn();
+ if (layer != null) Object.DestroyImmediate(layer.gameObject);
+ layer = UnitLayer.Create(map, Units, C.Hexes, still: true);
+ CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo("he-IL");
+ hebrew = Drawn();
+ }
+ finally { CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = ui; }
+ StringAssert.Contains(Golani + " xxxo ", english, "fixture: the damaged unit's pips");
+ Assert.AreEqual(english, hebrew, "the same pips in the same order in both languages");
+ }
+
+ /// <summary>#2432: the end-turn Dim shades the pips with the rest of the badge (each at UnitLayer.DimShade of its own
+ /// colour) and lifts it again.</summary>
+ [Test]
+ public void ThePipsDimWithTheBadge()
+ {
+ layer!.Show(C, NewGame());
+ var pips = Badge(Golani).Find("Pips");
+ Assert.IsNotNull(pips, "golani's badge carries pips");
+ var r = pips.GetComponent<Renderer>();
+ Assert.AreSame(Badge(Golani).Find("Glyph").GetComponent<Renderer>().sharedMaterial, r.sharedMaterial,
+ "the pips use the glyph's unlit badge material");
+ var block = new MaterialPropertyBlock();
+ layer.Dim(new[] { Golani });
+ r.GetPropertyBlock(block);
+ var own = r.sharedMaterial.color;
+ var want = new Vector4(own.r * UnitLayer.DimShade, own.g * UnitLayer.DimShade, own.b * UnitLayer.DimShade, own.a);
+ Assert.Less(Vector4.Distance(want, (Vector4)block.GetColor("_BaseColor")), 1e-3f, "the pips dim with the badge");
+ layer.Dim(new string[0]);
+ r.GetPropertyBlock(block);
+ Assert.IsTrue(block.isEmpty, "and come back with it");
+ }
+
+ /// <summary>#2432 "at most 2.5 ms", no per-frame work: the pips are children of the badge, built with the tokens, so
+ /// turning the badges to a moving camera allocates nothing.</summary>
+ [Test]
+ public void FacingBadgesWithPipsDoesNotAllocate()
+ {
+ var eye = new GameObject("PipsCamera");
+ try
+ {
+ layer!.Show(C, NewGame());
+ Assert.IsNotNull(Badge(Golani).Find("Pips"), "golani's badge carries pips");
+ var cam = eye.AddComponent<Camera>(); cam.farClipPlane = 1e6f;
+ cam.transform.position = Badge(Golani).position + new Vector3(0f, 20000f, -30000f);
+ for (int k = 0; k < 5; k++) { cam.transform.Rotate(0f, 0.1f, 0f); layer.FaceCamera(cam); }
+ Assert.That(() => { for (int k = 0; k < 50; k++) { cam.transform.Rotate(0f, 0.1f, 0f); layer.FaceCamera(cam); } }, Is.Not.AllocatingGCMemory());
+ }
+ finally { Object.DestroyImmediate(eye); }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/UnitBadgePipsTests.cs.meta b/unity/Assets/Tests/EditMode/UnitBadgePipsTests.cs.meta
new file mode 100644
index 000000000..f01b197f2
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitBadgePipsTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 2343572c69a14072879b7f0e45c84627
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/UnitPipsShots.cs b/unity/Assets/Tests/EditMode/UnitPipsShots.cs
new file mode 100644
index 000000000..7ef13fa73
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitPipsShots.cs
@@ -0,0 +1,118 @@
+#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.Collection;
+using Statecraft.Game.Map.Units;
+using Statecraft.Sim;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using Object = UnityEngine.Object;
+
+/// <summary>Writes the stills #2432 asks for (#2960 PR 2): a full, a damaged and a badly damaged unit's badge pips, on both
+/// sides, at the gameplay zoom (31 km, yaw 10 as PromoPose.Gameplay03) and from 60 km (nearer, the badge leaves the top of
+/// the frame at this look-at point), to `.superpowers/shots-2960/&lt;SHOTS_TAG&gt;/`
+/// at the repository root (local, not committed; "untagged" when SHOTS_TAG is unset). Each still is the map camera at
+/// 1920x1080 without the UI, plus a 4x crop round the unit's badge. The figures come from the AssetDatabase. Explicit, so it
+/// does not run with the checks.</summary>
+[Explicit("writes stills for a pull request, not a check")]
+public class UnitPipsShots
+{
+ const int Width = 1920, Height = 1080, Crop = 120, Zoom = 4;
+ static readonly Content C = ContentLoader.Load(Paths.Content);
+
+ [Test]
+ public void FullDamagedAndBadlyDamaged()
+ {
+ var tag = Environment.GetEnvironmentVariable("SHOTS_TAG");
+ var dir = Path.GetFullPath(Path.Combine(Application.dataPath, "..", "..", ".superpowers", "shots-2960", string.IsNullOrEmpty(tag) ? "untagged" : tag));
+ Directory.CreateDirectory(dir);
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build();
+ UnitFigures.Forget();
+ UnitFigures.Source = (id, detail, done) => done(AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, detail)));
+ var cam = Camera.main; var rig = cam.GetComponent<CameraRig>();
+ ShotCamera.Configure(cam, Width, Height);
+ var rt = new RenderTexture(Width, Height, 24, RenderTextureFormat.ARGB32);
+ try
+ {
+ cam.targetTexture = rt; rig.TopInset = 0f;
+ var units = UnitData.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", UnitData.DefaultFileName)));
+ var layer = UnitLayer.Create(map, units, C.Hexes, still: true);
+ var s = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Clone();
+ var cases = new List<(string name, string row, int strength, int full)>
+ {
+ ("israel-full", "golani", 0, 0), ("israel-damaged", "golani", 3, 4), ("israel-badly", "golani", 1, 4),
+ ("egypt-full", "egyptian_expeditionary_force", 0, 0), ("egypt-damaged", "egyptian_expeditionary_force", 7, 10),
+ ("egypt-badly", "egyptian_expeditionary_force", 2, 10),
+ };
+ foreach (var (name, row, strength, full) in cases)
+ {
+ int id = C.StartingForces.FindIndex(f => f.Row == row);
+ var u = Simulation.NewGame(C, GoldenRun.Seed, Mode.Historical).Units[id];
+ // An enemy's unit keeps no Full (UnitDamage): its starting strength is its full strength.
+ int setFull = u.Side == UnitData.Israel ? full : 0;
+ s.Units[id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, strength > 0 ? strength : u.Strength, u.Order, u.OrderTarget, u.HomeCity, setFull, u.CombatXp);
+ layer.Show(C, s, slide: false);
+ var badge = layer.transform.Find("Tokens/" + row + "/Badge");
+ Assert.IsNotNull(badge, $"{row} is drawn");
+ var at = badge.position; at.y = 0f;
+ foreach (var km in new[] { 31f, 60f })
+ {
+ rig.LookAt = at; rig.Distance = km * 1000f; rig.Yaw = 10f; rig.Apply();
+ for (int i = 0; i < 4; i++) { layer.FaceCamera(cam); UnitFlagFacing.FaceAll(cam.transform.position); cam.Render(); }
+ var px = Read(rt);
+ var still = FormattableString.Invariant($"{name}-{km:0}km");
+ Write(Path.Combine(dir, still + ".png"), px, Width, Height);
+ var sp = cam.WorldToScreenPoint(badge.position);
+ WriteCrop(Path.Combine(dir, still + "-badge.png"), px, Mathf.RoundToInt(sp.x * Width / cam.pixelWidth), Mathf.RoundToInt(sp.y * Height / cam.pixelHeight));
+ Debug.Log(FormattableString.Invariant($"SHOT {still}: {row} {s.Units[id].Strength} of {UnitDamage.FullStrength(C, s.Units[id])}, badge {badge.lossyScale.x:F0} m at ({sp.x:F0}, {sp.y:F0})"));
+ }
+ }
+ }
+ finally
+ {
+ cam.targetTexture = null; rt.Release(); Object.DestroyImmediate(rt);
+ UnitFigures.Source = null; UnitFigures.Forget();
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ }
+ }
+
+ static Color32[] Read(RenderTexture from)
+ {
+ var prev = RenderTexture.active; RenderTexture.active = from;
+ var tex = new Texture2D(from.width, from.height, TextureFormat.RGBA32, false);
+ tex.ReadPixels(new Rect(0, 0, from.width, from.height), 0, 0); tex.Apply();
+ RenderTexture.active = prev;
+ var px = tex.GetPixels32(); Object.DestroyImmediate(tex);
+ return px;
+ }
+
+ static void Write(string path, Color32[] px, int w, int h)
+ {
+ var tex = new Texture2D(w, h, TextureFormat.RGBA32, false);
+ tex.SetPixels32(px); tex.Apply();
+ File.WriteAllBytes(path, tex.EncodeToPNG()); Object.DestroyImmediate(tex);
+ }
+
+ /// <summary>A <see cref="Crop"/>-pixel square round (<paramref name="cx"/>, <paramref name="cy"/>) drawn <see cref="Zoom"/>
+ /// times larger, nearest pixel, so the pips can be counted.</summary>
+ static void WriteCrop(string path, Color32[] px, int cx, int cy)
+ {
+ int size = Crop * Zoom;
+ var outPx = new Color32[size * size];
+ for (int y = 0; y < size; y++)
+ for (int x = 0; x < size; x++)
+ {
+ int sx = Mathf.Clamp(cx - Crop / 2 + x / Zoom, 0, Width - 1), sy = Mathf.Clamp(cy - Crop / 2 + y / Zoom, 0, Height - 1);
+ outPx[y * size + x] = px[sy * Width + sx];
+ }
+ Write(path, outPx, size, size);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/UnitPipsShots.cs.meta b/unity/Assets/Tests/EditMode/UnitPipsShots.cs.meta
new file mode 100644
index 000000000..17ff46dd7
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/UnitPipsShots.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 46f9077b9d78488a86dcc67ce573d98b
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs
index 3c23bae60..0d7cd12fa 100644
--- a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs
+++ b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs
@@ -1157,13 +1157,14 @@ 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");
- // A plate and a glyph show; the hit's flash plate (#2614) is there but off until a hit lands, and nothing else is.
+ // A plate, a glyph and the unit's strength in pips (#2432) 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");
+ CollectionAssert.AreEqual(new[] { "Plate", "Glyph", "Pips" }, badgeRenderers.Where(r => r.enabled).Select(r => r.name).ToArray(), "a plate, a glyph and the pips");
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.AreEqual(4, badgeRenderers.Length, "the plate, the glyph, the pips 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++)
{