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 road vehicles on the 1948 roads, on Israeli-held ground and smaller than the locomotive (fixes #725) (#1028)
Eyal Golan0161d463dda3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0c480157f..87d7264f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -59,6 +59,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBchecked every row against the Village Statistics 1945 scan and #490 applied the corrections. No other field changes.Open from #488, not touched here: the six split-or-merge rows, Dayr al-Qassi's landmark, 'Ilut. The localities areoutside the content hash, so no golden moves (#200).+- MATKOT's road vehicles from The 1948 Collection stand on the 1948 roads up close: the intercity bus and the citrus+ truck on the Tel Aviv–Haifa road, the sandwich-armoured convoy truck and the canvas-tilt lorry on the Burma Road from+ 14 June 1948. They stand only on ground Israel held on the game date, half as long as the steam train's locomotive,+ and stream after the first frame (#725).### Fixed- The sim tests no longer leave a temp folder behind for every `Fixture.Write` call (about 1,150 per run): thediff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex 8fb58d175..a711998d1 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -54,6 +54,9 @@ namespace Statecraft.Game.Map/// <summary>The game date the routes were last shown at (RouteLayer.ShowAt), so a rebuild draws them as at that date;/// null before the game has set one (the routes then show as at the game's start).</summary>public DateTime? RouteDate { get; set; }+ /// <summary>Who held which hex on a date (content/map/control_hexes_1948_49.yaml), as GameRoot read it for the borders,+ /// or null before it has: the road vehicles (issue #725) stand only on ground Israel held. Display only.</summary>+ public Control1948 Control { get; set; }/// <summary>The selected hex's outline: a child of the terrain (so a rebuild destroys it).</summary>public const string SelectionName = "HexSelection";@@ -406,7 +409,7 @@ namespace Statecraft.Game.Map// the service train from its sourced date (issue #668), streamed then, never at boot. The ribbons are// placed from their bake when it was made from these inputs (issue #321), else derived.Routes.RouteLayer.Build(Terrain, Frame, routes, Routes.RouteLayer.ModeForThisRun(), RouteDate ?? Routes.RouteLayer.DefaultDate,- Routes.RouteRibbonFile.Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml));+ Routes.RouteRibbonFile.Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml), this);DiagLog.BootPhase("routes built");if (!cam.TryGetComponent(out CameraRig rig)) rig = cam.gameObject.AddComponent<CameraRig>();diff --git a/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs b/unity/Assets/Scripts/Map/Routes/RoadVehicles.csnew file mode 100644index 000000000..97fb40f37--- /dev/null+++ b/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs@@ -0,0 +1,259 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using Statecraft.Game.Map.Collection;+using UnityEngine;+using UnityEngine.Rendering;++namespace Statecraft.Game.Map.Routes+{+ /// <summary>MATKOT's four civilian road vehicles of The 1948 Collection (H01, H04, H06, H10) on their 1948 roads (issue+ /// #725). Presentation only: a few parked vehicles, never units, never in the sim. The near prefabs stream through+ /// <see cref="CollectionStream"/> (nothing is fetched before the frame after the request, so never for the first frame)+ /// and draw only at the close zoom. Each vehicle stands on its road's drawn line, faces along it, keeps clear of the+ /// towns (their labels), the unit tokens and the other vehicles, and stands only on ground Israel held on the game date+ /// (<see cref="Control1948"/>, the map's own sourced control layer). It is sized against the steam locomotive the map+ /// runs (<see cref="ServiceTrain"/>): <see cref="LengthShare"/> of the locomotive's car. A model that does not stream+ /// removes only its own vehicles.</summary>+ public sealed class RoadVehicles : MonoBehaviour+ {+ public const string Name = "RoadVehicles";+ public const string IntercityBus = "figure-vehicle-intercity-bus-1948-v2";+ public const string CitrusTruck = "figure-vehicle-citrus-truck-1948-v2";+ public const string CanvasLorry = "figure-vehicle-canvas-lorry-1948-v2";+ public const string SandwichConvoy = "figure-vehicle-sandwich-convoy-1948-v2";++ /// <summary>The placement seed (design value).</summary>+ public const int Seed = 19480725;+ /// <summary>The close zoom (design value): the vehicles draw from 30 km of camera distance in, and off again beyond 36 km.</summary>+ public const float CloseEnterM = 30000f, CloseExitM = 36000f;+ /// <summary>The locomotive's car of the service train on the map (m): MATKOT's locomotive and tender at+ /// RouteTrain.Scale times ServiceTrain.ModelSize, in ServiceTrain.Cars cars (about 204 m).</summary>+ public const float LocomotiveCarM = RouteTrain.ModelRealLengthM * RouteTrain.Scale * ServiceTrain.ModelSize / ServiceTrain.Cars;+ /// <summary>A vehicle's length as a share of the locomotive's car (design value; the owner on v0.1.1, 18 October+ /// 2026: MATKOT's models were "way bigger then the train"): every road vehicle reads smaller than the locomotive,+ /// about 102 m.</summary>+ public const float LengthShare = 0.5f;+ public const float VehicleLengthM = LengthShare * LocomotiveCarM;+ /// <summary>How far a vehicle keeps from a town's ground, a unit's clearing or a token's ring (m, design value).</summary>+ public const float AnchorClearanceM = 450f;+ /// <summary>How far apart two vehicles stand (m, design value).</summary>+ public const float PairSpacingM = 1800f;+ /// <summary>Seeded spots tried per vehicle before it is left out (design value).</summary>+ public const int CandidateCount = 96;+ /// <summary>The vehicle's base above the ground under its centre (m): the route ribbons' own lift+ /// (RouteLayer.ClearanceM), plus 2 m, so it stands on the ribbon, not in it.</summary>+ public const float RideM = RouteLayer.ClearanceM + 2f;++ /// <summary>One model on one route from a date (and to one, exclusive). Counts are design values.</summary>+ public readonly struct Plan+ {+ public readonly string Model, Route; public readonly DateTime From; public readonly DateTime? To; public readonly int Count;+ public Plan(string model, string route, DateTime from, DateTime? to, int count)+ { Model = model; Route = route; From = from; To = to; Count = count; }+ public bool Covers(DateTime date) => date >= From && (To == null || date < To.Value);+ }++ static readonly DateTime Start = new DateTime(1948, 5, 15), BurmaOpen = new DateTime(1948, 6, 14);++ /// <summary>Where each model runs (content/map/routes_1948.yaml): the convoy truck and the canvas-tilt lorry on the+ /// Burma Road, Jerusalem's supply road from its completion on 14 June 1948 (the route's `from`, Burma Road (Israel));+ /// the Jaffa–Jerusalem road gets no convoy, as no source in content dates one on it inside the game window (from 15+ /// May 1948; the Arab Legion held Latrun from 18 May). The bus and the citrus truck on the Tel Aviv–Haifa road (1946+ /// map, from 1937) from the game's start. On every date a vehicle stands only where the control layer has Israel.</summary>+ public static readonly IReadOnlyList<Plan> Plans = new[]+ {+ new Plan(SandwichConvoy, "burma_road", BurmaOpen, null, 1),+ new Plan(CanvasLorry, "burma_road", BurmaOpen, null, 1),+ new Plan(IntercityBus, "tel_aviv_haifa_road", Start, null, 2),+ new Plan(CitrusTruck, "tel_aviv_haifa_road", Start, null, 2),+ };++ /// <summary>A test seam: how the layer asks for a model. Null (the default): the game's stream in Play mode, and none+ /// in the editor's edit mode (as UnitFigures), so a map built by an editor tool or another test fetches nothing.</summary>+ internal static Action<string, CollectionDetail, Action<GameObject?>>? Request;+ static Action<string, CollectionDetail, Action<GameObject?>>? Stream =>+ Request ?? (Application.isPlaying ? CollectionStream.Request : (Action<string, CollectionDetail, Action<GameObject?>>?)null);++ public readonly struct PlacedVehicle+ {+ public readonly string Model, Route; public readonly Vector2 At, Along; public readonly Transform Transform;+ public PlacedVehicle(string model, string route, Vector2 at, Vector2 along, Transform transform)+ { Model = model; Route = route; At = at; Along = along; Transform = transform; }+ }++ MapScene? map;+ TerrainData? terrain;+ Vector3 terrainOrigin;+ readonly Dictionary<string, List<Vector2>> lines = new Dictionary<string, List<Vector2>>(StringComparer.Ordinal);+ readonly Dictionary<string, GameObject?> prefabs = new Dictionary<string, GameObject?>(StringComparer.Ordinal);+ readonly HashSet<string> asked = new HashSet<string>(StringComparer.Ordinal);+ readonly Dictionary<int, bool> closeFor = new Dictionary<int, bool>();+ readonly List<Renderer> renderers = new List<Renderer>();+ DateTime date;+ string? drawnKey;+ bool lastClose;++ public readonly List<PlacedVehicle> Placed = new List<PlacedVehicle>();+ /// <summary>How many times the vehicles were laid out (a test reads it: a date change with nothing new costs nothing).</summary>+ public int Builds { get; private set; }++ public static RoadVehicles Create(Transform parent, MapScene map, IReadOnlyList<RoutePath> routes, DateTime date)+ {+ var go = new GameObject(Name); go.transform.SetParent(parent, false);+ var layer = go.AddComponent<RoadVehicles>();+ layer.map = map; layer.terrain = map.Terrain.terrainData; layer.terrainOrigin = map.Terrain.transform.position;+ foreach (var route in routes)+ if (Plans.Any(p => p.Route == route.Id)) layer.lines[route.Id] = RouteLayer.Drawn(map.Frame, route);+ layer.ShowAt(date);+ return layer;+ }++ /// <summary>Shows the vehicles as at <paramref name="at"/>. The game calls it on every state change, so it lays them+ /// out again only when what it would draw changes: the plans in force, the control period, or a model arriving.</summary>+ public void ShowAt(DateTime at)+ {+ date = at;+ var stream = Stream;+ if (stream != null)+ foreach (var plan in Plans)+ if (plan.Covers(at) && asked.Add(plan.Model)) { var id = plan.Model; stream(id, CollectionDetail.Near, p => OnModel(id, p)); }+ Rebuild();+ }++ void OnModel(string model, GameObject? prefab)+ {+ if (this == null) return; // the map was rebuilt before the model came; the new layer asks again+ prefabs[model] = prefab;+ if (prefab == null)+ Debug.LogWarning($"ROAD VEHICLES: {model} did not stream; its vehicles are not drawn, and the map plays on without them.");+ Rebuild();+ }++ /// <summary>What the layer would draw on the current date, as a key: the control period, the plans in force and the+ /// models that have arrived.</summary>+ string Key()+ {+ var control = map != null ? map.Control : null;+ var period = control?.PeriodOn(date)?.Id ?? "none";+ return period + "|" + string.Concat(Plans.Select(p => p.Covers(date) ? "1" : "0")) + "|"+ + string.Concat(Plans.Select(p => prefabs.TryGetValue(p.Model, out var g) && g != null ? "1" : "0"));+ }++ void Rebuild()+ {+ if (map == null || terrain == null) return;+ var key = Key();+ if (key == drawnKey) return;+ drawnKey = key; Builds++;+ for (int i = transform.childCount - 1; i >= 0; i--)+ {+ var old = transform.GetChild(i).gameObject;+ if (Application.isPlaying) { old.transform.SetParent(null); Destroy(old); } else DestroyImmediate(old);+ }+ renderers.Clear(); Placed.Clear();+ var control = map.Control;+ if (control == null) return; // no control layer: no claim about who held a road, so no vehicle+ // Every plan in force reserves its spots, drawn or not, so a model streaming in late never moves another's.+ var taken = new List<Vector2>();+ for (int planIndex = 0; planIndex < Plans.Count; planIndex++)+ {+ var plan = Plans[planIndex];+ if (!plan.Covers(date) || !lines.TryGetValue(plan.Route, out var line)) continue;+ prefabs.TryGetValue(plan.Model, out var prefab);+ for (int n = 0; n < plan.Count; n++)+ {+ var spot = Spot(line, planIndex, n, taken, control);+ if (spot == null) continue;+ var (at, along) = spot.Value;+ taken.Add(at);+ if (prefab != null) Place(plan, n, prefab, at, along);+ }+ }+ }++ /// <summary>One vehicle: the prefab (its root keeps the FBX's axis turn), its long side turned to +Z, sized to+ /// <see cref="VehicleLengthM"/> while still unturned (a box measured after the yaw would shrink it on a diagonal),+ /// then the road's yaw on top, centred on the spot with its base <see cref="RideM"/> over the ground.</summary>+ void Place(Plan plan, int n, GameObject prefab, Vector2 at, Vector2 along)+ {+ var go = Instantiate(prefab, transform, false); go.name = $"{plan.Model}_{n}";+ var own = prefab.transform.localRotation;+ go.transform.localRotation = own;+ var b = Bounds(go);+ if (b.size.x > b.size.z) { own = Quaternion.Euler(0f, 90f, 0f) * own; go.transform.localRotation = own; b = Bounds(go); }+ if (b.size.z > 1e-3f) go.transform.localScale *= VehicleLengthM / b.size.z;+ float yaw = Mathf.Atan2(along.x, along.y) * Mathf.Rad2Deg;+ go.transform.localRotation = Quaternion.Euler(0f, yaw, 0f) * own;+ float y = RouteLayer.Ground(terrain!, terrainOrigin, at) + RideM;+ go.transform.position = new Vector3(at.x, y, at.y);+ b = Bounds(go);+ go.transform.position += new Vector3(at.x - b.center.x, y - b.min.y, at.y - b.center.z);+ foreach (var r in go.GetComponentsInChildren<Renderer>(true))+ {+ r.shadowCastingMode = ShadowCastingMode.On; r.forceRenderingOff = !lastClose; renderers.Add(r);+ }+ Placed.Add(new PlacedVehicle(plan.Model, plan.Route, at, along, go.transform));+ }++ (Vector2 at, Vector2 along)? Spot(IReadOnlyList<Vector2> line, int planIndex, int ordinal, List<Vector2> taken, Control1948 control)+ {+ if (map == null || line.Count < 2) return null;+ var lengths = new float[line.Count];+ for (int i = 1; i < line.Count; i++) lengths[i] = lengths[i - 1] + (line[i] - line[i - 1]).magnitude;+ float total = lengths[lengths.Length - 1]; if (total < 1f) return null;+ uint state = (uint)(Seed ^ (planIndex * 73856093) ^ (ordinal * 19349663));+ for (int k = 0; k < CandidateCount; k++)+ {+ state = state * 1664525u + 1013904223u;+ float s = total * ((state & 0x00ffffffu) / 16777216f);+ int i = 1; while (i < lengths.Length - 1 && lengths[i] < s) i++;+ var delta = line[i] - line[i - 1]; float len = delta.magnitude;+ if (len < 1e-3f) continue;+ var at = Vector2.Lerp(line[i - 1], line[i], (s - lengths[i - 1]) / len);+ if (Free(at, taken) && Held(at, control)) return (at, delta / len);+ }+ return null;+ }++ /// <summary>Israel held the hex under <paramref name="at"/> on the date (the control layer's code; contested,+ /// no-man's land and no data count as not held).</summary>+ bool Held(Vector2 at, Control1948 control)+ {+ var (q, r) = MapPointer.Pick(map!, new Vector3(at.x, 0f, at.y));+ return control.At(q, r, date).side == Control1948.Side.Israel;+ }++ bool Free(Vector2 at, IEnumerable<Vector2> taken)+ {+ if (map == null) return false;+ foreach (var p in taken) if ((at - p).sqrMagnitude < PairSpacingM * PairSpacingM) return false;+ foreach (var f in map.KitFootprints)+ { float d = f.radius + AnchorClearanceM; if ((at - f.centre).sqrMagnitude < d * d) return false; }+ foreach (var c in map.UnitClearings)+ { float d = c.radius + AnchorClearanceM; if ((at - c.centre).sqrMagnitude < d * d) return false; }+ foreach (var t in map.UnitTokens)+ { float d = t.radius + AnchorClearanceM; if ((at - t.centre).sqrMagnitude < d * d) return false; }+ return true;+ }++ 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;+ }++ public static bool CloseAt(float distanceM, bool was) => was ? distanceM <= CloseExitM : distanceM <= CloseEnterM;+ void OnEnable() => RenderPipelineManager.beginCameraRendering += Choose;+ void OnDisable() => RenderPipelineManager.beginCameraRendering -= Choose;+ internal void Choose(ScriptableRenderContext context, Camera cam)+ {+ if (cam.cameraType == CameraType.Preview || cam.cameraType == CameraType.Reflection) return;+ int id = cam.GetInstanceID(); bool on = CloseAt(TownLandmarks.ViewDistance(cam), closeFor.TryGetValue(id, out var was) && was);+ closeFor[id] = on; lastClose = on;+ foreach (var r in renderers) if (r != null) r.forceRenderingOff = !on;+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs.meta b/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs.metanew file mode 100644index 000000000..8c4a8a76d--- /dev/null+++ b/unity/Assets/Scripts/Map/Routes/RoadVehicles.cs.meta@@ -0,0 +1,11 @@+fileFormatVersion: 2+guid: 43e2577dd9d54aa39dc8910725725725+MonoImporter:+ externalObjects: {}+ serializedVersion: 2+ defaultReferences: []+ executionOrder: 0+ icon: {instanceID: 0}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/Routes/RouteLayer.cs b/unity/Assets/Scripts/Map/Routes/RouteLayer.csindex 3d90991a3..0d2facc74 100644--- a/unity/Assets/Scripts/Map/Routes/RouteLayer.cs+++ b/unity/Assets/Scripts/Map/Routes/RouteLayer.cs@@ -76,6 +76,8 @@ namespace Statecraft.Game.Map.Routesif (map.Terrain == null) return;var service = map.Terrain.transform.Find($"{RootName}/{ServiceTrain.Name}");if (service != null) service.GetComponent<ServiceTrain>().ShowAt(date); // from the service date on (issue #668)+ var vehicles = map.Terrain.transform.Find($"{RootName}/{RoadVehicles.Name}");+ if (vehicles != null) vehicles.GetComponent<RoadVehicles>().ShowAt(date);var ribbons = map.Terrain.transform.Find($"{RootName}/{RibbonsName}");if (ribbons == null) return;foreach (var g in ribbons.GetComponentsInChildren<RouteGroup>(true)) g.gameObject.SetActive(g.Window.Covers(date));@@ -146,7 +148,7 @@ namespace Statecraft.Game.Map.Routes/// is refused with a warning and the ribbons derived at load, the same meshes, only slower (issue #321). Without it/// they are derived.</summary>public static GameObject Build(Terrain terrain, GeoFrame frame, IReadOnlyList<RoutePath> routes, TrainMode train, DateTime date,- RouteRibbonFile.Source? baked = null)+ RouteRibbonFile.Source? baked = null, MapScene? map = null){if (terrain == null) throw new ArgumentNullException(nameof(terrain));if (routes == null) throw new ArgumentNullException(nameof(routes));@@ -189,6 +191,8 @@ namespace Statecraft.Game.Map.Routes}assets.OnTeardown(VisualToggles.Register(RoutesToggle, on => { if (ribbons != null) ribbons.SetActive(on); }));+ if (map != null) RoadVehicles.Create(root.transform, map, routes, date);+var trainRoute = routes.FirstOrDefault(r => r.Id == TrainRoute);if (trainRoute != null && train == TrainMode.Service){diff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 592724d98..58fabc1cc 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -244,6 +244,7 @@ namespace Statecraft.Game.UIstring.IsNullOrWhiteSpace(inputs.Map.ArmisticeYaml) ? null : Armistice1949.ReadRuntimeOrYaml(inputs.Map.ArmisticeTsv, inputs.Map.ArmisticeYaml, Debug.LogWarning),string.IsNullOrWhiteSpace(inputs.Map.ControlYaml) ? null : Control1948.ReadRuntimeOrYaml(inputs.Map.ControlTsv, inputs.Map.ControlYaml, Debug.LogWarning));Regions = regions;+ map.Control = regions.Control; // the road vehicles stand only where Israel held the ground (#725)var layerLabel = root.Q<Label>("map-layer");Action onDate = () =>{diff --git a/unity/Assets/Tests/EditMode/RoadVehiclesTests.cs b/unity/Assets/Tests/EditMode/RoadVehiclesTests.csnew file mode 100644index 000000000..5f2ff8b11--- /dev/null+++ b/unity/Assets/Tests/EditMode/RoadVehiclesTests.cs@@ -0,0 +1,289 @@+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Boot;+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 #725: MATKOT's four road vehicles on their 1948 roads, streamed, close zoom only, on ground Israel held,+/// and sized against the steam locomotive (the owner on v0.1.1, 18 October 2026: MATKOT's models were "way bigger then the+/// train").</summary>+public class RoadVehiclesTests+{+ static readonly DateTime Start = new DateTime(1948, 5, 15), BurmaOpen = new DateTime(1948, 6, 14), TrainDate = new DateTime(1950, 3, 2);++ Action<string, CollectionDetail, Action<GameObject>> saved, savedTrain;+ readonly List<(string id, CollectionDetail detail, Action<GameObject> done)> asked =+ new List<(string, CollectionDetail, Action<GameObject>)>();+ readonly List<Action<GameObject>> trainAsked = new List<Action<GameObject>>();++ [SetUp]+ public void Seam()+ {+ saved = RoadVehicles.Request; savedTrain = ServiceTrain.Request;+ asked.Clear(); trainAsked.Clear();+ RoadVehicles.Request = (id, detail, done) => asked.Add((id, detail, done));+ ServiceTrain.Request = (id, detail, done) => trainAsked.Add(done);+ }++ [TearDown]+ public void Reset()+ {+ RoadVehicles.Request = saved; ServiceTrain.Request = savedTrain;+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ VisualToggles.Clear();+ }++ static List<RoutePath> Routes()+ {+ var inputs = GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap);+ var b = HeightmapLoader.Load(Paths.StreamingMap).meta;+ var warnings = new List<string>();+ var routes = RoutePaths.ReadRuntimeOrYaml(inputs.RoutesTsv, inputs.RoutesYaml, (b.lon0, b.lon1, b.lat0, b.lat1), warnings.Add);+ CollectionAssert.IsEmpty(warnings);+ return routes;+ }++ static Control1948 Control() => Control1948.Parse(File.ReadAllText(Path.Combine(Paths.Content, "map", Control1948.FileName)));++ static GameObject Prefab(string id) => AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(id, CollectionDetail.Near));++ /// <summary>A built map with the control layer (as GameRoot gives it), its routes rebuilt at <paramref name="date"/>.</summary>+ (MapScene map, RoadVehicles layer) Build(DateTime date, RouteLayer.TrainMode train = RouteLayer.TrainMode.None, bool control = true)+ {+ var map = RouteTests.BuildMap();+ if (control) map.Control = Control();+ Object.DestroyImmediate(RouteTests.RoutesRoot(map).gameObject);+ asked.Clear(); trainAsked.Clear(); // the map's own build asked too; that layer is gone+ RouteLayer.Build(map.Terrain, map.Frame, Routes(), train, date, map: map);+ return (map, RouteTests.RoutesRoot(map).Find(RoadVehicles.Name).GetComponent<RoadVehicles>());+ }++ void AnswerAll()+ {+ foreach (var q in asked.ToArray()) q.done(Prefab(q.id));+ }++ /// <summary>A shape's extent along <paramref name="axis"/> (world x-z) and its height: the corners of each mesh's own+ /// bounds through its transform.</summary>+ static (float along, float across, float height) Extent(Transform t, Vector2 axis)+ {+ axis = axis.normalized; var right = new Vector2(axis.y, -axis.x);+ float a0 = float.MaxValue, a1 = float.MinValue, c0 = float.MaxValue, c1 = float.MinValue, y0 = float.MaxValue, y1 = float.MinValue;+ foreach (var f in t.GetComponentsInChildren<MeshFilter>(true))+ {+ if (f.sharedMesh == null) continue;+ var b = f.sharedMesh.bounds;+ for (int c = 0; c < 8; c++)+ {+ var p = f.transform.TransformPoint(new Vector3((c & 1) == 0 ? b.min.x : b.max.x, (c & 2) == 0 ? b.min.y : b.max.y, (c & 4) == 0 ? b.min.z : b.max.z));+ var xz = new Vector2(p.x, p.z);+ float a = Vector2.Dot(xz, axis), r = Vector2.Dot(xz, right);+ a0 = Mathf.Min(a0, a); a1 = Mathf.Max(a1, a); c0 = Mathf.Min(c0, r); c1 = Mathf.Max(c1, r); y0 = Mathf.Min(y0, p.y); y1 = Mathf.Max(y1, p.y);+ }+ }+ return (a1 - a0, c1 - c0, y1 - y0);+ }++ [Test]+ public void EveryModelHasItsRouteAndDate()+ {+ CollectionAssert.AreEquivalent(new[] { RoadVehicles.IntercityBus, RoadVehicles.CitrusTruck, RoadVehicles.CanvasLorry, RoadVehicles.SandwichConvoy },+ RoadVehicles.Plans.Select(p => p.Model).Distinct(), "all four of MATKOT's road vehicles are placed");+ CollectionAssert.AreEqual(new[]+ {+ (RoadVehicles.SandwichConvoy, "burma_road", "1948-06-14", (string)null, 1),+ (RoadVehicles.CanvasLorry, "burma_road", "1948-06-14", (string)null, 1),+ (RoadVehicles.IntercityBus, "tel_aviv_haifa_road", "1948-05-15", (string)null, 2),+ (RoadVehicles.CitrusTruck, "tel_aviv_haifa_road", "1948-05-15", (string)null, 2),+ }, RoadVehicles.Plans.Select(p => (p.Model, p.Route, p.From.ToString("yyyy-MM-dd"), p.To?.ToString("yyyy-MM-dd"), p.Count)));+ var routes = Routes().ToDictionary(r => r.Id);+ // The Burma Road's date is its route record's (content, sourced): the convoy runs only while the road is drawn.+ Assert.AreEqual(RoutePaths.Bound(routes["burma_road"].From), BurmaOpen);+ Assert.IsFalse(RoadVehicles.Plans.Any(p => p.Route == "jaffa_jerusalem_road"), "no convoy date on the Latrun road is sourced in the game window");+ }++ [Test]+ public void ModelsStreamFromTheirDateAndOneThatFailsDropsOnlyItsOwn()+ {+ var (map, layer) = Build(Start);+ try+ {+ CollectionAssert.AreEquivalent(new[] { RoadVehicles.IntercityBus, RoadVehicles.CitrusTruck }, asked.Select(q => q.id),+ "15 May 1948: only the Tel Aviv–Haifa road's models are asked for");+ Assert.IsTrue(asked.All(q => q.detail == CollectionDetail.Near), "close zoom: the near models");+ Assert.IsNull(saved, "the default: the game's stream in Play mode (CollectionStream.Request), none in edit mode");+ CollectionAssert.IsEmpty(layer.Placed, "nothing drawn until the stream answers (a later frame)");+ AnswerAll();+ Assert.AreEqual(4, layer.Placed.Count, "two buses and two citrus trucks");++ RouteLayer.ShowAt(map, BurmaOpen.AddDays(-1));+ Assert.AreEqual(2, asked.Count, "13 June: the convoy models are not asked for yet");+ RouteLayer.ShowAt(map, BurmaOpen);+ Assert.AreEqual(4, asked.Count, "14 June: the Burma Road's two models");+ var failed = asked.Single(q => q.id == RoadVehicles.SandwichConvoy);+ LogAssert.Expect(LogType.Warning, $"ROAD VEHICLES: {RoadVehicles.SandwichConvoy} did not stream; its vehicles are not drawn, and the map plays on without them.");+ failed.done(null);+ asked.Single(q => q.id == RoadVehicles.CanvasLorry).done(Prefab(RoadVehicles.CanvasLorry));+ Assert.AreEqual(5, layer.Placed.Count, "the failed convoy truck removes only itself");+ Assert.IsTrue(layer.Placed.All(p => p.Model != RoadVehicles.SandwichConvoy));++ int builds = layer.Builds;+ RouteLayer.ShowAt(map, BurmaOpen.AddDays(1));+ RouteLayer.ShowAt(map, BurmaOpen.AddDays(2));+ Assert.AreEqual(builds, layer.Builds, "a state change with nothing new lays nothing out again");+ RouteLayer.ShowAt(map, Start);+ Assert.AreEqual(4, layer.Placed.Count, "an earlier date (a loaded save): no convoy");+ Assert.AreEqual(4, asked.Count, "date changes never ask again");+ LogAssert.NoUnexpectedReceived();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The issue's history rule: no vehicle on a road the other side held at that date. Every vehicle stands on a+ /// hex the control layer gives to Israel on the date; with no control layer, none.</summary>+ [Test]+ public void EveryVehicleStandsWhereIsraelHeldTheGround()+ {+ var control = Control();+ var (map, layer) = Build(BurmaOpen);+ try+ {+ AnswerAll();+ foreach (var date in new[] { Start, BurmaOpen, new DateTime(1948, 7, 20), new DateTime(1948, 11, 1), TrainDate })+ {+ RouteLayer.ShowAt(map, date); AnswerAll();+ Assert.Greater(layer.Placed.Count, 0, $"{date:yyyy-MM-dd}: some vehicles");+ foreach (var p in layer.Placed)+ {+ var (q, r) = MapPointer.Pick(map, new Vector3(p.At.x, 0f, p.At.y));+ Assert.AreEqual(Control1948.Side.Israel, control.At(q, r, date).side, $"{date:yyyy-MM-dd} {p.Model} on {p.Route} at hex {q},{r}");+ }+ }+ // A control layer that gives Israel no hex: no vehicle anywhere.+ map.Control = Control1948.Parse("layer: x\nshown_from: 1948-05-15\nperiods:\n - { id: none_held, from: 1948-05-15, until: null, legend: held, line_date: '1948-07-09', fronts: [] }\nhexes: []\n");+ RouteLayer.ShowAt(map, TrainDate);+ CollectionAssert.IsEmpty(layer.Placed, "no hex held: no vehicle");+ }+ finally { Object.DestroyImmediate(map.gameObject); }++ asked.Clear();+ (map, layer) = Build(BurmaOpen, control: false);+ try+ {+ AnswerAll();+ CollectionAssert.IsEmpty(layer.Placed, "no control layer: no claim about who held a road, so no vehicle");+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ [Test]+ public void SeededSpotsRepeatFaceTheRoadStandUprightAndKeepClear()+ {+ List<RoadVehicles.PlacedVehicle> first;+ var (map, layer) = Build(BurmaOpen);+ try+ {+ AnswerAll();+ first = layer.Placed.ToList();+ Assert.AreEqual(6, first.Count, "two of each on the Tel Aviv–Haifa road, one of each on the Burma Road");+ foreach (var p in first)+ {+ var (along, across, _) = Extent(p.Transform, p.Along);+ Assert.Greater(along, 1.5f * across, $"{p.Model}: its long side runs along the road");+ // Upright: the prefab's own root rotation (the FBX's axis turn) is kept under the yaw, so its up stays up.+ var own = Prefab(p.Model).transform.localRotation;+ Assert.Less(Vector3.Angle(p.Transform.rotation * Quaternion.Inverse(own) * Vector3.up, Vector3.up), 0.01f, $"{p.Model} is upright");+ var bounds = p.Transform.GetComponentsInChildren<Renderer>().Select(r => r.bounds).Aggregate((a, b) => { a.Encapsulate(b); return a; });+ float ground = RouteLayer.Ground(map.Terrain.terrainData, map.Terrain.transform.position, p.At) + RoadVehicles.RideM;+ Assert.AreEqual(ground, bounds.min.y, 1f, $"{p.Model} stands on the road");+ foreach (var f in map.KitFootprints)+ Assert.GreaterOrEqual((p.At - f.centre).magnitude, f.radius + RoadVehicles.AnchorClearanceM, $"{p.Model} clear of {f.id} (its town and label)");+ foreach (var t in map.UnitTokens)+ Assert.GreaterOrEqual((p.At - t.centre).magnitude, t.radius + RoadVehicles.AnchorClearanceM, $"{p.Model} clear of a unit token");+ foreach (var c in map.UnitClearings)+ Assert.GreaterOrEqual((p.At - c.centre).magnitude, c.radius + RoadVehicles.AnchorClearanceM, $"{p.Model} clear of a unit's clearing");+ }+ for (int i = 0; i < first.Count; i++)+ for (int j = i + 1; j < first.Count; j++)+ Assert.GreaterOrEqual((first[i].At - first[j].At).magnitude, RoadVehicles.PairSpacingM, "vehicles apart");+ }+ finally { Object.DestroyImmediate(map.gameObject); }++ asked.Clear();+ (map, layer) = Build(BurmaOpen);+ try+ {+ // The other order: a model streaming in late never moves another's vehicles.+ foreach (var q in asked.ToArray().Reverse()) q.done(Prefab(q.id));+ CollectionAssert.AreEqual(first.Select(p => (p.Model, p.Route, p.At)).ToList(),+ layer.Placed.Select(p => (p.Model, p.Route, p.At)).ToList(), "same seed, same spots, bit for bit");+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The owner on v0.1.1 (18 October 2026): MATKOT's models were "way bigger then the train". A bus or a lorry+ /// reads smaller than the steam locomotive the map runs: each vehicle's length is 0.3 to 0.8 of the locomotive's car as+ /// drawn (ServiceTrain, measured on the map, not from the constant), and it stands lower than the locomotive. The unit+ /// figures (#992) are Civ-sized pieces far larger still; the vehicles are scenery and stay under a figure's height.</summary>+ [Test]+ public void EveryVehicleReadsSmallerThanTheLocomotive()+ {+ var (map, layer) = Build(TrainDate, RouteLayer.TrainMode.Service);+ try+ {+ Assert.AreEqual(1, trainAsked.Count, "the service train asks for its locomotive on its date");+ LogAssert.Expect(LogType.Log, new System.Text.RegularExpressions.Regex("^TRAIN: the steam train runs"));+ trainAsked[0](AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(ServiceTrain.ModelId, CollectionDetail.Far)));+ var service = RouteTests.RoutesRoot(map).Find(ServiceTrain.Name).GetComponent<ServiceTrain>();+ var loco = service.Train.Cars[0];+ Assert.AreEqual("Locomotive", loco.name);+ var (locoLong, _, locoHigh) = Extent(loco, new Vector2(loco.forward.x, loco.forward.z));+ Assert.AreEqual(RoadVehicles.LocomotiveCarM, locoLong, 0.05f * locoLong, "the locomotive's car as drawn");++ AnswerAll();+ Assert.AreEqual(6, layer.Placed.Count);+ float figure = UnitBadge.FigureHeightM * UnitShowcase.FigureScale;+ foreach (var p in layer.Placed)+ {+ var (len, _, high) = Extent(p.Transform, p.Along);+ float share = len / locoLong;+ TestContext.WriteLine($"{p.Model}: {len:0} m long, {high:0} m high; locomotive {locoLong:0} m long, {locoHigh:0} m high; share {share:0.00}");+ Assert.That(share, Is.InRange(0.3f, 0.8f), $"{p.Model}: {len:0} m against the locomotive's {locoLong:0} m");+ Assert.Less(high, locoHigh, $"{p.Model} stands lower than the locomotive");+ Assert.Less(high, figure, $"{p.Model} stands lower than a unit figure");+ }+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ [Test]+ public void VehiclesDrawOnlyAtCloseZoomAndAssetsStayOutOfResources()+ {+ Assert.IsTrue(RoadVehicles.CloseAt(RoadVehicles.CloseEnterM, false));+ Assert.IsTrue(RoadVehicles.CloseAt(RoadVehicles.CloseExitM, true));+ Assert.IsFalse(RoadVehicles.CloseAt(RoadVehicles.CloseEnterM + 1f, false));+ Assert.IsFalse(RoadVehicles.CloseAt(RoadVehicles.CloseExitM + 1f, true));+ Assert.Greater(RoadVehicles.CloseExitM / RoadVehicles.CloseEnterM, 1f / (1f - CameraController.ZoomPerStep), "the band is wider than one zoom step");++ foreach (var id in RoadVehicles.Plans.Select(p => p.Model).Distinct())+ {+ Assert.AreEqual(CollectionCatalog.Vehicles, CollectionCatalog.BundleOf(id));+ var path = CollectionCatalog.PrefabPath(id, CollectionDetail.Near);+ Assert.IsNotNull(AssetDatabase.LoadAssetAtPath<GameObject>(path), path);+ StringAssert.DoesNotContain("/Resources/", path);+ foreach (var dep in AssetDatabase.GetDependencies(path, true)) StringAssert.DoesNotContain("/Resources/", dep);+ Assert.IsNull(Resources.Load<GameObject>(id));+ }+ }+}diff --git a/unity/Assets/Tests/EditMode/RoadVehiclesTests.cs.meta b/unity/Assets/Tests/EditMode/RoadVehiclesTests.cs.metanew file mode 100644index 000000000..8a2028c0f--- /dev/null+++ b/unity/Assets/Tests/EditMode/RoadVehiclesTests.cs.meta@@ -0,0 +1,11 @@+fileFormatVersion: 2+guid: 51514a9b3a2c43ff96dd8fb989725725+MonoImporter:+ externalObjects: {}+ serializedVersion: 2+ defaultReferences: []+ executionOrder: 0+ icon: {instanceID: 0}+ userData:+ assetBundleName:+ assetBundleVariant: