A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: hide the kit trees under the shown unit figures at draw time (fixes #249) (#428)
Eyal Golan8bb8141e05a9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex be8b49ce6..068d40fe4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -287,6 +287,9 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBIt decodes to the same bytes, so the terrain is unchanged (#44).### Fixed+- Map: kit orchard trees no longer grow through the unit figures' boots and bases. The trees under each figure drawn now+ are left out at draw time and come back when the figure goes (a later date, or the "units" toggle off, so plain+ screenshot checkpoints keep every tree); the kits' layout does not change (fixes #249).- "The Jews of Iraq" cites two primary sources for its asset freeze and its count of those waiting to fly: the Israeliletter to the Palestine Conciliation Commission of 19 March 1951 and FRUS 1951, vol. V, doc. 340. Its English Wikipediasource puts the first flights a year late (#135) but stays, because it alone covers the transit camps' crowding. Text,diff --git a/docs/units.md b/docs/units.mdindex 1f09a4677..47498901b 100644--- a/docs/units.md+++ b/docs/units.md@@ -195,6 +195,11 @@ checks every anchor and logs each spot and its distance.hills.- **Tests:** `AFigureStandsOnASteepSlopeWithoutSinking` and `NoRiflemanSinksIntoTheHillsOfTheMap`.- **Close-ups** (`MapCapture.Promo -units -extraPose …`, at 12 and 20 km): at 6 km the camera sees only boots.+- **Trees (#249).** The kit trees whose crowns reach a drawn figure's boots (its 400 m foot radius, which is also its+ base's) are left out at draw time (`VegetationLayer.Hide`), so no orchard grows through a figure. Only the figures drawn+ that day clear trees, and they come back when the figure goes. With the `units` toggle off, as in a plain `?shot` run,+ every tree is drawn. The planting, and so the kits' layout, never changes. Tests:+ `NoKitTreeGrowsThroughAShownFiguresFeet` and `OnlyTheShownFiguresTreesGoAndTheToggleBringsThemBack`.**Selection and the card.**- Clicking a token's hex selects it. The ring goes round it and the hex outline is cleared, so it has one highlight.diff --git a/unity/Assets/Scripts/Map/Kits/VegetationLayer.cs b/unity/Assets/Scripts/Map/Kits/VegetationLayer.csindex 4c119f3c8..59434d768 100644--- a/unity/Assets/Scripts/Map/Kits/VegetationLayer.cs+++ b/unity/Assets/Scripts/Map/Kits/VegetationLayer.cs@@ -17,15 +17,25 @@ namespace Statecraft.Game.Map.Kits/// <summary>Tiles nearer than this draw every tree; beyond it the share falls as (ThinStartM / distance)^2.</summary>public const float ThinStartM = 110000f;- sealed class Tile { public TreeKind kind; public Bounds bounds; public Matrix4x4[] m = System.Array.Empty<Matrix4x4>(); }+ /// <summary>A tile's trees: <c>all</c> as planted (shuffled), <c>m</c> the ones drawn (all, less those under a unit+ /// figure: <see cref="Hide"/>), in the same order, so drawing a prefix still thins evenly; <c>crown</c> is the largest+ /// crown radius (m) among them.</summary>+ sealed class Tile { public TreeKind kind; public Bounds bounds; public float crown; public Matrix4x4[] all = System.Array.Empty<Matrix4x4>(), m = System.Array.Empty<Matrix4x4>(); }readonly List<Tile> tiles = new List<Tile>();+ readonly SortedDictionary<string, List<(Vector2 centre, float radius)>> holes = new SortedDictionary<string, List<(Vector2, float)>>(System.StringComparer.Ordinal);readonly Dictionary<TreeKind, Mesh> meshes = new Dictionary<TreeKind, Mesh>();Material? material;public bool Draw { get; set; } = true;public int Count { get; private set; }/// <summary>Instances submitted for the last camera (a test and profiling aid).</summary>public int LastDrawn { get; private set; }+ /// <summary>Trees left out now because they stand under a unit figure (<see cref="Hide"/>).</summary>+ public int Hidden { get; private set; }++ /// <summary>A tree's crown radius (m) as placed: its kind's real crown times the instance's scale, with the planting+ /// margin (Vegetation.Plant keeps a crown this wide off the lots and routes).</summary>+ public static float CrownRadius(TreeKind kind, Matrix4x4 m) => Vegetation.CrownRadiusM(kind) * ((Vector3)m.GetColumn(0)).magnitude * 1.15f;public void Init(List<(TreeKind kind, Matrix4x4 m)> trees, Material treeMaterial, MapRuntimeAssets assets){@@ -50,9 +60,72 @@ namespace Statecraft.Game.Map.Kitsvar b = new Bounds((Vector3)list[0].GetColumn(3), Vector3.zero);foreach (var m in list) b.Encapsulate((Vector3)m.GetColumn(3));b.Expand(new Vector3(400f, 800f, 400f) * (KitScale.Trees / KitScale.CountReference)); // the crowns round the trunk points- tiles.Add(new Tile { kind = key.Item1, bounds = b, m = list.ToArray() });+ float crown = 0f;+ foreach (var m in list) crown = Mathf.Max(crown, CrownRadius(key.Item1, m));+ var arr = list.ToArray();+ tiles.Add(new Tile { kind = key.Item1, bounds = b, crown = crown, all = arr, m = arr });}Count = trees.Count;+ holes.Clear(); Hidden = 0;+ }++ /// <summary>Issue #249: leaves out, at draw time, every tree whose crown reaches into one of <paramref name="where"/>+ /// (centre x, z; radius m): the ground under the unit figures drawn now. Each caller (<paramref name="owner"/>: the+ /// units in play, the showcase) sets its own holes, and an empty list gives its trees back. The planting itself, and+ /// so the kits' layout, never changes; only the tiles a hole reaches are rebuilt, when a caller's holes change (a+ /// roster change), never per frame.</summary>+ public void Hide(string owner, IReadOnlyList<(Vector2 centre, float radius)> where)+ {+ if (where.Count == 0) holes.Remove(owner); else holes[owner] = new List<(Vector2, float)>(where);+ var all = new List<(Vector2 centre, float radius)>();+ foreach (var h in holes.Values) all.AddRange(h);+ int hidden = 0;+ var keep = new List<Matrix4x4>();+ foreach (var t in tiles)+ {+ if (!Reaches(t, all)) { t.m = t.all; continue; }+ keep.Clear();+ foreach (var m in t.all)+ {+ if (Covered(t.kind, m, all)) hidden++; else keep.Add(m);+ }+ t.m = keep.Count == t.all.Length ? t.all : keep.ToArray();+ }+ Hidden = hidden;+ }++ static bool Reaches(Tile t, List<(Vector2 centre, float radius)> where)+ {+ foreach (var (c, r) in where)+ {+ float reach = r + t.crown;+ float dx = Mathf.Max(t.bounds.min.x - c.x, 0f, c.x - t.bounds.max.x), dz = Mathf.Max(t.bounds.min.z - c.y, 0f, c.y - t.bounds.max.z);+ if (dx * dx + dz * dz < reach * reach) return true;+ }+ return false;+ }++ static bool Covered(TreeKind kind, Matrix4x4 m, List<(Vector2 centre, float radius)> where)+ {+ var p = m.GetColumn(3); float crown = CrownRadius(kind, m);+ foreach (var (c, r) in where)+ {+ float dx = p.x - c.x, dz = p.z - c.y, reach = r + crown;+ if (dx * dx + dz * dz < reach * reach) return true;+ }+ return false;+ }++ /// <summary>Every tree as planted, hidden or not (kind, world matrix): a test aid.</summary>+ public IEnumerable<(TreeKind kind, Matrix4x4 m)> Planted()+ {+ foreach (var t in tiles) foreach (var m in t.all) yield return (t.kind, m);+ }++ /// <summary>The trees a camera near enough to draw every tree would submit now (kind, world matrix): a test aid.</summary>+ public IEnumerable<(TreeKind kind, Matrix4x4 m)> Drawable()+ {+ foreach (var t in tiles) foreach (var m in t.m) yield return (t.kind, m);}void OnEnable() => RenderPipelineManager.beginCameraRendering += Submit;diff --git a/unity/Assets/Scripts/Map/Units/UnitLayer.cs b/unity/Assets/Scripts/Map/Units/UnitLayer.csindex 1e937c02e..05b09efc6 100644--- a/unity/Assets/Scripts/Map/Units/UnitLayer.cs+++ b/unity/Assets/Scripts/Map/Units/UnitLayer.cs@@ -35,6 +35,7 @@ namespace Statecraft.Game.Map.UnitsList<PlacedToken> placed = new List<PlacedToken>();Transform tokensRoot = null!;readonly List<Transform> badges = new List<Transform>();+ readonly List<(Vector2 centre, float radius)> treeHoles = new List<(Vector2, float)>();GameObject? ring;bool still;@@ -82,7 +83,14 @@ namespace Statecraft.Game.Map.Unitslayer.badgeGlyph = layer.assets.Own(new Material(ringTemplate) { name = "UnitBadge (glyph)", color = UnitBadge.GlyphColour });layer.tokensRoot = new GameObject("Tokens").transform;layer.tokensRoot.SetParent(root.transform, false);- layer.assets.OnTeardown(VisualToggles.Register(ToggleName, on => { if (root != null) root.SetActive(on); }));+ // The kit trees under the figures are left out while the layer shows (issue #249), and come back with the layer+ // off: a plain screenshot run (HiddenInCaptures) keeps every tree, so its checkpoints stay comparable.+ layer.assets.OnTeardown(() => UnitShowcase.HideTrees(map, ToggleName, Array.Empty<(Vector2, float)>()));+ layer.assets.OnTeardown(VisualToggles.Register(ToggleName, on =>+ {+ if (root != null) root.SetActive(on);+ if (layer != null) layer.HideTrees();+ }));return layer;}@@ -94,6 +102,11 @@ namespace Statecraft.Game.Map.Unitsvoid OnEnable() => RenderPipelineManager.beginCameraRendering += FaceBadges;void OnDisable() => RenderPipelineManager.beginCameraRendering -= FaceBadges;+ /// <summary>The kit trees under the drawn figures, left out while the layer shows (issue #249).</summary>+ public IReadOnlyList<(Vector2 centre, float radius)> TreeHoles => treeHoles;++ void HideTrees() => UnitShowcase.HideTrees(map, ToggleName, gameObject.activeSelf ? treeHoles : (IReadOnlyList<(Vector2, float)>)Array.Empty<(Vector2, float)>());+/// <summary>Turns every badge to face the camera about to render (game, editor capture or scene view alike).</summary>void FaceBadges(ScriptableRenderContext _, Camera cam){@@ -181,6 +194,7 @@ namespace Statecraft.Game.Map.Unitsif (Application.isPlaying) Destroy(old); else DestroyImmediate(old);}badges.Clear();+ treeHoles.Clear();float hex = map.Hexes.hex_size_km * 1000f;foreach (var p in placed){@@ -204,6 +218,7 @@ namespace Statecraft.Game.Map.Unitsvar figure = UnitShowcase.Piece(go.transform, $"Rifleman{i}", type, () => MeshFor($"{type}/{pose}", () => UnitModels.Rifleman(hat, pose, faded, type)),paint, at, Quaternion.Euler(0, heading, 0), UnitShowcase.FigureScale, out _);UnitShowcase.AddBase(map, figure.transform, at, MeshFor("figure-base", () => UnitShowcase.BaseMesh("UnitFigureBase")), paint);+ treeHoles.Add(UnitShowcase.TreeHole(at));}top = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;break;@@ -228,6 +243,7 @@ namespace Statecraft.Game.Map.UnitsAddRenderer(badge.transform, "Plate", MeshFor("badge-plate", UnitBadge.PlateMesh), badgePlate, 0f);AddRenderer(badge.transform, "Glyph", MeshFor("badge-" + t.Unit.Service, () => UnitBadge.GlyphMesh(t.Unit.Service)), badgeGlyph, -UnitBadge.GlyphLift);}+ HideTrees();}static void AddRenderer(Transform parent, string name, Mesh mesh, Material mat, float z)diff --git a/unity/Assets/Scripts/Map/Units/UnitShowcase.cs b/unity/Assets/Scripts/Map/Units/UnitShowcase.csindex 4acef2a3f..ce9db2000 100644--- a/unity/Assets/Scripts/Map/Units/UnitShowcase.cs+++ b/unity/Assets/Scripts/Map/Units/UnitShowcase.cs@@ -123,10 +123,12 @@ namespace Statecraft.Game.Map.Units// The trio: three riflemen in a loose triangle facing the camera's side of south-west, around the hex's centre.var centre = HexCentreNear(map, TrioAt.lon, TrioAt.lat);var looks = Trio;+ var holes = new List<(Vector2 centre, float radius)>();for (int i = 0; i < looks.Length; i++){var (type, hat, pose, faded, offset, heading) = looks[i];var p = Stand(map, centre + new Vector3(offset.x, 0, offset.y) * TrioSpread * hex);+ holes.Add(TreeHole(p));Piece(root.transform, $"Rifleman{i}", type, () => Built(UnitModels.Rifleman(hat, pose, faded, $"Rifleman1948-{i}")),paint, p, Quaternion.Euler(0, heading, 0), FigureScale);}@@ -153,10 +155,32 @@ namespace Statecraft.Game.Map.UnitsPiece(root.transform, "Corvette1948", CorvetteType, () => Built(UnitModels.Corvette("CorvetteK20")), paint, ship,Quaternion.Euler(0, ShipHeadingDegrees, 0), ShipScale);- assets.OnTeardown(VisualToggles.Register(ToggleName, on => { if (root != null) root.SetActive(on); }));+ HideTrees(map, ToggleName, holes);+ assets.OnTeardown(() => HideTrees(map, ToggleName, NoHoles));+ assets.OnTeardown(VisualToggles.Register(ToggleName, on =>+ {+ if (root != null) root.SetActive(on);+ HideTrees(map, ToggleName, on ? holes : NoHoles);+ }));return root;}+ static readonly IReadOnlyList<(Vector2 centre, float radius)> NoHoles = Array.Empty<(Vector2, float)>();++ /// <summary>The ground a figure standing at <paramref name="feet"/> keeps free of kit trees (issue #249): its boots'+ /// radius, which is also its base's (<see cref="AddBase"/>). Its legs, body and rifle are far above every crown.</summary>+ public static (Vector2 centre, float radius) TreeHole(Vector3 feet) => (new Vector2(feet.x, feet.z), FootRadiusM);++ /// <summary>Leaves out the map's kit trees under <paramref name="holes"/> for <paramref name="owner"/> (an empty list+ /// gives them back), at draw time (Kits.VegetationLayer.Hide), so the kits' layout never changes. A map without kits+ /// has no trees to hide.</summary>+ internal static void HideTrees(MapScene map, string owner, IReadOnlyList<(Vector2 centre, float radius)> holes)+ {+ if (map == null) return;+ var veg = map.GetComponentInChildren<Kits.VegetationLayer>(true);+ if (veg != null) veg.Hide(owner, holes);+ }+/// <summary>One unit model: the authored prefab for <paramref name="type"/> when there is one (the art hook),/// otherwise the code-built mesh.</summary>static GameObject Piece(Transform parent, string name, string type, Func<Mesh> codeBuilt, Material paint, Vector3 position,diff --git a/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs b/unity/Assets/Tests/EditMode/UnitShowcaseTests.csindex 3106f1e0c..a004e9dc7 100644--- a/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs+++ b/unity/Assets/Tests/EditMode/UnitShowcaseTests.cs@@ -161,6 +161,32 @@ public class UnitShowcaseTestsreturn list;}+ /// <summary>Issue #249: the showcase trio leaves out the kit trees under its boots, and its toggle gives them back.</summary>+ [Test]+ public void TheShowcaseTrioStandsClearOfTheTrees()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = Object.FindFirstObjectByType<MapScene>();+ map.Build();+ try+ {+ var veg = map.GetComponentInChildren<Statecraft.Game.Map.Kits.VegetationLayer>(true);+ Assert.IsNotNull(veg, "the kits and their trees are on");+ var root = UnitShowcase.Spawn(map, still: true);+ var feet = Enumerable.Range(0, 3).Select(i => root.transform.Find("Rifleman" + i).position).Select(p => new Vector2(p.x, p.z)).ToList();+ bool Under(Statecraft.Game.Map.Kits.TreeKind k, Matrix4x4 m)+ {+ var p = m.GetColumn(3); float reach = UnitShowcase.FootRadiusM + Statecraft.Game.Map.Kits.VegetationLayer.CrownRadius(k, m);+ return feet.Any(f => (f - new Vector2(p.x, p.z)).sqrMagnitude < reach * reach);+ }+ Assert.IsFalse(veg.Drawable().Any(t => Under(t.kind, t.m)), "no drawn tree reaches the trio's boots");+ Assert.AreEqual(veg.Planted().Count(t => Under(t.kind, t.m)), veg.Hidden, "only the trio's trees are left out");+ VisualToggles.Set(UnitShowcase.ToggleName, false);+ Assert.AreEqual(0, veg.Hidden, "the showcase off gives them back");+ }+ finally { if (VisualToggles.Names.Contains(UnitShowcase.ToggleName)) VisualToggles.Set(UnitShowcase.ToggleName, true); Object.DestroyImmediate(map.gameObject); }+ }+[Test]public void SpawnBuildsTheSliceAtGameplay03AndTheToggleHidesIt(){diff --git a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs b/unity/Assets/Tests/EditMode/UnitsInPlayTests.csindex 2921a16ea..fcfa173a2 100644--- a/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs+++ b/unity/Assets/Tests/EditMode/UnitsInPlayTests.cs@@ -433,6 +433,95 @@ public class UnitsInPlayTestsfinally { UnityEngine.Object.DestroyImmediate(map.gameObject); }}+ static readonly DateTime[] OrchardDates = { new DateTime(1948, 5, 29), new DateTime(1948, 6, 5), new DateTime(1948, 7, 12), new DateTime(1948, 12, 4) };++ /// <summary>The game's map scene with its kits and trees on (BuildMap configures no kit materials).</summary>+ static MapScene BuildMapWithTrees()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>();+ Statecraft.Game.Map.Kits.KitPopulation.Use(Statecraft.Game.Map.Kits.KitPopulation.Parse(+ File.ReadAllText(Path.Combine(Paths.Content, "map", Statecraft.Game.Map.Kits.KitPopulation.FileName))));+ map.Build();+ return map;+ }++ static List<Vector2> FigureFeet(MapScene map) =>+ map.Terrain.transform.Find(UnitLayer.RootName).Find("Tokens").GetComponentsInChildren<Transform>()+ .Where(t => t.name.StartsWith("Rifleman")).Select(t => new Vector2(t.position.x, t.position.z)).ToList();++ static bool UnderAFigure(Statecraft.Game.Map.Kits.TreeKind kind, Matrix4x4 m, List<Vector2> feet)+ {+ var p = m.GetColumn(3); var at = new Vector2(p.x, p.z);+ float reach = UnitShowcase.FootRadiusM + Statecraft.Game.Map.Kits.VegetationLayer.CrownRadius(kind, m);+ return feet.Any(f => (f - at).sqrMagnitude < reach * reach);+ }++ /// <summary>Issue #249: on every date the units are checked on, no kit tree that is drawn has its crown within a shown+ /// figure's boots (the boot radius plus the tree's crown radius), and some trees were in the way, so the check bites.</summary>+ [Test]+ public void NoKitTreeGrowsThroughAShownFiguresFeet()+ {+ var map = BuildMapWithTrees();+ try+ {+ var veg = map.GetComponentInChildren<Statecraft.Game.Map.Kits.VegetationLayer>(true);+ Assert.IsNotNull(veg, "the kits and their trees are on");+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ int figures = 0, hidden = 0;+ foreach (var d in OrchardDates)+ {+ layer.Show(C, StateAt(d, 5, 0.8));+ var feet = FigureFeet(map);+ Assert.Greater(feet.Count, 0, $"{d:yyyy-MM-dd}: figures are drawn");+ var through = veg.Drawable().Where(t => UnderAFigure(t.kind, t.m, feet)).ToList();+ Assert.IsEmpty(through, $"{d:yyyy-MM-dd}: {through.Count} drawn trees reach a figure's boots, the first at {(through.Count > 0 ? (Vector3)through[0].m.GetColumn(3) : Vector3.zero)}");+ figures += feet.Count; hidden += veg.Hidden;+ TestContext.WriteLine($"{d:yyyy-MM-dd}: {feet.Count} figures, {veg.Hidden} trees left out");+ }+ Assert.Greater(hidden, 0, "some figure stands where trees grow, so this test can fail");+ }+ finally { UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Issue #249: only the trees under the figures drawn that day are left out (a token not shown that day leaves+ /// its trees alone, so Lydda's come back after Yiftach's window); the planting never changes; and with the "units"+ /// toggle off (a plain screenshot run) every tree is drawn, so plain checkpoints stay comparable (review I5).</summary>+ [Test]+ public void OnlyTheShownFiguresTreesGoAndTheToggleBringsThemBack()+ {+ var map = BuildMapWithTrees();+ try+ {+ var veg = map.GetComponentInChildren<Statecraft.Game.Map.Kits.VegetationLayer>(true);+ var planted = veg.Planted().Select(t => t.m).ToList();+ var layer = UnitLayer.Create(map, Units, C.Hexes, still: true);+ foreach (var d in OrchardDates.Concat(new[] { new DateTime(1948, 7, 25) }))+ {+ layer.Show(C, StateAt(d, 5, 0.8));+ var feet = FigureFeet(map);+ int expected = veg.Planted().Count(t => UnderAFigure(t.kind, t.m, feet));+ Assert.AreEqual(expected, veg.Hidden, $"{d:yyyy-MM-dd}: exactly the trees under the shown figures are left out");+ Assert.AreEqual(veg.Count - expected, veg.Drawable().Count(), $"{d:yyyy-MM-dd}: every other tree is drawn");+ }+ CollectionAssert.AreEqual(planted, veg.Planted().Select(t => t.m).ToList(), "the planting (the kits' layout) never changes");++ Assert.Greater(veg.Hidden, 0);+ VisualToggles.Set(UnitLayer.ToggleName, false);+ Assert.AreEqual(0, veg.Hidden, "the layer off gives every tree back");+ Assert.AreEqual(veg.Count, veg.Drawable().Count());+ VisualToggles.Set(UnitLayer.ToggleName, true);+ Assert.Greater(veg.Hidden, 0, "and on again leaves them out again");++ // A screenshot run that does not ask for the units: the toggle is off before the first draw.+ var shot = UnitLayer.Create(map, Units, C.Hexes, still: true);+ VisualToggles.Set(UnitLayer.ToggleName, false);+ shot.Show(C, StateAt(OrchardDates[0], 5, 0.8));+ Assert.AreEqual(0, veg.Hidden, "a plain checkpoint draws every tree");+ }+ finally { if (VisualToggles.Names.Contains(UnitLayer.ToggleName)) VisualToggles.Set(UnitLayer.ToggleName, true); UnityEngine.Object.DestroyImmediate(map.gameObject); }+ }+[Test]public void TheTrioIsSpreadSoEachFigureReadsOnItsOwn(){