A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Statecraft.Sim;
using UnityEngine;
using UnityEngine.Rendering;
namespace Statecraft.Game.Map.Collection
{
/// <summary>The nine whole-town models of The 1948 Collection (issue #663; owner ruling of 17 October 2026: "The nine
/// whole-town models ship (this reverses the 15 Oct 'layout references only' ruling). They are slimmed, streamed after
/// the first frame, and pass the load gate. The ma'abara and the shikun appear only from their sourced 1950s dates.").
/// The models are Tal Heuberger's, made with Tripo Studio and offered in #507; which town each stands at is #507's own mapping
/// (BuildingPreview at 3ef0a7a5): White City at Tel Aviv, the stone city at Jerusalem, the port city at Haifa, the
/// moshava town at the six moshavot, Nahalal at the moshav, the compound at every kibbutz, the stone village at every
/// Arab town, the ma'abara at a transit camp and the shikun at a housing project.
/// Tel Aviv, Jerusalem, Haifa and Jaffa, the major cities (<see cref="Kits.TownModels.IsMajorCity"/>), have no whole-town
/// model: since the owner's ruling of 6 November 2026, "Big blocks, every zoom", their kits draw from 40 km out, and since
/// the owner's ruling of 7 November 2026, "Tal's models close (Recommended)", their building models below the close
/// switch (before them, the 2 November 2026 ruling, "Yes, small buildings at every zoom" (superseded), drew their building
/// models at every zoom). Tel
/// Aviv's, Jerusalem's and Haifa's whole-town models stay in the repository and the streamed catalogue, unused on the map;
/// the stone village still stands at the other Arab towns but Ramla (its own town, see <see cref="ById"/>).
/// Owner ruling of 18 October 2026 (recorded on #917, #663, #659 and #700): the towns are Tal Heuberger's models, "Whole model
/// far, buildings near". Far off, a mapped town's whole-town model stands ON its town, on its core (<see cref="CoreOf"/>:
/// where most of its building models stand, inside its kit footprint, clear of the next town and of the sea), as wide as
/// that core, tilted to its ground and seated so it never floats (<see cref="SeatOn"/>).
/// Whole-town originals and placement landmarks are Far representations requested map-wide. Close cameras show individual
/// building originals where available; only a complete detailed representation hides that town's whole-town model.
/// A placement's landmark (ma'abara or shikun) stands beside its camp/housing project on free ground (Spot).
/// CollectionDetail.Far now names the same original file, not a generated 4,500-triangle mesh. Requests stream after
/// the first frame, are shared by acquired lease and retire when the last camera leaves. A failed model warns once;
/// a stale reply never revives an evicted town. No source mesh, texture or animation is rewritten.</summary>
[ExecuteAlways]
public sealed class TownLandmarks : MonoBehaviour
{
public const string Name = "TownLandmarks";
/// <summary>A placement's landmark's largest edge on the ground (m), beside its camp or housing project: about 41 px
/// across at 250 km and 86 px at 120 km on a 1080 px screen (CameraRig.Fov 35 degrees; owner on #917: "Larger", about
/// 6 km). A town's whole-town model is as wide as the town's kit footprint instead.</summary>
public const float SizeM = 6000f;
/// <summary>The ma'abara from the date the first one is reported: Kachansky, "The Ma'abarot" (Yad Ben-Zvi, 1987),
/// quoting Davar of 23 May 1950 on the first ma'abara, at Kesalon (content/events/maabarot_policy.yaml, with its
/// sources).</summary>
public static readonly DateTime MaabaraFrom = new DateTime(1950, 5, 23);
/// <summary>The shikun from 11 December 1949: the owner's ruling on #917 (17 October 2026, "Use 11 Dec 1949",
/// https://github.com/eyalgolan/statecraft-israel/pull/917#issuecomment-6240322628), a conservative "completed
/// immigrant housing existed by this date" landmark resting on one source, the government's review as published by
/// Project Ben-Yehuda (single-source). [GAP] The exact first shikun project and its day are not known. On the game's
/// monthly turns (the 15th) it first shows on the 15 December 1949 turn; in play it stands only by a housing project
/// the player has built, and those can be placed from rules.yaml's map_actions_from (1 January 1950).</summary>
public static readonly DateTime ShikunFrom = new DateTime(1949, 12, 11);
public const string TelAviv = "tel-aviv-white-city-v1", Jerusalem = "jerusalem-stone-city-v1", Haifa = "haifa-port-city-v1",
Moshava = "moshava-town-v1", Nahalal = "nahalal-moshav-v1", Kibbutz = "kibbutz-compound-v2", StoneVillage = "stone-village-v1",
Maabara = "maabara-camp-v1", Shikun = "shikun-housing-v1", Jerusalem3D = "jerusalem-stone-city-v1-3denhance",
// Tal Heuberger's generated whole towns (#2085): the three towns #1288 lists, and Ramla.
Tiberias = CollectionCatalog.TiberiasTown, Safed = CollectionCatalog.SafedTown, Netanya = CollectionCatalog.NetanyaTown,
Ramla = CollectionCatalog.RamlaTown;
/// <summary>By settlement id first (#507's mapping). Tel Aviv, Jerusalem and Haifa have no row: the owner, 2 November
/// 2026, "Yes, small buildings at every zoom" (superseded on 6 November 2026 by "Big blocks, every zoom", itself
/// superseded below the close switch on 7 November 2026 by "Tal's models close (Recommended)"; both keep them without a
/// whole-town model: <see cref="Kits.TownModels.IsMajorCity"/>). That replaces #507's
/// White City at Tel Aviv and port city at Haifa, and the owner's ruling of 21 October 2026 on #708
/// (issuecomment-6323524970) that #336's second stone city (<see cref="Jerusalem3D"/>, Tal Heuberger, #886) "is
/// Jerusalem's only far-zoom model for the whole game". <see cref="TelAviv"/>, <see cref="Haifa"/>,
/// <see cref="Jerusalem3D"/> and #507's <see cref="Jerusalem"/> stay in the repository, unused on the map.
/// Tiberias, Safed and Netanya stand as Tal Heuberger's own whole-town models (#2085), the three towns #1288 found with
/// none. Ramla, an Arab town, stands as Tal's own town instead of the stone village (<see cref="ByType"/>): the owner,
/// 2 November 2026, "Yes, Tal's Ramla (Recommended)" ("Ramla draws Tal's town instead of the stone village").</summary>
public static readonly IReadOnlyDictionary<string, string> ById = new Dictionary<string, string>(StringComparer.Ordinal)
{
["petah_tikva"] = Moshava, ["rishon_lezion"] = Moshava, ["zikhron_yaakov"] = Moshava,
["rosh_pinna"] = Moshava, ["rehovot"] = Moshava, ["hadera"] = Moshava,
["tiberias"] = Tiberias, ["safed"] = Safed, ["netanya"] = Netanya, ["ramla"] = Ramla,
};
/// <summary>Then by settlement type (#507's mapping).</summary>
public static readonly IReadOnlyDictionary<string, string> ByType = new Dictionary<string, string>(StringComparer.Ordinal)
{
["kibbutz"] = Kibbutz, ["moshav"] = Nahalal, ["arab_town"] = StoneVillage,
};
/// <summary>The player's placements (#507's mapping), each with the first day it may show (the owner's ruling: "only
/// from their sourced 1950s dates"): the ma'abara from <see cref="MaabaraFrom"/>, the shikun from
/// <see cref="ShikunFrom"/>. A row with no date (null) is never drawn.</summary>
public static readonly IReadOnlyDictionary<string, (string Model, DateTime? From)> ByAction =
new Dictionary<string, (string, DateTime?)>(StringComparer.Ordinal)
{
[MapActions.TransitCamp] = (Maabara, MaabaraFrom), [MapActions.Housing] = (Shikun, ShikunFrom),
};
/// <summary>The turn about the vertical (degrees) that shows each model's front to a camera looking north: #507's
/// table (BuildingPreview.Yaw at 3ef0a7a5, tuned there from renders), 200 for a model without a row of its own. #2085's
/// generated towns have no row yet: they take 200 until a render at their landing tunes them.</summary>
public static float YawOf(string model) => model == TelAviv ? 200f : model == StoneVillage ? 40f : 200f;
/// <summary>How the landmarks ask for a model: the game's stream. A test seam (internal; the tests see it through
/// InternalsVisibleTo).</summary>
static readonly Action<string, CollectionDetail, Action<GameObject?>> DefaultRequest = CollectionStream.Request;
internal static Action<string, CollectionDetail, Action<GameObject?>> Request = DefaultRequest;
internal static Func<string, CollectionDetail, Action<GameObject?>, IDisposable> Acquire = CollectionStream.Acquire;
/// <summary>The model for settlement <paramref name="s"/>, or null for none: none for the major cities, which draw their
/// kits from 40 km out and their building models below the close switch (<see cref="Kits.TownModels.IsMajorCity"/>; Jaffa, an Arab town, would otherwise take
/// <see cref="ByType"/>'s stone village).</summary>
public static string? ModelFor(Settlement s) => Kits.TownModels.IsMajorCity(s.Id) ? null
: ById.TryGetValue(s.Id, out var m) ? m : ByType.TryGetValue(s.Type, out var t) ? t : null;
/// <summary>The model for a placement of <paramref name="action"/> as at <paramref name="date"/>, or null: none for that
/// action, before its sourced date, or no sourced date at all.</summary>
public static string? ModelFor(string action, DateTime date) =>
ByAction.TryGetValue(action, out var row) && row.From is { } from && date >= from ? row.Model : null;
/// <summary>One landmark to draw: its key (the settlement id, or the placement's box name), its model, the centre
/// and radius (m, world x/z) of the ground its town or placement holds, and whether it stands on that ground (a town)
/// or beside it (a placement).</summary>
public readonly struct Want : IEquatable<Want>
{
public readonly string Key, Model; public readonly Vector2 At; public readonly float Radius; public readonly bool OnTown;
/// <summary>A city whose point lies in a water hex: the centre (world x/z) of the land hex the map gives it
/// (settlement_hexes.yaml, hexgrid.settlement_hex), where its core is seated (<see cref="CoreOf"/>); else null.</summary>
public readonly Vector2? Land;
public Want(string key, string model, Vector2 at, float radius, bool onTown, Vector2? land = null)
{ Key = key; Model = model; At = at; Radius = radius; OnTown = onTown; Land = land; }
public bool Equals(Want o) => Key == o.Key && Model == o.Model && At == o.At && Radius == o.Radius && OnTown == o.OnTown && Land == o.Land;
public override bool Equals(object? o) => o is Want w && Equals(w);
public override int GetHashCode() => (Key, Model, At, Radius, OnTown, Land).GetHashCode();
}
/// <summary>The landmarks the map wants as at <paramref name="date"/>: one per mapped settlement, on its kit footprint
/// (its centre and radius; without kits its marker box's half edge), and one per mapped placement from its date (its
/// hex's half width), in a fixed order: settlements as the file lists them, then placements as placed.</summary>
public static List<Want> Wants(MapScene map, DateTime date, IEnumerable<Placement> placements, Content content)
{
var footprint = new Dictionary<string, (Vector2 centre, float radius)>(StringComparer.Ordinal);
foreach (var (c, r, id) in map.KitFootprints) if (!footprint.ContainsKey(id)) footprint[id] = (c, r);
var wants = new List<Want>();
foreach (var s in map.Settlements)
{
var model = ModelFor(s);
if (model == null) continue;
var w = map.Frame.ToWorld(s.Lon, s.Lat, 0);
var (at, r) = footprint.TryGetValue(s.Id, out var f) ? f : (new Vector2(w.x, w.z), 0.5f * SettlementPlacer.MarkerHeightM(s.Type));
// #1183: on 4.4 km hexes Haifa's point lies in a sea hex and the map gives the city its land neighbour (6, 9),
// where the owner put its model (26 October 2026). Only a city: Acre (an arab_town whose point is in a sea hex
// too) keeps its core on its own plots, which stay dry.
Vector2? land = null;
var sh = s.Type == "city" ? content.SettlementHexes.FirstOrDefault(x => x.Id == s.Id) : null;
var hx = sh == null || (sh.Q, sh.R) == HexPicker.FromLonLat(s.Lon, s.Lat, map.Hexes.bounds, map.Hexes.hex_size_km)
? null : content.HexAt(sh.Q, sh.R);
if (hx != null) { var lw = map.Frame.ToWorld(hx.Lon, hx.Lat, 0); land = new Vector2(lw.x, lw.z); }
wants.Add(new Want(s.Id, model, at, r, onTown: true, land));
}
float hexHalf = 500f * map.Hexes.hex_size_km;
foreach (var p in placements)
{
var model = ModelFor(p.Action, date);
var hex = model == null ? null : content.HexAt(p.Q, p.R);
if (hex == null) continue;
var w = map.Frame.ToWorld(hex.Lon, hex.Lat, 0);
wants.Add(new Want($"{p.Action}_{p.Q}_{p.R}", model!, new Vector2(w.x, w.z), hexHalf, onTown: false));
}
return wants;
}
/// <summary>The first spot (world x/z) for a landmark of radius <paramref name="radius"/> beside a town at
/// <paramref name="town"/> holding <paramref name="townRadius"/>, for which <paramref name="free"/> holds: rings from
/// the town's edge outwards (one landmark radius apart, <see cref="Rings"/> of them), <see cref="Bearings"/> bearings
/// each, starting north-east and turning clockwise. Null when none is free.</summary>
public static Vector2? Spot(Vector2 town, float townRadius, float radius, Func<Vector2, float, bool> free)
{
for (int ring = 0; ring < Rings; ring++)
{
float d = townRadius + radius * (1.1f + ring);
for (int k = 0; k < Bearings; k++)
{
float a = (45f - 360f * k / Bearings) * Mathf.Deg2Rad;
var p = town + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * d;
if (free(p, radius)) return p;
}
}
return null;
}
public const int Rings = 8, Bearings = 16;
/// <summary>The share of a town's building plots (#700's models at the world scale, SettlementKits.ModelScale) its
/// core holds: the whole-town model is as wide as the disc round them (<see cref="CoreOf"/>).</summary>
public const float CoreShare = 0.7f;
/// <summary>The most of the ground under a whole-town model that may be water (a coastal town keeps its shore).</summary>
public const float MaxWaterShare = 0.2f;
/// <summary>A whole-town model's half edge stays under this share of the distance to the nearest other game settlement,
/// so its ground rectangle (its corners reach about 1.41 half edges out) never covers that town.</summary>
public const float NeighbourShare = 0.65f;
/// <summary>A town's core (owner, 18 October 2026, through the coordinator: sized "so Tel Aviv doesn't cover Jaffa and
/// Haifa doesn't reach into the bay"): the centroid of the <see cref="CoreShare"/> of its building plots
/// (<paramref name="plots"/>) nearest its centre (<paramref name="centre"/>), and the radius that holds that share round
/// it, no more than its kit footprint (<paramref name="footprint"/>), under <see cref="NeighbourShare"/> of the distance
/// to the nearest of <paramref name="others"/>, then pulled in (by tenths, to a third of where it started) while more
/// than <see cref="MaxWaterShare"/> of the disc is water. With fewer than five plots (counting the clearings'): the centre
/// and the footprint, under the same two limits. A unit clearing in the town (<paramref name="clearings"/>, MapScene.UnitClearings) counts
/// as if it still held plots (#588, owner, 18 October 2026: "Clearing doesn't move the core"), so a token's clearing
/// does not pull the core away from it (Carmeli's put Haifa's model in the bay).</summary>
public static (Vector2 centre, float radius) CoreOf(Vector2 centre, float footprint, IReadOnlyList<Vector2> plots,
IEnumerable<(Vector2 centre, float radius)> clearings, IEnumerable<Vector2> others, Func<float, float, bool> water,
Vector2? land = null)
{
Vector2 c = centre; float r = footprint;
// The clearings' ground as plots: a grid at the town's own plot spacing (the median distance from a plot to its
// nearest; at least a twentieth of the clearing's radius), over each clearing that is in the town as the unit
// placer counts it (UnitGround.FootprintMargin).
var counted = new List<Vector2>(plots);
var inTown = clearings.Where(cl => (cl.centre - centre).magnitude < footprint * Units.UnitGround.FootprintMargin).ToList();
if (inTown.Count > 0 && plots.Count >= 2)
{
float step = Enumerable.Range(0, plots.Count)
.Select(i => Enumerable.Range(0, plots.Count).Where(j => j != i).Min(j => (plots[j] - plots[i]).magnitude))
.OrderBy(x => x).ElementAt(plots.Count / 2);
foreach (var (cc, cr) in inTown)
{
float st = Mathf.Max(step, cr / 20f);
int n = Mathf.FloorToInt(cr / st);
for (int i = -n; i <= n; i++)
for (int k = -n; k <= n; k++)
{
var q = cc + new Vector2(i, k) * st;
if ((q - cc).magnitude < cr) counted.Add(q);
}
}
}
if (counted.Count >= 5)
{
var near = counted.OrderBy(p => (p - centre).sqrMagnitude).Take(Mathf.Max(5, Mathf.CeilToInt(CoreShare * counted.Count))).ToList();
c = near.Aggregate(Vector2.zero, (a, p) => a + p) / near.Count;
var d = near.Select(p => (p - c).magnitude).OrderBy(x => x).ToList();
r = Mathf.Min(footprint, d[d.Count - 1]);
}
// #1183 (owner, 26 October 2026, Haifa's model: "Move to land (6,9)"): a land hex given (Want.Land) seats the core
// on that hex's centre, as wide as its plots made it, under the same limits.
if (land is Vector2 l) c = l;
foreach (var o in others) r = Mathf.Min(r, NeighbourShare * (o - c).magnitude);
float floor = r / 3f;
for (int i = 0; i < 12 && r > floor && WaterShare(c, r, water) > MaxWaterShare; i++) r = Mathf.Max(floor, 0.9f * r);
return (c, r);
}
/// <summary>The share of 11 x 11 points in the disc at <paramref name="c"/> of <paramref name="r"/> that are water.</summary>
public static float WaterShare(Vector2 c, float r, Func<float, float, bool> water)
{
int n = 0, wet = 0;
for (int i = 0; i <= 10; i++)
for (int k = 0; k <= 10; k++)
{
var q = c + new Vector2(-r + 2f * r * i / 10f, -r + 2f * r * k / 10f);
if ((q - c).sqrMagnitude > r * r * 1.0001f) continue;
n++; if (water(q.x, q.y)) wet++;
}
return n == 0 ? 0f : (float)wet / n;
}
/// <summary>The steepest a whole-town model leans with its ground (degrees).</summary>
public const float MaxTiltDeg = 10f;
/// <summary>Samples across the footprint's square (per side) for <see cref="SeatOn"/>.</summary>
public const int SeatSamples = 11;
/// <summary>Where a whole-town model sits: the centre of its town (world x/z), its largest horizontal edge (m), the
/// normal of its base plane and that plane's height (m) at the centre.</summary>
public readonly struct Seat
{
public readonly Vector2 Centre; public readonly float Edge; public readonly Vector3 Normal; public readonly float BaseY;
public Seat(Vector2 centre, float edge, Vector3 normal, float baseY) { Centre = centre; Edge = edge; Normal = normal; BaseY = baseY; }
}
/// <summary>The base plane of a model over the disc at <paramref name="centre"/> of <paramref name="radius"/>: the
/// least-squares plane of the ground heights <paramref name="y"/> at <see cref="SeatSamples"/> squared points in the disc
/// (water points left out, <paramref name="water"/>), its slope clamped to <see cref="MaxTiltDeg"/>, then lowered to
/// the lowest of them, so no land point lies below it: the model follows its slope and never floats (the kibbutz cut
/// into its hill on #917 when it stood level at its centre's height). Returns the plane's normal and its height at the
/// centre; on flat or all-water ground, level at the centre's height.</summary>
public static (Vector3 normal, float baseY) SeatOn(Vector2 centre, float radius, Func<float, float, float> y, Func<float, float, bool> water)
{
var pts = new List<(float dx, float dz, float h)>();
for (int i = 0; i < SeatSamples; i++)
for (int k = 0; k < SeatSamples; k++)
{
float dx = radius * (2f * i / (SeatSamples - 1) - 1f), dz = radius * (2f * k / (SeatSamples - 1) - 1f);
if (dx * dx + dz * dz > radius * radius * 1.0001f || water(centre.x + dx, centre.y + dz)) continue; // the rim kept despite rounding
pts.Add((dx, dz, y(centre.x + dx, centre.y + dz)));
}
if (pts.Count < 3) return (Vector3.up, y(centre.x, centre.y));
// Least squares h = a + b dx + c dz (in doubles: the sums of squares of 10 km offsets).
double n = pts.Count, sx = 0, sz = 0, sh = 0, sxx = 0, szz = 0, sxz = 0, sxh = 0, szh = 0;
foreach (var (dx, dz, h) in pts) { sx += dx; sz += dz; sh += h; sxx += dx * dx; szz += dz * dz; sxz += dx * dz; sxh += dx * h; szh += dz * h; }
double mx = sx / n, mz = sz / n, mh = sh / n;
double cxx = sxx / n - mx * mx, czz = szz / n - mz * mz, cxz = sxz / n - mx * mz, cxh = sxh / n - mx * mh, czh = szh / n - mz * mh;
double det = cxx * czz - cxz * cxz;
double b = det > 1e-6 ? (cxh * czz - czh * cxz) / det : 0, c = det > 1e-6 ? (czh * cxx - cxh * cxz) / det : 0;
double slope = Math.Sqrt(b * b + c * c), max = Math.Tan(MaxTiltDeg * Mathf.Deg2Rad);
if (slope > max) { b *= max / slope; c *= max / slope; }
double low = double.MaxValue;
foreach (var (dx, dz, h) in pts) low = Math.Min(low, h - (b * dx + c * dz));
return (new Vector3((float)-b, 1f, (float)-c).normalized, (float)low);
}
/// <summary>Whether a disc at <paramref name="p"/> of radius <paramref name="r"/> stays off every disc of
/// <paramref name="discs"/> (edge to edge).</summary>
public static bool Clear(Vector2 p, float r, IEnumerable<(Vector2 centre, float radius)> discs)
{
foreach (var (c, cr) in discs) { float d = cr + r; if ((p - c).sqrMagnitude < d * d) return false; }
return true;
}
// ---- the layer ----
MapScene? map;
readonly Dictionary<string, GameObject?> prefabs = new Dictionary<string, GameObject?>(StringComparer.Ordinal);
readonly HashSet<string> asked = new HashSet<string>(StringComparer.Ordinal);
readonly Dictionary<string, IDisposable?> leases = new Dictionary<string, IDisposable?>(StringComparer.Ordinal);
readonly Dictionary<string, int> versions = new Dictionary<string, int>(StringComparer.Ordinal);
readonly Dictionary<string, List<GameObject>> originals = new Dictionary<string, List<GameObject>>(StringComparer.Ordinal);
readonly List<IDisposable> retiring = new List<IDisposable>();
readonly List<UnityEngine.Object> retiredInstances = new List<UnityEngine.Object>();
readonly Dictionary<Renderer, string> rendererTowns = new Dictionary<Renderer, string>();
readonly List<(Renderer renderer, bool off)> previous = new List<(Renderer, bool)>();
readonly HashSet<string> admittedKeys = new HashSet<string>(StringComparer.Ordinal);
int requestVersion;
bool? focusPolicy;
bool retirementScheduled;
int pendingRetirementLeases;
readonly List<(string id, CollectionDetail detail)> retiringKeys = new List<(string, CollectionDetail)>();
readonly List<Renderer> renderers = new List<Renderer>();
List<Want> wants = new List<Want>();
DateTime date;
bool dirty;
bool refreshDirty;
bool? refreshedAllowed;
/// <summary>The landmarks drawn (key, model, the spot its footprint is centred on, at ground height): a test aid.</summary>
public readonly List<(string Key, string Model, Vector3 At)> Placed = new List<(string, string, Vector3)>();
/// <summary>The landmarks wanted but not drawn: their model did not stream, or no spot was free (a test aid).</summary>
public readonly List<string> Missing = new List<string>();
/// <summary>Where each town's whole-town model sits, by settlement id (a test aid).</summary>
public readonly Dictionary<string, Seat> Seats = new Dictionary<string, Seat>(StringComparer.Ordinal);
/// <summary>For the last camera: whether it hid the landmarks (up close, where #700's building models draw).</summary>
public bool LastHidden { get; private set; }
public IReadOnlyList<Want> Wanted => wants;
/// <summary>Shows the landmarks the map wants as at <paramref name="date"/> (GameRoot calls it on every change, beside
/// RouteLayer.ShowAt): makes the layer under the terrain the first time, asks the stream for each model the first time
/// one is wanted, and redraws only when the wanted set changes.</summary>
public static TownLandmarks? ShowAt(MapScene map, DateTime date, IEnumerable<Placement> placements, Content content)
{
if (map == null || map.Terrain == null || map.Hexes == null) return null;
var t = map.Terrain.transform.Find(Name)?.GetComponent<TownLandmarks>();
if (t == null)
{
var go = new GameObject(Name);
go.transform.SetParent(map.Terrain.transform, false);
t = go.AddComponent<TownLandmarks>();
t.map = map;
}
t.Show(Wants(map, date, placements, content), date);
return t;
}
internal CollectionResidencyMetrics.Category ResidencySnapshot()
{
var row = CollectionResidencyMetrics.Row("whole_towns", isActiveAndEnabled ? admittedKeys.Count : 0, transform.childCount,
asked.Concat(prefabs.Keys), leases.Values.Count(l => l != null), asked.Count(k => !prefabs.ContainsKey(k)),
prefabs.Values.Count(p => p != null), renderers.Count(r => r != null), 0, prefabs.Values.Count(p => p == null),
asked.Select(id => id + "|Far"));
row.retiringLeases = retiring.Count; row.pendingDestroy = retiredInstances.Count(o => o != null && o is GameObject); return row;
}
// 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;
void Show(List<Want> next, DateTime at)
{
date = at;
bool focused = Layer()?.UsesFocusedOriginals == true;
if (next.SequenceEqual(wants) && focusPolicy == focused) return;
focusPolicy = focused; wants = next;
var layer = Layer();
if (layer != null)
{
layer.ConfigureWholeTowns(wants.Where(w => w.OnTown || map != null).Select(w =>
(w.Key, new Bounds(new Vector3(w.At.x, 0, w.At.y), new Vector3(w.Radius * 2, 0, w.Radius * 2)))).ToList());
layer.WholeTownReady = WholeReady;
}
dirty = true; refreshDirty = true; RefreshWanted();
}
/// <summary>Whether <see cref="RefreshWanted"/> has work: a redraw, a lease to retire, or a change of the admitted towns
/// or of the models asked for. RefreshWanted returns at once without it, and the edit-mode render callback asks for a
/// player-loop update only with it, so a settled layer never keeps the editor updating (#2099).</summary>
internal bool RefreshPending => dirty || refreshDirty || retiring.Count != 0 || pendingRetirementLeases != 0
|| refreshedAllowed != (map?.Residency.Towns.Enabled ?? true);
void RefreshWanted()
{
if (!RefreshPending) return;
if (pendingRetirementLeases != 0) return;
var keep = new HashSet<string>(StringComparer.Ordinal);
var keys = new HashSet<string>(StringComparer.Ordinal);
foreach (var want in wants) if (Allowed(want)) { keep.Add(want.Model); keys.Add(want.Key); }
bool townsChanged = !admittedKeys.SetEquals(keys);
admittedKeys.Clear(); admittedKeys.UnionWith(keys);
var old = new List<string>();
foreach (var model in asked) if (!keep.Contains(model)) old.Add(model);
foreach (string model in old)
{
asked.Remove(model); prefabs.Remove(model); versions.Remove(model);
if (leases.TryGetValue(model, out var lease) && lease != null) { retiring.Add(lease); retiringKeys.Add((model, CollectionDetail.Far)); }
leases.Remove(model);
}
bool membershipChanged = !keep.SetEquals(asked);
if (townsChanged || old.Count > 0 || membershipChanged) CollectionResidencyMetrics.MarkDirty();
// Retire the old generation before rebuilding or acquiring the next batch.
if (old.Count > 0 && retiring.Count > 0)
{
// Retiring one model must not destroy/recreate surviving town instances (the visible panning/date blink).
ClearInstances(old); dirty |= townsChanged || keep.Except(asked).Any();
if (Application.isPlaying && !retirementScheduled) { retirementScheduled = true; StartCoroutine(RetireAfterFrame()); }
else if (!Application.isPlaying) RetireLeases();
return;
}
if (townsChanged || membershipChanged) dirty = true;
if (pendingRetirementLeases > 0) return;
Rebuild(); // stop old instances before retiring their asset ownership
if (retiring.Count > 0 && !retirementScheduled && Application.isPlaying)
{ retirementScheduled = true; StartCoroutine(RetireAfterFrame()); }
else if (!Application.isPlaying) RetireLeases();
if (pendingRetirementLeases == 0 && retiring.Count == 0 && keep.Count > 0 && membershipChanged)
{
// Admission already validated this camera's production policy. The stream itself waits for GameReady.
RequestWanted();
}
if (retiring.Count == 0 && pendingRetirementLeases == 0)
{
refreshedAllowed = map?.Residency.Towns.Enabled ?? true;
refreshDirty = false;
}
}
void RequestWanted()
{
if (this == null || !isActiveAndEnabled || pendingRetirementLeases != 0 || retiring.Count != 0) return;
foreach (var want in wants)
{
if (!isActiveAndEnabled) break;
if (!Allowed(want) || !asked.Add(want.Model)) continue;
string model = want.Model; int version = ++requestVersion;
versions[model] = version; leases[model] = null;
Action<GameObject?> answer = prefab =>
{
if (this == null || !isActiveAndEnabled || !versions.TryGetValue(model, out int current) || current != version) return;
OnModel(model, prefab);
};
if (Request == DefaultRequest)
{
var lease = Acquire(model, CollectionDetail.Far, answer);
if (this != null && isActiveAndEnabled && versions.TryGetValue(model, out int live) && live == version) leases[model] = lease;
else { retiring.Add(lease); retiringKeys.Add((model, CollectionDetail.Far)); RetireLeases(); }
}
else Request(model, CollectionDetail.Far, answer); // existing editor/fake-source seam owns its assets
}
}
System.Collections.IEnumerator RetireAfterFrame()
{
yield return null; retirementScheduled = false; RetireLeases();
}
internal void RetireLeases()
{
if (retiring.Count == 0) { retiredInstances.RemoveAll(instance => instance == null); return; }
var batch = retiring.ToArray(); var instances = retiredInstances.ToArray(); var keys = retiringKeys.ToArray();
retiring.Clear(); retiredInstances.Clear(); retiringKeys.Clear(); pendingRetirementLeases += batch.Length;
CollectionResidencyMetrics.AfterDestroyed("whole_towns", instances, batch, () =>
{
pendingRetirementLeases -= batch.Length;
if (this != null && isActiveAndEnabled) { refreshDirty = true; RefreshWanted(); }
CollectionResidencyMetrics.MarkDirty();
}, Application.isPlaying && Acquire == CollectionStream.Acquire ? () => CollectionStream.Settled(keys) : (Func<bool>?)null, keys);
}
void OnModel(string model, GameObject? prefab)
{
if (this == null) return; // the map was rebuilt before the model came; the new map asks again
prefabs[model] = prefab;
if (prefab == null)
Debug.LogWarning($"LANDMARKS: the town model {model} did not stream; its landmarks are not drawn, and the map plays on without them.");
dirty = true;
CollectionResidencyMetrics.MarkDirty();
Rebuild();
}
/// <summary>Redraws every landmark whose model has come, in the wanted order, each on the first free spot by its town.</summary>
void Rebuild()
{
if (!dirty || map == null || map.Terrain == null) return;
dirty = false;
ClearInstances();
if (!wants.Any(w => Allowed(w) && prefabs.TryGetValue(w.Model, out var p) && p != null))
{
Missing.AddRange(wants.Where(w => Allowed(w) && prefabs.ContainsKey(w.Model)).Select(w => w.Key));
Layer()?.Suppress(Array.Empty<string>());
return;
}
var ground = PlacementLayer.CampGround(map);
float r = 0.5f * SizeM;
var taken = new List<(Vector2 centre, float radius)>();
var footprints = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();
// The other towns' and placements' own ground, for those the kits do not draw (the placements, or no kits at all).
footprints.AddRange(wants.Select(w => (w.At, w.Radius)));
bool Free(Vector2 p, float rad)
{
if (!Clear(p, rad, footprints) || !Clear(p, rad, taken)) return false;
if (!ground.Inside(p.x - rad, p.y - rad) || !ground.Inside(p.x + rad, p.y + rad)) return false;
for (int k = 0; k < 9; k++)
{
var q = k == 0 ? p : p + new Vector2(Mathf.Cos(k * Mathf.PI / 4f), Mathf.Sin(k * Mathf.PI / 4f)) * rad * 0.8f;
if (ground.Water(q.x, q.y)) return false;
}
return !ground.OnRoute(p, rad) && !ground.OnToken(p, rad) && !ground.OnToken(p, rad, date);
}
var layer = Layer();
var centres = TownCentres(map);
foreach (var w in wants)
{
if (!Allowed(w)) continue;
if (!prefabs.TryGetValue(w.Model, out var prefab)) continue; // still streaming
if (prefab == null) { Missing.Add(w.Key); continue; }
Vector2 at; float edge, baseY; Vector3 normal = Vector3.up;
if (w.OnTown)
{
// On the town's core, not its whole kit footprint (Tel Aviv's held Jaffa, Haifa's the bay).
var (core, rad) = CoreFor(map, layer, wants, w, ground, centres);
at = core; edge = 2f * rad;
(normal, baseY) = SeatOn(at, rad, ground.Y, ground.Water);
}
else
{
var spot = Spot(w.At, w.Radius, r, Free);
if (spot == null) { Missing.Add(w.Key); continue; }
at = spot.Value; edge = SizeM; baseY = ground.Y(at.x, at.y);
taken.Add((at, r));
}
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);
// This owned instance obeys the map's approved town view band and per-camera fallback swap.
// The prefab's older strategic cap must not override that policy or hide a ready original early.
foreach (var cap in go.GetComponentsInChildren<OriginalModelDistance>(true)) cap.enabled = false;
// The yaw goes on top of the prefab's own rotation: every Collection Far prefab's root carries the FBX axis
// conversion (-90 degrees about X; bakeAxisConversion is off), and setting the yaw alone laid each model on its
// side (owner, 18 October 2026: the models "seem to be on their side on the map"; #979).
go.transform.localRotation = Quaternion.Euler(0f, YawOf(w.Model), 0f) * prefab.transform.localRotation;
var bounds = Bounds(go);
float size = Mathf.Max(bounds.size.x, bounds.size.z);
go.transform.localScale *= size > 1e-3f ? edge / size : 1f;
// The model's base, after the scale, stands on its seat, centred on its town or spot; then it leans with the
// ground about that point (level for a placement).
var pos = new Vector3(at.x, baseY, at.y);
go.transform.position = pos;
var b = Bounds(go);
go.transform.position += new Vector3(pos.x - b.center.x, pos.y - b.min.y, pos.z - b.center.z);
var tilt = Quaternion.FromToRotation(Vector3.up, normal);
go.transform.SetPositionAndRotation(pos + tilt * (go.transform.position - pos), tilt * go.transform.rotation);
foreach (var rr in go.GetComponentsInChildren<Renderer>(true))
{
rr.shadowCastingMode = ShadowCastingMode.On;
rr.forceRenderingOff = false;
renderers.Add(rr);
if (w.OnTown) rendererTowns[rr] = w.Key;
}
if (w.OnTown) Seats[w.Key] = new Seat(at, edge, normal, baseY);
Placed.Add((w.Key, w.Model, pos));
}
// Record seats; only WholeReady for the current camera may hide a town's fallback.
if (layer != null) layer.Suppress(Seats.Keys);
Debug.Log($"LANDMARKS: {Placed.Count} town landmarks placed, {Missing.Count} not drawn");
}
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>The camera's view distance (m), as TownModelLayer measures it (the rig's zoom); the people, wildlife and
/// road vehicle layers read it from here.</summary>
public static float ViewDistance(Camera cam) => Kits.TownModelLayer.ViewDistance(cam);
/// <summary>#700's building layer of this map (null without kits). Found once and kept: WholeReady asks for it for
/// every town swap, up to three times per camera per frame, and the walk of the whole map hierarchy grows below the
/// close switch (frame cost finding, 7 November 2026). A destroyed layer, or one no longer under this map, is looked
/// up again.</summary>
Kits.TownModelLayer? Layer()
{
if (map == null) return null;
if (buildingLayer != null && buildingLayer.transform.IsChildOf(map.transform)) return buildingLayer;
LayerLookups++;
return buildingLayer = map.GetComponentInChildren<Kits.TownModelLayer>(true);
}
Kits.TownModelLayer? buildingLayer;
/// <summary>How many times <see cref="Layer"/> has walked the map's hierarchy for the building layer (a test aid).</summary>
internal int LayerLookups { get; private set; }
void OnEnable()
{
RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering += EndCamera;
if (wants.Count > 0) { focusPolicy = null; Show(wants, date); }
}
void OnDisable()
{
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering -= EndCamera;
StopAllCoroutines(); retirementScheduled = false;
RestoreRenderers(); ReleaseOwned();
}
void ClearInstances(IReadOnlyCollection<string>? models = null)
{
CollectionResidencyMetrics.MarkDirty();
RestoreRenderers();
if (models != null)
{
var removed = new HashSet<string>(models, StringComparer.Ordinal);
var removedTownKeys = new HashSet<string>(Placed.Where(p => removed.Contains(p.Model)).Select(p => p.Key), StringComparer.Ordinal);
var removedRenderers = new HashSet<Renderer>();
foreach (string model in removed)
{
if (!originals.TryGetValue(model, out var instances)) continue;
foreach (var old in instances.Where(go => go != null).ToArray())
{
removedRenderers.UnionWith(old.GetComponentsInChildren<Renderer>(true));
RetireInstance(old);
}
originals.Remove(model);
}
renderers.RemoveAll(renderer => renderer == null || removedRenderers.Contains(renderer));
foreach (var renderer in rendererTowns.Where(pair => pair.Key == null || removedRenderers.Contains(pair.Key)
|| removedTownKeys.Contains(pair.Value)).Select(pair => pair.Key).ToArray())
rendererTowns.Remove(renderer);
Placed.RemoveAll(p => removed.Contains(p.Model));
Missing.RemoveAll(removedTownKeys.Contains);
foreach (string key in removedTownKeys) Seats.Remove(key);
Layer()?.Suppress(Seats.Keys);
return;
}
for (int i = transform.childCount - 1; i >= 0; i--)
RetireInstance(transform.GetChild(i).gameObject);
originals.Clear();
renderers.Clear(); rendererTowns.Clear(); Placed.Clear(); Missing.Clear(); Seats.Clear();
}
void RetireInstance(GameObject old)
{
old.SetActive(false);
retiredInstances.RemoveAll(instance => instance == null); retiredInstances.Add(old);
retiredInstances.AddRange(old.GetComponentsInChildren<Renderer>(true));
retiredInstances.AddRange(old.GetComponentsInChildren<MeshFilter>(true));
if (Application.isPlaying)
{
// Unity forbids hierarchy changes while this layer is being deactivated (OnDisable -> ReleaseOwned). The
// inactive instance is then destroyed in place; detach only while the layer is active, as RoadVehicles does.
if (gameObject.activeInHierarchy) old.transform.SetParent(null);
Destroy(old);
}
else DestroyImmediate(old);
}
void ReleaseOwned()
{
ClearInstances();
var layer = Layer();
if (layer != null) { layer.Suppress(Array.Empty<string>()); layer.WholeTownReady = null; }
versions.Clear(); asked.Clear(); prefabs.Clear(); admittedKeys.Clear();
foreach (var pair in leases) if (pair.Value != null) { retiring.Add(pair.Value); retiringKeys.Add((pair.Key, CollectionDetail.Far)); }
leases.Clear(); RetireLeases();
}
void OnDestroy() => ReleaseOwned();
void RestoreRenderers()
{
foreach (var (renderer, off) in previous) if (renderer != null) renderer.forceRenderingOff = off;
previous.Clear();
}
void EndCamera(ScriptableRenderContext _, Camera camera) => RestoreRenderers();
/// <summary>One production frame's reconciliation; exposed internally so allocation tests measure no reflection.</summary>
internal void Tick() => RefreshWanted();
void LateUpdate() => Tick();
/// <summary>The render callback. Nothing is acquired, instantiated or destroyed while a camera renders, in edit mode
/// either (a Scene or Game view camera): the change waits for LateUpdate, as in play mode.</summary>
void OnBeginCameraRendering(ScriptableRenderContext context, Camera cam) => ChooseCore(cam, inRender: true);
/// <summary>Show each map-wide whole-town original unless this camera has that town's detailed buildings ready. A direct
/// call (tests and editor tools, outside any render) applies a change at once in edit mode.</summary>
internal void Choose(ScriptableRenderContext context, Camera cam) => ChooseCore(cam, inRender: false);
internal void ChooseCore(Camera cam, bool inRender)
{
if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;
RestoreRenderers();
var layer = Layer(); LastHidden = false;
// Do not depend on which beginCameraRendering subscriber was enabled first.
layer?.PrepareCameraCore(cam, inRender);
if (!Application.isPlaying && !inRender) RefreshWanted();
#if UNITY_EDITOR
// In a render, LateUpdate refreshes instead; edit mode runs it only when something asks for a player-loop update,
// so ask only when RefreshWanted has work (a request every render would keep the editor updating).
if (inRender && !Application.isPlaying && RefreshPending) UnityEditor.EditorApplication.QueuePlayerLoopUpdate();
#endif
layer?.PrepareCameraCore(cam, inRender); // synchronous editor/fake arrivals may have made a whole seat ready
foreach (var renderer in renderers)
{
if (renderer == null) continue;
bool hide = rendererTowns.TryGetValue(renderer, out var town) && layer?.ReadyForTown(town, cam) == true;
previous.Add((renderer, renderer.forceRenderingOff)); renderer.forceRenderingOff = hide;
LastHidden |= hide;
}
}
}
}