Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Map: MATKOT's farm and village life, tractors, wagons, horses, sheep, donkeys and camels at the train's scale (refs #667) (#1029)

Eyal Golanada6e9899b0f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d08048390..3a2faca30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,12 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
each written into the state hash only when set, so a halutz hashes as before and no golden moves. `unit_types.yaml`
gains Israel's `veteran_soldier` (infantry), `artillery` and `armoured_car` (armour) with a `side` and a `class`; the
loader refuses a military type without both (R-UNIT-001, R-UNIT-002; refs #741, #385). Nothing uses them yet.
+- Farm and village life from MATKOT's 1948 Collection: three tractors by kibbutz fields, three horse wagons and three
+ draught horses by moshav and moshava fields, three flocks of five sheep and three donkeys by villages, and three camels
+ by Bedouin camp areas, each anchor chosen by a fixed hash and kept clear of the kits, routes, unit tokens, water,
+ civilians (#666) and wildlife (#670), with the kit trees over them left out.
+ They stand at the #700 buildings' one world scale (24x real: a tractor about a third of the steam train's locomotive,
+ a sheep about a seventh), stream after the first frame, and play their idle clip only at close zoom (40 km) (#667).
- Kiryat Shmona (founded 18 July 1949) and Beit Shemesh (15 December 1950, the National Library's December 1950
under the monthly turn) join the yishuv sites in `content/sites.yaml`, each with a field site in its hex; the
founding days are the owner's (#785), and the rows stay draft. The reference player builds them in id order, so
diff --git a/unity/Assets/Scripts/Map/Collection/RuralLife.cs b/unity/Assets/Scripts/Map/Collection/RuralLife.cs
new file mode 100644
index 000000000..bd6a2b826
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Collection/RuralLife.cs
@@ -0,0 +1,335 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Game.Map.Routes;
+using UnityEngine;
+using UnityEngine.Rendering;
+
+namespace Statecraft.Game.Map.Collection
+{
+ /// <summary>Period-generic farm and village life from MATKOT's 1948 Collection (issue #667, whose sourced setting is:
+ /// tractors and horse-drawn work at kibbutz, moshav and moshava fields; sheep and donkeys at villages; camels at
+ /// Bedouin areas). This is presentation only: the figures are scenery, never civilian or combat units.
+ ///
+ /// A fixed hash orders the eligible anchors, the first <see cref="MaxAnchorsPerModel"/> with clear ground are used, and
+ /// another hash chooses each anchor's first bearing. Models stand outside the anchor footprint, clear of every kit,
+ /// route, unit token, water and other rural model, at the buildings' one world scale (<see cref="WorldScale"/>: a
+ /// tractor is about a third of the steam train's locomotive, a sheep about a seventh). Sheep stand as a small flock.
+ /// Both shared prefab details stream through <see cref="CollectionStream"/> after the first frame. Far static meshes draw above 45 km; near meshes
+ /// draw at 40 km and closer, with hysteresis, and only their existing idle Animators run there. A missing streamed
+ /// prefab leaves that detail out and the map continues.</summary>
+ public sealed class RuralLife : MonoBehaviour
+ {
+ public const string Name = "RuralLife";
+ public const string Tractor = "figure-vehicle-farm-tractor-1948-v2";
+ public const string Wagon = "figure-vehicle-horse-wagon-1948-v2";
+ public const string Horse = "figure-draught-horse-idle-1948-v2";
+ public const string Sheep = "figure-sheep-idle-1948-v1";
+ public const string Donkey = "figure-donkey-1948-v1";
+ public const string Camel = "figure-dromedary-camel-1948-v1";
+ public static readonly string[] Models = { Tractor, Wagon, Horse, Sheep, Donkey, Camel };
+
+ // Design values (#667): sparse scenery, not a population statement or simulation rule.
+ public const int MaxAnchorsPerModel = 3;
+ /// <summary>The house the world scale is set by (m, real): the middle of the kit's default house, 7.5 to 10 m long.</summary>
+ public const float ReferenceHouseM = 8.5f;
+ /// <summary>The one world scale of the map's MATKOT models up close (the owner on v0.1.1, 18 October 2026: the
+ /// buildings were "way bigger then the train"): the reference house is as long as the locomotive's car of the steam
+ /// train the map runs (ServiceTrain: MATKOT's locomotive and tender at RouteTrain.Scale x ServiceTrain.ModelSize,
+ /// about 816 m, in ServiceTrain.Cars cars of about 204 m), so 204 / 8.5 = 24x real. The same rule as the #700
+ /// buildings' scale fix (branch map/town-models-world-scale, SettlementKits.ModelScale), so a tractor stands beside
+ /// a kibbutz house at their real proportion. (Tripo's meshes are all about one unit across, so one shared scale
+ /// would make a sheep as long as a tractor.)</summary>
+ public const float WorldScale = RouteTrain.ModelRealLengthM * RouteTrain.Scale * ServiceTrain.ModelSize / ServiceTrain.Cars / ReferenceHouseM;
+ /// <summary>Design values (#667), typical of each kind, not sourced measurements: the real long side (m), seen from
+ /// above, each model stands for.</summary>
+ public static float RealLengthM(string model) => model switch
+ {
+ Tractor => 3f, Wagon => 5f, Horse => 2.5f, Sheep => 1.3f, Donkey => 1.8f, Camel => 3f,
+ _ => throw new ArgumentException($"'{model}' is not one of #667's models", nameof(model)),
+ };
+ /// <summary>The model's long side on the map (m).</summary>
+ public static float SizeOf(string model) => RealLengthM(model) * WorldScale;
+ // Design values (#667): a flock is a few sheep, spaced a couple of sheep apart around the scene's spot.
+ public const int FlockSize = 5;
+ public const float FlockSpacingLengths = 2.5f;
+ public static int MembersOf(string model) => model == Sheep ? FlockSize : 1;
+ /// <summary>The ground a scene takes (m, radius about its spot): its model, or the flock around the spot, with one
+ /// model's length to spare. The kit trees whose crowns reach into it are left out at draw time
+ /// (Kits.VegetationLayer.Hide, as under the unit figures), so no orchard tree stands over a tractor.</summary>
+ public static float SceneRadiusM(string model) => (MembersOf(model) > 1 ? FlockSpacingLengths + 1.5f : 1.5f) * SizeOf(model);
+ // Design value (#667): clearance for the scaled model and its readable space at gameplay zoom.
+ public const float ClearanceRadiusM = 700f;
+ // #700's town-detail close/far band (40/45 km), reused.
+ public const float CloseEnterM = Kits.TownModelLayer.CloseEnterM, CloseExitM = Kits.TownModelLayer.CloseExitM;
+ // Design value (#667): eight bearings on three rings gives a bounded search without dense scattering.
+ public const int Bearings = 8, Rings = 3;
+ // Design values (#667): start beyond the clearance disc, then step outward by one clearance radius per ring.
+ public const float FirstRingClearances = 1.25f, RingStepClearances = 1f;
+ // Design value (#667): neutral headings diversified by the deterministic seed.
+ public const float DefaultYaw = 0f;
+
+ internal static Action<string, CollectionDetail, Action<GameObject?>> Request = CollectionStream.Request;
+
+ public readonly struct Want : IEquatable<Want>
+ {
+ public readonly string Key, Model; public readonly Vector2 Anchor; public readonly float AnchorRadius;
+ public Want(string key, string model, Vector2 anchor, float anchorRadius)
+ { Key = key; Model = model; Anchor = anchor; AnchorRadius = anchorRadius; }
+ public bool Equals(Want other) => Key == other.Key && Model == other.Model && Anchor == other.Anchor && AnchorRadius == other.AnchorRadius;
+ public override bool Equals(object? obj) => obj is Want other && Equals(other);
+ public override int GetHashCode() => (Key, Model, Anchor, AnchorRadius).GetHashCode();
+ }
+
+ readonly struct Anchor
+ {
+ public readonly string Key, Type; public readonly Vector2 At; public readonly float Radius;
+ public Anchor(string key, string type, Vector2 at, float radius) { Key = key; Type = type; At = at; Radius = radius; }
+ }
+
+ /// <summary>Every eligible anchor for every model, each model's in its fixed hash order; the layer uses the first
+ /// <see cref="MaxAnchorsPerModel"/> of each that have clear ground.</summary>
+ public static List<Want> Wants(MapScene map)
+ {
+ var footprints = new Dictionary<string, (Vector2 At, float Radius)>(StringComparer.Ordinal);
+ foreach (var f in map.KitFootprints) if (!footprints.ContainsKey(f.id)) footprints[f.id] = (f.centre, f.radius);
+ var anchors = new List<Anchor>();
+ void Add(Statecraft.Game.Map.Settlement s)
+ {
+ if (!footprints.TryGetValue(s.Id, out var f)) return;
+ if (!anchors.Any(a => a.Key == s.Id)) anchors.Add(new Anchor(s.Id, s.Type, f.At, f.Radius));
+ }
+ foreach (var s in map.Settlements) Add(s);
+ foreach (var p in map.Localities) Add(p.Settlement);
+ foreach (var f in map.KitFootprints.Where(f => f.id.StartsWith("camp:", StringComparison.Ordinal)))
+ if (!anchors.Any(a => a.Key == f.id)) anchors.Add(new Anchor(f.id, "bedouin_area", f.centre, f.radius));
+
+ var result = new List<Want>();
+ AddModel(Tractor, anchors.Where(a => a.Type == "kibbutz"));
+ var horseFields = anchors.Where(a => a.Type == "moshav" ||
+ (TownLandmarks.ById.TryGetValue(a.Key, out var model) && model == TownLandmarks.Moshava)).ToList();
+ AddModel(Wagon, horseFields); AddModel(Horse, horseFields);
+ var villages = anchors.Where(a => a.Type == "village").ToList(); // #667: "at the villages", not the towns
+ AddModel(Sheep, villages); AddModel(Donkey, villages);
+ AddModel(Camel, anchors.Where(a => a.Type == "bedouin_area"));
+ return result;
+
+ void AddModel(string model, IEnumerable<Anchor> eligible)
+ {
+ foreach (var a in eligible.OrderBy(x => StableHash(model + ":" + x.Key)).ThenBy(x => x.Key, StringComparer.Ordinal))
+ result.Add(new Want(a.Key, model, a.At, a.Radius));
+ }
+ }
+
+ /// <summary>FNV-1a over UTF-16 code units: stable across Unity runtimes (unlike string.GetHashCode).</summary>
+ public static uint StableHash(string value)
+ {
+ uint h = 2166136261u;
+ foreach (char c in value) { h ^= c; h = unchecked(h * 16777619u); }
+ return h;
+ }
+
+ public static Vector2? Spot(Want want, Func<Vector2, float, bool> free)
+ {
+ uint seed = StableHash(want.Model + ":" + want.Key);
+ int first = (int)(seed % Bearings);
+ for (int ring = 0; ring < Rings; ring++)
+ {
+ float distance = want.AnchorRadius + ClearanceRadiusM * (FirstRingClearances + ring * RingStepClearances);
+ for (int k = 0; k < Bearings; k++)
+ {
+ float angle = (first + k) * (360f / Bearings) * Mathf.Deg2Rad;
+ var p = want.Anchor + new Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * distance;
+ if (free(p, ClearanceRadiusM)) return p;
+ }
+ }
+ return null;
+ }
+
+ public static float YawOf(Want want, int member = 0) => DefaultYaw + StableHash(want.Key + ":" + want.Model + (member == 0 ? "" : "#" + member)) % 360u;
+
+ /// <summary>Where member <paramref name="member"/> of a scene at <paramref name="spot"/> stands: the spot itself, or
+ /// around it for a flock's other sheep.</summary>
+ public static Vector2 MemberAt(Want want, Vector2 spot, int member)
+ {
+ if (member == 0) return spot;
+ float a = (StableHash(want.Key + ":" + want.Model) % 360u + member * 360f / (MembersOf(want.Model) - 1)) * Mathf.Deg2Rad;
+ return spot + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * FlockSpacingLengths * SizeOf(want.Model);
+ }
+ public static bool CloseAt(float distanceM, bool? was) => was == true ? distanceM <= CloseExitM : distanceM <= CloseEnterM;
+
+ MapScene? map;
+ readonly Dictionary<(string Model, CollectionDetail Detail), GameObject?> prefabs = new Dictionary<(string, CollectionDetail), GameObject?>();
+ readonly HashSet<(string Model, CollectionDetail Detail)> asked = new HashSet<(string, CollectionDetail)>();
+ readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();
+ readonly List<(Renderer Renderer, CollectionDetail Detail)> renderers = new List<(Renderer, CollectionDetail)>();
+ readonly List<(Animator Animator, CollectionDetail Detail)> animators = new List<(Animator, CollectionDetail)>();
+ List<Want> wants = new List<Want>();
+
+ public readonly List<(string Key, string Model, CollectionDetail Detail, Vector3 At, string Name, int Member)> Placed =
+ new List<(string, string, CollectionDetail, Vector3, string, int)>();
+ /// <summary>The scenes drawn (one per anchor used), and the models with fewer than MaxAnchorsPerModel of them.</summary>
+ public readonly List<Want> Scenes = new List<Want>();
+ public readonly List<string> Missing = new List<string>();
+ public IReadOnlyList<Want> Wanted => wants;
+ public bool LastClose { get; private set; }
+
+ /// <summary>The ground the other Collection layers hold (centre, radius m): the civilian figures CivilianPeople wants
+ /// now (its FigureClearanceM) and the wildlife (half WildlifeLayer.SizeM), so no rural scene stands under them (#667:
+ /// kept clear of the other props). GameRoot shows those layers first.</summary>
+ public static List<(Vector2 centre, float radius)> OtherProps(MapScene map)
+ {
+ var discs = new List<(Vector2, float)>();
+ var people = map.Terrain != null ? map.Terrain.transform.Find(CivilianPeople.Name)?.GetComponent<CivilianPeople>() : null;
+ if (people != null) foreach (var w in people.Wanted) discs.Add((new Vector2(w.At.x, w.At.z), CivilianPeople.FigureClearanceM));
+ foreach (var w in WildlifeLayer.Wants(map)) discs.Add((w.At, 0.5f * WildlifeLayer.SizeM));
+ return discs;
+ }
+
+ public static RuralLife? Show(MapScene map)
+ {
+ if (map == null || map.Terrain == null || map.Hexes == null) return null;
+ var layer = map.Terrain.transform.Find(Name)?.GetComponent<RuralLife>();
+ if (layer == null)
+ {
+ var go = new GameObject(Name);
+ go.transform.SetParent(map.Terrain.transform, false);
+ layer = go.AddComponent<RuralLife>();
+ layer.map = map;
+ }
+ layer.Show(Wants(map), OtherProps(map));
+ return layer;
+ }
+
+ List<(Vector2 centre, float radius)> others = new List<(Vector2, float)>();
+
+ void Show(List<Want> next, List<(Vector2 centre, float radius)> nextOthers)
+ {
+ if (next.SequenceEqual(wants) && nextOthers.SequenceEqual(others)) return;
+ wants = next; others = nextOthers;
+ foreach (var model in wants.Select(w => w.Model).Distinct())
+ foreach (var detail in new[] { CollectionDetail.Far, CollectionDetail.Near })
+ if (asked.Add((model, detail)))
+ {
+ var m = model; var d = detail;
+ Request(m, d, prefab => OnModel(m, d, prefab));
+ }
+ Rebuild();
+ }
+
+ void OnModel(string model, CollectionDetail detail, GameObject? prefab)
+ {
+ if (this == null) return;
+ prefabs[(model, detail)] = prefab;
+ if (prefab == null) Debug.LogWarning($"RURAL: {model} {detail.ToString().ToLowerInvariant()} did not stream; that rural detail stays off the map.");
+ Rebuild();
+ }
+
+ void Rebuild()
+ {
+ if (map == null || map.Terrain == null) return;
+ for (int i = transform.childCount - 1; i >= 0; i--) DestroyNow(transform.GetChild(i).gameObject);
+ renderers.Clear(); animators.Clear(); Placed.Clear(); Scenes.Clear(); Missing.Clear();
+ var ground = PlacementLayer.CampGround(map);
+ var footprints = map.KitFootprints.Select(f => (f.centre, f.radius)).ToList();
+ var taken = new List<(Vector2 centre, float radius)>();
+ bool Free(Vector2 p, float radius)
+ {
+ if (!TownLandmarks.Clear(p, radius, footprints) || !TownLandmarks.Clear(p, radius, taken) || !TownLandmarks.Clear(p, radius, others)) return false;
+ if (!ground.Inside(p.x - radius, p.y - radius) || !ground.Inside(p.x + radius, p.y + radius)) 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)) * radius * 0.8f;
+ if (ground.Water(q.x, q.y)) return false;
+ }
+ return !ground.OnRoute(p, radius) && !ground.OnToken(p, radius);
+ }
+ var used = new Dictionary<string, int>(StringComparer.Ordinal);
+ var holes = new List<(Vector2 centre, float radius)>();
+ foreach (var want in wants)
+ {
+ bool answered = prefabs.ContainsKey((want.Model, CollectionDetail.Far)) && prefabs.ContainsKey((want.Model, CollectionDetail.Near));
+ if (!answered) continue;
+ bool any = prefabs[(want.Model, CollectionDetail.Far)] != null || prefabs[(want.Model, CollectionDetail.Near)] != null;
+ used.TryGetValue(want.Model, out int n);
+ if (!any || 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));
+ holes.Add((at.Value, SceneRadiusM(want.Model)));
+ for (int member = 0; member < MembersOf(want.Model); member++)
+ {
+ var flat = MemberAt(want, at.Value, member);
+ var pos = new Vector3(flat.x, ground.Y(flat.x, flat.y), flat.y);
+ foreach (var detail in new[] { CollectionDetail.Far, CollectionDetail.Near })
+ {
+ var prefab = prefabs[(want.Model, detail)];
+ if (prefab == null) continue;
+ var go = Instantiate(prefab, transform, false);
+ string instanceName = want.Key + ":" + want.Model + (member == 0 ? "" : "#" + member) + ":" + detail.ToString().ToLowerInvariant();
+ go.name = instanceName;
+ // Sized at the world scale by its long side seen from above, measured before the map's yaw.
+ go.transform.localRotation = prefab.transform.localRotation;
+ var own = Bounds(go);
+ float edge = Mathf.Max(own.size.x, own.size.z);
+ go.transform.localScale = prefab.transform.localScale * (edge > 1e-4f ? SizeOf(want.Model) / edge : 1f);
+ go.transform.localRotation = Quaternion.Euler(0f, YawOf(want, member), 0f) * prefab.transform.localRotation;
+ go.transform.position = pos;
+ var bounds = Bounds(go);
+ go.transform.position += new Vector3(pos.x - bounds.center.x, pos.y - bounds.min.y, pos.z - bounds.center.z);
+ foreach (var renderer in go.GetComponentsInChildren<Renderer>(true))
+ {
+ renderer.shadowCastingMode = ShadowCastingMode.On;
+ renderer.forceRenderingOff = detail == CollectionDetail.Near ? !LastClose : LastClose;
+ renderers.Add((renderer, detail));
+ }
+ foreach (var animator in go.GetComponentsInChildren<Animator>(true))
+ {
+ animator.enabled = detail == CollectionDetail.Near && LastClose;
+ animators.Add((animator, detail));
+ }
+ Placed.Add((want.Key, want.Model, detail, pos, instanceName, member));
+ }
+ }
+ }
+ Units.UnitShowcase.HideTrees(map, Name, holes);
+ foreach (var model in wants.Select(w => w.Model).Distinct())
+ if (prefabs.ContainsKey((model, CollectionDetail.Far)) && prefabs.ContainsKey((model, CollectionDetail.Near))
+ && (!used.TryGetValue(model, out int got) || got < MaxAnchorsPerModel)) Missing.Add(model);
+ Debug.Log($"RURAL: {Scenes.Count} rural scenes placed ({Placed.Count} models); {Missing.Count} models short of {MaxAnchorsPerModel} scenes");
+ }
+
+ static Bounds Bounds(GameObject go)
+ {
+ var rs = go.GetComponentsInChildren<Renderer>(true);
+ if (rs.Length == 0) return new Bounds(go.transform.position, Vector3.zero);
+ var bounds = rs[0].bounds;
+ foreach (var r in rs) bounds.Encapsulate(r.bounds);
+ return bounds;
+ }
+
+ static void DestroyNow(GameObject go)
+ {
+ if (Application.isPlaying) { go.transform.SetParent(null); Destroy(go); }
+ else DestroyImmediate(go);
+ }
+
+ void OnEnable() => RenderPipelineManager.beginCameraRendering += Choose;
+ void OnDisable() => RenderPipelineManager.beginCameraRendering -= Choose;
+
+ internal void Choose(ScriptableRenderContext context, Camera camera)
+ {
+ if (camera.cameraType == CameraType.Preview || camera.cameraType == CameraType.Reflection) return;
+ int id = camera.GetInstanceID();
+ bool close = CloseAt(TownLandmarks.ViewDistance(camera), closeFor.TryGetValue(id, out var was) ? was : (bool?)null);
+ closeFor[id] = close; LastClose = close;
+ foreach (var (renderer, detail) in renderers)
+ if (renderer != null) renderer.forceRenderingOff = detail == CollectionDetail.Near ? !close : close;
+ foreach (var (animator, detail) in animators)
+ if (animator != null) animator.enabled = detail == CollectionDetail.Near && close;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/Collection/RuralLife.cs.meta b/unity/Assets/Scripts/Map/Collection/RuralLife.cs.meta
new file mode 100644
index 000000000..f9b275a78
--- /dev/null
+++ b/unity/Assets/Scripts/Map/Collection/RuralLife.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 04c6f60a34c14118a58acd572288b6e8
diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.cs
index 58fabc1cc..e981b272c 100644
--- a/unity/Assets/Scripts/UI/GameRoot.cs
+++ b/unity/Assets/Scripts/UI/GameRoot.cs
@@ -450,6 +450,8 @@ namespace Statecraft.Game.UI
Statecraft.Game.Map.Collection.WildlifeLayer.Show(map);
// MATKOT's civilian figures at towns and transit camps, ambience only and streamed after the first frame (#666).
Statecraft.Game.Map.Collection.CivilianPeople.ShowAt(map, Bridge.State.Date, Bridge.State.Placements, Bridge.Content);
+ // MATKOT's period-generic farm and village scenery, streamed after the first frame (#667); never game units.
+ Statecraft.Game.Map.Collection.RuralLife.Show(map);
RenderSitesIfChanged();
var now = Bridge.State.Placements.Select(p => (p.Action, p.Q, p.R, p.Date)).ToList();
if (drawn != null && drawn.SequenceEqual(now)) return;
diff --git a/unity/Assets/Tests/EditMode/RuralLifeTests.cs b/unity/Assets/Tests/EditMode/RuralLifeTests.cs
new file mode 100644
index 000000000..031d7f248
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/RuralLifeTests.cs
@@ -0,0 +1,271 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using Statecraft.Game.Map.Collection;
+using Statecraft.Game.Map.Routes;
+using Statecraft.Game.Map.Units;
+using UnityEditor;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.TestTools;
+using Object = UnityEngine.Object;
+
+/// <summary>Issue #667: all six of MATKOT's rural models are sparsely and deterministically placed by settlement type,
+/// clear of the map's occupied ground, streamed after the first frame, upright, and absent without harming the map when
+/// their bundle cannot be read.</summary>
+public class RuralLifeTests
+{
+ Action<string, CollectionDetail, Action<GameObject?>> saved = null!;
+ readonly List<(string id, CollectionDetail detail, Action<GameObject?> done)> asked = new List<(string, CollectionDetail, Action<GameObject?>)>();
+
+ [SetUp]
+ public void Seam()
+ {
+ saved = RuralLife.Request;
+ asked.Clear();
+ RuralLife.Request = (id, detail, done) => asked.Add((id, detail, done));
+ }
+
+ [TearDown]
+ public void Reset()
+ {
+ RuralLife.Request = saved;
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ }
+
+ static MapScene OpenMap()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>();
+ map.Build();
+ return map;
+ }
+
+ static GameObject Prefab(string id, CollectionDetail detail) =>
+ AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, detail));
+
+ void AnswerAll(bool found = true)
+ {
+ var pending = asked.ToList();
+ asked.Clear();
+ foreach (var (id, detail, done) in pending) done(found ? Prefab(id, detail) : null);
+ }
+
+ [Test]
+ public void EveryLaneModelIsPlacedInItsSourcedSettingAtBothDetails()
+ {
+ var map = OpenMap();
+ var layer = RuralLife.Show(map)!;
+ CollectionAssert.AreEquivalent(RuralLife.Models, layer.Wanted.Select(w => w.Model).Distinct());
+ Assert.AreEqual(layer.Wanted.Count, layer.Wanted.Select(w => (w.Key, w.Model)).Distinct().Count(), "each anchor once per model");
+ foreach (var id in RuralLife.Models)
+ {
+ Assert.Greater(layer.Wanted.Count(w => w.Model == id), RuralLife.MaxAnchorsPerModel, id + " has spare anchors");
+ Assert.AreEqual(2, asked.Count(a => a.id == id), id + " asks for far and near once");
+ CollectionAssert.AreEquivalent(new[] { CollectionDetail.Far, CollectionDetail.Near }, asked.Where(a => a.id == id).Select(a => a.detail));
+ }
+ AnswerAll();
+ foreach (var id in RuralLife.Models)
+ Assert.AreEqual(RuralLife.MaxAnchorsPerModel, layer.Scenes.Count(w => w.Model == id), id + " sparse placement count");
+ Assert.AreEqual(RuralLife.Models.Length * RuralLife.MaxAnchorsPerModel, layer.Scenes.Count, "18 sparse rural scenes");
+ CollectionAssert.IsEmpty(layer.Missing);
+ var types = map.Settlements.Concat(map.Localities.Select(p => p.Settlement))
+ .GroupBy(s => s.Id).ToDictionary(g => g.Key, g => g.First().Type);
+ foreach (var want in layer.Scenes)
+ {
+ if (want.Model == RuralLife.Camel) StringAssert.StartsWith("camp:", want.Key, want.Model + " uses a Bedouin-area camp");
+ else if (want.Model == RuralLife.Tractor) Assert.AreEqual("kibbutz", types[want.Key], want.Key);
+ else if (want.Model == RuralLife.Wagon || want.Model == RuralLife.Horse)
+ Assert.IsTrue(types[want.Key] == "moshav" ||
+ (TownLandmarks.ById.TryGetValue(want.Key, out var model) && model == TownLandmarks.Moshava), want.Key);
+ else Assert.AreEqual("village", types[want.Key], want.Key);
+ }
+ Assert.AreEqual(layer.Scenes.Sum(w => RuralLife.MembersOf(w.Model)) * 2, layer.Placed.Count, "one far and one near instance of every scene's models");
+ Assert.AreEqual(RuralLife.MaxAnchorsPerModel * RuralLife.FlockSize * 2, layer.Placed.Count(p => p.Model == RuralLife.Sheep), "the sheep stand in flocks");
+ }
+
+ [Test]
+ public void SeededSpotsAreDeterministicClearAndUpright()
+ {
+ var map = OpenMap();
+ var first = RuralLife.Show(map)!;
+ AnswerAll();
+ var spots = first.Placed.Select(p => (p.Key, p.Model, p.Detail, p.At, p.Member)).ToList();
+ Object.DestroyImmediate(first.gameObject);
+ var second = RuralLife.Show(map)!;
+ AnswerAll();
+ CollectionAssert.AreEqual(spots, second.Placed.Select(p => (p.Key, p.Model, p.Detail, p.At, p.Member)).ToList(), "same map, same seeded spots");
+
+ var ground = PlacementLayer.CampGround(map);
+ foreach (var p in second.Placed.Where(p => p.Detail == CollectionDetail.Far))
+ {
+ var flat = new Vector2(p.At.x, p.At.z);
+ Assert.IsFalse(ground.OnRoute(flat, RuralLife.ClearanceRadiusM), p.Key + " route clearance");
+ Assert.IsFalse(ground.OnToken(flat, RuralLife.ClearanceRadiusM), p.Key + " token clearance");
+ var go = second.transform.Find(p.Name);
+ Assert.IsNotNull(go, p.Name);
+ var want = second.Scenes.Single(w => w.Key == p.Key && w.Model == p.Model);
+ var prefab = Prefab(p.Model, p.Detail);
+ Assert.Less(Quaternion.Angle(Quaternion.Euler(0f, RuralLife.YawOf(want, p.Member), 0f) * prefab.transform.localRotation,
+ go!.localRotation), 0.01f, p.Name + " preserves the prefab's FBX axis conversion under its yaw");
+ var bounds = go.GetComponentsInChildren<Renderer>().Select(r => r.bounds).Aggregate((a, b) => { a.Encapsulate(b); return a; });
+ Assert.AreEqual(p.At.y, bounds.min.y, 1f, p.Name + " rests on the ground");
+ }
+ // No kit tree stands over a scene: the trees whose crowns reach its ground are left out (#667: kept clear of the other props).
+ var veg = map.GetComponentInChildren<Statecraft.Game.Map.Kits.VegetationLayer>(true);
+ Assert.IsNotNull(veg);
+ var over = new List<string>();
+ foreach (var w in second.Scenes)
+ {
+ var c = second.Placed.First(p => p.Key == w.Key && p.Model == w.Model && p.Member == 0).At;
+ float r = RuralLife.SceneRadiusM(w.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(c.x, c.z)).sqrMagnitude < reach * reach;
+ });
+ if (n > 0) over.Add($"{w.Key}:{w.Model}: {n} trees");
+ }
+ CollectionAssert.IsEmpty(over, "kit trees over a rural scene");
+ }
+
+ [Test]
+ public void CloseZoomUsesNearModelsAndOnlyNearAnimalsAnimate()
+ {
+ var map = OpenMap();
+ var layer = RuralLife.Show(map)!;
+ AnswerAll();
+ Assert.IsFalse(RuralLife.CloseAt(RuralLife.CloseExitM + 1f, true));
+ Assert.IsTrue(RuralLife.CloseAt(RuralLife.CloseEnterM, false));
+ Assert.IsTrue(RuralLife.CloseAt(RuralLife.CloseExitM, true));
+
+ var cam = Camera.main!;
+ cam.transform.SetPositionAndRotation(new Vector3(0f, RuralLife.CloseEnterM, 0f), Quaternion.Euler(90f, 0f, 0f));
+ layer.Choose(default, cam);
+ Assert.IsTrue(layer.LastClose);
+ Assert.IsTrue(layer.transform.Cast<Transform>().Where(t => t.name.EndsWith(":near")).
+ SelectMany(t => t.GetComponentsInChildren<Renderer>(true)).All(r => !r.forceRenderingOff));
+ Assert.IsTrue(layer.transform.Cast<Transform>().Where(t => t.name.EndsWith(":far")).
+ SelectMany(t => t.GetComponentsInChildren<Renderer>(true)).All(r => r.forceRenderingOff));
+ var animated = layer.GetComponentsInChildren<Animator>(true).Where(a => a.runtimeAnimatorController != null).ToList();
+ Assert.Greater(animated.Count, 0, "the supplied near-detail horse and sheep idle clips are present");
+ Assert.IsTrue(animated.All(a => a.enabled));
+ cam.transform.position = new Vector3(0f, RuralLife.CloseExitM + 1f, 0f);
+ layer.Choose(default, cam);
+ Assert.IsFalse(layer.LastClose);
+ Assert.IsTrue(layer.transform.Cast<Transform>().Where(t => t.name.EndsWith(":near")).
+ SelectMany(t => t.GetComponentsInChildren<Renderer>(true)).All(r => r.forceRenderingOff));
+ Assert.IsTrue(layer.transform.Cast<Transform>().Where(t => t.name.EndsWith(":far")).
+ SelectMany(t => t.GetComponentsInChildren<Renderer>(true)).All(r => !r.forceRenderingOff));
+ Assert.IsTrue(layer.GetComponentsInChildren<Animator>(true).All(a => !a.enabled));
+ }
+
+ [Test]
+ public void ABundleThatDoesNotStreamLeavesTheMapRunning()
+ {
+ var map = OpenMap();
+ var layer = RuralLife.Show(map)!;
+ int requests = asked.Count;
+ for (int i = 0; i < requests; i++)
+ LogAssert.Expect(LogType.Warning, new Regex("^RURAL: .* did not stream"));
+ AnswerAll(found: false);
+ Assert.AreEqual(0, layer.transform.childCount);
+ CollectionAssert.AreEquivalent(RuralLife.Models, layer.Missing);
+ Assert.IsNotNull(map.Terrain);
+ Assert.DoesNotThrow(() => RuralLife.Show(map));
+ Assert.AreEqual(0, asked.Count, "a failed detail is not requested every frame");
+ }
+
+ [Test]
+ public void ModelsUseTheCollectionStreamAndNeverResources()
+ {
+ Assert.AreEqual(typeof(CollectionStream), saved.Method.DeclaringType);
+ Assert.AreEqual(nameof(CollectionStream.Request), saved.Method.Name);
+ foreach (var id in RuralLife.Models)
+ {
+ Assert.IsTrue(CollectionCatalog.BundleOf(id) == CollectionCatalog.Vehicles || CollectionCatalog.BundleOf(id) == CollectionCatalog.Animals, id);
+ foreach (var detail in new[] { CollectionDetail.Far, CollectionDetail.Near })
+ {
+ var path = CollectionCatalog.PrefabPath(id, detail);
+ Assert.IsNotNull(Prefab(id, detail), path);
+ StringAssert.DoesNotContain("/Resources/", path);
+ foreach (var dep in AssetDatabase.GetDependencies(path, true)) StringAssert.DoesNotContain("/Resources/", dep);
+ }
+ Assert.IsNull(Resources.Load<GameObject>(id));
+ }
+ }
+
+ /// <summary>The owner on v0.1.1 (18 October 2026): MATKOT's buildings were "way bigger then the train". The farm and
+ /// village models stand at a believable size beside the steam train the map runs (ServiceTrain): each one's long side,
+ /// seen from above, is inside its band of the locomotive's car (about 204 m: MATKOT's locomotive and tender at
+ /// RouteTrain.Scale x ServiceTrain.ModelSize / ServiceTrain.Cars), so a tractor or a wagon is shorter than the
+ /// locomotive, a sheep is a small fraction of it, and every model is far smaller than a unit token's figure
+ /// (UnitBadge.FigureHeightM x UnitShowcase.FigureScale, about 2.5 km). The bands follow the buildings' one world scale
+ /// (an 8.5 m house as long as the locomotive's car, 24x real): a tractor about 3 m real is about 0.35 of the car.
+ /// The far and near models of a scene are one size.</summary>
+ [Test]
+ public void EveryModelStandsAtABelievableSizeBesideTheTrain()
+ {
+ var map = OpenMap();
+ var layer = RuralLife.Show(map)!;
+ AnswerAll();
+ float loco = RouteTrain.ModelRealLengthM * RouteTrain.Scale * ServiceTrain.ModelSize / ServiceTrain.Cars;
+ float figure = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;
+ Assert.AreEqual(204f, loco, 1f, "the locomotive's car");
+ var bands = new Dictionary<string, (float lo, float hi)>
+ {
+ [RuralLife.Tractor] = (0.25f, 0.5f), [RuralLife.Wagon] = (0.3f, 0.85f), [RuralLife.Horse] = (0.2f, 0.4f),
+ [RuralLife.Sheep] = (0.1f, 0.2f), [RuralLife.Donkey] = (0.13f, 0.3f), [RuralLife.Camel] = (0.25f, 0.5f),
+ };
+ var bad = new List<string>();
+ var sizes = new Dictionary<(string, string, CollectionDetail), float>();
+ foreach (var p in layer.Placed)
+ {
+ var go = layer.transform.Find(p.Name)!;
+ var b = go.GetComponentsInChildren<Renderer>(true).Select(r => r.bounds).Aggregate((a, c) => { a.Encapsulate(c); return a; });
+ float side = Mathf.Max(b.size.x, b.size.z), share = side / loco;
+ sizes[(p.Name, p.Model, p.Detail)] = side;
+ var (lo, hi) = bands[p.Model];
+ if (share < lo || share > hi) bad.Add($"{p.Name}: {side:0.0} m long, {share:0.00} of the locomotive's car (band {lo}-{hi})");
+ if (b.size.y > figure / 10f) bad.Add($"{p.Name}: {b.size.y:0} m tall against a {figure:0} m unit figure");
+ }
+ foreach (var g in sizes.GroupBy(kv => kv.Key.Item2))
+ TestContext.WriteLine($"{g.Key}: {string.Join(", ", g.Select(kv => $"{kv.Key.Item3} {kv.Value:0.0} m").Distinct().Take(4))}");
+ foreach (var p in layer.Placed.Where(p => p.Detail == CollectionDetail.Far))
+ {
+ string near = p.Name.Substring(0, p.Name.Length - "far".Length) + "near";
+ var n = sizes.Where(kv => kv.Key.Item1 == near).Select(kv => kv.Value).ToList();
+ if (n.Count == 1 && Mathf.Abs(n[0] - sizes[(p.Name, p.Model, p.Detail)]) > 0.1f * n[0]) bad.Add($"{p.Name}: far and near differ ({sizes[(p.Name, p.Model, p.Detail)]:0} / {n[0]:0} m)");
+ }
+ CollectionAssert.IsEmpty(bad, $"{bad.Count} rural models off the train's scale");
+ foreach (var id in RuralLife.Models) Assert.Greater(layer.Placed.Count(p => p.Model == id), 0, id + " drew");
+ }
+
+ /// <summary>#667: kept clear of the other props. No rural scene stands under a civilian figure (#666, shown first by
+ /// GameRoot) or a wild animal (#670).</summary>
+ [Test]
+ public void ScenesKeepClearOfTheCiviliansAndTheWildlife()
+ {
+ var map = OpenMap();
+ var savedPeople = CivilianPeople.Request;
+ CivilianPeople.Request = (id, detail, done) => { };
+ try
+ {
+ var content = Statecraft.Sim.ContentLoader.Load(Statecraft.Game.Paths.Content);
+ var people = CivilianPeople.ShowAt(map, new DateTime(1948, 5, 15), Array.Empty<Statecraft.Sim.Placement>(), content)!;
+ Assert.Greater(people.Wanted.Count, 0, "the civilians are wanted");
+ var layer = RuralLife.Show(map)!;
+ AnswerAll();
+ var others = RuralLife.OtherProps(map);
+ Assert.Greater(others.Count, people.Wanted.Count, "the civilians and the wildlife");
+ Assert.AreEqual(RuralLife.Models.Length * RuralLife.MaxAnchorsPerModel, layer.Scenes.Count);
+ foreach (var p in layer.Placed.Where(p => p.Member == 0 && p.Detail == CollectionDetail.Far))
+ Assert.IsTrue(TownLandmarks.Clear(new Vector2(p.At.x, p.At.z), RuralLife.ClearanceRadiusM, others), p.Name + " clear of the civilians and the wildlife");
+ }
+ finally { CivilianPeople.Request = savedPeople; }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/RuralLifeTests.cs.meta b/unity/Assets/Tests/EditMode/RuralLifeTests.cs.meta
new file mode 100644
index 000000000..e613778d7
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/RuralLifeTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 6ddba56a34934ca1877de049c759e4f7