A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: Tal Heuberger's hex props on the main map, and the railway halt on the hex board (Refs #2007) (#2266)
Eyal Golan42401a17f6f1
diff --git a/changelog.d/tal-hex-props.md b/changelog.d/tal-hex-props.mdnew file mode 100644index 000000000..88927df15--- /dev/null+++ b/changelog.d/tal-hex-props.md@@ -0,0 +1,11 @@+- Tal Heuberger's hex-tile props on the main map (Refs #2007, #1155). Up close only:+ - the railway halt's station building at 17 of the 20 stations the 1948 railways name (Jaffa, Jerusalem's Khan and+ Haifa East stand inside their cities and get none);+ - a goat-hair tent beside each of the 64 Bedouin camps;+ - a prickly-pear hedge of 3 to 5 clumps along the edge of each Arab village with clear ground;+ - a light scatter of garrigue and scrub on open hill ground.+- Tal Heuberger's minaret, belfry and Jaffa clock tower now stand in place of the kit's code-built ones, at every zoom+ where the kit draws them. The kit keeps its own parts while the props stream, and for good if they fail. The+ hex-props bundle streams after the first frame.+- The `israel` hex board puts the railway-halt tile on the five free hexes that hold a named station (Atlit,+ Binyamina, Qaqun, Rosh HaAyin South and Beit Shemesh).diff --git a/tools/hex_tiles/make_board.py b/tools/hex_tiles/make_board.pyindex 93076e127..38aafb4d3 100644--- a/tools/hex_tiles/make_board.py+++ b/tools/hex_tiles/make_board.py@@ -231,6 +231,21 @@ def flora_entry(region):'rock': rock.get('model', 'sandbox:limestone*'), 'rockChance': float(rock.get('chance', 0.6)), 'rocksOnFlat': bool(rock.get('on_flat', False))}+def rail_stations(path, before):+ """The named stations of the 1948 railways (routes_1948.yaml): every `via` waypoint of a rail route the map draws+ before the given date whose name says "station", once, by name: (name, lon, lat). A bare year is its 1 January, as+ the map reads it (RoutePaths.Bound)."""+ out = {}+ for r in _yaml(path)['routes']:+ if r.get('kind') != 'rail': continue+ start = str(r['from']); start = start + '-01-01' if len(start) == 4 else start+ end = r.get('to'); end = None if end is None else (str(end) + '-01-01' if len(str(end)) == 4 else str(end))+ if not (start < before and (end is None or before < end)): continue+ for w in r.get('via', []):+ if 'station' in w['name'].lower(): out.setdefault(w['name'], (w['name'], float(w['lon']), float(w['lat'])))+ return sorted(out.values())++def route_roads(cells, kinds, before):"""Roads along the traced 1948 routes (route_paths_1948.tsv): each route's points snapped to their nearest boardland hex, gaps joined along hex lines; only routes of the given kinds that the map draws before the given date."""@@ -435,6 +450,17 @@ def build_board(a):h = nearest(s['lon'], s['lat']); k = (h['q'], h['r'])if k in owner or not h['land'] or env_of(k): continueowner[k] = s+ # Then the railways' named stations (defaults.stations): a free land hex holding one takes the halt tile, so the+ # station stands where the map's railway data names it. A settlement's hex keeps its own tile; the first station by+ # name keeps a hex two would share.+ halts = {}+ if recipes and 'stations' in recipes.defaults:+ st = recipes.defaults['stations']+ for name, lon, lat in rail_stations(os.path.join(ROOT, 'content/map/routes_1948.yaml'), str(st.get('before', '1948-05-15'))):+ if not in_box({'lon': lon, 'lat': lat}): continue+ h = nearest(lon, lat); k = (h['q'], h['r'])+ if k in owner or k in halts or not h['land'] or env_of(k): continue+ halts[k] = nameout, used_regions = [], set()lowland = recipes.defaults.get('lowland', LOWLAND) if recipes else LOWLAND@@ -466,6 +492,8 @@ def build_board(a):e['prototype'] = SETTLEMENT_TILE.get(s['id'], TYPE_TILE.get(s.get('type'), 'moshava_village'))e['note'] = s['id']if e['prototype'] in ('tel_aviv_city', 'moshava_village', 'kibbutz') and terrain == 'mountain': e['terrain'] = 'hills'+ elif k in halts:+ e['prototype'], e['note'] = recipes.defaults['stations']['prototype'], halts[k]elif recipes:e['prototype'], ground, set_terrain = apply_rule(recipes.rules(region, 'nature'), k[0], k[1], terrain=terrain, biome=h['biome'], coastal=coastal)if set_terrain: e['terrain'] = set_terraindiff --git a/tools/hex_tiles/regions.yaml b/tools/hex_tiles/regions.yamlindex 7cf27294d..a883bd62d 100644--- a/tools/hex_tiles/regions.yaml+++ b/tools/hex_tiles/regions.yaml@@ -61,6 +61,9 @@ defaults:# Roads follow the traced 1948 routes (content/map/route_paths_1948.tsv) of these kinds that the map draws before# this date.roads: {kinds: [road], before: '1948-05-15'}+ # The railways' named stations (content/map/routes_1948.yaml: a rail route's `via` waypoint whose name says "station",+ # on a route the map draws before this date): a free land hex holding one takes this tile (the railway halt, #1155).+ stations: {prototype: railway_halt, before: '1948-05-15'}units:- {unit: palmach_squad, near: tel_aviv, facing: 40}- {unit: sandwich_truck, near: ramla, facing: 100}diff --git a/tools/tests/test_hex_regions.py b/tools/tests/test_hex_regions.pyindex 6e970c51c..78eef5c25 100644--- a/tools/tests/test_hex_regions.py+++ b/tools/tests/test_hex_regions.py@@ -47,7 +47,7 @@ def test_the_whole_country_is_deterministic(country):def test_default_country_balances_villages_and_regional_landscape(country):hexes = {(h["q"], h["r"]): h for h in country["hexes"]}assert sum(h["prototype"] == "arab_village" for h in hexes.values()) == 67 # 4.4 km hexes since #1183- assert sum(bool(h["note"]) for h in hexes.values()) == 97 # Hanita kept out of the fringe (owner, 26 October 2026, #1183)+ assert sum(bool(h["note"]) for h in hexes.values()) == 97 + 5 # Hanita kept out of the fringe (owner, 26 October 2026, #1183); 5 haltsvariants = {h["prototype"] for h in hexes.values() if re.fullmatch(r"(wheat_fields|citrus_orchard|olive_terraces|mixed_farm|forest)_(north|centre|south)_[ab]", h["prototype"])}assert len(variants) == 22 # 16 on the 5 km grid@@ -59,6 +59,23 @@ def test_default_country_balances_villages_and_regional_landscape(country):assert core <= {h["note"] for h in hexes.values()}+def test_the_railways_named_stations_take_the_halt_tile_on_free_land_hexes(country):+ """Owner, 27 October 2026, "2+3": Tal Heuberger's railway-halt props go on the board where the map's railway data names+ a station (routes_1948.yaml, a rail route's `via` waypoint whose name says "station", drawn before 15 May 1948). A+ station on a settlement's hex leaves that hex's own tile; no halt stands anywhere else."""+ halts = {(h["q"], h["r"]): h["note"] for h in country["hexes"] if h["prototype"] == "railway_halt"}+ assert halts == {(4, 11): "Atlit railway station", (2, 14): "Binyamina railway station", (2, 16): "Qaqun (Ahituv station)",+ (-1, 21): "Rosh HaAyin South railway station", (-4, 27): "Beit Shemesh railway station (Artuf)"}+ names = [n for n, _, _ in mb.rail_stations(str(ROOT / "content/map/routes_1948.yaml"), "1948-05-15")]+ assert len(names) == 18 and set(halts.values()) <= set(names)+ # The Yarkon link's two stations are drawn only from 20 September 1949.+ assert "Tel Aviv North railway station" not in names+ assert "Tel Aviv North railway station" in [n for n, _, _ in mb.rail_stations(str(ROOT / "content/map/routes_1948.yaml"), "1949-09-21")]+ # Every hex a settlement holds keeps its settlement tile.+ settled = {h["note"] for h in country["hexes"] if h["note"] and h["prototype"] != "railway_halt"}+ assert len(settled) == 97++def test_published_country_matches_its_region_recipes(country):published = json.loads((ROOT / "unity/Assets/Resources/HexTiles/Boards/israel.json").read_text())assert published == countrydiff --git a/unity/Assets/Editor/HexPropsBundle.cs b/unity/Assets/Editor/HexPropsBundle.csindex 7e33abc00..59d9cb847 100644--- a/unity/Assets/Editor/HexPropsBundle.cs+++ b/unity/Assets/Editor/HexPropsBundle.cs@@ -7,7 +7,8 @@ using UnityEditor;namespace Statecraft.Game.EditorTools{/// <summary>The hex tiles' props bundles (<see cref="HexProps"/>; owner, 23 October 2026: "Own streamed bundle"): one- /// bundle of the prop prefabs, and the papyrus alone in a second (the main map's Hula asks for it without the rest), whose+ /// bundle of the prop prefabs, the papyrus alone in a second (the main map's Hula asks for it without the rest) and the+ /// tamarisk alone in a third (boards only, so the main map's first camera does not fetch it), whose/// models, materials and colour maps come in as dependencies, built by the/// Collection's bundle build into StreamingAssets/<see cref="HexProps.StreamingFolder"/> with its own checks file./// Every Build.* player build runs it after The 1948 Collection's; HexPropsTests pins what it carries.</summary>@@ -20,6 +21,7 @@ namespace Statecraft.Game.EditorTools{new AssetBundleBuild { assetBundleName = HexProps.Bundle, assetNames = HexProps.Ids.Where(id => HexProps.BundleOf(id) == HexProps.Bundle).Select(HexProps.PrefabPath).ToArray() },new AssetBundleBuild { assetBundleName = HexProps.PapyrusBundle, assetNames = new[] { HexProps.PrefabPath(HexProps.Papyrus) } },+ new AssetBundleBuild { assetBundleName = HexProps.TamariskBundle, assetNames = new[] { HexProps.PrefabPath(HexProps.Tamarisk) } },};public static string BuildBundles(BuildTarget target) =>diff --git a/unity/Assets/Resources/HexTiles/Boards/israel.json b/unity/Assets/Resources/HexTiles/Boards/israel.jsonindex f798ab75c..39e8050af 100644--- a/unity/Assets/Resources/HexTiles/Boards/israel.json+++ b/unity/Assets/Resources/HexTiles/Boards/israel.json@@ -967,8 +967,8 @@"r": 11,"terrain": "flat","ground": "grass",- "prototype": "coastal_dunes",- "note": "",+ "prototype": "railway_halt",+ "note": "Atlit railway station","unit": "","facing": 0.0,"env": false,@@ -1351,8 +1351,8 @@"r": 14,"terrain": "flat","ground": "grass",- "prototype": "coastal_dunes",- "note": "",+ "prototype": "railway_halt",+ "note": "Binyamina railway station","unit": "","facing": 0.0,"env": false,@@ -1627,8 +1627,8 @@"r": 16,"terrain": "flat","ground": "grass",- "prototype": "mixed_farm_centre_a",- "note": "",+ "prototype": "railway_halt",+ "note": "Qaqun (Ahituv station)","unit": "","facing": 0.0,"env": false,@@ -2299,8 +2299,8 @@"r": 21,"terrain": "flat","ground": "grass",- "prototype": "sharon_kurkar",- "note": "",+ "prototype": "railway_halt",+ "note": "Rosh HaAyin South railway station","unit": "","facing": 0.0,"env": false,@@ -3211,8 +3211,8 @@"r": 27,"terrain": "hills","ground": "hills",- "prototype": "forest_centre_a",- "note": "",+ "prototype": "railway_halt",+ "note": "Beit Shemesh railway station (Artuf)","unit": "","facing": 0.0,"env": false,diff --git a/unity/Assets/Scripts/Map/Collection/HexPropModels.cs b/unity/Assets/Scripts/Map/Collection/HexPropModels.csnew file mode 100644index 000000000..ea30e0a1a--- /dev/null+++ b/unity/Assets/Scripts/Map/Collection/HexPropModels.cs@@ -0,0 +1,627 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using Statecraft.HexTiles;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.Game.Map.Collection+{+ /// <summary>Tal Heuberger's hex-tile props (#1155) on the main map (owner, 27 October 2026, "2+3": put them on the hex boards AND+ /// bring them to the main diorama map; owner, 2 November 2026: "make sure all of tal's new models are used"), only where the+ /// map's content gives the place:+ /// - the railway halt's station building at each station the 1948 railways name (content/map/routes_1948.yaml, a rail+ /// route's `via` waypoint whose name says "station"), from its route's first day;+ /// - the desert-edge goat-hair tent beside each Bedouin camp (localities_1948.yaml `encampments`: the kits scatter one+ /// symbolic camp per 1,000 people as `camp:` footprints, which RuralLife's camel and tent use too); the camps' own+ /// tents stay as they are;+ /// - the Arab village's prickly-pear hedge beside each Arab village (localities_1948.yaml, type village), as the+ /// arab_village hex tile draws it at the village's edge: a short row of 3 to 5 clumps along the edge (owner, 2 November+ /// 2026: "Hedge row of several clumps (Recommended)");+ /// - a light scatter of garrigue and scrub on open hill ground (the land hexes of biome hills or mountains in+ /// content/map/hexes.json), up close only (owner, 2 November 2026: "Sparse, close zoom only (Recommended)");+ /// - and in place of the kit's own minarets, belfries and Jaffa's clock tower, Tal Heuberger's at every spot the kit builds+ /// one, far off and up close (owner, 2 November 2026: "tal's high quality models replace the built ones everytwhere"):+ /// the kit draws those parts (their meshes' submesh 1, KitLayer.LandmarkParts) until the models stand there, and keeps+ /// them if the bundle fails.+ /// Each stands on the nearest clear ground to its place (<see cref="NearestSpot"/>: a station within one hex of its+ /// point, a tent or a hedge just outside its camp's or village's kit footprint), clear of every kit footprint, the+ /// routes, the unit tokens, water, the other Collection layers and each other, at the buildings' one world scale, and+ /// draws only up close (#700's switch). The landmark models draw where the kit's part would, far off or up close, each+ /// following its kit renderer's swap (TownModelLayer.Follow). The props stream from their own bundle+ /// (<see cref="HexProps"/>, 5.8 MB for WebGL), asked for by the first camera that renders (after the first frame) when the+ /// map has landmark parts to replace, else by the first close camera. A prop that does not stream stays off the map.</summary>+ [ExecuteAlways]+ public sealed class HexPropModels : MonoBehaviour+ {+ public const string Name = "HexPropModels";+ public const string Station = "tiles:railway_halt/station", Tent = "tiles:desert_edge/tent", PricklyPear = "tiles:arab_village/prickly_pear",+ Garrigue = "tiles:judean_highlands/garrigue", Scrub = "tiles:coastal_dunes/scrub",+ Minaret = "tiles:arab_village/minaret", Belfry = "tiles:jaffa_old_city/belfry", ClockTower = "tiles:jaffa_old_city/clock_tower";+ /// <summary>The props this layer places on clear ground (close up only).</summary>+ public static readonly string[] Standalone = { Station, Tent, PricklyPear, Garrigue, Scrub };+ /// <summary>The props that replace the kit's landmark parts, by the part's kind (KitLayer.LandmarkPart.Kind).</summary>+ public static readonly IReadOnlyDictionary<string, string> ByPart = new Dictionary<string, string>(StringComparer.Ordinal)+ { ["minaret"] = Minaret, ["belfry"] = Belfry, ["clock_tower"] = ClockTower };+ public static readonly string[] Models = { Station, Tent, PricklyPear, Garrigue, Scrub, Minaret, Belfry, ClockTower };+ /// <summary>The child that holds the landmark models (a rebuild of the standalone props leaves it alone).</summary>+ public const string LandmarksName = "Landmarks";++ /// <summary>The one world scale of Tal Heuberger's models (<see cref="Kits.SettlementKits.ModelScale"/>, issue #1032).</summary>+ public const float WorldScale = Kits.SettlementKits.ModelScale;++ /// <summary>Design values, not sourced measurements: the real long side (m) each prop stands for, seen from above. A+ /// small stone station building; the camp kit's goat-hair tents are 7 to 12 m (SettlementKits.Encampments, as+ /// RuralLife's tent); a prickly-pear clump a few metres across.</summary>+ public static float RealLengthM(string model) => model switch+ {+ Station => 12f, Tent => 10f, PricklyPear => 4f,+ // Design values: a low shrub a few metres across.+ Garrigue => 3f, Scrub => 3f,+ _ => throw new ArgumentException($"'{model}' is not one of the main map's hex props", nameof(model)),+ };++ public static float SizeOf(string model) => RealLengthM(model) * WorldScale;+ public static float ClearanceOf(string model) => 0.71f * SizeOf(model);++ /// <summary>How far beyond <see cref="Want.Start"/> the search for clear ground goes (m). Design values: a station may+ /// stand up to one map hex (<paramref name="hexSizeM"/>, the 4.4 km grid's circumradius) from its sourced point, since+ /// a station inside a town's kit footprint has its nearest clear ground beyond the town's edge; a tent or a hedge+ /// stays within four of its clearances of its place's footprint.</summary>+ public static float ReachOf(string model, float hexSizeM) => model == Station ? hexSizeM : 4f * ClearanceOf(model);++ // Design values: 24 bearings, the ring radius growing by half a clearance from one and a half clearances out.+ public const int SpotBearings = 24;+ public const float FirstRingClearances = 1.5f, RingStepClearances = 0.5f;++ /// <summary>Design values (owner, 2 November 2026: "A short row of 3-5 clumps along each village's edge"): a village's+ /// hedge is 3 to 5 clumps (FNV-1a of its key), one and a quarter clumps apart, along the tangent to its footprint.</summary>+ public static int HedgeClumps(string key) => 3 + (int)(RuralLife.StableHash(key + ":hedge") % 3u);+ public const float HedgeSpacingSizes = 1.25f;+ public static Vector2[] HedgeMembers(Want w, Vector2 spot)+ {+ var members = new Vector2[HedgeClumps(w.Key)];+ HedgeMembers(w, spot, members);+ return members;+ }++ /// <summary>As HedgeMembers, into <paramref name="into"/> (at least five long); returns how many.</summary>+ public static int HedgeMembers(Want w, Vector2 spot, Vector2[] into)+ {+ var radial = spot - w.Anchor; var along = radial.sqrMagnitude > 1e-6f ? new Vector2(-radial.y, radial.x).normalized : Vector2.right;+ int n = HedgeClumps(w.Key);+ for (int i = 0; i < n; i++) into[i] = spot + along * ((i - 0.5f * (n - 1)) * HedgeSpacingSizes * SizeOf(PricklyPear));+ return n;+ }++ /// <summary>Design values (owner, 2 November 2026: "A light scatter on open hill ground under 40 km"): one garrigue and+ /// one scrub per land hex of biome hills or mountains, each at a point FNV-1a picks within ScatterReachHex of the hex's+ /// size from its centre, moved to the nearest clear ground.</summary>+ public static readonly string[] HillBiomes = { "hills", "mountains" };+ public const float ScatterReachHex = 0.6f;++ /// <summary>The nearest clear point to <paramref name="anchor"/> on rings from <paramref name="start"/> plus+ /// FirstRingClearances clearances out, growing by RingStepClearances clearances up to <paramref name="start"/> plus+ /// <paramref name="reach"/>; on each ring the first bearing is chosen by FNV-1a of <paramref name="key"/> (no Unity+ /// random stream or simulation state moves). Null when none is clear.</summary>+ public static Vector2? NearestSpot(string key, Vector2 anchor, float clearance, Func<Vector2, float, bool> free, float start, float reach)+ {+ int first = (int)(RuralLife.StableHash(key) % SpotBearings);+ for (int ring = 0; ; ring++)+ {+ float radius = start + clearance * (FirstRingClearances + ring * RingStepClearances);+ if (radius > start + reach) return null;+ for (int k = 0; k < SpotBearings; k++)+ {+ float angle = 2f * Mathf.PI * ((first + k) % SpotBearings) / SpotBearings;+ var p = anchor + new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * radius;+ if (free(p, clearance)) return p;+ }+ }+ }++ /// <summary>A named station of the 1948 railways: its waypoint in content/map/routes_1948.yaml (name, point) and the first+ /// day the map draws a route through it (the earliest `from` of the routes whose `via` lists it). HexPropModelsTests+ /// checks this list against the file.</summary>+ public readonly struct RailStation+ {+ public readonly string Name; public readonly double Lon, Lat; public readonly DateTime From; public readonly DateTime? To;+ public RailStation(string name, double lon, double lat, DateTime from, DateTime? to = null) { Name = name; Lon = lon; Lat = lat; From = from; To = to; }+ /// <summary>Whether a route through it is drawn on <paramref name="date"/> (RouteWindow: from inclusive, to exclusive).</summary>+ public bool DrawnOn(DateTime date) => date >= From && (To == null || date < To.Value);+ }++ public static readonly RailStation[] Stations =+ {+ new RailStation("Jaffa railway station", 34.7614, 32.059, new DateTime(1920, 10, 5)),+ new RailStation("Lod railway station", 34.87556, 31.94583, new DateTime(1915, 1, 1)),+ new RailStation("Ramla railway station", 34.87684, 31.92936, new DateTime(1920, 10, 5)),+ new RailStation("Beit Shemesh railway station (Artuf)", 34.99088, 31.75744, new DateTime(1920, 10, 5)),+ new RailStation("Jerusalem (Khan) railway station", 35.22471, 31.76685, new DateTime(1920, 10, 5)),+ new RailStation("Rehovot railway station", 34.80639, 31.90889, new DateTime(1946, 1, 1)),+ new RailStation("Dir Snid station", 34.55776, 31.58195, new DateTime(1946, 1, 1)),+ new RailStation("Rosh HaAyin South railway station", 34.93472, 32.10417, new DateTime(1915, 1, 1)),+ new RailStation("Qaqun (Ahituv station)", 35.00194, 32.38356, new DateTime(1915, 1, 1)),+ new RailStation("Hadera East railway station", 34.95, 32.44611, new DateTime(1915, 1, 1)),+ new RailStation("Binyamina railway station", 34.94972, 32.51389, new DateTime(1918, 1, 1)),+ new RailStation("Atlit railway station", 34.9402, 32.69275, new DateTime(1918, 1, 1)),+ new RailStation("Haifa East railway station", 35.00472, 32.81194, new DateTime(1905, 10, 15)),+ new RailStation("Acre railway station", 35.08282, 32.92815, new DateTime(1942, 1, 1)),+ new RailStation("Nahariya railway station", 35.09889, 33.00528, new DateTime(1942, 1, 1)),+ new RailStation("Beit She'an former railway station", 35.4936, 32.5128, new DateTime(1905, 10, 15)),+ new RailStation("Samakh railway station", 35.587, 32.7032, new DateTime(1905, 10, 15)),+ new RailStation("Al-Hamma station", 35.66648, 32.68675, new DateTime(1905, 10, 15)),+ new RailStation("Petah Tikva railway station (1921)", 34.8813, 32.0968, new DateTime(1949, 9, 20)),+ new RailStation("Tel Aviv North railway station", 34.831, 32.1029, new DateTime(1949, 9, 20)),+ };++ public readonly struct Want : IEquatable<Want>+ {+ /// <summary>Key: "station:<name>", or the village's or camp's footprint id. Anchor: the station's sourced point, or+ /// the place's footprint centre. Start: where the search for clear ground starts (0 at a station's point; the+ /// place's footprint radius).</summary>+ public readonly string Key, Model; public readonly Vector2 Anchor; public readonly float Start;+ public Want(string key, string model, Vector2 anchor, float start) { Key = key; Model = model; Anchor = anchor; Start = start; }+ public bool Equals(Want o) => Key == o.Key && Model == o.Model && Anchor == o.Anchor && Start == o.Start;+ public override bool Equals(object? o) => o is Want w && Equals(w);+ public override int GetHashCode() => (Key, Model, Anchor, Start).GetHashCode();+ }++ /// <summary>Every prop the map wants on <paramref name="date"/>, in a fixed order: the stations as listed, then the+ /// camps and the villages by key.</summary>+ public static List<Want> Wants(MapScene map, DateTime date)+ {+ var result = StationWants(map, date);+ result.AddRange(FixedWants(map));+ return result;+ }++ /// <summary>The stations drawn on <paramref name="date"/>, in the listed order.</summary>+ static List<Want> StationWants(MapScene map, DateTime date)+ {+ var result = new List<Want>();+ foreach (var s in Stations)+ {+ if (!s.DrawnOn(date)) continue;+ var w = map.Frame.ToWorld(s.Lon, s.Lat, 0);+ result.Add(new Want("station:" + s.Name, Station, new Vector2(w.x, w.z), 0f));+ }+ return result;+ }++ /// <summary>The wants that do not change with the date: the camps, the villages by key and the hill scatter.</summary>+ static List<Want> FixedWants(MapScene map)+ {+ var result = new List<Want>();+ // Every camp: a sub-district's camps share their area's footprint id, so each is keyed by its id and its place+ // among them, in claim order (the kits' seeded scatter).+ var seen = new Dictionary<string, int>(StringComparer.Ordinal);+ var camps = new List<Want>();+ foreach (var f in map.KitFootprints.Where(f => f.id.StartsWith("camp:", StringComparison.Ordinal)))+ {+ seen.TryGetValue(f.id, out int n); seen[f.id] = n + 1;+ camps.Add(new Want(f.id + "#" + n, Tent, f.centre, f.radius));+ }+ result.AddRange(camps.OrderBy(w => w.Key, StringComparer.Ordinal));+ var byId = new Dictionary<string, (Vector2 centre, float radius)>(StringComparer.Ordinal);+ foreach (var f in map.KitFootprints) if (!byId.ContainsKey(f.id)) byId[f.id] = (f.centre, f.radius);+ var villages = map.Localities.Select(p => p.Settlement).Where(s => s.Type == "village" && byId.ContainsKey(s.Id))+ .Select(s => s.Id).Distinct().OrderBy(k => k, StringComparer.Ordinal);+ foreach (var id in villages) result.Add(new Want(id, PricklyPear, byId[id].centre, byId[id].radius));+ float hexM = map.Hexes.hex_size_km * 1000f;+ foreach (var h in map.Hexes.hexes.Where(h => h.land && HillBiomes.Contains(h.biome)).OrderBy(h => h.r).ThenBy(h => h.q))+ foreach (var model in new[] { Garrigue, Scrub })+ {+ string key = $"scatter:{h.q},{h.r}:{model.Substring(model.LastIndexOf('/') + 1)}";+ uint hash = RuralLife.StableHash(key);+ float a = (hash % 3600u) * Mathf.PI / 1800f, d = ScatterReachHex * hexM * Mathf.Sqrt((hash / 3600u % 1000u) / 1000f);+ var c = map.Frame.ToWorld(h.lon, h.lat, 0);+ result.Add(new Want(key, model, new Vector2(c.x, c.z) + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * d, 0f));+ }+ return result;+ }++ /// <summary>Test seam: how a prop is asked for (the hex props' own stream in a player, the AssetDatabase in the editor).</summary>+ internal static Action<string, Action<GameObject?>> Request = (id, done) =>+ CollectionStream.Request(HexProps.Catalog, id, CollectionDetail.Near, done);++ MapScene? map; DateTime date; bool shown, requested;+ /// <summary>Whether a camera has come in to the close zoom: the standalone props are built only from then on (none of+ /// them draws further out, #2266 review).</summary>+ bool everClose;+ /// <summary>The standalone props need a build (an arrival or a date change) once a camera is close; in a render, it+ /// waits for LateUpdate (nothing is instantiated while a camera renders).</summary>+ bool standaloneDirty, standaloneQueued;+ /// <summary>A camera asked for the props while rendering: the request waits for LateUpdate, so an answer that comes at+ /// once never instantiates inside a render (#2266 review).</summary>+ bool askQueued;+ /// <summary>The close state last written to the standalone renderers (null: none yet): ChooseCore writes only a change.</summary>+ bool? appliedClose;+ List<Want> wants = new List<Want>();+ List<Want>? fixedWants;+ readonly Dictionary<string, GameObject?> prefabs = new Dictionary<string, GameObject?>(StringComparer.Ordinal);+ readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();+ readonly List<Renderer> renderers = new List<Renderer>();+ /// <summary>The standalone props standing, by object name: a rebuild keeps one whose model and spot are unchanged.</summary>+ Dictionary<string, (GameObject go, string model, Vector2 spot)> live = new Dictionary<string, (GameObject, string, Vector2)>(StringComparer.Ordinal);+ List<(Vector2 centre, float radius)>? lastHoles;+ /// <summary>Every standalone prop placed: its want's key, model, ground point and object name (a hedge's clumps share+ /// their village's key).</summary>+ public readonly List<(string Key, string Model, Vector3 At, string Name)> Placed = new List<(string, string, Vector3, string)>();+ /// <summary>Every landmark model standing in for a kit part: owner, kind, far or close, object name.</summary>+ public readonly List<(string Owner, string Kind, bool Close, string Name)> Replaced = new List<(string, string, bool, string)>();+ /// <summary>The kit renderers (by name) whose own parts are hidden because Tal Heuberger's models stand in for them.</summary>+ public readonly List<string> Hidden = new List<string>();+ public IReadOnlyList<Want> Wanted => wants;+ /// <summary>Whether the props were asked for: by the first camera to render when there are landmark parts, else by the+ /// first close camera.</summary>+ public bool Requested => requested;+ public bool LastClose { get; private set; }+ /// <summary>The last standalone build's phases (ms): the keep-clear ground, the search, the instances and the total (the+ /// rest is the trees' pass; a test aid).</summary>+ public (long others, long search, long instances, long total) LastBuildMs { get; private set; }++ public static HexPropModels? ShowAt(MapScene map, DateTime date)+ {+ if (map == null || map.Terrain == null || map.Hexes == null) return null;+ var layer = map.Terrain.transform.Find(Name)?.GetComponent<HexPropModels>();+ if (layer == null)+ {+ var go = new GameObject(Name); go.transform.SetParent(map.Terrain.transform, false);+ layer = go.AddComponent<HexPropModels>(); layer.map = map;+ }+ // GameRoot calls this on every refresh: rebuild only when the date changes (the dated stations and tokens follow it).+ if (layer.shown && layer.date == date) return layer;+ layer.fixedWants ??= FixedWants(map);+ layer.shown = true; layer.date = date;+ layer.wants = StationWants(map, date); layer.wants.AddRange(layer.fixedWants);+ layer.standaloneDirty = true; layer.BuildStandaloneIfDue(inRender: false);+ return layer;+ }++ void Ask()+ {+ if (requested) return;+ requested = true;+ Boot.DiagLog.BootPhase("hex props asked");+ foreach (var id in Models)+ {+ string model = id;+ // Each answer builds what it can at once: one answer that never comes holds back nothing else (#2266 review).+ Request(model, p =>+ {+ if (this == null || prefabs.ContainsKey(model)) return; // a duplicate answer changes nothing+ prefabs[model] = p;+ if (p == null) Debug.LogWarning($"HEXPROPS: {model} did not stream; it stays off the map.");+ if (ByPart.Values.Contains(model)) RebuildLandmarks();+ else { standaloneDirty = true; BuildStandaloneIfDue(inRender: false); }+ });+ }+ }++ /// <summary>Builds the standalone props when they are due: something changed and a camera has come in close.</summary>+ void BuildStandaloneIfDue(bool inRender)+ {+ if (!standaloneDirty || !everClose) return;+ if (inRender)+ {+ standaloneQueued = true;+#if UNITY_EDITOR+ if (!Application.isPlaying) UnityEditor.EditorApplication.QueuePlayerLoopUpdate();+#endif+ return;+ }+ standaloneDirty = standaloneQueued = false;+ Rebuild();+ }++ void LateUpdate()+ {+ if (askQueued) { askQueued = false; Ask(); }+ if (standaloneQueued) BuildStandaloneIfDue(inRender: false);+ }++ // ---- The keep-clear ground (#2266 review: planned, cached, indexed) ----++ List<(Vector2 centre, float radius)>? ruralPlan; IReadOnlyList<RuralLife.Want>? ruralPlanWants; List<(Vector2, float)>? ruralPlanOthers;+ IReadOnlyList<(string Key, Vector2 Core, float Reach)>? seatsPlan; object? seatsPlanWants;++ /// <summary>The ground the other Collection layers hold or will hold, so no prop stands on them: the civilian figures+ /// and the wildlife (as RuralLife.OtherProps), and the rural scenes', special buildings' and whole-town models' PLANNED+ /// spots (their plans with every model available, which is also where each of them draws its streamed models), never+ /// what has streamed so far: the props stand in the same places whatever the camera has visited, and a scene or+ /// building that streams in later never lands on one (#2266 review). The layers' own inputs are read when they are+ /// shown (GameRoot shows them first); the date-independent plans are kept until their inputs change.</summary>+ internal List<(Vector2 centre, float radius)> Others(MapScene map, DateTime date)+ {+ var otherProps = RuralLife.OtherProps(map);+ var discs = new List<(Vector2 centre, float radius)>(otherProps);+ var rural = map.Terrain.transform.Find(RuralLife.Name)?.GetComponent<RuralLife>();+ IReadOnlyList<RuralLife.Want> rw = rural != null ? rural.Wanted : RuralLife.Wants(map);+ var ro = rural != null && rural.OthersShown.Count > 0 ? rural.OthersShown : otherProps;+ if (ruralPlan == null || !ReferenceEquals(rw, ruralPlanWants) && !rw.SequenceEqual(ruralPlanWants!) || !ro.SequenceEqual(ruralPlanOthers!))+ {+ ruralPlan = RuralLife.Plan(map, rw, ro, _ => true).Select(x => (x.spot, RuralLife.SceneRadiusM(x.want.Model))).ToList();+ ruralPlanWants = rw; ruralPlanOthers = new List<(Vector2, float)>(ro);+ }+ discs.AddRange(ruralPlan);+ foreach (var (w, at) in SpecialBuildingModels.Plan(map, date, SpecialBuildingModels.Placements(date), _ => true, log: false))+ discs.Add((at, SpecialBuildingModels.ClearanceOf(w.Model)));+ // The whole-town models (TownLandmarks, shown first by GameRoot) where they will stand, by the same plan.+ var towns = map.Terrain.transform.Find(TownLandmarks.Name)?.GetComponent<TownLandmarks>();+ if (towns != null)+ {+ if (seatsPlan == null || !ReferenceEquals(seatsPlanWants, towns.Wanted)) { seatsPlan = towns.PlannedSeats(); seatsPlanWants = towns.Wanted; }+ foreach (var seat in seatsPlan) discs.Add((seat.Core, seat.Reach));+ }+ return discs;+ }++ /// <summary>Discs in a uniform grid: the same answer as TownLandmarks.Clear over all of them, checking only the cells a+ /// query's disc reaches (#2266 review: the linear scans made a build O(n²)).</summary>+ internal sealed class DiscGrid+ {+ const float Cell = 2000f;+ readonly Dictionary<(int, int), List<(Vector2 c, float r)>> cells = new Dictionary<(int, int), List<(Vector2, float)>>();+ public DiscGrid(IEnumerable<(Vector2 centre, float radius)> discs) { foreach (var (c, r) in discs) Add(c, r); }+ public void Add(Vector2 c, float r)+ {+ for (int x = Mathf.FloorToInt((c.x - r) / Cell); x <= Mathf.FloorToInt((c.x + r) / Cell); x++)+ for (int z = Mathf.FloorToInt((c.y - r) / Cell); z <= Mathf.FloorToInt((c.y + r) / Cell); z++)+ {+ if (!cells.TryGetValue((x, z), out var list)) cells[(x, z)] = list = new List<(Vector2, float)>();+ list.Add((c, r));+ }+ }+ /// <summary>Whether the disc at <paramref name="p"/> of <paramref name="r"/> overlaps none of the discs.</summary>+ public bool Clear(Vector2 p, float r)+ {+ // A stored disc that overlaps the query is in every cell it covers, including the cell of their nearest+ // point, which is within the query's own box: so the query's box of cells finds it.+ for (int x = Mathf.FloorToInt((p.x - r) / Cell); x <= Mathf.FloorToInt((p.x + r) / Cell); x++)+ for (int z = Mathf.FloorToInt((p.y - r) / Cell); z <= Mathf.FloorToInt((p.y + r) / Cell); z++)+ if (cells.TryGetValue((x, z), out var list))+ foreach (var (c, cr) in list) { float d = cr + r; if ((p - c).sqrMagnitude < d * d) return false; }+ return true;+ }+ }++ /// <summary>The heading (degrees about up) of the mapped route segment nearest <paramref name="p"/> (for a station, its+ /// sourced point, which lies on its railway's traced line), or null with no routes.</summary>+ internal static float? AlongNearestRoute(Vector2 p, IEnumerable<(List<Vector2> line, float halfWidth)> routes)+ {+ float best = float.MaxValue; float? yaw = null;+ foreach (var (line, _) in routes)+ for (int i = 0; i + 1 < line.Count; i++)+ {+ var a = line[i]; var ab = line[i + 1] - a; if (ab.sqrMagnitude < 1e-6f) continue;+ float t = Mathf.Clamp01(Vector2.Dot(p - a, ab) / ab.sqrMagnitude);+ float d = (a + ab * t - p).sqrMagnitude;+ if (d < best) { best = d; yaw = -Mathf.Atan2(ab.y, ab.x) * Mathf.Rad2Deg; }+ }+ return yaw;+ }++ /// <summary>A fixed heading per place (FNV-1a, as RuralLife.YawOf): no Unity random stream or simulation state moves.</summary>+ public static float YawOf(string key) => RuralLife.StableHash(key) % 360u;++ void Rebuild()+ {+ if (map == null || map.Terrain == null) return;+ if (!Standalone.Any(m => prefabs.TryGetValue(m, out var p) && p != null)) { ClearVisuals(); return; }+ var clock = System.Diagnostics.Stopwatch.StartNew();+ var ground = PlacementLayer.CampGround(map);+ var footprints = new DiscGrid(map.KitFootprints.Select(f => (f.centre, f.radius)));+ var taken = new DiscGrid(Others(map, date));+ long othersMs = clock.ElapsedMilliseconds;+ bool Free(Vector2 p, float r) => taken.Clear(p, r) && footprints.Clear(p, r)+ && ground.Inside(p.x - r, p.y - r) && ground.Inside(p.x + r, p.y + r)+ && !ground.Water(p.x, p.y) && !ground.OnRoute(p, r) && !ground.OnToken(p, r, date);+ var holes = new List<(Vector2 centre, float radius)>();+ var row = new Vector2[5];+ var spots = new List<(Want w, Vector2 spot, string name)>();+ // Every want takes its ground whether or not its model has streamed (or failed): a prop's spot never depends on+ // which others have arrived (#2266 review, as RuralLife.Plan). Only the streamed ones are drawn.+ foreach (var w in wants)+ {+ bool drawn = prefabs.TryGetValue(w.Model, out var prefab) && prefab != null;+ float clearance = ClearanceOf(w.Model);+ bool hedge = w.Model == PricklyPear;+ bool RowFree(Vector2 p, float r)+ {+ int n = HedgeMembers(w, p, row);+ for (int i = 0; i < n; i++) if (!Free(row[i], r)) return false;+ return true;+ }+ var at = NearestSpot(w.Key, w.Anchor, clearance, hedge ? RowFree : (Func<Vector2, float, bool>)Free, w.Start, ReachOf(w.Model, ground.HexSizeM));+ if (at == null)+ {+ if (drawn && w.Model != Garrigue && w.Model != Scrub) Debug.LogWarning($"HEXPROPS: no clear ground near {w.Key}; its {w.Model} is not drawn.");+ continue;+ }+ int count = hedge ? HedgeMembers(w, at.Value, row) : 1;+ for (int i = 0; i < count; i++)+ {+ var spot = hedge ? row[i] : at.Value;+ taken.Add(spot, clearance);+ if (!drawn) continue;+ holes.Add((spot, clearance));+ spots.Add((w, spot, hedge ? w.Key + "#" + i : w.Key));+ }+ }+ long searchMs = clock.ElapsedMilliseconds - othersMs;+ // A prop whose model and spot did not change keeps its object: a date change usually moves few of them.+ var next = new Dictionary<string, (GameObject go, string model, Vector2 spot)>(StringComparer.Ordinal);+ renderers.Clear(); Placed.Clear();+ int kept = 0;+ foreach (var (w, spot, name) in spots)+ {+ var pos = new Vector3(spot.x, ground.Y(spot.x, spot.y), spot.y);+ GameObject go;+ if (live.TryGetValue(name, out var old) && old.go != null && old.model == w.Model && (old.spot - spot).sqrMagnitude < 1e-6f)+ { go = old.go; live.Remove(name); kept++; }+ else+ {+ if (live.TryGetValue(name, out var stale)) { DestroyNow(stale.go); live.Remove(name); }+ var prefab = prefabs[w.Model]!;+ float yaw = w.Model == Station ? AlongNearestRoute(w.Anchor, map.KitRouteCorridors) ?? 0f : YawOf(name);+ go = Instantiate(prefab, transform, false); go.name = name;+ go.transform.localRotation = prefab.transform.localRotation;+ var b = Bounds(go); float edge = Mathf.Max(b.size.x, b.size.z);+ go.transform.localScale = prefab.transform.localScale * (edge > 1e-4f ? SizeOf(w.Model) / edge : 1f);+ go.transform.localRotation = SpecialBuildingModels.Rotation(prefab.transform.localRotation, yaw);+ go.transform.position = pos; b = Bounds(go);+ go.transform.position += new Vector3(pos.x - b.center.x, pos.y - b.min.y, pos.z - b.center.z);+ foreach (var r in go.GetComponentsInChildren<Renderer>(true)) r.shadowCastingMode = ShadowCastingMode.On;+ }+ next[name] = (go, w.Model, spot);+ foreach (var r in go.GetComponentsInChildren<Renderer>(true)) { r.forceRenderingOff = !(appliedClose ?? LastClose); renderers.Add(r); }+ Placed.Add((w.Key, w.Model, pos, name));+ }+ foreach (var gone in live.Values) DestroyNow(gone.go);+ live = next;+ long instancesMs = clock.ElapsedMilliseconds - othersMs - searchMs;+ // No kit tree stands on a prop (Kits.VegetationLayer.Hide, as under the special buildings); unchanged holes need no pass.+ if (lastHoles == null || !holes.SequenceEqual(lastHoles)) { Units.UnitShowcase.HideTrees(map, Name, holes); lastHoles = holes; }+ long total = clock.ElapsedMilliseconds;+ LastBuildMs = (othersMs, searchMs, instancesMs, total);+ Debug.Log($"HEXPROPS: {Placed.Count} hex props placed for {wants.Count} wants in {total} ms (keep-clear ground {othersMs} ms, " ++ $"search {searchMs} ms, instances {instancesMs} ms with {kept} kept, trees {total - othersMs - searchMs - instancesMs} ms) " ++ $"({string.Join(", ", Standalone.Select(m => $"{m.Substring(m.LastIndexOf('/') + 1)} {Placed.Count(p => p.Model == m)}"))})");+ }++ void DestroyNow(GameObject go)+ {+ if (go == null) return;+ if (Application.isPlaying) { if (gameObject.activeInHierarchy) go.transform.SetParent(null); Destroy(go); } else DestroyImmediate(go);+ }++ /// <summary>Tal Heuberger's minarets, belfries and clock tower in place of the kit's parts (#2266). A kit renderer's parts+ /// are replaced together, and only when every kind among them streamed; then its fallback parts (far and close) are+ /// hidden. It runs on each landmark answer and builds the kit meshes that answer completes, so an answer that never+ /// comes holds back only the kit meshes that need it.+ /// Each model stands on its part's own base (its box's bottom, or the ground where the part reaches below it), as tall+ /// as the part, turned as the kit turns it, and draws exactly when the part's kit or close renderer does+ /// (TownModelLayer.Follow). The kit renderers then stop drawing their own parts (KitLayer.ShowParts).</summary>+ void RebuildLandmarks()+ {+ if (map == null || map.Terrain == null || map.KitStats == null) return;+ var kits = map.transform.Find(Kits.KitLayer.RootName);+ var towns = kits != null ? kits.GetComponentInChildren<Kits.TownModelLayer>(true) : null;+ if (kits == null || towns == null || map.KitStats.LandmarkParts.Count == 0) return;+ var holder = transform.Find(LandmarksName);+ if (holder == null) { holder = new GameObject(LandmarksName).transform; holder.SetParent(transform, false); }+ var ground = PlacementLayer.CampGround(map);+ // Only the kit meshes this answer completes: those already replaced stay as they are.+ foreach (var group in map.KitStats.LandmarkParts.GroupBy(p => p.Kit))+ {+ if (Hidden.Contains(group.Key)) continue;+ if (!group.All(p => ByPart.TryGetValue(p.Kind, out var id) && prefabs.TryGetValue(id, out var pf) && pf != null)) continue;+ var kit = kits.Find(group.Key)?.GetComponent<Renderer>();+ if (kit == null) continue;+ int n = 0;+ foreach (var part in group)+ {+ var prefab = prefabs[ByPart[part.Kind]]!;+ Stand(part, prefab, part.Far, kit, false, n);+ var close = part.Close != null ? kits.Find(part.Close)?.GetComponent<Renderer>() : null;+ if (close != null) Stand(part, prefab, part.Near, close, true, n);+ n++;+ }+ Hidden.Add(group.Key);+ }+ if (isActiveAndEnabled) foreach (var name in Hidden) ShowKitParts(kits, name, false);+ Boot.DiagLog.BootPhase("hex landmarks built");+ Debug.Log($"HEXPROPS: {Replaced.Count} landmark models stand in for the kit's parts of {Hidden.Count} kit meshes " ++ $"({string.Join(", ", ByPart.Keys.Select(k => $"{k} {Replaced.Count(r => r.Kind == k && !r.Close)}"))})");++ void Stand(Kits.KitLayer.LandmarkPart part, GameObject prefab, Bounds box, Renderer leader, bool close, int n)+ {+ var go = Instantiate(prefab, holder, false); go.name = $"{part.Owner}:{part.Kind}:{n}:{(close ? "close" : "far")}";+ go.transform.localRotation = SpecialBuildingModels.Rotation(prefab.transform.localRotation, part.Yaw);+ // A roof-mounted part (a village minaret, a belfry) starts on the roof; a part with foundations starts on the ground.+ float baseY = Mathf.Max(box.min.y, ground.Y(box.center.x, box.center.z)), height = box.max.y - baseY;+ var b = Bounds(go);+ go.transform.localScale = prefab.transform.localScale * (b.size.y > 1e-4f && height > 0f ? height / b.size.y : 1f);+ var pos = new Vector3(box.center.x, baseY, box.center.z);+ go.transform.position = pos; b = Bounds(go);+ go.transform.position += new Vector3(pos.x - b.center.x, pos.y - b.min.y, pos.z - b.center.z);+ foreach (var r in go.GetComponentsInChildren<Renderer>(true)) { r.shadowCastingMode = ShadowCastingMode.On; towns!.Follow(leader, r); }+ Replaced.Add((part.Owner, part.Kind, close, go.name));+ }+ }++ /// <summary>Whether the kit draws its own parts where Tal Heuberger's models stand (<see cref="Hidden"/>).</summary>+ void ShowAllKitParts(bool on)+ {+ var kits = map != null ? map.transform.Find(Kits.KitLayer.RootName) : null;+ if (kits != null) foreach (var name in Hidden) ShowKitParts(kits, name, on);+ }++ static void ShowKitParts(Transform kits, string kit, bool on)+ {+ foreach (var name in new[] { kit, kit + Kits.KitLayer.CloseSuffix })+ if (kits.Find(name)?.GetComponent<Renderer>() is Renderer r) Kits.KitLayer.ShowParts(r, on);+ }++ void ClearVisuals()+ {+ for (int i = transform.childCount - 1; i >= 0; i--)+ {+ var old = transform.GetChild(i).gameObject;+ if (old.name != LandmarksName) DestroyNow(old);+ }+ live.Clear(); renderers.Clear(); Placed.Clear();+ if (map != null && lastHoles != null) { Units.UnitShowcase.HideTrees(map, Name, Array.Empty<(Vector2, float)>()); lastHoles = null; }+ }++ static Bounds Bounds(GameObject go)+ {+ var rs = go.GetComponentsInChildren<Renderer>(true); if (rs.Length == 0) return new Bounds(go.transform.position, Vector3.zero);+ var b = rs[0].bounds; foreach (var r in rs) b.Encapsulate(r.bounds); return b;+ }++ /// <summary>Never an empty spot: while the layer (and so Tal Heuberger's models under it) is disabled or gone, the kit+ /// draws its own parts again; enabled, the models stand in for them (#2266 review).</summary>+ void OnEnable() { RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering; ShowAllKitParts(false); }+ void OnDisable() { RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering; ShowAllKitParts(true); }+ void OnDestroy() => ShowAllKitParts(true);++ void OnBeginCameraRendering(ScriptableRenderContext context, Camera cam) => ChooseCore(cam, inRender: true);+ /// <summary>A direct call (tests and editor tools, outside any render) builds what is due at once.</summary>+ internal void Choose(ScriptableRenderContext context, Camera cam) => ChooseCore(cam, inRender: false);++ /// <summary>#700's close-zoom switch with its hysteresis (<see cref="SpecialBuildingModels.CloseAt"/>) for the standalone+ /// props, and the request (Ask). The landmark models follow their kit renderers instead.</summary>+ void ChooseCore(Camera cam, bool inRender)+ {+ if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;+ int id = cam.GetInstanceID();+ bool close = SpecialBuildingModels.CloseAt(TownLandmarks.ViewDistance(cam), closeFor.TryGetValue(id, out var was) ? was : (bool?)null);+ closeFor[id] = close; LastClose = close;+ // The kit's minarets, belfries and clock tower draw at every zoom (owner, 2 November 2026: "tal's high quality models+ // replace the built ones everytwhere"), so with any to replace the first camera to render (after the first frame)+ // asks; the standalone props are built only once a camera comes in close, where they draw.+ if (map != null && !requested && (close || map.KitStats?.LandmarkParts.Count > 0))+ {+ if (!inRender) Ask();+ else+ {+ askQueued = true;+#if UNITY_EDITOR+ if (!Application.isPlaying) UnityEditor.EditorApplication.QueuePlayerLoopUpdate();+#endif+ }+ }+ if (close && !everClose) { everClose = true; standaloneDirty = true; }+ if (close) BuildStandaloneIfDue(inRender);+ // Only a change is written: thousands of props, every camera, every frame (#2266 review).+ if (appliedClose != close)+ {+ appliedClose = close;+ foreach (var r in renderers) if (r != null) r.forceRenderingOff = !close;+ }+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Collection/HexPropModels.cs.meta b/unity/Assets/Scripts/Map/Collection/HexPropModels.cs.metanew file mode 100644index 000000000..ed8610551--- /dev/null+++ b/unity/Assets/Scripts/Map/Collection/HexPropModels.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 8a0e669aea1294ad38d0be2dd30b3a47\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/Collection/RuralLife.cs b/unity/Assets/Scripts/Map/Collection/RuralLife.csindex 0fa4ae4ac..1247d74f3 100644--- a/unity/Assets/Scripts/Map/Collection/RuralLife.cs+++ b/unity/Assets/Scripts/Map/Collection/RuralLife.cs@@ -268,6 +268,8 @@ namespace Statecraft.Game.Map.Collectionpublic readonly List<Want> Scenes = new List<Want>();public readonly List<string> Missing = new List<string>();public IReadOnlyList<Want> Wanted => wants;+ /// <summary>The other layers' ground this layer keeps clear of (its Plan's input), as last shown.</summary>+ internal List<(Vector2 centre, float radius)> OthersShown => others;public bool LastClose { get; private set; }/// <summary>The ground the other Collection layers hold (centre, radius m): the civilian figures CivilianPeople wants@@ -357,11 +359,14 @@ namespace Statecraft.Game.Map.Collection}}- void Rebuild()+ /// <summary>Where the scenes stand: each want in order, the first MaxAnchorsPerModel of each model with clear ground (Spot),+ /// clear of <paramref name="others"/> and of each other, every one taking its ground; those whose model+ /// <paramref name="available"/> holds are listed. It reads only+ /// the map, the wants and the other layers' ground, never what has streamed, so with every model available it is the+ /// plan the layer draws once everything has arrived (HexPropModels keeps clear of it, #2266).</summary>+ internal static List<(Want want, Vector2 spot)> Plan(MapScene map, IReadOnlyList<Want> wants, List<(Vector2 centre, float radius)> others,+ Func<string, bool> available){- CollectionResidencyMetrics.MarkDirty();- if (map == null || map.Terrain == null) return;- ClearVisuals();var ground = PlacementLayer.CampGround(map);var footprints = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();var taken = new List<(Vector2 centre, float radius)>();@@ -377,22 +382,41 @@ namespace Statecraft.Game.Map.Collectionreturn !ground.OnRoute(p, radius) && !ground.OnToken(p, radius);}var used = new Dictionary<string, int>(StringComparer.Ordinal);- var holes = new List<(Vector2 centre, float radius)>();- var nearKeys = residencyView?.Keys;+ var plan = new List<(Want, Vector2)>();foreach (var want in wants){- bool hasFar = prefabs.TryGetValue((want.Model, CollectionDetail.Far), out var farPrefab) && farPrefab != null;- bool hasNear = prefabs.TryGetValue((want.Model, CollectionDetail.Near), out var nearPrefab) && nearPrefab != null;- // A streamed representation is what makes this a real scene. Until then it owns no anchor, clearance,- // tree hole or Near demand; a failed Far answer therefore cannot leave an empty permanent clearing.- if (!hasFar && !hasNear) continue;+ // Every want takes its ground whether or not its model has streamed (only the plan's output is filtered), so a+ // later scene's spot never depends on what streamed first (#2266 review; the same shape as #2281's).used.TryGetValue(want.Model, out int n);if (n >= MaxAnchorsPerModel) continue;var at = Spot(want, Free);if (at == null) continue;used[want.Model] = n + 1;- Scenes.Add(want);taken.Add((at.Value, ClearanceRadiusM));+ if (available(want.Model)) plan.Add((want, at.Value));+ }+ return plan;+ }++ void Rebuild()+ {+ CollectionResidencyMetrics.MarkDirty();+ if (map == null || map.Terrain == null) return;+ ClearVisuals();+ var ground = PlacementLayer.CampGround(map);+ // A streamed representation is what makes this a real scene. Until then it draws nothing, owns no tree hole and+ // asks for no Near; but every scene stands at its spot in the plan with every model available, so a scene that+ // streams in later lands where the plan put it, which the hex props keep clear of (HexPropModels, #2266 review).+ bool Streamed(string model) => (prefabs.TryGetValue((model, CollectionDetail.Far), out var f) && f != null)+ || (prefabs.TryGetValue((model, CollectionDetail.Near), out var nr) && nr != null);+ var used = new Dictionary<string, int>(StringComparer.Ordinal);+ var holes = new List<(Vector2 centre, float radius)>();+ var nearKeys = residencyView?.Keys;+ foreach (var (want, spot) in Plan(map, wants, others, Streamed))+ {+ used.TryGetValue(want.Model, out int n); used[want.Model] = n + 1;+ Vector2? at = spot;+ Scenes.Add(want);holes.Add((at.Value, SceneRadiusM(want.Model)));bool nearAvailable = (nearKeys == null || nearKeys.Contains(want.Key + "|" + want.Model))&& prefabs.TryGetValue((want.Model, CollectionDetail.Near), out var admittedNear) && admittedNear != null;diff --git a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.csindex cfbb4645f..9fe92fb5d 100644--- a/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs+++ b/unity/Assets/Scripts/Map/Collection/SpecialBuildingModels.cs@@ -315,11 +315,12 @@ namespace Statecraft.Game.Map.CollectionRebuild();}- void Rebuild()+ /// <summary>Where the buildings stand: each want in order, of the models <paramref name="available"/> holds, at its+ /// route-facing (Degania) or seeded spot, clear of the towns, the routes, the tokens of <paramref name="date"/>, the+ /// civilians, the wildlife and each other. It reads only the map and the date, never what has streamed, so with every+ /// model available it is the plan the layer draws once everything has arrived (HexPropModels keeps clear of it, #2266).</summary>+ internal static List<(Want want, Vector2 at)> Plan(MapScene map, DateTime date, IReadOnlyList<Want> wants, Func<string, bool> available, bool log){- CollectionResidencyMetrics.MarkDirty();- if (map == null || map.Terrain == null) return;- ClearVisuals();var ground = PlacementLayer.CampGround(map);var footprints = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();var taken = new List<(Vector2 centre, float radius)>();@@ -330,11 +331,11 @@ namespace Statecraft.Game.Map.Collectionbool Free(Vector2 p, float r) => TownLandmarks.Clear(p, r, taken) && TownLandmarks.Clear(p, r, footprints)&& ground.Inside(p.x - r, p.y - r) && ground.Inside(p.x + r, p.y + r)&& !ground.Water(p.x, p.y) && !ground.OnRoute(p, r) && !ground.OnToken(p, r, date);- var holes = new List<(Vector2 centre, float radius)>();+ var plan = new List<(Want, Vector2)>();var kits = map.transform.Find(Kits.KitLayer.RootName);foreach (var w in wants){- if (!prefabs.TryGetValue(w.Model, out var prefab) || prefab == null) continue;+ if (!available(w.Model)) continue;var anchor3 = map.Frame.ToWorld(w.Lon, w.Lat, 0); var anchor = new Vector2(anchor3.x, anchor3.z);float clearance = ClearanceOf(w.Model);Vector2? at = null;@@ -347,13 +348,29 @@ namespace Statecraft.Game.Map.Collection}if (at == null){- if (w.Key == "degania_r35")+ if (w.Key == "degania_r35" && log)Debug.LogWarning("BUILDINGS: route-facing spot unavailable for degania_r35; falling back to the seeded spot.");at = SeededSpot(w.Key, anchor, clearance, Free, Inside(anchor, footprints));}- if (at == null) { Debug.LogWarning($"BUILDINGS: no clear ground near {w.Key}; its {w.Model} is not drawn."); continue; }+ if (at == null) { if (log) Debug.LogWarning($"BUILDINGS: no clear ground near {w.Key}; its {w.Model} is not drawn."); continue; }taken.Add((at.Value, clearance));- holes.Add((at.Value, clearance));+ plan.Add((w, at.Value));+ }+ return plan;+ }++ void Rebuild()+ {+ CollectionResidencyMetrics.MarkDirty();+ if (map == null || map.Terrain == null) return;+ ClearVisuals();+ var ground = PlacementLayer.CampGround(map);+ var holes = new List<(Vector2 centre, float radius)>();+ foreach (var (w, spot) in Plan(map, date, wants, m => prefabs.TryGetValue(m, out var p) && p != null, log: true))+ {+ var prefab = prefabs[w.Model]!;+ Vector2? at = spot;+ holes.Add((at.Value, ClearanceOf(w.Model)));var go = Instantiate(prefab, transform, false); go.name = w.Key;if (!originals.TryGetValue(w.Model, out var owned)) originals[w.Model] = owned = new List<GameObject>();owned.Add(go);diff --git a/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs b/unity/Assets/Scripts/Map/Collection/TownLandmarks.csindex cbabb6b87..2873da7f7 100644--- a/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs+++ b/unity/Assets/Scripts/Map/Collection/TownLandmarks.cs@@ -372,6 +372,34 @@ namespace Statecraft.Game.Map.Collection}// Owner ruling, 30 October 2026: whole towns and placement landmarks remain v0.3.1 Far demand, map-wide.bool Allowed(Want want) => map != null ? map.Residency.Towns.Enabled : true;++ /// <summary>A town want's core and radius, as the whole-town model is seated on it (<see cref="CoreOf"/>): its kit plots+ /// (TownModelLayer, built with the kits), the unit clearings, the other towns and the water. No streamed state.</summary>+ static (Vector2 core, float radius) CoreFor(MapScene map, Kits.TownModelLayer? layer, IReadOnlyList<Want> wants, Want w, Kits.KitGround ground,+ List<(Vector2 c, string id)> townCentres)+ {+ var plots = layer == null ? (IReadOnlyList<Vector2>)Array.Empty<Vector2>()+ : layer.InstancesOf(w.Key).Select(m => m.Plot).Distinct().ToList();+ var others = wants.Where(o => o.OnTown && o.Key != w.Key).Select(o => o.At).Concat(townCentres.Where(o => o.id != w.Key).Select(o => o.c));+ return CoreOf(w.At, w.Radius, plots, map.UnitClearings, others, ground.Water, w.Land);+ }++ /// <summary>Every game settlement's centre (its kit footprint's), for the cores' neighbour limit; once per build.</summary>+ static List<(Vector2 c, string id)> TownCentres(MapScene map)+ {+ var gameIds = new HashSet<string>(map.Settlements.Select(x => x.Id), StringComparer.Ordinal);+ return map.KitFootprints.Where(f => gameIds.Contains(f.id)).Select(f => (c: f.centre, id: f.id)).ToList();+ }++ /// <summary>#2266: where each wanted whole-town model stands once it streams: its core and the reach of its square+ /// model about it (its half edge, the core's radius, times the square root of two, for any yaw). Planned from the map and+ /// the wants alone, so the hex props keep clear of the whole towns whatever has streamed (HexPropModels.Others).</summary>+ internal IReadOnlyList<(string Key, Vector2 Core, float Reach)> PlannedSeats()+ {+ if (map == null || !map.Residency.Towns.Enabled) return Array.Empty<(string, Vector2, float)>();+ var ground = PlacementLayer.CampGround(map); var layer = Layer(); var centres = TownCentres(map);+ return wants.Where(w => w.OnTown).Select(w => { var (c, r) = CoreFor(map, layer, wants, w, ground, centres); return (w.Key, c, r * Mathf.Sqrt(2f)); }).ToList();+ }bool WholeReady(string id, Camera camera) =>Seats.ContainsKey(id) && Layer()?.ReadyForTown(id, camera) != true;@@ -518,9 +546,7 @@ namespace Statecraft.Game.Map.Collectionreturn !ground.OnRoute(p, rad) && !ground.OnToken(p, rad) && !ground.OnToken(p, rad, date);}var layer = Layer();- // Every game settlement's centre (its kit footprint's), for the cores' neighbour limit.- var gameIds = new HashSet<string>(map.Settlements.Select(x => x.Id), StringComparer.Ordinal);- var townCentres = map.KitFootprints.Where(f => gameIds.Contains(f.id)).Select(f => (c: f.centre, id: f.id)).ToList();+ var centres = TownCentres(map);foreach (var w in wants){if (!Allowed(w)) continue;@@ -530,10 +556,7 @@ namespace Statecraft.Game.Map.Collectionif (w.OnTown){// On the town's core, not its whole kit footprint (Tel Aviv's held Jaffa, Haifa's the bay).- var plots = layer == null ? (IReadOnlyList<Vector2>)Array.Empty<Vector2>()- : layer.InstancesOf(w.Key).Select(m => m.Plot).Distinct().ToList();- var others = wants.Where(o => o.OnTown && o.Key != w.Key).Select(o => o.At).Concat(townCentres.Where(o => o.id != w.Key).Select(o => o.c));- var (core, rad) = CoreOf(w.At, w.Radius, plots, map.UnitClearings, others, ground.Water, w.Land);+ var (core, rad) = CoreFor(map, layer, wants, w, ground, centres);at = core; edge = 2f * rad;(normal, baseY) = SeatOn(at, rad, ground.Y, ground.Water);}diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexProps.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexProps.csindex 791f1fc79..b3c8b366e 100644--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexProps.cs+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexProps.cs@@ -10,16 +10,19 @@ namespace Statecraft.HexTiles/// Owner, 23 October 2026: "Own streamed bundle". They are outside every Resources folder, so the first download does not/// carry them, and outside The 1948 Collection (<see cref="CollectionCatalog"/>, Tal's Tripo models only). They ship as/// one bundle of their own, <see cref="Bundle"/>, which the Collection's loader (<see cref="CollectionStream"/>) streams- /// with this catalog after the first frame, and only when a hex board asks for one, so only with ?hex-tiles on. Until a- /// prop arrives (and for good if its bundle fails) its placement draws the tile's stand-in. The editor (the painter, the+ /// with this catalog after the first frame, and only when a hex board asks for one (so with ?hex-tiles on) or when the+ /// main map's first camera does (<see cref="Statecraft.Game.Map.Collection.HexPropModels"/>, after the first frame). Until a prop arrives+ /// (and for good if its bundle fails) a board's placement draws the tile's stand-in. The editor (the painter, the/// captures, the tests) loads the prefabs from the AssetDatabase (HexModels.Prefab)./// Each prefab sits at Assets/Art/HexTiles/<tile>/<prop>.prefab, beside its model in/// Assets/Art/HexTiles/Props/<tile>_<prop>/ (HexSandboxImport.RunHiggsfield -prefabsRoot Assets/Art)./// The papyrus is a bundle of its own, <see cref="PapyrusBundle"/>, in the same stream: the main map asks for it at the- /// Hula (HulaPapyrusLayer) without the hex boards' other props.</summary>+ /// Hula (HulaPapyrusLayer) without the hex boards' other props. The tamarisk is a bundle of its own too,+ /// <see cref="TamariskBundle"/>: only the boards draw it (no tamarisk on the main map, #1951), so the main map's first+ /// camera, which fetches <see cref="Bundle"/>, does not fetch it.</summary>public static class HexProps{- public const string Bundle = "hex-props", PapyrusBundle = "hex-props-papyrus";+ public const string Bundle = "hex-props", PapyrusBundle = "hex-props-papyrus", TamariskBundle = "hex-props-tamarisk";public const string Papyrus = "tiles:hula_swamp/papyrus", Tamarisk = "tiles:arava_oasis/tamarisk";/// <summary>The folder in the build's StreamingAssets that holds the bundle, and the checks file beside it.</summary>public const string StreamingFolder = "hex-props", ChecksFile = "hex-props-checks.txt";@@ -46,14 +49,14 @@ namespace Statecraft.HexTilespublic static bool Has(string id) => ids.Contains(id);- /// <summary>The prop's bundle: <see cref="PapyrusBundle"/> for the papyrus, <see cref="Bundle"/> for the rest; null- /// for an id that is not a prop.</summary>- public static string? BundleOf(string id) => !Has(id) ? null : id == Papyrus ? PapyrusBundle : Bundle;+ /// <summary>The prop's bundle: <see cref="PapyrusBundle"/> for the papyrus, <see cref="TamariskBundle"/> for the+ /// tamarisk, <see cref="Bundle"/> for the rest; null for an id that is not a prop.</summary>+ public static string? BundleOf(string id) => !Has(id) ? null : id == Papyrus ? PapyrusBundle : id == Tamarisk ? TamariskBundle : Bundle;/// <summary>The prop's prefab path in the project, which is also its name inside the bundle (lower case there).</summary>public static string PrefabPath(string id) => PrefabRoot + HexModels.PathOf(id) + ".prefab";- /// <summary>What the loader streams: two bundles, one prefab per prop (the detail is not used).</summary>+ /// <summary>What the loader streams: three bundles, one prefab per prop (the detail is not used).</summary>public static readonly CollectionStream.Catalog Catalog = new CollectionStream.Catalog("the hex-tile props", StreamingFolder,ChecksFile, BundleOf, (id, _) => PrefabPath(id));}diff --git a/unity/Assets/Scripts/Map/Kits/KitLayer.cs b/unity/Assets/Scripts/Map/Kits/KitLayer.csindex e4a423747..25f20a08a 100644--- a/unity/Assets/Scripts/Map/Kits/KitLayer.cs+++ b/unity/Assets/Scripts/Map/Kits/KitLayer.cs@@ -18,6 +18,15 @@ namespace Statecraft.Game.Map.Kitspublic const string RootName = "Kits", VegetationName = "Vegetation", SeaCraftName = "SeaCraft", TownModelsName = "TownModels",CloseSuffix = " close";+ /// <summary>One replaceable landmark part (#2266): Kit and Close name its kit mesh's renderers under the root (Close+ /// null without a close mesh). Each draws the part as its submesh 1 while it has two materials (<see cref="ShowParts"/>).</summary>+ public readonly struct LandmarkPart+ {+ public readonly string Kind, Owner, Kit; public readonly string? Close; public readonly float Yaw; public readonly Bounds Far, Near;+ public LandmarkPart(string kind, string owner, string kit, string? close, float yaw, Bounds far, Bounds near)+ { Kind = kind; Owner = owner; Kit = kit; Close = close; Yaw = yaw; Far = far; Near = near; }+ }+public sealed class Stats{public int Buildings, Vertices, Triangles, Trees, CorridorSegments, Localities, LocalityBuildings, Camps, Tents, Draws, Boats, Models, CloseVertices; public float BuildMs, PlantMs;@@ -27,11 +36,27 @@ namespace Statecraft.Game.Map.Kits/// Collection's craft (SeaAirCollection, #669) keep clear of both.</summary>public IReadOnlyList<SeaCraft.Craft> Crafts = System.Array.Empty<SeaCraft.Craft>();public IReadOnlyList<SettlementKits.Placed> HarbourWorks = System.Array.Empty<SettlementKits.Placed>();+ /// <summary>#2266: every replaceable landmark part (a minaret, a belfry, Jaffa's clock tower), with the names of the+ /// kit and close renderers that draw it as their submesh 1 (the code-built fallback), its yaw and its boxes far off and+ /// up close.</summary>+ public IReadOnlyList<LandmarkPart> LandmarkParts = System.Array.Empty<LandmarkPart>();public override string ToString() =>$"KITS buildings={Buildings} vertices={Vertices} triangles={Triangles} trees={Trees} route_segments={CorridorSegments} build_ms={BuildMs:0} plant_ms={PlantMs:0} " +$"localities={Localities} locality_buildings={LocalityBuildings} camps={Camps} tents={Tents} boats={Boats} draws={Draws} models={Models} close_vertices={CloseVertices}";}+ /// <summary>#2266: whether <paramref name="renderer"/> draws its mesh's submesh 1, the kit's code-built landmark parts+ /// (two materials), or not (one), when Tal Heuberger's models stand in their place.</summary>+ public static void ShowParts(Renderer renderer, bool on)+ {+ if (!(renderer.GetComponent<MeshFilter>()?.sharedMesh is Mesh mesh) || mesh.subMeshCount < 2) return;+ var m = renderer.sharedMaterial;+ renderer.sharedMaterials = on ? new[] { m, m } : new[] { m };+ }++ /// <summary>Whether the renderer draws its landmark parts (submesh 1).</summary>+ public static bool PartsShown(Renderer renderer) => renderer.sharedMaterials.Length > 1;+public static GameObject Build(IReadOnlyList<Settlement> settlements, Terrain terrain, GeoFrame frame, HexFile hexes, float elevMinM,Material kitMaterial, Material treeMaterial, TownModelSet? townModels, MapRuntimeAssets assets, GameObject markers, out Stats stats,IReadOnlyList<(List<Vector2> line, float halfWidth)>? corridors = null, Dictionary<string, Bounds[]>? columns = null) =>@@ -55,7 +80,7 @@ namespace Statecraft.Game.Map.Kitsstats.CorridorSegments = ground.CorridorSegments;if (tokens != null) ground.Tokens.AddRange(tokens);var clock = System.Diagnostics.Stopwatch.StartNew();- var built = SettlementKits.Build(settlements, localities, camps, ground, out var placed, columns); // columns: the labels' kit footprints (issue #214)+ var built = SettlementKits.Build(settlements, localities, camps, ground, out var placed, columns, replaceParts: true); // columns: the labels' kit footprints (issue #214)foreach (var l in built.Claimed) ground.Lots.Add((l.centre, l.radius));stats.Footprints = new List<(Vector2, float, string)>(ground.Footprints);MeshRenderer Add(string name, Mesh mesh, bool count = true)@@ -73,6 +98,7 @@ namespace Statecraft.Game.Map.Kits// Issue #659 (owner ruling on #700: "Models up close only"): each kit mesh, and beside it its close mesh (without// its buildings, with the models' plinths), which TownModelLayer swaps in when the camera is close.var swaps = new List<(Renderer kit, Renderer? close)>();+ var parts = new List<LandmarkPart>();var rendererTownIds = new Dictionary<Renderer, string>();var rendererTileIds = new Dictionary<Renderer, string[]>();Renderer AddKit(string name, Mesh mesh, string? townId = null)@@ -81,6 +107,14 @@ namespace Statecraft.Game.Map.KitsRenderer? close = null;if (built.Close.TryGetValue(mesh.name, out var cm)) { close = Add(name + CloseSuffix, cm, count: false); st.CloseVertices += cm.vertexCount; }swaps.Add((kit, close));+ // #2266: the kit's replaceable landmark parts are each mesh's submesh 1, drawn (the code-built fallback) until+ // Tal Heuberger's models stand in their place (HexPropModels gives the renderers one material then).+ if (built.Parts.TryGetValue(mesh.name, out var lp))+ {+ ShowParts(kit, true); if (close != null) ShowParts(close, true);+ foreach (var (kind, owner, yaw, far, near) in lp.Parts)+ parts.Add(new LandmarkPart(kind, owner, name, close != null ? name + CloseSuffix : null, yaw, far, near));+ }if (townId != null) rendererTownIds[kit] = townId;return kit;}@@ -112,6 +146,7 @@ namespace Statecraft.Game.Map.Kitsif (residency == null) throw new System.ArgumentNullException(nameof(residency));towns.ConfigureProduction(residency.Towns);towns.Init(built.Models, townModels, swaps, nearTowns, rendererTownIds, rendererTileIds);+ stats.LandmarkParts = parts;var localityIds = new HashSet<string>(System.StringComparer.Ordinal);foreach (var locality in localities) localityIds.Add(locality.Id);towns.ConfigureTownFootprints(stats.Footprints, localityIds);diff --git a/unity/Assets/Scripts/Map/Kits/KitMesh.cs b/unity/Assets/Scripts/Map/Kits/KitMesh.csindex 5ef88a8dc..bfdf8ab86 100644--- a/unity/Assets/Scripts/Map/Kits/KitMesh.cs+++ b/unity/Assets/Scripts/Map/Kits/KitMesh.cs@@ -45,22 +45,61 @@ namespace Statecraft.Game.Map.Kitsinternal Bounds CloseCopy((int v, int i) start, Vector3 anchor, float yawDeg, float along, float across, float up){CutEnd(start);- var to = Plinths;- int off = to.pos.Count;+ return Copy(start, (pos.Count, tri.Count), Plinths, anchor, yawDeg, along, across, up, new Bounds(anchor, Vector3.zero));+ }++ // ---- #2266 (owner, 2 November 2026: "tal's high quality models replace the built ones everytwhere") ----------------+ // A landmark's replaceable part (a minaret, a belfry, a clock tower) moves to a second submesh: of this mesh at the kit's+ // scale (FarParts), and of the close mesh as the close copy (CloseParts). Its renderer draws that submesh, the code-built+ // fallback, until the map gives it one material only, once Tal Heuberger's model stands there (HexPropModels).++ readonly List<(int v0, int v1, int i0, int i1)> detached = new List<(int, int, int, int)>();+ KitMesh? farParts, closeParts;+ internal KitMesh FarParts => farParts ??= new KitMesh();+ internal KitMesh CloseParts => closeParts ??= new KitMesh();+ internal bool HasParts => farParts != null;+ /// <summary>The replaceable parts detached from this mesh: their kind ("minaret", "belfry", "clock_tower"), owner, yaw+ /// and boxes far off and up close, in placement order.</summary>+ internal readonly List<(string kind, string owner, float yaw, Bounds far, Bounds close)> Parts = new List<(string, string, float, Bounds, Bounds)>();++ /// <summary>As CloseCopy for a landmark from <paramref name="start"/>, whose parts from <paramref name="part"/> on are a+ /// replaceable <paramref name="kind"/>: those leave this mesh for FarParts and their close copy goes to CloseParts, with+ /// the same transform as the rest. Returns the whole landmark's close box, as CloseCopy's.</summary>+ internal Bounds CloseCopySplit((int v, int i) start, (int v, int i) part, string kind, string owner, float partYaw,+ Vector3 anchor, float yawDeg, float along, float across, float up)+ {+ CutEnd(start);+ var end = (pos.Count, tri.Count);+ var b = Copy(start, part, Plinths, anchor, yawDeg, along, across, up, new Bounds(anchor, Vector3.zero));+ var close = Copy(part, end, CloseParts, anchor, yawDeg, along, across, up, new Bounds(anchor, Vector3.zero), fresh: true);+ b.Encapsulate(close);+ var far = Copy(part, end, FarParts, Vector3.zero, 0f, 1f, 1f, 1f, default, fresh: true);+ if (end.Item1 > part.v) detached.Add((part.v, end.Item1, part.i, end.Item2));+ Parts.Add((kind, owner, partYaw, far, close));+ return b;+ }++ /// <summary>Appends a copy of vertices and triangles [<paramref name="from"/>, <paramref name="to"/>) to+ /// <paramref name="into"/>, shrunk about <paramref name="anchor"/> as CloseCopy describes; returns <paramref name="b"/>+ /// grown by the copy (with <paramref name="fresh"/>, the copy's own box).</summary>+ Bounds Copy((int v, int i) from, (int v, int i) to, KitMesh into, Vector3 anchor, float yawDeg, float along, float across, float up,+ Bounds b, bool fresh = false)+ {+ int off = into.pos.Count;float a = yawDeg * Mathf.Deg2Rad, ca = Mathf.Cos(a), sa = Mathf.Sin(a);- var b = new Bounds(anchor, Vector3.zero);- for (int v = start.v; v < pos.Count; v++)+ bool first = fresh;+ for (int v = from.v; v < to.v; v++){Vector3 p = pos[v] - anchor, n = nrm[v];// Into the yaw's frame (u along, w across), scaled, and back; a normal by the inverse scale.float u = (p.x * ca + p.z * sa) * along, w = (-p.x * sa + p.z * ca) * across;float nu = (n.x * ca + n.z * sa) / along, nw = (-n.x * sa + n.z * ca) / across;var q = anchor + new Vector3(u * ca - w * sa, p.y > 0f ? p.y * up : p.y, u * sa + w * ca);- to.pos.Add(q); b.Encapsulate(q);- to.nrm.Add(new Vector3(nu * ca - nw * sa, p.y > 0f ? n.y / up : n.y, nu * sa + nw * ca).normalized);- to.col.Add(col[v]); to.uv.Add(uv[v]);+ into.pos.Add(q); if (first) { b = new Bounds(q, Vector3.zero); first = false; } else b.Encapsulate(q);+ into.nrm.Add(new Vector3(nu * ca - nw * sa, p.y > 0f ? n.y / up : n.y, nu * sa + nw * ca).normalized);+ into.col.Add(col[v]); into.uv.Add(uv[v]);}- for (int i = start.i; i < tri.Count; i++) to.tri.Add(tri[i] - start.v + off);+ for (int i = from.i; i < to.i; i++) into.tri.Add(tri[i] - from.v + off);return b;}/// <summary>Buildings marked (a test aid).</summary>@@ -96,12 +135,8 @@ namespace Statecraft.Game.Map.Kitsp.AddRange(plinths.pos); n.AddRange(plinths.nrm); c.AddRange(plinths.col); u.AddRange(plinths.uv);foreach (var i in plinths.tri) t.Add(i + off);}- if (t.Count == 0) return null;- var m = new Mesh { name = name, indexFormat = p.Count > 65000 ? IndexFormat.UInt32 : IndexFormat.UInt16 };- m.SetVertices(p); m.SetNormals(n); m.SetColors(c); m.SetUVs(0, u); m.SetTriangles(t, 0);- m.RecalculateBounds();- m.UploadMeshData(true);- return m;+ if (t.Count == 0 && (closeParts == null || closeParts.tri.Count == 0)) return null;+ return Upload(name, p, n, c, u, t, closeParts);}public int TriangleCount => tri.Count / 3;/// <summary>Vertices whose normal is not unit length (a degenerate face): the shader would light them as NaN on WebGL 2.</summary>@@ -109,6 +144,7 @@ namespace Statecraft.Game.Map.Kitspublic Mesh ToMesh(string name){+ if (detached.Count > 0) return Without(name, detached, farParts);var m = new Mesh { name = name, indexFormat = pos.Count > 65000 ? IndexFormat.UInt32 : IndexFormat.UInt16 };m.SetVertices(pos); m.SetNormals(nrm); m.SetColors(col); m.SetUVs(0, uv); m.SetTriangles(tri, 0);m.RecalculateBounds();@@ -116,6 +152,50 @@ namespace Statecraft.Game.Map.Kitsreturn m;}+ /// <summary>This mesh without the vertex and index spans <paramref name="ranges"/> (in order), as ToMesh uploads it.</summary>+ Mesh Without(string name, List<(int v0, int v1, int i0, int i1)> ranges, KitMesh? second)+ {+ var map = new int[pos.Count];+ var p = new List<Vector3>(); var n = new List<Vector3>(); var c = new List<Color32>(); var u = new List<Vector2>(); var t = new List<int>();+ int k = 0;+ for (int v = 0; v < pos.Count; v++)+ {+ while (k < ranges.Count && v >= ranges[k].v1) k++;+ if (k < ranges.Count && v >= ranges[k].v0) { map[v] = -1; continue; }+ map[v] = p.Count; p.Add(pos[v]); n.Add(nrm[v]); c.Add(col[v]); u.Add(uv[v]);+ }+ k = 0;+ for (int i = 0; i < tri.Count; i++)+ {+ while (k < ranges.Count && i >= ranges[k].i1) k++;+ if (k < ranges.Count && i >= ranges[k].i0) continue;+ int at = map[tri[i]];+ if (at < 0) throw new System.InvalidOperationException("a kept triangle uses a detached part's vertex");+ t.Add(at);+ }+ return Upload(name, p, n, c, u, t, second);+ }++ /// <summary>The mesh of these lists, with <paramref name="second"/>'s parts (if any) as submesh 1.</summary>+ static Mesh Upload(string name, List<Vector3> p, List<Vector3> n, List<Color32> c, List<Vector2> u, List<int> t, KitMesh? second)+ {+ var t1 = new List<int>();+ if (second != null && second.tri.Count > 0)+ {+ int off = p.Count;+ p.AddRange(second.pos); n.AddRange(second.nrm); c.AddRange(second.col); u.AddRange(second.uv);+ foreach (var i in second.tri) t1.Add(i + off);+ }+ var m = new Mesh { name = name, indexFormat = p.Count > 65000 ? IndexFormat.UInt32 : IndexFormat.UInt16 };+ m.SetVertices(p); m.SetNormals(n); m.SetColors(c); m.SetUVs(0, u);+ m.subMeshCount = t1.Count > 0 ? 2 : 1;+ m.SetTriangles(t, 0);+ if (t1.Count > 0) m.SetTriangles(t1, 1);+ m.RecalculateBounds();+ m.UploadMeshData(true);+ return m;+ }+/// <summary>The grid a kit's columns are counted on (Columns).</summary>public const int ColumnGrid = 4;diff --git a/unity/Assets/Scripts/Map/Kits/SettlementKits.Landmarks.cs b/unity/Assets/Scripts/Map/Kits/SettlementKits.Landmarks.csindex 2e5a738ef..66ec1f019 100644--- a/unity/Assets/Scripts/Map/Kits/SettlementKits.Landmarks.cs+++ b/unity/Assets/Scripts/Map/Kits/SettlementKits.Landmarks.cs@@ -54,6 +54,19 @@ namespace Statecraft.Game.Map.KitscloseLandmarks?.Add(new Placed(id, kind, at, yaw, b.size.x, b.size.z, b.max.y - y, default, y));}+ /// <summary>As AtWorldScale, where the landmark's parts from <paramref name="part"/> on are a replaceable+ /// <paramref name="partKind"/> (a minaret, a belfry, a clock tower; #2266, owner 2 November 2026: "tal's high quality+ /// models replace the built ones everytwhere"). On the main map (replaceParts) they leave the kit and close meshes+ /// for their own fallback meshes (KitMesh.CloseCopySplit); elsewhere the landmark is as AtWorldScale draws it.</summary>+ static void AtWorldScale(string id, string kind, KitMesh km, (int v, int i) start, (int v, int i) part, string partKind, float partYaw,+ Vector2 at, float y, float kitScale)+ {+ if (!replaceParts) { AtWorldScale(id, kind, km, start, at, y, kitScale); return; }+ float k = Mathf.Min(1f, ModelScale / kitScale);+ var b = km.CloseCopySplit(start, part, partKind, id, partYaw, new Vector3(at.x, y, at.y), 0f, k, k, k);+ closeLandmarks?.Add(new Placed(id, kind, at, 0f, b.size.x, b.size.z, b.max.y - y, default, y));+ }+static Vector2 World(KitGround g, double lon, double lat) { var w = g.Frame.ToWorld(lon, lat, 0); return new Vector2(w.x, w.z); }/// <summary>The unit vector from settlement <paramref name="s"/>'s point towards a sourced coordinate.</summary>@@ -105,7 +118,7 @@ namespace Statecraft.Game.Map.Kitskm.Box(p.x, p.y, 15f, 5f * m, 5f * m, y - 2f * m, y, 24f * m, stone, stone, Facade.Stone, m, roofed: true);km.Box(p.x, p.y, 15f, 4f * m, 4f * m, y + 24f * m, y + 24f * m, 4f * m, C(0.90f, 0.82f, 0.64f), stone, Facade.Plain, m, roofed: true);km.Pyramid(p.x, p.y, 15f, 4.4f * m, 4.4f * m, y + 28f * m, 3.5f * m, C(0.55f, 0.47f, 0.40f));- AtWorldScale(s.Id, "clock_tower", km, start, p, y, m);+ AtWorldScale(s.Id, "clock_tower", km, start, start, "clock_tower", 15f, p, y, m);Record(s.Id, "clock_tower", p, 15f, 5f * m, 5f * m, 31.5f * m, stone);n++;}@@ -507,10 +520,11 @@ namespace Statecraft.Game.Map.Kitskm.Dome(p.x, p.y, y + 7f * m - 0.5f * m, 5.5f * m, C(0.80f, 0.80f, 0.76f));float mx = p.x + 8.5f * m, mz = p.y - 6f * m;float my = ground.Y(mx, mz);+ var minaret = km.CutStart();km.Shaft(new Vector3(mx, my - 2f * m, mz), new Vector3(mx, my + 26f * m, mz), 1.6f * m, 1.35f * m, stone, 8);km.Shaft(new Vector3(mx, my + 20f * m, mz), new Vector3(mx, my + 21f * m, mz), 2.1f * m, 2.1f * m, stone, 8); // the balconykm.Cone(new Vector3(mx, my + 26f * m, mz), 1.5f * m, 4.5f * m, C(0.62f, 0.62f, 0.58f), 8);- AtWorldScale(owner, "mosque", km, start, p, y, m);+ AtWorldScale(owner, "mosque", km, start, minaret, "minaret", 0f, p, y, m);Record(owner, "mosque", p, 0f, 14f * m, 14f * m, 30.5f * m, stone);return 1;}@@ -533,9 +547,10 @@ namespace Statecraft.Game.Map.Kitskm.Box(p.x, p.y, yaw, w, d, bottom, top, 5.5f * m, stone, roof, Facade.Stone, m);float a = yaw * Mathf.Deg2Rad, u = 0.5f * w - 1.4f * m, v = -(0.5f * d - 1.4f * m);float mx = p.x + u * Mathf.Cos(a) - v * Mathf.Sin(a), mz = p.y + u * Mathf.Sin(a) + v * Mathf.Cos(a);+ var minaret = km.CutStart();km.Box(mx, mz, yaw, 2.8f * m, 2.8f * m, top + 5.5f * m - 0.3f * m, top + 5.5f * m, 7.9f * m, stone, roof, Facade.Plain, m);km.Box(mx, mz, yaw, 3.3f * m, 3.3f * m, top + 13.4f * m - 0.2f * m, top + 13.4f * m, 0.6f * m, stone, roof, Facade.Plain, m); // the balcony's parapet- AtWorldScale(owner, "village_mosque", km, start, p, top, m);+ AtWorldScale(owner, "village_mosque", km, start, minaret, "minaret", yaw, p, top, m);Record(owner, "village_mosque", p, yaw, w, d, 14f * m, stone);return 1;}@@ -550,10 +565,11 @@ namespace Statecraft.Game.Map.Kitsfloat yq = ground.Y(q.x, q.y);var start = km.CutStart();km.Box(q.x, q.y, 0f, 9f * m, 18f * m, yq - 2f * m, yq, 12f * m, stone, stone, Facade.Stone, m, roofed: true);+ km.Gable(q.x, q.y, 0f, 9f * m, 18f * m, yq + 12f * m, 4f * m, C(0.66f, 0.34f, 0.24f), stone);+ var belfry = km.CutStart(); // the belfry last, so it can be replaced (#2266)km.Box(q.x, q.y + 7f * m, 0f, 4.5f * m, 4.5f * m, yq + 12f * m, yq + 12f * m, 14f * m, stone, stone, Facade.Stone, m, roofed: true);km.Pyramid(q.x, q.y + 7f * m, 0f, 4.8f * m, 4.8f * m, yq + 26f * m, 6f * m, C(0.60f, 0.52f, 0.44f));- km.Gable(q.x, q.y, 0f, 9f * m, 18f * m, yq + 12f * m, 4f * m, C(0.66f, 0.34f, 0.24f), stone);- AtWorldScale(owner, "church", km, start, q, yq, m);+ AtWorldScale(owner, "church", km, start, belfry, "belfry", 0f, q, yq, m);Record(owner, "church", q, 0f, 9f * m, 18f * m, 32f * m, stone);return true;}diff --git a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs b/unity/Assets/Scripts/Map/Kits/SettlementKits.csindex 8c7b9bc18..33dc19aba 100644--- a/unity/Assets/Scripts/Map/Kits/SettlementKits.cs+++ b/unity/Assets/Scripts/Map/Kits/SettlementKits.cs@@ -120,13 +120,25 @@ namespace Statecraft.Game.Map.Kitsreturn all.Towns;}- /// <summary>As the full Build, also listing everything placed (<see cref="Placed"/>), in placement order.</summary>+ /// <summary>As the full Build, also listing everything placed (<see cref="Placed"/>), in placement order. With+ /// <paramref name="replaceParts"/> (the main map, KitLayer), the landmarks' minarets, belfries and Jaffa's clock tower+ /// leave the kit meshes for their own fallback meshes (<see cref="Result.Parts"/>), which Tal Heuberger's models+ /// replace once they stream (#2266).</summary>public static Result Build(IReadOnlyList<Settlement> towns, IReadOnlyList<Settlement> localities, IReadOnlyList<Localities.Area> camps,- KitGround ground, out List<Placed> placed, Dictionary<string, Bounds[]>? columns = null)+ KitGround ground, out List<Placed> placed, Dictionary<string, Bounds[]>? columns = null, bool replaceParts = false){- census = placed = new List<Placed>();+ census = placed = new List<Placed>(); SettlementKits.replaceParts = replaceParts;try { return Build(towns, localities, camps, ground, columns); }- finally { census = null; }+ finally { census = null; SettlementKits.replaceParts = false; }+ }++ [System.ThreadStatic] static bool replaceParts;++ /// <summary>#2266: a kit mesh's replaceable landmark parts (KitMesh.CloseCopySplit), drawn as submesh 1 of the kit mesh+ /// and of its close mesh: each part's kind, owner, yaw and boxes far off and up close.</summary>+ public sealed class LandmarkParts+ {+ public List<(string kind, string owner, float yaw, Bounds far, Bounds close)> Parts = new List<(string, string, float, Bounds, Bounds)>();}/// <summary>What <see cref="Build(IReadOnlyList{Settlement}, IReadOnlyList{Settlement}, IReadOnlyList{Localities.Area}, KitGround)"/>@@ -155,6 +167,8 @@ namespace Statecraft.Game.Map.Kits/// (SettlementKits.AtWorldScale): its kind, its anchor, and its copy's box (width along x, depth along z, height/// over its ground level Y), in placement order.</summary>public List<Placed> CloseLandmarks = new List<Placed>();+ /// <summary>#2266: the replaceable landmark parts of each kit mesh, by its name (only with replaceParts).</summary>+ public Dictionary<string, LandmarkParts> Parts = new Dictionary<string, LandmarkParts>();}/// <summary>Side of the square tiles the localities' and camps' buildings are merged into (the trees' tile size).</summary>@@ -175,6 +189,12 @@ namespace Statecraft.Game.Map.Kitsfinally { models = null; closeLandmarks = null; places = null; onceGiven = null; }}+ static void AddParts(Result result, KitMesh km, string meshName)+ {+ if (!km.HasParts) return;+ result.Parts[meshName] = new LandmarkParts { Parts = new List<(string, string, float, Bounds, Bounds)>(km.Parts) };+ }+static Result Build(IReadOnlyList<Settlement> towns, IReadOnlyList<Settlement> localities, IReadOnlyList<Localities.Area> camps,KitGround ground, Dictionary<string, Bounds[]>? columns, Result result){@@ -282,6 +302,7 @@ namespace Statecraft.Game.Map.Kitsif (columns != null && km.VertexCount > 0) columns[s.Id] = km.Columns();var mesh = km.ToMesh(s.Id + "_kit");if (km.ToCloseMesh(s.Id + "_close") is Mesh close) result.Close[mesh.name] = close;+ AddParts(result, km, mesh.name);result.Towns.Add((s, mesh, totals[i]));}// A locality's columns, from its own vertices in its tile (read before ToMesh drops the CPU copy).@@ -297,6 +318,7 @@ namespace Statecraft.Game.Map.Kits{var mesh = kv.Value.ToMesh($"localities_{kv.Key.Item1}_{kv.Key.Item2}");if (kv.Value.ToCloseMesh(mesh.name + "_close") is Mesh close) result.Close[mesh.name] = close;+ AddParts(result, kv.Value, mesh.name);result.Tiles.Add((TileName(kv.Key), mesh));}foreach (var id in spans.Keys)diff --git a/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs b/unity/Assets/Scripts/Map/Kits/TownModelLayer.csindex 8e5fa01f6..ccbd34e7c 100644--- a/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs+++ b/unity/Assets/Scripts/Map/Kits/TownModelLayer.cs@@ -35,6 +35,9 @@ namespace Statecraft.Game.Map.Kitsreadonly List<Tile> tiles = new List<Tile>();readonly Dictionary<string, List<SettlementKits.ModelInstance>> perPlace = new Dictionary<string, List<SettlementKits.ModelInstance>>();readonly List<(Renderer kit, Renderer? close)> swaps = new List<(Renderer, Renderer?)>();+ /// <summary>#2266: renderers that draw exactly when their leader (a kit or close renderer of <see cref="swaps"/>) does:+ /// the kit's replaceable landmark parts and Tal Heuberger's models standing in for them (HexPropModels).</summary>+ readonly Dictionary<Renderer, List<Renderer>> followers = new Dictionary<Renderer, List<Renderer>>();readonly Dictionary<Renderer, string> swapIds = new Dictionary<Renderer, string>();/// <summary>Each merged locality tile renderer's villages with building models: the tile swaps as one, only when every/// one of them is ready (<see cref="villageTiles"/>: each village's group).</summary>@@ -355,8 +358,23 @@ namespace Statecraft.Game.Map.KitsCount = instances.Count;foreach (var (kit, close) in this.swaps){ if (kit != null) kit.forceRenderingOff = false; if (close != null) close.forceRenderingOff = true; }+ followers.Clear();}+ /// <summary>#2266: <paramref name="follower"/> draws from now on exactly when <paramref name="leader"/> does, camera by+ /// camera; it takes the leader's state between cameras at once.</summary>+ internal void Follow(Renderer leader, Renderer follower)+ {+ if (!followers.TryGetValue(leader, out var list)) followers[leader] = list = new List<Renderer>();+ list.RemoveAll(r => r == null);+ if (!list.Contains(follower)) list.Add(follower);+ bool resting = leader.forceRenderingOff;+ foreach (var (renderer, off) in previousRenderers) if (renderer == leader) { resting = off; break; }+ follower.forceRenderingOff = resting;+ }++ internal void Unfollow(Renderer leader, Renderer follower) { if (followers.TryGetValue(leader, out var list)) list.Remove(follower); }+/// <summary>Records instantiated whole-town seats for diagnostics. Rendering decisions use WholeTownReady per/// camera; a seat loaded for another camera never suppresses this camera's fallback.</summary>public void Suppress(IEnumerable<string> ids)@@ -539,6 +557,8 @@ namespace Statecraft.Game.Map.Kits{if (renderer == null) return;previousRenderers.Add((renderer, renderer.forceRenderingOff)); renderer.forceRenderingOff = off;+ if (followers.TryGetValue(renderer, out var list))+ foreach (var f in list) if (f != null) { previousRenderers.Add((f, f.forceRenderingOff)); f.forceRenderingOff = off; }}internal void RestoreRenderers(){diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 6433fc5ff..3dd0f01e3 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -989,6 +989,11 @@ namespace Statecraft.Game.UIStatecraft.Game.Map.Collection.RuralLife.Show(map);// Tal Heuberger's Tegart fort, barracks and factory at their sourced places and dates, close up only, streamed (#707).Statecraft.Game.Map.Collection.SpecialBuildingModels.ShowAt(map, Bridge.State.Date);+ // Tal Heuberger's hex-tile props (owner, 27 October 2026: "2+3"; 2 November 2026: "Every zoom" for the landmarks): his+ // minarets, belfries and Jaffa's clock tower in place of the kit's at every zoom, so the bundle streams after the first+ // frame; the stations, camp tents, village hedges and hill scatter close up only, built at the first close camera.+ // After the layers they keep clear of.+ Statecraft.Game.Map.Collection.HexPropModels.ShowAt(map, Bridge.State.Date);// Tal Heuberger's ships off Haifa, Jaffa, Acre and (on the Altalena's turn) Tel Aviv, and the C-54 at Lod, streamed after the first frame (#669).seaAir = Statecraft.Game.Map.Collection.SeaAirCollection.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content);RenderSitesIfChanged();diff --git a/unity/Assets/Tests/EditMode/HexPropModelsTests.cs b/unity/Assets/Tests/EditMode/HexPropModelsTests.csnew file mode 100644index 000000000..b9ddc57c8--- /dev/null+++ b/unity/Assets/Tests/EditMode/HexPropModelsTests.cs@@ -0,0 +1,865 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Globalization;+using System.IO;+using System.Linq;+using System.Text.RegularExpressions;+using NUnit.Framework;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Collection;+using Statecraft.HexTiles;+using UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using YamlDotNet.RepresentationModel;++namespace Statecraft.Game.Tests+{+ /// <summary>Tal Heuberger's hex-tile props on the main map (owner, 27 October 2026, "2+3"; 2 November 2026: "make sure all of+ /// tal's new models are used"): only at the places the content names, clear, upright, deterministic, close up only, and+ /// their bundle asked for only at the close zoom (the load gate, owner 15 October 2026).</summary>+ public sealed class HexPropModelsTests+ {+ static readonly DateTime Opening = new DateTime(1948, 5, 15), YarkonLink = new DateTime(1949, 9, 20);++ /// <summary>Every rail route's `via` waypoint in routes_1948.yaml whose name says "station", with the earliest `from` of+ /// the routes through it (a bare year is its 1 January, as RoutePaths.Bound reads it).</summary>+ static Dictionary<string, (double lon, double lat, DateTime from)> NamedStations()+ {+ var yaml = new YamlStream();+ yaml.Load(new StringReader(File.ReadAllText(Path.Combine(Paths.Content, "map", "routes_1948.yaml"))));+ var routes = (YamlSequenceNode)((YamlMappingNode)yaml.Documents[0].RootNode)["routes"];+ var got = new Dictionary<string, (double, double, DateTime)>(StringComparer.Ordinal);+ string S(YamlNode n, string key) => ((YamlScalarNode)((YamlMappingNode)n)[key]).Value!;+ foreach (var r in routes.Children)+ {+ if (S(r, "kind") != "rail") continue;+ string f = S(r, "from");+ var from = f.Length == 4 ? new DateTime(int.Parse(f, CultureInfo.InvariantCulture), 1, 1)+ : DateTime.ParseExact(f, "yyyy-MM-dd", CultureInfo.InvariantCulture);+ // A route's `to` (none today) would end its stations' window, as RouteWindow and make_board.rail_stations read it.+ Assert.IsFalse(((YamlMappingNode)r).Children.ContainsKey(new YamlScalarNode("to")), S(r, "id") + " has an end date: give its stations a To");+ foreach (var w in ((YamlSequenceNode)((YamlMappingNode)r)["via"]).Children)+ {+ string name = S(w, "name");+ if (name.IndexOf("station", StringComparison.OrdinalIgnoreCase) < 0) continue;+ double lon = double.Parse(S(w, "lon"), CultureInfo.InvariantCulture), lat = double.Parse(S(w, "lat"), CultureInfo.InvariantCulture);+ got[name] = got.TryGetValue(name, out var had) ? (lon, lat, had.Item3 < from ? had.Item3 : from) : (lon, lat, from);+ }+ }+ return got;+ }++ [Test]+ public void TheStationsAreExactlyTheRailwaysNamedStationsFromTheirRoutesFirstDay()+ {+ var want = NamedStations();+ Assert.AreEqual(20, want.Count, "routes_1948.yaml names 20 stations on its railways");+ CollectionAssert.AreEquivalent(want.Keys, HexPropModels.Stations.Select(s => s.Name), "no station is invented or left out");+ foreach (var s in HexPropModels.Stations)+ {+ var (lon, lat, from) = want[s.Name];+ Assert.AreEqual(lon, s.Lon, 1e-9, s.Name); Assert.AreEqual(lat, s.Lat, 1e-9, s.Name);+ Assert.AreEqual(from, s.From, s.Name + ": drawn from its route's first day");+ }+ }++ [Test]+ public void AStationIsDrawnOnlyInsideItsRoutesWindow()+ {+ var s = new HexPropModels.RailStation("x", 0, 0, new DateTime(1920, 1, 1), new DateTime(1949, 9, 1));+ Assert.IsFalse(s.DrawnOn(new DateTime(1919, 12, 31)));+ Assert.IsTrue(s.DrawnOn(new DateTime(1948, 5, 15)));+ Assert.IsFalse(s.DrawnOn(new DateTime(1949, 9, 1)), "to is exclusive, as RouteWindow.Covers");+ Assert.IsTrue(HexPropModels.Stations.All(x => x.To == null), "no route through a station has an end date today");+ }++ [Test]+ public void SizesAreTheDesignValuesAtTheOneWorldScale()+ {+ Assert.AreEqual(12f * Statecraft.Game.Map.Kits.SettlementKits.ModelScale, HexPropModels.SizeOf(HexPropModels.Station), 1e-3f);+ Assert.AreEqual(RuralLife.SizeOf(RuralLife.BedouinTent), HexPropModels.SizeOf(HexPropModels.Tent), 1e-3f, "the same tent size as RuralLife's");+ Assert.AreEqual(4f * Statecraft.Game.Map.Kits.SettlementKits.ModelScale, HexPropModels.SizeOf(HexPropModels.PricklyPear), 1e-3f);+ foreach (var id in HexPropModels.Models) Assert.IsTrue(HexProps.Has(id), id + " is one of the bundle's props");+ }++ [Test]+ public void TheSpotIsTheNearestClearRingWithinReachAndDeterministic()+ {+ var anchor = new Vector2(100f, 200f);+ bool Free(Vector2 p, float r) => (p - anchor).magnitude > 1000f;+ var a = HexPropModels.NearestSpot("x", anchor, 100f, Free, 0f, 4400f);+ Assert.AreEqual(a, HexPropModels.NearestSpot("x", anchor, 100f, Free, 0f, 4400f));+ // Rings at 150 m + 50 m steps: 1000 m is not clear, 1050 m is the first that is.+ Assert.AreEqual(1050f, (a!.Value - anchor).magnitude, 0.01f);+ Assert.IsNull(HexPropModels.NearestSpot("x", anchor, 100f, Free, 0f, 900f), "nothing beyond its reach");+ Assert.IsNull(HexPropModels.NearestSpot("x", anchor, 100f, (_, __) => false, 0f, 4400f));+ var outside = HexPropModels.NearestSpot("x", anchor, 100f, (_, __) => true, 500f, 400f);+ Assert.AreEqual(650f, (outside!.Value - anchor).magnitude, 0.01f, "from the start radius out");+ }++ // ---- on the real map, with the real prefabs ----++ Action<string, Action<GameObject?>> saved = null!;+ Action<string, CollectionDetail, Action<GameObject?>> savedPeople = null!, savedRural = null!, savedSpecial = null!;+ readonly List<(string id, Action<GameObject?> done)> asked = new List<(string, Action<GameObject?>)>();++ [SetUp]+ public void Seam()+ {+ saved = HexPropModels.Request; savedPeople = CivilianPeople.Request; savedRural = RuralLife.Request; savedSpecial = SpecialBuildingModels.Request;+ asked.Clear();+ HexPropModels.Request = (id, done) => asked.Add((id, done));+ // The layers the props keep clear of: the civilians' places without their figures (as SpecialBuildingModelsTests),+ // the rural scenes and the special buildings with the editor's prefabs, as the player's stream would answer them.+ CivilianPeople.Request = (id, detail, done) => { };+ RuralLife.Request = SpecialBuildingModels.Request = (id, detail, done) =>+ done(AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, detail)));+ }++ [TearDown]+ public void Restore()+ {+ HexPropModels.Request = saved; CivilianPeople.Request = savedPeople; RuralLife.Request = savedRural; SpecialBuildingModels.Request = savedSpecial;+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ }++ static MapScene OpenMap()+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ var map = UnityEngine.Object.FindFirstObjectByType<MapScene>();+ map.Build();+ return map;+ }++ static Camera At(float height)+ {+ var cam = Camera.main!;+ cam.transform.SetPositionAndRotation(new Vector3(0f, height, 0f), Quaternion.Euler(90f, 0f, 0f));+ return cam;+ }++ void AnswerAll(bool found = true)+ {+ var pending = asked.ToList(); asked.Clear();+ foreach (var (id, done) in pending) done(found ? AssetDatabase.LoadAssetAtPath<GameObject>(HexProps.PrefabPath(id)) : null);+ }++ /// <summary>The map as GameRoot shows it: the layers the props keep clear of first, then the props, then a close camera.</summary>+ HexPropModels Show(MapScene map, DateTime date)+ {+ CollectionGeometryFixture.People(map, date, Array.Empty<Statecraft.Sim.Placement>(), Statecraft.Sim.ContentLoader.Load(Paths.Content));+ CollectionGeometryFixture.Rural(map);+ CollectionGeometryFixture.Special(map, date);+ var layer = HexPropModels.ShowAt(map, date)!;+ Assert.IsNotNull(layer);+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ AnswerAll();+ return layer;+ }++ /// <summary>The load gate. The kit's minarets, belfries and clock tower draw at every zoom, so the first camera to render+ /// asks once for the props (after the first frame); the standalone props still draw only up close.</summary>+ [Test]+ public void ThePropsAreAskedForOnceByTheFirstCameraAndTheStandaloneOnesDrawOnlyUpClose()+ {+ var map = OpenMap();+ var layer = HexPropModels.ShowAt(map, Opening)!;+ Assert.IsFalse(layer.Requested, "nothing is asked for before a camera renders");+ layer.Choose(default, At(60000f));+ Assert.IsTrue(layer.Requested, "the kit has landmark parts to replace at this zoom");+ CollectionAssert.AreEquivalent(HexPropModels.Models, asked.Select(a => a.id), "one request per prop");+ AnswerAll();+ Assert.Greater(layer.Replaced.Count, 0, "the landmark models stand from the first camera");+ Assert.AreEqual(0, layer.Placed.Count, "the standalone props wait for the first close camera (#2266 review: none draws further out)");+ layer.Choose(default, At(60000f));+ Assert.AreEqual(0, layer.Placed.Count);+ HexPropModels.ShowAt(map, Opening.AddDays(1));+ Assert.AreEqual(0, layer.Placed.Count, "a date change before any close camera builds nothing either");+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ Assert.Greater(layer.Placed.Count, 0, "built at the first close camera");+ layer.Choose(default, At(60000f));+ Assert.IsTrue(layer.Placed.All(p => layer.transform.Find(p.Name).GetComponentsInChildren<Renderer>(true).All(r => r.forceRenderingOff)),+ "no standalone prop draws beyond the close zoom");+ CollectionAssert.IsEmpty(asked, "asked once");+ }++ /// <summary>#2266 review of the tamarisk round: the main map's props, from the first camera to the first close one, ask+ /// for the hex-props bundle alone. Never the tamarisk's (only the boards draw it; no tamarisk on the main map, #1951),+ /// and never the papyrus's (HulaPapyrusLayer asks for that one at the Hula).</summary>+ [Test]+ public void TheMainMapsPropsAskOnlyForTheHexPropsBundle()+ {+ var map = OpenMap();+ var layer = HexPropModels.ShowAt(map, Opening)!;+ layer.Choose(default, At(60000f));+ var ids = asked.Select(a => a.id).ToList();+ AnswerAll();+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ ids.AddRange(asked.Select(a => a.id));+ Assert.That(ids, Is.Not.Empty, "the first camera asked for the props");+ CollectionAssert.AreEquivalent(new[] { HexProps.Bundle }, ids.Select(HexProps.Catalog.BundleOf).Distinct(),+ "the bundles the main map's props ask for: " + string.Join(", ", ids));+ }++ // ---- #2266 rulings (owner, 2 November 2026) ----++ static Transform Kits(MapScene map) => map.transform.Find(Statecraft.Game.Map.Kits.KitLayer.RootName)!;++ /// <summary>"tal's high quality models replace the built ones everytwhere": every minaret, belfry and clock tower the kit+ /// builds (the mosques of the localities and towns, the churches, Jaffa's clock tower) is a replaceable part, and once the+ /// props stream each has Tal Heuberger's model far off and up close, standing where the part stood, as tall as it, while+ /// the kit's own part is hidden.</summary>+ [Test]+ public void TalsModelsReplaceEveryKitMinaretBelfryAndClockTower()+ {+ var map = OpenMap();+ var parts = map.KitStats.LandmarkParts;+ int minarets = parts.Count(p => p.Kind == "minaret"), belfries = parts.Count(p => p.Kind == "belfry");+ TestContext.WriteLine($"parts: {minarets} minarets, {belfries} belfries, {parts.Count(p => p.Kind == "clock_tower")} clock towers, {parts.Select(p => p.Kit).Distinct().Count()} kit meshes");+ Assert.Greater(minarets, 200, "the mosques of the 1948 localities and the Arab towns");+ Assert.GreaterOrEqual(belfries, 1, "Jaffa's St Peter's and the Christian localities' churches");+ Assert.AreEqual("jaffa", parts.Single(p => p.Kind == "clock_tower").Owner, "Jaffa's clock tower");+ Assert.IsTrue(parts.Any(p => p.Kind == "belfry" && p.Owner == "jaffa"), "St Peter's belfry");+ var layer = Show(map, Opening);+ Assert.AreEqual(parts.Count, layer.Replaced.Count(r => !r.Close), "one far model per part");+ Assert.AreEqual(parts.Count(p => p.Close != null), layer.Replaced.Count(r => r.Close), "one close model per part with a close mesh");+ var kits = Kits(map);+ foreach (var kit in parts.Select(p => p.Kit).Distinct())+ {+ Assert.IsFalse(Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(kit).GetComponent<Renderer>()), kit + ": the kit's own parts are hidden far off");+ var close = kits.Find(kit + Statecraft.Game.Map.Kits.KitLayer.CloseSuffix);+ if (close != null) Assert.IsFalse(Statecraft.Game.Map.Kits.KitLayer.PartsShown(close.GetComponent<Renderer>()), kit + ": and up close");+ }+ var holder = layer.transform.Find(HexPropModels.LandmarksName);+ var ground = PlacementLayer.CampGround(map);+ foreach (var kit in parts.Select(p => p.Kit).Distinct())+ Assert.AreEqual(1, kits.Cast<Transform>().Count(t => t.name == kit), kit + ": one kit renderer by that name (they are found by name)");+ int n = 0;+ foreach (var group in parts.GroupBy(p => p.Kit))+ {+ int i = 0;+ foreach (var part in group)+ {+ var go = holder.Find($"{part.Owner}:{part.Kind}:{i}:far"); Assert.IsNotNull(go, part.Owner + " " + part.Kind);+ var b = go!.GetComponentsInChildren<Renderer>(true).Select(r => r.bounds).Aggregate((x, y) => { x.Encapsulate(y); return x; });+ Assert.AreEqual(part.Far.max.y, b.max.y, 0.02f * part.Far.size.y + 0.5f, part.Owner + ": as tall as the kit's part");+ Assert.AreEqual(part.Far.center.x, b.center.x, 0.5f, part.Owner + ": where the part stood");+ Assert.AreEqual(part.Far.center.z, b.center.z, 0.5f);+ // On the part's own base: the roof for a village minaret or a belfry, the ground for a part with foundations.+ Assert.AreEqual(Mathf.Max(part.Far.min.y, ground.Y(part.Far.center.x, part.Far.center.z)), b.min.y, 0.5f, part.Owner + " " + part.Kind + ": on the part's base");+ Assert.Less(Vector3.Angle(go.up, Vector3.up), 0.01f, part.Owner + ": upright");+ i++; n++;+ }+ }+ Assert.AreEqual(parts.Count, n);+ }++ /// <summary>Each landmark model draws exactly when its kit part would: the far one with the kit mesh, the close one with+ /// the close mesh, camera by camera (TownModelLayer's swap).</summary>+ [Test]+ public void TheLandmarkModelsFollowTheirKitRenderersSwap()+ {+ var map = OpenMap();+ var layer = Show(map, Opening);+ var kits = Kits(map);+ var towns = kits.GetComponentInChildren<Statecraft.Game.Map.Kits.TownModelLayer>(true);+ var holder = layer.transform.Find(HexPropModels.LandmarksName);+ foreach (var height in new[] { 60000f, (float)CameraController.MinDistance })+ {+ var cam = At(height);+ towns.PrepareCamera(cam);+ try+ {+ foreach (var part in map.KitStats.LandmarkParts.GroupBy(p => p.Kit).Select(g => g.First()))+ {+ var kit = kits.Find(part.Kit).GetComponent<Renderer>();+ foreach (var r in holder.Find($"{part.Owner}:{part.Kind}:0:far").GetComponentsInChildren<Renderer>(true))+ Assert.AreEqual(kit.forceRenderingOff, r.forceRenderingOff, part.Kit + " far, at " + height);+ if (part.Close == null) continue;+ var close = kits.Find(part.Close).GetComponent<Renderer>();+ foreach (var r in holder.Find($"{part.Owner}:{part.Kind}:0:close").GetComponentsInChildren<Renderer>(true))+ Assert.AreEqual(close.forceRenderingOff, r.forceRenderingOff, part.Kit + " close, at " + height);+ }+ }+ finally { towns.RestoreRenderers(); }+ }+ }++ /// <summary>Never an empty spot: until the props answer, and for good when the bundle fails, the kit draws its own parts.</summary>+ [Test]+ public void TheKitKeepsItsOwnPartsUntilAndUnlessTalsModelsStream()+ {+ var map = OpenMap();+ var kits = Kits(map);+ var parts = map.KitStats.LandmarkParts;+ Assert.Greater(parts.Count, 0);+ var layer = HexPropModels.ShowAt(map, Opening)!;+ layer.Choose(default, At(60000f));+ foreach (var kit in parts.Select(p => p.Kit).Distinct())+ Assert.IsTrue(Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(kit).GetComponent<Renderer>()), kit + ": drawn while streaming");+ foreach (var m in HexPropModels.Models) LogAssert.Expect(LogType.Warning, new Regex(Regex.Escape($"HEXPROPS: {m} did not stream")));+ AnswerAll(found: false);+ Assert.AreEqual(0, layer.Replaced.Count);+ foreach (var kit in parts.Select(p => p.Kit).Distinct())+ Assert.IsTrue(Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(kit).GetComponent<Renderer>()), kit + ": drawn when the bundle fails");+ // A layer that replaced them gives them back when it goes.+ UnityEngine.Object.DestroyImmediate(layer.gameObject);+ var again = Show(map, Opening);+ Assert.Greater(again.Hidden.Count, 0);+ UnityEngine.Object.DestroyImmediate(again.gameObject);+ Assert.IsTrue(parts.Select(p => p.Kit).Distinct().All(k => Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(k).GetComponent<Renderer>())), "the kit draws its parts again");+ }++ /// <summary>The kit draws no part twice: the replaced parts are gone from the kit and close meshes and drawn only by their+ /// fallbacks; off the main map (SettlementKits.Build without replaceParts) the landmarks are whole, as before.</summary>+ [Test]+ public void ThePartsLeaveTheKitMeshesOnlyOnTheMainMap()+ {+ var map = OpenMap();+ var kits = Kits(map);+ var part = map.KitStats.LandmarkParts.First(p => p.Kind == "minaret");+ var kitMesh = kits.Find(part.Kit).GetComponent<MeshFilter>().sharedMesh;+ Assert.AreEqual(2, kitMesh.subMeshCount, "the parts are the kit mesh's submesh 1");+ var sub = kitMesh.GetSubMesh(1);+ Assert.Greater(sub.indexCount, 0);+ Assert.IsTrue(sub.bounds.Contains(part.Far.center), "submesh 1 holds the part");+ Assert.Less(kitMesh.GetSubMesh(0).bounds.max.y, part.Far.max.y + 1f, "submesh 0 does not reach above the part's top through it");+ var ground = PlacementLayer.CampGround(map);+ var plain = Statecraft.Game.Map.Kits.SettlementKits.Build(map.Settlements, new List<Settlement>(), new List<Statecraft.Game.Map.Kits.Localities.Area>(), ground, out _);+ CollectionAssert.IsEmpty(plain.Parts, "no replaceable parts off the main map");+ }++ /// <summary>"Hedge row of several clumps": each village's hedge is 3 to 5 clumps in a row along its edge, clear of the+ /// kit footprints, one and a quarter clumps apart.</summary>+ [Test]+ public void EachVillagesHedgeIsARowOfThreeToFiveClumpsAlongItsEdge()+ {+ var map = OpenMap();+ var layer = Show(map, Opening);+ var footprints = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();+ var rows = layer.Placed.Where(p => p.Model == HexPropModels.PricklyPear).GroupBy(p => p.Key).ToList();+ Assert.Greater(rows.Count, 200);+ foreach (var row in rows)+ {+ var pts = row.Select(p => new Vector2(p.At.x, p.At.z)).ToList();+ Assert.AreEqual(HexPropModels.HedgeClumps(row.Key), pts.Count, row.Key);+ Assert.That(pts.Count, Is.InRange(3, 5), row.Key);+ for (int i = 1; i < pts.Count; i++)+ Assert.AreEqual(HexPropModels.HedgeSpacingSizes * HexPropModels.SizeOf(HexPropModels.PricklyPear), (pts[i] - pts[i - 1]).magnitude, 1f, row.Key + ": evenly spaced");+ var dir = (pts[pts.Count - 1] - pts[0]).normalized;+ for (int i = 1; i < pts.Count - 1; i++) Assert.Less(Mathf.Abs(Vector3.Cross(dir, (pts[i] - pts[0]).normalized).z), 0.01f, row.Key + ": in a row");+ foreach (var p in pts) Assert.IsTrue(Statecraft.Game.Map.Collection.TownLandmarks.Clear(p, HexPropModels.ClearanceOf(HexPropModels.PricklyPear), footprints), row.Key);+ }+ Assert.Greater(rows.Sum(r => r.Count()), 3 * 200);+ }++ /// <summary>"Sparse, close zoom only": one garrigue and one scrub per land hex of biome hills or mountains, near the+ /// point FNV-1a picks in it, on clear ground, drawn only up close; none on other ground.</summary>+ [Test]+ public void GarrigueAndScrubAreALightScatterOnOpenHillGroundOnlyUpClose()+ {+ var map = OpenMap();+ var hill = map.Hexes.hexes.Where(h => h.land && (h.biome == "hills" || h.biome == "mountains")).ToList();+ var wants = HexPropModels.Wants(map, Opening);+ Assert.AreEqual(hill.Count, wants.Count(w => w.Model == HexPropModels.Garrigue));+ Assert.AreEqual(hill.Count, wants.Count(w => w.Model == HexPropModels.Scrub));+ var hexM = map.Hexes.hex_size_km * 1000f;+ var layer = Show(map, Opening);+ var ground = PlacementLayer.CampGround(map);+ var footprints = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();+ var byKey = wants.ToDictionary(w => w.Key);+ var scatter = layer.Placed.Where(p => p.Model == HexPropModels.Garrigue || p.Model == HexPropModels.Scrub).ToList();+ TestContext.WriteLine($"scatter: {scatter.Count} placed of {2 * hill.Count} wanted");+ Assert.Greater(scatter.Count, hill.Count, "most hill hexes have their two plants");+ foreach (var p in scatter)+ {+ var flat = new Vector2(p.At.x, p.At.z); float r = HexPropModels.ClearanceOf(p.Model);+ var w = byKey[p.Key];+ var q = w.Key.Split(':')[1].Split(','); var h = hill.Single(x => x.q == int.Parse(q[0]) && x.r == int.Parse(q[1]));+ var c = map.Frame.ToWorld(h.lon, h.lat, 0);+ Assert.LessOrEqual((flat - new Vector2(c.x, c.z)).magnitude, HexPropModels.ScatterReachHex * hexM + HexPropModels.ReachOf(p.Model, hexM) + 1f, p.Key + ": in its hill hex");+ Assert.IsTrue(Statecraft.Game.Map.Collection.TownLandmarks.Clear(flat, r, footprints), p.Key + " clear of the towns");+ Assert.IsFalse(ground.OnRoute(flat, r), p.Key + " clear of the routes");+ Assert.IsFalse(ground.OnToken(flat, r, Opening), p.Key + " clear of the tokens");+ }+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseExitM + 1f));+ Assert.IsTrue(scatter.All(p => layer.transform.Find(p.Name).GetComponentsInChildren<Renderer>(true).All(x => x.forceRenderingOff)), "close zoom only");+ }++ /// <summary>Each prop stands just outside its sourced place, clear of the towns' footprints, the routes, the unit tokens,+ /// water, the other Collection layers and each other, upright on the prefab's own axes, on the ground, with no kit tree+ /// on it, and hidden beyond the close zoom.</summary>+ [Test]+ public void OnTheMapEachPropStandsBesideItsPlaceClearUprightAndOnlyUpClose()+ {+ var map = OpenMap();+ var layer = Show(map, YarkonLink);+ var wants = layer.Wanted.ToDictionary(w => w.Key);+ int camps = map.KitFootprints.Count(f => f.id.StartsWith("camp:", StringComparison.Ordinal));+ int villages = map.Localities.Select(p => p.Settlement).Where(s => s.Type == "village").Select(s => s.Id).Distinct()+ .Count(id => map.KitFootprints.Any(f => f.id == id));+ Assert.AreEqual(20, wants.Values.Count(w => w.Model == HexPropModels.Station));+ Assert.AreEqual(camps, wants.Values.Count(w => w.Model == HexPropModels.Tent), "one tent per Bedouin camp");+ Assert.AreEqual(camps, wants.Values.Select(w => w.Key).Where(k => k.StartsWith("camp:", StringComparison.Ordinal)).Distinct().Count(), "each camp keyed once");+ Assert.AreEqual(villages, wants.Values.Count(w => w.Model == HexPropModels.PricklyPear), "one hedge per Arab village");+ Assert.Greater(camps, 0); Assert.Greater(villages, 100);+ foreach (var m in HexPropModels.Models)+ TestContext.WriteLine($"{m}: {layer.Placed.Count(p => p.Model == m)} placed of {wants.Values.Count(w => w.Model == m)}");+ // A station is left out only when no clear ground lies within one hex of its point, which happens only for a station+ // inside a city's kit footprint (Jaffa, Jerusalem's Khan and Haifa East on this map).+ var footprintsAll = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();+ var unplaced = wants.Values.Where(w => w.Model == HexPropModels.Station && layer.Placed.All(p => p.Key != w.Key)).ToList();+ foreach (var w in unplaced)+ {+ TestContext.WriteLine($"{w.Key}: not drawn, {SpecialBuildingModels.Inside(w.Anchor, footprintsAll):0} m inside a kit footprint");+ Assert.Greater(SpecialBuildingModels.Inside(w.Anchor, footprintsAll), 0f, w.Key + " is left out only inside a town's footprint");+ }+ Assert.GreaterOrEqual(20 - unplaced.Count, 17, "the stations outside the three cities all stand");+ Assert.GreaterOrEqual(layer.Placed.Count(p => p.Model == HexPropModels.Tent), (int)(0.9f * camps), "nearly every camp has its tent");+ Assert.GreaterOrEqual(layer.Placed.Where(p => p.Model == HexPropModels.PricklyPear).Select(p => p.Key).Distinct().Count(), (int)(0.9f * villages), "nearly every village has its hedge");++ var ground = PlacementLayer.CampGround(map);+ var footprints = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();+ var others = RuralLife.OtherProps(map);+ foreach (var p in map.Terrain.transform.Find(RuralLife.Name).GetComponent<RuralLife>().Placed) others.Add((new Vector2(p.At.x, p.At.z), RuralLife.SceneRadiusM(p.Model)));+ foreach (var p in map.Terrain.transform.Find(SpecialBuildingModels.Name).GetComponent<SpecialBuildingModels>().Placed)+ others.Add((new Vector2(p.At.x, p.At.z), SpecialBuildingModels.ClearanceOf(p.Model)));+ var spots = new List<(Vector2, float, string)>();+ foreach (var p in layer.Placed)+ {+ var w = wants[p.Key]; var flat = new Vector2(p.At.x, p.At.z); float r = HexPropModels.ClearanceOf(p.Model);+ float off = (flat - w.Anchor).magnitude;+ if (p.Model == HexPropModels.Station) TestContext.WriteLine($"{p.Key}: {off:0} m from its sourced point");+ // A hedge's clumps stand in a row about its spot (EachVillagesHedgeIsARowOfThreeToFiveClumpsAlongItsEdge).+ float row = p.Model == HexPropModels.PricklyPear ? 0.5f * 4f * HexPropModels.HedgeSpacingSizes * HexPropModels.SizeOf(p.Model) : 0f;+ Assert.LessOrEqual(off, w.Start + HexPropModels.ReachOf(p.Model, ground.HexSizeM) + row + 1e-2f, p.Key + " stands beside its place");+ Assert.IsTrue(Statecraft.Game.Map.Collection.TownLandmarks.Clear(flat, r, footprints), p.Key + " clear of every kit footprint");+ Assert.IsFalse(ground.OnRoute(flat, r), p.Key + " clear of the routes");+ Assert.IsFalse(ground.OnToken(flat, r, YarkonLink), p.Key + " clear of the unit tokens");+ Assert.IsFalse(ground.Water(flat.x, flat.y), p.Key + " on land");+ Assert.IsTrue(Statecraft.Game.Map.Collection.TownLandmarks.Clear(flat, r, others), p.Key + " clear of the other Collection layers");+ Assert.IsTrue(Statecraft.Game.Map.Collection.TownLandmarks.Clear(flat, r, spots.Where(x => x.Item3 != p.Key).Select(x => (x.Item1, x.Item2)).ToList()), p.Key + " clear of the other props");+ spots.Add((flat, r, p.Key));+ var go = layer.transform.Find(p.Name)!;+ var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(HexProps.PrefabPath(p.Model));+ Assert.Less(Vector3.Angle(go.up, prefab.transform.up), 0.01f, p.Key + " upright: turned only about the vertical");+ var rs = go.GetComponentsInChildren<Renderer>(true);+ var b = rs.Select(x => x.bounds).Aggregate((x, y) => { x.Encapsulate(y); return x; });+ Assert.AreEqual(p.At.y, b.min.y, 1f, p.Key + " stands on the ground");+ // Its long side seen from above, in its own axes (the box of a turned model is wider than the model).+ float side = go.GetComponentsInChildren<MeshFilter>(true).Max(f =>+ { var s = Vector3.Scale(f.sharedMesh.bounds.size, f.transform.lossyScale); return Mathf.Max(s.x, s.z); });+ Assert.AreEqual(HexPropModels.SizeOf(p.Model), side, 0.02f * HexPropModels.SizeOf(p.Model), p.Key + " at its world size");+ Assert.IsTrue(rs.All(x => !x.forceRenderingOff), p.Key + " drawn at the close zoom");+ }+ var veg = map.GetComponentInChildren<Statecraft.Game.Map.Kits.VegetationLayer>(true);+ foreach (var p in layer.Placed)+ {+ float r = HexPropModels.ClearanceOf(p.Model);+ int n = veg.Drawable().Count(t =>+ {+ var q = t.m.GetColumn(3); float reach = r + Statecraft.Game.Map.Kits.VegetationLayer.CrownRadius(t.kind, t.m);+ return (new Vector2(q.x, q.z) - new Vector2(p.At.x, p.At.z)).sqrMagnitude < reach * reach;+ });+ Assert.AreEqual(0, n, p.Key + ": kit trees on the prop");+ }+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseExitM + 1f));+ Assert.IsTrue(layer.Placed.All(p => layer.transform.Find(p.Name).GetComponentsInChildren<Renderer>(true).All(x => x.forceRenderingOff)), "hidden beyond the close zoom's exit");+ }++ /// <summary>The same map and date place the same props at the same spots.</summary>+ [Test]+ public void PlacementIsDeterministic()+ {+ var map = OpenMap();+ var first = Show(map, Opening).Placed.ToList();+ UnityEngine.Object.DestroyImmediate(map.Terrain.transform.Find(HexPropModels.Name).gameObject);+ var second = Show(map, Opening).Placed.ToList();+ Assert.Greater(first.Count, 0);+ CollectionAssert.AreEqual(first, second);+ }++ /// <summary>Absent where the content gives no place: the Yarkon link's two stations before its first day, a prickly pear+ /// at any place that is not an Arab village, a tent anywhere but a Bedouin camp; and nothing at all when the bundle+ /// fails (the map goes on).</summary>+ [Test]+ public void NothingStandsWhereTheContentGivesNoPlace()+ {+ var map = OpenMap();+ var opening = HexPropModels.Wants(map, Opening);+ CollectionAssert.DoesNotContain(opening.Select(w => w.Key), "station:Petah Tikva railway station (1921)");+ CollectionAssert.DoesNotContain(opening.Select(w => w.Key), "station:Tel Aviv North railway station");+ Assert.AreEqual(18, opening.Count(w => w.Model == HexPropModels.Station));+ Assert.AreEqual(20, HexPropModels.Wants(map, YarkonLink).Count(w => w.Model == HexPropModels.Station));+ var villages = new HashSet<string>(map.Localities.Select(p => p.Settlement).Where(s => s.Type == "village").Select(s => s.Id));+ Assert.IsTrue(opening.Where(w => w.Model == HexPropModels.PricklyPear).All(w => villages.Contains(w.Key)), "prickly pears at Arab villages only");+ foreach (var s in map.Settlements) CollectionAssert.DoesNotContain(opening.Select(w => w.Key), s.Id, s.Id + ": a game town takes no village prop");+ Assert.IsTrue(opening.Where(w => w.Model == HexPropModels.Tent).All(w => w.Key.StartsWith("camp:", StringComparison.Ordinal)), "tents at Bedouin camps only");+ Assert.IsTrue(opening.All(w => w.Model != HexPropModels.Station || w.Key.StartsWith("station:", StringComparison.Ordinal)));++ var layer = HexPropModels.ShowAt(map, Opening)!;+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ foreach (var m in HexPropModels.Models) LogAssert.Expect(LogType.Warning, new Regex(Regex.Escape($"HEXPROPS: {m} did not stream")));+ AnswerAll(found: false);+ Assert.AreEqual(0, layer.Placed.Count, "a failed bundle leaves the props off the map");+ Assert.AreEqual(0, layer.transform.childCount - (layer.transform.Find(HexPropModels.LandmarksName) != null ? 1 : 0));+ }++ /// <summary>Review of #2266 (blocking): the props keep clear of where the special buildings and rural scenes WILL stand+ /// (their plans), not of what has streamed so far. With the props answered first and those layers streaming in after,+ /// nothing overlaps, and the props stand exactly where they stand when everything streamed first.</summary>+ [Test]+ public void PropsStandInTheSamePlacesWhateverStreamedFirstAndNothingLandsOnThem()+ {+ var map = OpenMap();+ var waiting = new List<(string id, CollectionDetail detail, Action<GameObject?> done)>();+ RuralLife.Request = SpecialBuildingModels.Request = (id, detail, done) => waiting.Add((id, detail, done));+ CollectionGeometryFixture.People(map, Opening, Array.Empty<Statecraft.Sim.Placement>(), Statecraft.Sim.ContentLoader.Load(Paths.Content));+ var rural = CollectionGeometryFixture.Rural(map)!;+ var special = CollectionGeometryFixture.Special(map, Opening)!;+ var layer = HexPropModels.ShowAt(map, Opening)!;+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ AnswerAll();+ Assert.AreEqual(0, rural.Placed.Count + special.Placed.Count, "the props stood before the rural scenes and the buildings streamed");+ var propsFirst = layer.Placed.Select(p => (p.Name, p.At)).ToList();+ // Others is the layer's keep-clear ground (static before #2266's review fixes, per layer after): by reflection, so+ // this test runs red against either.+ var keptClearBefore = (List<(Vector2 centre, float radius)>)typeof(HexPropModels).GetMethod("Others",+ System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance)!+ .Invoke(layer, new object[] { map, Opening })!;+ for (int round = 0; round < 10 && waiting.Count > 0; round++)+ {+ var now = waiting.ToList(); waiting.Clear();+ foreach (var (id, detail, done) in now) done(AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, detail)));+ }+ Assert.Greater(rural.Placed.Count, 0); Assert.Greater(special.Placed.Count, 0);+ // What the props kept clear of before anything streamed already held every spot those layers then took.+ foreach (var p in rural.Placed.Where(x => x.Member == 0).Select(x => (x.Key, x.At)).Concat(special.Placed.Select(x => (x.Key, x.At))))+ Assert.IsTrue(keptClearBefore.Any(d => (d.centre - new Vector2(p.At.x, p.At.z)).magnitude < 1f),+ p.Key + ": its planned spot was kept clear before it streamed");+ var theirs = rural.Placed.Select(p => (new Vector2(p.At.x, p.At.z), RuralLife.SceneRadiusM(p.Model)))+ .Concat(special.Placed.Select(p => (new Vector2(p.At.x, p.At.z), SpecialBuildingModels.ClearanceOf(p.Model)))).ToList();+ foreach (var p in layer.Placed)+ Assert.IsTrue(Statecraft.Game.Map.Collection.TownLandmarks.Clear(new Vector2(p.At.x, p.At.z), HexPropModels.ClearanceOf(p.Model), theirs),+ p.Name + ": no rural scene or building streamed in on it");+ UnityEngine.Object.DestroyImmediate(layer.gameObject);+ var after = HexPropModels.ShowAt(map, Opening)!;+ after.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ AnswerAll();+ CollectionAssert.AreEqual(propsFirst, after.Placed.Select(p => (p.Name, p.At)).ToList(), "the same places in either order");+ }++ sealed class Lease : IDisposable { public void Dispose() { } }++ /// <summary>Review of #2266's delta, C1, on today's map: with one model withheld and the rest streamed in later, every+ /// rural scene and special building stands at its spot in the plan with every model available, and none lands on a hex+ /// prop. On today's map no single model's absence moves another scene or building, so this test cannot fail on its own+ /// for C1 (it passes on the old code too): it guards the real map's ordering and overlap. C1 itself is covered by the+ /// constructed case, AStreamedModelStandsAtItsFullPlanSpotWhenAnEarlierOneHasNotStreamed (the farm scenes; #2281 fixes+ /// SpecialBuildingModels.Plan the same way).</summary>+ [Test]+ public void ScenesAndBuildingsStandAtTheirFullPlanSpotsWhateverHasStreamed()+ {+ var map = OpenMap();+ CollectionGeometryFixture.People(map, Opening, Array.Empty<Statecraft.Sim.Placement>(), Statecraft.Sim.ContentLoader.Load(Paths.Content));+ var ruralWants = RuralLife.Wants(map); var ruralOthers = RuralLife.OtherProps(map);+ var full = RuralLife.Plan(map, ruralWants, ruralOthers, _ => true).ToDictionary(x => x.want.Key + "|" + x.want.Model, x => x.spot);+ // On today's map no single rural model's absence moves another scene (the constructed case shows the flaw); the+ // first model is withheld here.+ string withheld = RuralLife.Models[0];+ var waiting = new List<(string id, CollectionDetail detail, Action<GameObject?> done)>();+ RuralLife.Request = SpecialBuildingModels.Request = (id, detail, done) => waiting.Add((id, detail, done));+ var rural = CollectionGeometryFixture.Rural(map)!;+ var special = CollectionGeometryFixture.Special(map, Opening)!;+ var layer = HexPropModels.ShowAt(map, Opening)!;+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ AnswerAll();+ var props = layer.Placed.Select(p => (new Vector2(p.At.x, p.At.z), HexPropModels.ClearanceOf(p.Model))).ToList();+ void Answer(Func<string, bool> which)+ {+ for (int round = 0; round < 10; round++)+ {+ var now = waiting.Where(x => which(x.id)).ToList(); if (now.Count == 0) return;+ foreach (var x in now) { waiting.Remove(x); x.done(AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(x.id, x.detail))); }+ }+ }+ void Check(string stage)+ {+ foreach (var p in rural.Placed.Where(x => x.Member == 0))+ {+ Assert.IsTrue(full.TryGetValue(p.Key + "|" + p.Model, out var f), stage + ": " + p.Key + " " + p.Model + " is in the full plan");+ Assert.Less((f - new Vector2(p.At.x, p.At.z)).magnitude, 1f, stage + ": " + p.Key + " " + p.Model + " at its full-plan spot");+ }+ var plan = SpecialBuildingModels.Plan(map, Opening, SpecialBuildingModels.Placements(Opening), _ => true, log: false).ToDictionary(x => x.want.Key, x => x.at);+ foreach (var p in special.Placed) Assert.Less((plan[p.Key] - new Vector2(p.At.x, p.At.z)).magnitude, 1f, stage + ": " + p.Key + " at its full-plan spot");+ var theirs = rural.Placed.Select(p => (new Vector2(p.At.x, p.At.z), RuralLife.SceneRadiusM(p.Model)))+ .Concat(special.Placed.Select(p => (new Vector2(p.At.x, p.At.z), SpecialBuildingModels.ClearanceOf(p.Model)))).ToList();+ foreach (var (c, r) in props) Assert.IsTrue(Statecraft.Game.Map.Collection.TownLandmarks.Clear(c, r, theirs), stage + ": a prop at " + c + " is landed on");+ }+ // Everything but the withheld model (and, for the buildings, the barracks) streams; then the rest, in reverse order.+ Answer(id => id != withheld && id != SpecialBuildingModels.Barracks);+ Assert.Greater(rural.Placed.Count, 0);+ Check("a subset streamed");+ Answer(id => true);+ Check("everything streamed");+ }++ /// <summary>Review of #2266's delta, C1 (the farm scenes; #2281 fixes SpecialBuildingModels.Plan the same way), constructed:+ /// two wants on one anchor, keyed so that the second stands+ /// elsewhere in the plan with the first model than in the plan without it. Only the second model streams; it must stand+ /// at its full-plan spot (where the hex props keep clear), not where the first one's absence would let it.</summary>+ [Test]+ public void AStreamedModelStandsAtItsFullPlanSpotWhenAnEarlierOneHasNotStreamed()+ {+ var map = OpenMap();+ CollectionGeometryFixture.People(map, Opening, Array.Empty<Statecraft.Sim.Placement>(), Statecraft.Sim.ContentLoader.Load(Paths.Content));+ var waiting = new List<(string id, CollectionDetail detail, Action<GameObject?> done)>();+ RuralLife.Request = SpecialBuildingModels.Request = (id, detail, done) => waiting.Add((id, detail, done));+ void Answer(string model)+ {+ for (int round = 0; round < 10; round++)+ {+ var now = waiting.Where(x => x.id == model).ToList(); if (now.Count == 0) return;+ foreach (var x in now) { waiting.Remove(x); x.done(AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(x.id, x.detail))); }+ }+ }+ // Rural: a sheep on a planned scene's anchor at its first ring, and a donkey on the same anchor keyed so that its+ // first candidate (RuralLife.Spot: FNV-1a of model and key picks the bearing) is the sheep's spot: in the plan with+ // the sheep it must go elsewhere, alone (the old greedy subset plan) it would stand there.+ var others = RuralLife.OtherProps(map);+ var real = RuralLife.Plan(map, RuralLife.Wants(map), others, _ => true);+ List<RuralLife.Want>? pair = null; Vector2 fullSpot = default, subSpot = default;+ foreach (var (seed, _) in real)+ {+ for (int k = 0; k < 64 && pair == null; k++)+ {+ var a = new RuralLife.Want("c1:" + k, RuralLife.Sheep, seed.Anchor, seed.AnchorRadius);+ var alone = RuralLife.Plan(map, new[] { a }, others, _ => true);+ if (alone.Count != 1) continue;+ var off = alone[0].spot - seed.Anchor;+ if (Mathf.Abs(off.magnitude - (seed.AnchorRadius + RuralLife.ClearanceRadiusM * RuralLife.FirstRingClearances)) > 1f) continue;+ int bearing = ((int)Mathf.Round(Mathf.Atan2(off.y, off.x) * Mathf.Rad2Deg / (360f / RuralLife.Bearings)) % RuralLife.Bearings + RuralLife.Bearings) % RuralLife.Bearings;+ for (int j = 0; j < 256 && pair == null; j++)+ {+ var b = new RuralLife.Want("c1b:" + k + ":" + j, RuralLife.Donkey, seed.Anchor, seed.AnchorRadius);+ if (RuralLife.StableHash(b.Model + ":" + b.Key) % (uint)RuralLife.Bearings != bearing) continue;+ var full = RuralLife.Plan(map, new[] { a, b }, others, _ => true);+ var sub = RuralLife.Plan(map, new[] { b }, others, _ => true);+ if (full.Count == 2 && sub.Count == 1 && (full[1].spot - sub[0].spot).sqrMagnitude > 1f)+ { pair = new List<RuralLife.Want> { a, b }; fullSpot = full[1].spot; subSpot = sub[0].spot; }+ }+ }+ if (pair != null) break;+ }+ var rural = CollectionGeometryFixture.Rural(map)!;+ typeof(RuralLife).GetMethod("Show", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!+ .Invoke(rural, new object[] { pair!, others });+ Answer(RuralLife.Donkey);+ var donkey = rural.Placed.Where(p => p.Model == RuralLife.Donkey && p.Key == pair![1].Key).ToList();+ Assert.IsNotEmpty(donkey, "the donkey streamed and stands");+ Assert.Less((new Vector2(donkey[0].At.x, donkey[0].At.z) - fullSpot).magnitude, 1f,+ $"the donkey at its full-plan spot {fullSpot}, not {subSpot} where the absent sheep's ground would put it");+ }++ /// <summary>Review of #2266 at f9802bed6, C1: a standalone prop stands in the same place whichever props have streamed,+ /// in whatever order, and whichever failed: every want takes its ground, and only the streamed ones are drawn.</summary>+ [Test]+ public void StandalonePropsStandInTheSamePlacesWhateverStreamedOrFailed()+ {+ var map = OpenMap();+ List<(string Name, string Model, Vector3 At)> Run(Func<string, bool> answered, bool reverse)+ {+ var old = map.Terrain.transform.Find(HexPropModels.Name);+ if (old != null) UnityEngine.Object.DestroyImmediate(old.gameObject);+ asked.Clear();+ var layer = HexPropModels.ShowAt(map, Opening)!;+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ var pending = asked.ToList(); asked.Clear();+ if (reverse) pending.Reverse();+ foreach (var (id, done) in pending) done(answered(id) ? AssetDatabase.LoadAssetAtPath<GameObject>(HexProps.PrefabPath(id)) : null);+ return layer.Placed.Select(p => (p.Name, p.Model, p.At)).ToList();+ }+ var all = Run(_ => true, reverse: false);+ Assert.Greater(all.Count, 1000);+ int moved = 0;+ foreach (var missing in HexPropModels.Standalone)+ {+ var some = Run(id => id != missing, reverse: true);+ var expected = all.Where(p => p.Model != missing).ToList();+ CollectionAssert.AreEquivalent(expected.Select(p => p.Name), some.Select(p => p.Name), missing + " failed: the same props stand");+ var at = expected.ToDictionary(p => p.Name, p => p.At);+ foreach (var p in some) if ((at[p.Name] - p.At).magnitude >= 1f) moved++;+ TestContext.WriteLine($"{missing} failed: {some.Count} props, {some.Count(p => (at[p.Name] - p.At).magnitude >= 1f)} moved");+ }+ Assert.AreEqual(0, moved, "no prop moves when another model is missing or the answers come in another order");+ }++ /// <summary>Review of #2266 at f9802bed6, C2: a camera that asks for the props while rendering does not get its answer+ /// built inside the render, even when the answer comes at once: the request waits for LateUpdate.</summary>+ [Test]+ public void NothingIsBuiltInsideACameraRender()+ {+ var map = OpenMap();+ HexPropModels.Request = (id, done) => done(AssetDatabase.LoadAssetAtPath<GameObject>(HexProps.PrefabPath(id))); // answers at once+ var layer = HexPropModels.ShowAt(map, Opening)!;+ var flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;+ typeof(HexPropModels).GetMethod("ChooseCore", flags)!.Invoke(layer, new object[] { At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM), true });+ Assert.AreEqual(0, layer.Replaced.Count, "no landmark model instantiated inside the render");+ Assert.AreEqual(0, layer.Placed.Count, "no standalone prop instantiated inside the render");+ typeof(HexPropModels).GetMethod("LateUpdate", flags)!.Invoke(layer, null);+ Assert.Greater(layer.Replaced.Count, 0, "built after the render");+ Assert.Greater(layer.Placed.Count, 0);+ }++ /// <summary>Review of #2266 at f9802bed6, C3: the close switch writes the standalone renderers only when it changes,+ /// not for every camera every frame.</summary>+ [Test]+ public void TheCloseSwitchWritesOnlyAChange()+ {+ var map = OpenMap();+ var layer = Show(map, Opening);+ var r = layer.transform.Find(layer.Placed[0].Name).GetComponentInChildren<Renderer>();+ Assert.IsFalse(r.forceRenderingOff, "drawn up close");+ r.forceRenderingOff = true; // a marker: an unchanged switch must not touch it+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ Assert.IsTrue(r.forceRenderingOff, "still close: nothing written");+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseExitM + 1f));+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ Assert.IsFalse(r.forceRenderingOff, "a change writes every renderer");+ }++ /// <summary>Review of #2266 at f9802bed6, C6: the kits are built only by MapScene.Build, which first destroys the map's+ /// children, this layer and Tal Heuberger's models with them. After a rebuild no model is left over, and the new kit+ /// draws its own parts until a new layer replaces them.</summary>+ [Test]+ public void AMapRebuildLeavesNoModelBehindAndTheKitWhole()+ {+ var map = OpenMap();+ var layer = Show(map, Opening);+ Assert.Greater(layer.Replaced.Count, 0);+ map.Build();+ Assert.IsTrue(layer == null, "the layer went with the old map");+ Assert.AreEqual(0, UnityEngine.Object.FindObjectsByType<HexPropModels>(FindObjectsInactive.Include, FindObjectsSortMode.None).Length);+ Assert.AreEqual(0, UnityEngine.Object.FindObjectsByType<Transform>(FindObjectsInactive.Include, FindObjectsSortMode.None)+ .Count(t => t.name.EndsWith(":far", StringComparison.Ordinal) || t.name.EndsWith(":close", StringComparison.Ordinal)), "no landmark model left over");+ var kits = Kits(map);+ Assert.IsTrue(map.KitStats.LandmarkParts.Select(p => p.Kit).Distinct()+ .All(k => Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(k).GetComponent<Renderer>())), "the new kit draws its own parts");+ }++ /// <summary>Review of #2266's delta, C2: a disabled layer hides Tal Heuberger's models under it, so the kit draws its own+ /// parts again; enabled again, the models stand in for them. Never an empty spot.</summary>+ [Test]+ public void ADisabledLayerGivesTheKitItsPartsBack()+ {+ var map = OpenMap();+ var layer = Show(map, Opening);+ var kits = Kits(map);+ var kitNames = map.KitStats.LandmarkParts.Select(p => p.Kit).Distinct().ToList();+ Assert.IsTrue(kitNames.All(k => !Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(k).GetComponent<Renderer>())));+ layer.gameObject.SetActive(false);+ Assert.IsTrue(kitNames.All(k => Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(k).GetComponent<Renderer>())), "the kit's own parts while the models are off");+ layer.gameObject.SetActive(true);+ Assert.IsTrue(kitNames.All(k => !Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(k).GetComponent<Renderer>())), "the models stand in again");+ }++ /// <summary>Review of #2266's delta, C3: an answer that never comes holds back only what needs it. With the belfry and+ /// the garrigue never answered, every kit mesh without a belfry has Tal Heuberger's models and the other standalone+ /// props stand; the kit meshes with a belfry keep their own parts.</summary>+ [Test]+ public void AnAnswerThatNeverComesHoldsBackOnlyWhatNeedsIt()+ {+ var map = OpenMap();+ var layer = HexPropModels.ShowAt(map, Opening)!;+ layer.Choose(default, At(Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM));+ var pending = asked.ToList(); asked.Clear();+ foreach (var (id, done) in pending)+ if (id != HexPropModels.Belfry && id != HexPropModels.Garrigue) done(AssetDatabase.LoadAssetAtPath<GameObject>(HexProps.PrefabPath(id)));+ var parts = map.KitStats.LandmarkParts;+ var withBelfry = new HashSet<string>(parts.Where(p => p.Kind == "belfry").Select(p => p.Kit));+ var kits = Kits(map);+ foreach (var kit in parts.Select(p => p.Kit).Distinct())+ Assert.AreEqual(withBelfry.Contains(kit), Statecraft.Game.Map.Kits.KitLayer.PartsShown(kits.Find(kit).GetComponent<Renderer>()),+ kit + (withBelfry.Contains(kit) ? ": keeps its own parts (its belfry never came)" : ": Tal's models stand"));+ Assert.Greater(layer.Placed.Count(p => p.Model == HexPropModels.Station), 0, "the stations stand");+ Assert.Greater(layer.Placed.Count(p => p.Model == HexPropModels.PricklyPear), 0, "the hedges stand");+ Assert.AreEqual(0, layer.Placed.Count(p => p.Model == HexPropModels.Garrigue));+ }++ /// <summary>Review of #2266 with #2271: no standalone prop stands under a whole-town model (TownLandmarks), whose square+ /// reaches its core's radius times the square root of two from the core, past the kit footprint's edge for a core off+ /// the centre. The models are answered at once here; the props plan the seats, so the order does not matter.</summary>+ [Test]+ public void NoPropStandsUnderAWholeTownModel()+ {+ var map = OpenMap();+ var savedR = TownLandmarks.Request; var savedA = TownLandmarks.Acquire;+ try+ {+ GameObject? Prefab(string id, CollectionDetail d) => AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, d));+ TownLandmarks.Request = (id, d, done) => done(Prefab(id, d));+ TownLandmarks.Acquire = (id, d, done) => { done(Prefab(id, d)); return new Lease(); };+ var towns = TownLandmarks.ShowAt(map, Opening, Array.Empty<Statecraft.Sim.Placement>(), Statecraft.Sim.ContentLoader.Load(Paths.Content))!;+ towns.Choose(default, At(60000f));+ var layer = Show(map, Opening);+ Assert.Greater(towns.Seats.Count, 10, "the whole towns stand");+ int checkedProps = 0;+ foreach (var kv in towns.Seats)+ {+ float reach = 0.5f * kv.Value.Edge * Mathf.Sqrt(2f);+ foreach (var p in layer.Placed)+ {+ float d = (new Vector2(p.At.x, p.At.z) - kv.Value.Centre).magnitude;+ Assert.GreaterOrEqual(d + 1f, reach + HexPropModels.ClearanceOf(p.Model), p.Name + " under " + kv.Key + "'s whole-town model");+ checkedProps++;+ }+ }+ Assert.Greater(checkedProps, 0);+ }+ finally { TownLandmarks.Request = savedR; TownLandmarks.Acquire = savedA; }+ }++ /// <summary>Review of #2266: the load each zoom band adds, capped (the design budget the PR measured; see its load+ /// table). Far bands: no standalone prop, and the landmark models in view under the cap. Close views: the standalone+ /// props and landmark models in view under the cap. Counted with each camera's kit swap applied.</summary>+ [Test]+ public void EachZoomBandStaysInsideItsPropBudget()+ {+ var map = OpenMap();+ var layer = Show(map, Opening);+ var towns = Kits(map).GetComponentInChildren<Statecraft.Game.Map.Kits.TownModelLayer>(true);+ var rig = Camera.main!.GetComponent<CameraRig>();+ var planes = new Plane[6];+ int Tris(Renderer r) => r.GetComponent<MeshFilter>() is MeshFilter f && f.sharedMesh != null ? (int)(f.sharedMesh.triangles.Length / 3) : 0;+ var views = new List<PromoPose>(PromoPose.All); views.AddRange(PromoPose.CloseUps); views.AddRange(PromoPose.TownChecks);+ foreach (var pose in views)+ {+ pose.Apply(rig, map.Frame);+ var cam = Camera.main!;+ layer.Choose(default, cam); towns.PrepareCamera(cam);+ try+ {+ GeometryUtility.CalculateFrustumPlanes(cam, planes);+ bool Seen(Renderer r) => r.enabled && !r.forceRenderingOff && r.gameObject.activeInHierarchy && GeometryUtility.TestPlanesAABB(planes, r.bounds);+ var standalone = layer.Placed.SelectMany(p => layer.transform.Find(p.Name).GetComponentsInChildren<Renderer>(true)).Where(Seen).ToList();+ var holder = layer.transform.Find(HexPropModels.LandmarksName);+ Assert.IsNotNull(holder, "the landmark models stand");+ var landmarks = holder.GetComponentsInChildren<Renderer>(true).Where(Seen).ToList();+ bool close = pose.Distance <= Statecraft.Game.Map.Kits.TownModelLayer.CloseEnterM;+ TestContext.WriteLine($"BUDGET {pose.Name} ({pose.Distance:0} m): standalone {standalone.Count} / {standalone.Sum(Tris)} tris, landmarks {landmarks.Count} / {landmarks.Sum(Tris)} tris");+ if (!close) Assert.AreEqual(0, standalone.Count, pose.Name + ": no standalone prop beyond the close zoom");+ Assert.LessOrEqual(standalone.Count, MaxStandaloneInView, pose.Name);+ Assert.LessOrEqual(standalone.Sum(Tris), MaxStandaloneTrisInView, pose.Name);+ Assert.LessOrEqual(landmarks.Sum(Tris), MaxLandmarkTrisInView, pose.Name);+ }+ finally { towns.RestoreRenderers(); }+ }+ }++ // The budget (design values, set from the PR's measurements with headroom; a delta that needs more must say so).+ const int MaxStandaloneInView = 400, MaxStandaloneTrisInView = 250000, MaxLandmarkTrisInView = 900000;+ }+}diff --git a/unity/Assets/Tests/EditMode/HexPropModelsTests.cs.meta b/unity/Assets/Tests/EditMode/HexPropModelsTests.cs.metanew file mode 100644index 000000000..09d33ceeb--- /dev/null+++ b/unity/Assets/Tests/EditMode/HexPropModelsTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: e9d5af7c8eba242f7b2a65942457bad8\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/HexPropsTests.cs b/unity/Assets/Tests/EditMode/HexPropsTests.csindex f7bd4742c..c2398cf9c 100644--- a/unity/Assets/Tests/EditMode/HexPropsTests.cs+++ b/unity/Assets/Tests/EditMode/HexPropsTests.cs@@ -14,8 +14,8 @@ using UnityEngine.TestTools;/// <summary>The hex tiles' 20 Higgsfield props (Tal Heuberger, #1155) and their papyrus and tamarisk (#2082; owner, 2 November/// 2026: "Hula + Arava, map and boards (Recommended)") load under the owner's ruling of 23 October 2026, "Own streamed/// bundle": outside every Resources folder (so the default first download does not carry them), outside The 1948-/// Collection (which stays Tal's Tripo models), and in bundles of their own that only a ?hex-tiles board (or, for the-/// papyrus alone, the main map's Hula at close zoom) asks for.</summary>+/// Collection (which stays Tal's Tripo models), and in bundles of their own that only a ?hex-tiles board or the main map+/// (HexPropModels, its first camera; and, for the papyrus, the main map's Hula at close zoom) asks for.</summary>public class HexPropsTests{const string Art = "Assets/Art/HexTiles/";@@ -76,24 +76,31 @@ public class HexPropsTestsAssert.AreNotEqual(CollectionCatalog.ChecksFile, HexProps.ChecksFile);}- const string PapyrusPrefab = "Assets/Art/HexTiles/hula_swamp/papyrus.prefab";+ const string PapyrusPrefab = "Assets/Art/HexTiles/hula_swamp/papyrus.prefab", TamariskPrefab = "Assets/Art/HexTiles/arava_oasis/tamarisk.prefab";[Test]public void TheHexPropsBundlesCarryTheTwentyTwoPropsAndNothingElse(){var builds = Builds();- Assert.AreEqual(2, builds.Length);+ Assert.AreEqual(3, builds.Length);Assert.AreEqual("hex-props", builds[0].assetBundleName);- CollectionAssert.AreEqual(Prefabs.Where(p => p != PapyrusPrefab), builds[0].assetNames);+ CollectionAssert.AreEqual(Prefabs.Where(p => p != PapyrusPrefab && p != TamariskPrefab), builds[0].assetNames);// The papyrus alone in its own bundle: the main map's Hula fetches it without the boards' other props.Assert.AreEqual("hex-props-papyrus", builds[1].assetBundleName);CollectionAssert.AreEqual(new[] { PapyrusPrefab }, builds[1].assetNames);+ // The tamarisk alone in its own bundle: only the boards draw it, so the main map's first camera does not fetch it.+ Assert.AreEqual("hex-props-tamarisk", builds[2].assetBundleName);+ CollectionAssert.AreEqual(new[] { TamariskPrefab }, builds[2].assetNames);Assert.AreEqual("hex-props-papyrus", HexProps.BundleOf("tiles:hula_swamp/papyrus"));- Assert.AreEqual("hex-props", HexProps.BundleOf("tiles:arava_oasis/tamarisk"));+ Assert.AreEqual("hex-props-tamarisk", HexProps.BundleOf("tiles:arava_oasis/tamarisk"));+ Assert.IsTrue(HexProps.Has("tiles:jaffa_old_city/clock_tower"), "a prop that stays in hex-props");+ Assert.AreEqual("hex-props", HexProps.BundleOf("tiles:jaffa_old_city/clock_tower"));Assert.IsNull(HexProps.BundleOf("tiles:negev_loess/tamarisk"), "the other tamarisk ids stay stand-ins (#1950, #1952)");- CollectionAssert.IsEmpty(AssetDatabase.GetDependencies(builds[0].assetNames, true).Intersect(- AssetDatabase.GetDependencies(builds[1].assetNames, true)).Where(d => d.StartsWith(Art, StringComparison.Ordinal)),- "the two bundles share no prop file");+ for (int a = 0; a < builds.Length; a++)+ for (int b = a + 1; b < builds.Length; b++)+ CollectionAssert.IsEmpty(AssetDatabase.GetDependencies(builds[a].assetNames, true).Intersect(+ AssetDatabase.GetDependencies(builds[b].assetNames, true)).Where(d => d.StartsWith(Art, StringComparison.Ordinal)),+ $"{builds[a].assetBundleName} and {builds[b].assetBundleName} share a prop file");CollectionAssert.AreEqual(Prefabs, HexProps.Ids.Select(HexProps.PrefabPath));// Every prefab under the props' folder is in the bundle (none is left behind), and every dependency stays in it.var found = AssetDatabase.FindAssets("t:Prefab", new[] { Art.TrimEnd('/') }).Select(AssetDatabase.GUIDToAssetPath);@@ -105,6 +112,24 @@ public class HexPropsTestsforeach (var id in HexProps.Ids) StringAssert.StartsWith("tiles:", id);}+ /// <summary>The main map's first camera fetches the hex-props bundle (HexPropModels), so it carries neither of #2082's+ /// split-out props: the papyrus streams alone for the Hula's close view (the main map's only use of it), the tamarisk+ /// alone for the boards (no tamarisk on the main map, #1951). With the tamarisk in hex-props, #2278's build measured 9,470,644 B for it+ /// instead of 5,830,676 B.</summary>+ [Test]+ public void TheHexPropsBundleCarriesNoBoardOnlyProp()+ {+ var main = Builds().Single(b => b.assetBundleName == HexProps.Bundle).assetNames;+ var mainFiles = AssetDatabase.GetDependencies(main, true);+ foreach (var id in new[] { HexProps.Papyrus, HexProps.Tamarisk })+ {+ Assert.AreNotEqual(HexProps.Bundle, HexProps.BundleOf(id), id);+ CollectionAssert.DoesNotContain(main, HexProps.PrefabPath(id), id);+ CollectionAssert.IsEmpty(AssetDatabase.GetDependencies(HexProps.PrefabPath(id), true).Intersect(mainFiles)+ .Where(d => d.StartsWith(Art, StringComparison.Ordinal)), id + "'s files in the hex-props bundle");+ }+ }+[Test]public void TheCollectionsLoaderServesThePropsFromTheirOwnCatalog(){diff --git a/unity/Assets/Tests/EditMode/TalModelsShots.cs b/unity/Assets/Tests/EditMode/TalModelsShots.csindex 3215bd590..b1fc1ecf4 100644--- a/unity/Assets/Tests/EditMode/TalModelsShots.cs+++ b/unity/Assets/Tests/EditMode/TalModelsShots.cs@@ -10,6 +10,7 @@ using Statecraft.Game.Map.Collection;using Statecraft.Game.Map.Kits;using Statecraft.Game.Map.Units;using Statecraft.Game.UI;+using Statecraft.HexTiles;using Statecraft.Sim;using UnityEditor;using UnityEditor.SceneManagement;@@ -31,6 +32,7 @@ public class TalModelsShotsGameRoot root = null!;Action<string, CollectionDetail, Action<GameObject?>>? savedRural, savedPeople, savedSpecial, savedUnits, savedLandmark;Func<string, CollectionDetail, Action<GameObject?>, IDisposable>? savedTown, savedWhole;+ Action<string, Action<GameObject?>>? savedHexProps;[SetUp]public void Prepare()@@ -39,7 +41,7 @@ public class TalModelsShotsDirectory.CreateDirectory(ShotDir); Directory.CreateDirectory(CivMovementShots.ShotDir);savedRural = RuralLife.Request; savedPeople = CivilianPeople.Request; savedSpecial = SpecialBuildingModels.Request;savedUnits = UnitFigures.Source; savedTown = TownModelLayer.ModelAcquire; savedLandmark = TownLandmarks.Request;- savedWhole = TownLandmarks.Acquire;+ savedWhole = TownLandmarks.Acquire; savedHexProps = HexPropModels.Request;}[TearDown]@@ -47,7 +49,7 @@ public class TalModelsShots{RuralLife.Request = savedRural!; CivilianPeople.Request = savedPeople!; SpecialBuildingModels.Request = savedSpecial!;UnitFigures.Source = savedUnits; TownModelLayer.ModelAcquire = savedTown!; TownLandmarks.Request = savedLandmark!;- TownLandmarks.Acquire = savedWhole!;+ TownLandmarks.Acquire = savedWhole!; HexPropModels.Request = savedHexProps!;EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);if (ps != null) Object.DestroyImmediate(ps);if (rt != null) { rt.Release(); Object.DestroyImmediate(rt); }@@ -644,4 +646,70 @@ public class TalModelsShots[UnityTest] public IEnumerator BedouinAfterEnglish() { yield return Bedouin(false, true); }[UnityTest] public IEnumerator BedouinBeforeHebrew() { yield return Bedouin(true, false); }[UnityTest] public IEnumerator BedouinAfterHebrew() { yield return Bedouin(true, true); }++ /// <summary>Tal Heuberger's hex-tile props on the main map (owner, 27 October 2026, "2+3"; 2 November 2026: his models replace+ /// the kit's minarets, belfries and clock tower, a hedge row per village, a light hill scatter). Frames: Binyamina's station,+ /// the first Bedouin camp's tent, the first village's hedge row, the first hill hex's garrigue, the first village minaret and+ /// Jaffa's clock tower, a village mosque's minaret and St Peter's belfry, each from the closest zoom, from the gameplay zoom (60 km, where the kit's far parts draw) for the+ /// landmarks, and from the opening zoom (250 km). The town models are answered, so up close the close meshes draw.+ /// "Before" is main's map: the layer withheld (the kit's own parts come back) and its tree holes given back. The frames+ /// come from the map with the props, so they are the same before and after.</summary>+ IEnumerator HexPropShots(bool hebrew, bool after)+ {+ yield return Boot(hebrew);+ var map = Object.FindFirstObjectByType<MapScene>();+ TownModelLayer.ModelAcquire = (id, detail, done) => { done(Prefab(id, detail)); return new NoLease(); };+ HexPropModels.Request = (id, done) => done(AssetDatabase.LoadAssetAtPath<GameObject>(HexProps.PrefabPath(id)));+ Drop(map, HexPropModels.Name);+ var layer = HexPropModels.ShowAt(map, root.Bridge!.State.Date)!;+ Look(layer.transform.position, CameraController.MinDistance);+ layer.Choose(default, Camera.main);+ Assert.IsTrue(layer.Requested, "the camera asked for the props");+ var parts = map.KitStats.LandmarkParts;+ var minaret = parts.First(p => p.Kind == "minaret" && p.Close != null);+ var clock = parts.Single(p => p.Kind == "clock_tower");+ // #2266 review C7: a village mosque's roof-mounted minaret and St Peter's belfry, up close.+ var villages = new HashSet<string>(map.Localities.Select(p => p.Settlement).Where(s => s.Type == "village").Select(s => s.Id));+ var village = parts.First(p => p.Kind == "minaret" && p.Close != null && villages.Contains(p.Owner));+ var belfry = parts.Single(p => p.Kind == "belfry" && p.Owner == "jaffa");+ Vector3 Up(Bounds b) => new Vector3(b.center.x, 0f, b.center.z);+ var close = CameraController.MinDistance; const float Gameplay = 60000f; var opening = CameraController.MaxDistance;+ var frames = new List<(string what, string key, Vector3 at, float[] zooms)>+ {+ ("station", "station:Binyamina railway station", layer.Placed.First(p => p.Key == "station:Binyamina railway station").At, new[] { close, opening }),+ ("tent", layer.Placed.First(p => p.Model == HexPropModels.Tent).Key, layer.Placed.First(p => p.Model == HexPropModels.Tent).At, new[] { close, opening }),+ ("hedge", layer.Placed.First(p => p.Model == HexPropModels.PricklyPear).Key, layer.Placed.First(p => p.Model == HexPropModels.PricklyPear).At, new[] { close, opening }),+ ("scatter", layer.Placed.First(p => p.Model == HexPropModels.Garrigue).Key, layer.Placed.First(p => p.Model == HexPropModels.Garrigue).At, new[] { close, opening }),+ ("minaret", minaret.Owner, Up(minaret.Near), new[] { close, Gameplay, opening }),+ ("clocktower", clock.Owner, Up(clock.Near), new[] { close, Gameplay, opening }),+ ("villagemosque", village.Owner, Up(village.Near), new[] { close }),+ ("belfry", belfry.Owner, Up(belfry.Near), new[] { close }),+ };+ Debug.Log($"SHOT hexprops {(after ? "after" : "before")}: {layer.Placed.Count} placed, {layer.Replaced.Count} landmark models: " ++ string.Join(", ", HexPropModels.Standalone.Select(m => $"{m} {layer.Placed.Count(p => p.Model == m)}")));+ if (!after)+ {+ HexPropModels.Request = (id, done) => { }; // main streams no prop for the map+ Drop(map, HexPropModels.Name);+ UnitShowcase.HideTrees(map, HexPropModels.Name, Array.Empty<(Vector2, float)>());+ }+ foreach (var (what, key, flat, zooms) in frames)+ foreach (var distance in zooms)+ {+ string zoom = distance == close ? "close" : distance == Gameplay ? "gameplay" : "opening";+ var at = flat;+ at.y = map.Terrain.SampleHeight(at) + map.Terrain.transform.position.y;+ Look(at, distance);+ var shown = map.Terrain.transform.Find(HexPropModels.Name)?.GetComponent<HexPropModels>();+ if (shown != null) shown.Choose(default, Camera.main);+ for (int i = 0; i < 4; i++) { Camera.main.Render(); yield return null; }+ CivMovementShots.Shot(rt!, Path.Combine("..", "tal-models-shots", $"hexprops-{what}-{zoom}-{(after ? "after" : "before")}-{(hebrew ? "he" : "en")}"));+ Debug.Log($"SHOT hexprops {what} {key} at {at} from {distance:F0} m ({zoom}), standalone drawn {shown != null && shown.LastClose}, landmark models {shown?.Replaced.Count ?? 0}");+ }+ }++ [UnityTest] public IEnumerator HexPropsBeforeEnglish() { yield return HexPropShots(false, false); }+ [UnityTest] public IEnumerator HexPropsAfterEnglish() { yield return HexPropShots(false, true); }+ [UnityTest] public IEnumerator HexPropsBeforeHebrew() { yield return HexPropShots(true, false); }+ [UnityTest] public IEnumerator HexPropsAfterHebrew() { yield return HexPropShots(true, true); }}