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.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace Statecraft.Game.Map.Kits
{
/// <summary>Builds the art spike's procedural layer under a returned "Kits" root: one static mesh per settlement (its
/// buildings, merged: one draw each, culled by its bounds) drawn with the editor-made Kit.mat, the boats
/// (<see cref="SeaCraft"/>, one more mesh with the same material), and the instanced trees
/// (<see cref="VegetationLayer"/>) drawn with Tree.mat. Meshes are owned by the map's MapRuntimeAssets, so a rebuild
/// frees them. Hides the marker boxes under <paramref name="markers"/> while the kits show. Registers the "kits" and
/// "trees" visual toggles, so the frame-time profile prices each ("kits" off shows the markers again). Fills
/// <paramref name="columns"/>, when given, with each kit's columns (world space: the kits sit at the root's origin), the
/// 1948 localities' included.</summary>
public static class KitLayer
{
public 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;
/// <summary>Every footprint the build claimed (towns, localities, camps), in claim order (MapScene.KitFootprints).</summary>
public IReadOnlyList<(Vector2 centre, float radius, string id)> Footprints = System.Array.Empty<(Vector2, float, string)>();
/// <summary>The boats SeaCraft placed and the harbour works the kits recorded ("breakwater" pieces), so the 1948
/// 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>();
/// <summary>#1701 slice F: everything the kits placed that is not a building (walls, platforms, landmarks, harbour
/// works, street palms: SettlementKits.Placed, its yaw as KitMesh.Corners), then each landmark's close copy as its
/// world box (yaw 0), so a model placed among a town's houses (SpecialBuildingModels.TownGap) keeps off them.</summary>
public IReadOnlyList<SettlementKits.Placed> Landmarks = System.Array.Empty<SettlementKits.Placed>();
/// <summary>#2876: the kit blocks of the major cities (TownModels.IsMajorCity), which draw their kits from 40 km out
/// (owner, 6 November 2026, "Big blocks, every zoom") and Tal Heuberger's building models below the close switch
/// (owner, 7 November 2026, "Tal's models close (Recommended)"): each "building" and "wing" the kits placed for one
/// of them (SettlementKits.Placed, Id the city's, its yaw as KitMesh.Corners), in placement order, so a model placed
/// among a major city's houses (SpecialBuildingModels.TownGap) keeps off the blocks drawn there as well as off its
/// building models.</summary>
public IReadOnlyList<SettlementKits.Placed> MajorCityBlocks = System.Array.Empty<SettlementKits.Placed>();
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) =>
Build(settlements, new List<Settlement>(), new List<Localities.Area>(), terrain, frame, hexes, elevMinM, kitMaterial, treeMaterial,
townModels, assets, markers, out stats, corridors, columns, residency: Collection.ProductionResidency.Approved());
/// <summary>As Build, with the 1948 localities and the Bedouin camp areas (content/map/localities_1948.yaml) drawn
/// beside the game settlements: their buildings merged per tile (SettlementKits.Result.Tiles), one renderer each.</summary>
internal static GameObject Build(IReadOnlyList<Settlement> settlements, IReadOnlyList<Settlement> localities, IReadOnlyList<Localities.Area> camps,
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,
IReadOnlyList<(Vector2 centre, float radius)>? tokens = null, Collection.ProductionResidency? residency = null)
{
var st = stats = new Stats();
var root = new GameObject(RootName);
var ground = new KitGround(terrain, frame, hexes, elevMinM);
// Buildings and trees stay off the railways and roads (RouteLayer.Corridors): every route, whatever its date,
// since the kits are not rebuilt when a dated route (the Burma Road) appears.
if (corridors != null) foreach (var (line, half) in corridors) ground.AddCorridor(line, half);
stats.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, 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)
{
assets.Own(mesh);
var go = new GameObject(name);
go.transform.SetParent(root.transform, false);
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var r = go.AddComponent<MeshRenderer>();
r.sharedMaterial = kitMaterial;
r.shadowCastingMode = ShadowCastingMode.On;
if (count) { st.Vertices += mesh.vertexCount; st.Triangles += (int)mesh.GetIndexCount(0) / 3; st.Draws++; }
return r;
}
// 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)
{
var kit = Add(name, mesh);
Renderer? 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;
}
var nearTowns = new List<string>();
foreach (var (s, mesh, n) in built.Towns) { AddKit(s.Id, mesh, s.Id); nearTowns.Add(s.Id); stats.Buildings += n; }
// A merged tile is no named town: it carries its villages, and swaps once all of them are ready (owner ruling,
// 31 Oct 2026, "Load all in view (Recommended)").
foreach (var (name, mesh) in built.Tiles)
{
var kit = AddKit(name, mesh);
if (built.TileIds.TryGetValue(name, out var ids)) rendererTileIds[kit] = ids.ToArray();
}
// The boats (SeaCraft): off the coast and moored in the harbours the kits recorded.
var crafts = SeaCraft.Place(ground, placed);
if (crafts.Count > 0)
{
var km = new KitMesh();
SeaCraft.Draw(crafts, ground, km);
Add(SeaCraftName, km.ToMesh(SeaCraftName));
}
stats.Boats = crafts.Count; stats.Crafts = crafts;
var works = new List<SettlementKits.Placed>();
foreach (var p in placed) if (p.Kind == "breakwater") works.Add(p);
stats.HarbourWorks = works;
// Issue #659: the buildings' models, instanced up close (without a complete model list, the kits at every zoom).
var townGo = new GameObject(TownModelsName);
townGo.transform.SetParent(root.transform, false);
var towns = townGo.AddComponent<TownModelLayer>();
if (residency == null) throw new System.ArgumentNullException(nameof(residency));
towns.ConfigureProduction(residency.Towns);
// #2378: beyond the close switch every settlement with a whole-town model (the moshavot and towns, the kibbutzim,
// Nahalal and the Arab towns: Acre, Nazareth, Lod, Gaza, Beersheba) draws the far-off copies of its building
// models, in place of the whole-town model within the far band (owner, 3 November 2026, "Cities/towns only
// (Recommended)"); the 271 1948 localities keep their kit blocks. The major cities (TownModels.IsMajorCity) have
// no whole-town model and take no far-off copies: they draw their kits from 40 km out (owner, 6 November 2026, "Big
// blocks, every zoom", which superseded the 2 November 2026 ruling, "Yes, small buildings at every zoom") and their
// building models below the close switch, as every place (owner, 7 November 2026, "Tal's models close
// (Recommended)", which supersedes "Big blocks, every zoom" below 40 km).
var farTowns = new List<string>();
foreach (var s in settlements)
if (Collection.TownLandmarks.ModelFor(s) != null) farTowns.Add(s.Id);
towns.Init(built.Models, townModels, swaps, nearTowns, rendererTownIds, rendererTileIds, farTowns);
stats.LandmarkParts = parts;
var landmarks = new List<SettlementKits.Placed>();
foreach (var p in placed) if (p.Kind != "building" && p.Kind != "wing") landmarks.Add(p);
foreach (var p in built.CloseLandmarks) landmarks.Add(new SettlementKits.Placed(p.Id, p.Kind, p.C, 0f, p.W, p.D, p.H, p.Wall, p.Y));
stats.Landmarks = landmarks;
var majorBlocks = new List<SettlementKits.Placed>();
foreach (var p in placed) if ((p.Kind == "building" || p.Kind == "wing") && TownModels.IsMajorCity(p.Id)) majorBlocks.Add(p);
stats.MajorCityBlocks = majorBlocks;
var localityIds = new HashSet<string>(System.StringComparer.Ordinal);
foreach (var locality in localities) localityIds.Add(locality.Id);
towns.ConfigureTownFootprints(stats.Footprints, localityIds);
stats.Models = built.Models.Count;
stats.Localities = localities.Count; stats.LocalityBuildings = built.LocalityBuildings; stats.Camps = built.Camps; stats.Tents = built.Tents;
stats.Buildings += built.LocalityBuildings + built.Tents;
stats.BuildMs = (float)clock.Elapsed.TotalMilliseconds;
Boot.DiagLog.BootPhase("kit buildings built"); // issue #321: the buildings, apart from the trees
clock.Restart();
var all = new List<Settlement>(settlements); all.AddRange(localities);
var trees = Vegetation.Plant(all, ground);
var veg = new GameObject(VegetationName);
veg.transform.SetParent(root.transform, false);
var layer = veg.AddComponent<VegetationLayer>();
layer.Init(trees, treeMaterial, assets);
stats.Trees = trees.Count;
stats.PlantMs = (float)clock.Elapsed.TotalMilliseconds;
// "kits" off shows the placeholder marker boxes again, so a settlement is always drawn by one or the other.
void ShowKits(bool on)
{
if (root != null) foreach (var mr in root.GetComponentsInChildren<MeshRenderer>(true)) mr.enabled = on;
if (towns != null) towns.Draw = on;
if (markers != null) foreach (var mr in markers.GetComponentsInChildren<MeshRenderer>(true)) mr.enabled = !on;
}
ShowKits(true);
assets.OnTeardown(VisualToggles.Register("kits", ShowKits));
assets.OnTeardown(VisualToggles.Register("trees", on => { if (layer != null) layer.Draw = on; }));
return root;
}
}
}