A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(unity): MATKOT's building models at one world scale, set by the steam train (refs #659 #700) (#1030)
Eyal Golan57a707c6f6cf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 87d7264f1..d08048390 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -65,6 +65,13 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBand stream after the first frame (#725).### Fixed+- MATKOT's building models up close (#700) stand at one world scale, set by the steam train the map runs: a typical+ 8.5 m house is as long as the locomotive's car (about 204 m), so every model is 24x its building's real size+ (`SettlementKits.ModelScale`), keeps its own proportions and no longer fills the kit's plot; a plot holds a small+ grid of them instead (up to four a side), so the towns stay dense. In v0.1.1 they filled the+ kits' symbolic 60x and 100x plots, so a house was about 800 m, a Tel Aviv block up to 1.6 km, both bigger than the+ 816 m train, and Jaffa's 100x houses rose to about 490 m in front of Tel Aviv's blocks (owner, 18 October 2026). The+ kits far off keep their scale.- The sim tests no longer leave a temp folder behind for every `Fixture.Write` call (about 1,150 per run): thefolders share one root per run, deleted when the run ends (#1017).- Event city effects preserve the city's housing condition when changing its housing capacity or job slots (#1000).diff --git a/unity/Assets/Scripts/Map/Kits/SettlementKits.Models.cs b/unity/Assets/Scripts/Map/Kits/SettlementKits.Models.csindex 0253b596a..5264f05ac 100644--- a/unity/Assets/Scripts/Map/Kits/SettlementKits.Models.cs+++ b/unity/Assets/Scripts/Map/Kits/SettlementKits.Models.cs@@ -1,11 +1,13 @@#nullable enableusing System.Collections.Generic;+using Statecraft.Game.Map.Routes;using UnityEngine;namespace Statecraft.Game.Map.Kits{/// <summary>Issue #659, owner ruling on #700: "Models up close only". Every building the kit places also gets one of- /// MATKOT's building models (<see cref="TownModel"/>), fitted to the same plot (<see cref="Fit"/>),+ /// MATKOT's building models (<see cref="TownModel"/>), stood on the same plot at one world scale (<see cref="Fit"/>,+ /// <see cref="ModelScale"/>),/// standing on the plot's ground level with a stone plinth below it where the ground falls away. Far off the kit's/// own buildings draw, exactly as before; up close (TownModelLayer.CloseEnterM) the models draw instead, with each/// town's close mesh (KitMesh.ToCloseMesh: its landmarks and palms without the kit buildings, plus the plinths). The@@ -13,14 +15,19 @@ namespace Statecraft.Game.Map.Kitspublic static partial class SettlementKits{/// <summary>One placed model: its town (or locality) id, the model, its world matrix (the model's mesh space to the- /// world), and the fitted box it fills: centre, yaw (degrees, the kit's), width along the yaw and depth (m), the ground- /// level it stands on and its height (m).</summary>+ /// world), and the box it fills: centre, yaw (degrees, the kit's), width along the yaw and depth (m), the ground+ /// level it stands on and its height (m); and the centre of the kit plot it stands on (<see cref="Plot"/>: a plot+ /// holds several models at the world scale, <see cref="PlaceModel"/>).</summary>public readonly struct ModelInstance{public readonly string Id; public readonly TownModel Model; public readonly Matrix4x4 M;- public readonly Vector2 C; public readonly float Yaw, W, D, Ground, H;+ public readonly Vector2 C, Plot; public readonly float Yaw, W, D, Ground, H;public ModelInstance(string id, TownModel model, Matrix4x4 m, Vector2 c, float yaw, float w, float d, float ground, float h)- { Id = id; Model = model; M = m; C = c; Yaw = yaw; W = w; D = d; Ground = ground; H = h; }+ : this(id, model, m, c, yaw, w, d, ground, h, c) { }+ public ModelInstance(string id, TownModel model, Matrix4x4 m, Vector2 c, float yaw, float w, float d, float ground, float h, Vector2 plot)+ { Id = id; Model = model; M = m; C = c; Yaw = yaw; W = w; D = d; Ground = ground; H = h; Plot = plot; }+ /// <summary>This instance on the kit plot centred at <paramref name="plot"/>.</summary>+ public ModelInstance OnPlot(Vector2 plot) => new ModelInstance(Id, Model, M, C, Yaw, W, D, Ground, H, plot);/// <summary>The fitted box's eight corners (world space): the map labels keep clear of them (issue #214).</summary>public void Corners(List<Vector3> into)@@ -38,6 +45,19 @@ namespace Statecraft.Game.Map.Kits[System.ThreadStatic] static Dictionary<string, Settlement>? places;[System.ThreadStatic] static HashSet<string>? onceGiven;+ /// <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+ /// (SettlementKits.Pick).</summary>+ public const float ReferenceHouseM = 8.5f;++ /// <summary>The one world scale of MATKOT's building models (the owner on v0.1.1, 18 October 2026: the buildings were+ /// "way bigger then the train" and Jaffa's stood over Tel Aviv's): 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 a building's real+ /// size, for every model. Before, each model filled its kit plot, at the kits' own symbolic 60x (city blocks) and 100x+ /// (houses): a Tel Aviv block up to 1.6 km and a house 800 m, and Jaffa's 100x houses beside Tel Aviv's 60x blocks.+ /// The kits far off keep their own scale.</summary>+ public const float ModelScale = RouteTrain.ModelRealLengthM * RouteTrain.Scale * ServiceTrain.ModelSize / ServiceTrain.Cars / ReferenceHouseM;+/// <summary>How far a house's model may be stretched or squashed upright from its own proportions to meet the kit's/// height (a one-room village house of two storeys would otherwise stand twice as tall as its model). The city blocks/// (Tel Aviv's four to eight storeys, #652; Jerusalem's, Haifa's and the moshava centres') take the kit's height exactly.</summary>@@ -47,44 +67,83 @@ namespace Statecraft.Game.Map.Kits/// included) across its footprint.</summary>const float PlinthRiseM = 2.5f;- /// <summary>Fits <paramref name="model"/> to a plot: its longer side along the plot's longer side (turned a half turn- /// when <paramref name="flip"/>), scaled to fill <paramref name="w"/> x <paramref name="d"/>, standing on- /// <paramref name="ground"/>, <paramref name="h"/> tall (<paramref name="exactHeight"/>), or as near- /// <paramref name="h"/> as <see cref="MinStretch"/>..<see cref="MaxStretch"/> of the model's own proportions allow.</summary>- public static ModelInstance Fit(string id, TownModel model, Vector2 p, float yaw, float w, float d, float h, float ground, bool exactHeight, bool flip)+ /// <summary>Stands <paramref name="model"/> on a plot at the world scale: the plot's building is <paramref name="w"/> x+ /// <paramref name="d"/> x <paramref name="h"/> at the kit's scale <paramref name="kitScale"/> (its real size times+ /// that), so its real size times <see cref="ModelScale"/> is what the model stands for. The model keeps its own+ /// proportions on the ground (one scale on both axes, its longer side along the plot's longer side, as long as the+ /// building's longer side at the world scale; turned a half turn when <paramref name="flip"/>), centred on the plot,+ /// on <paramref name="ground"/>, as tall as the building at the world scale (<paramref name="exactHeight"/>: the city+ /// blocks' storeys), or as near that as <see cref="MinStretch"/>..<see cref="MaxStretch"/> of its own proportions+ /// allow. The plot keeps the space around it.</summary>+ public static ModelInstance Fit(string id, TownModel model, Vector2 p, float yaw, float w, float d, float h, float ground, bool exactHeight, bool flip,+ float kitScale){var size = TownModels.Size[(int)model];- float mw = w, md = d, my = yaw + (flip ? 180f : 0f);- if ((size.x >= size.y) != (w >= d)) { mw = d; md = w; my += 90f; }- float kx = mw / size.x, ky = md / size.y, H = h;- if (!exactHeight)- {- float natural = size.z * Mathf.Sqrt(kx * ky);- H = Mathf.Clamp(h, MinStretch * natural, MaxStretch * natural);- }+ float toWorld = ModelScale / kitScale, bh = h * toWorld, my = yaw + (flip ? 180f : 0f);+ bool turn = (size.x >= size.y) != (w >= d);+ if (turn) my += 90f;+ float k = Mathf.Max(w, d) * toWorld / Mathf.Max(size.x, size.y);+ float natural = size.z * k;+ float H = exactHeight ? bh : Mathf.Clamp(bh, MinStretch * natural, MaxStretch * natural);// Tripo's meshes are Z-up: a quarter turn about x stands them up (mesh z to world y, mesh y to world -z), then the// kit's yaw (counter-clockwise in x-z, so a negative turn about Unity's y).- var m = Matrix4x4.TRS(new Vector3(p.x, ground, p.y), Quaternion.Euler(0f, -my, 0f), new Vector3(kx, H / size.z, ky))+ var m = Matrix4x4.TRS(new Vector3(p.x, ground, p.y), Quaternion.Euler(0f, -my, 0f), new Vector3(k, H / size.z, k))* Matrix4x4.Rotate(Quaternion.Euler(-90f, 0f, 0f));- return new ModelInstance(id, model, m, p, yaw, w, d, ground, H);+ return new ModelInstance(id, model, m, p, yaw, (turn ? size.y : size.x) * k, (turn ? size.x : size.y) * k, ground, H);}/// <summary>Places one of <paramref name="from"/> on a plot (TownModels.Pick; a place's first house is its/// <see cref="TownModels.Once"/> building), with its plinth on <paramref name="km"/> where the ground falls away.</summary>+ /// <summary>The gap between the models a plot holds, as a share of a model's narrower side.</summary>+ public const float PlotGapShare = 0.25f;+ /// <summary>The most models a plot holds along either of its sides.</summary>+ public const int MaxPerSide = 4;++ /// <summary>Fills a house's or block's plot with models at the world scale (<see cref="ModelScale"/>): the plot is the+ /// kit's building at the kit's symbolic scale, several times the building at the world scale, so it holds a grid of+ /// them (as many as fit along each side with <see cref="PlotGapShare"/> between them, at most+ /// <see cref="MaxPerSide"/> a side), each one of <paramref name="from"/> (TownModels.Pick at its own spot), turned+ /// with the plot and centred on it, on the plot's ground level. A place's first house is its+ /// <see cref="TownModels.Once"/> building, alone on its plot. One plinth stands under the group where the ground falls+ /// away.</summary>static void PlaceModel(string id, TownModel[] from, Vector2 p, float yaw, float w, float d, float h, float bottom, float top, KitMesh km,float m, bool exactHeight){- var model = TownModels.Pick(from, id, p, out bool flip);- if (places != null && places.TryGetValue(id, out var s) && TownModels.Once(s) is TownModel once && onceGiven!.Add(id)) model = once;- AddModel(id, model, p, yaw, w, d, h, bottom, top, km, m, exactHeight, flip);+ if (models == null) throw new System.InvalidOperationException("a town model was placed outside SettlementKits.Build");+ var first = TownModels.Pick(from, id, p, out bool flip);+ bool once = places != null && places.TryGetValue(id, out var s) && TownModels.Once(s) is TownModel o && onceGiven!.Add(id) && (first = o) == o;+ // The grid's cell holds the widest and deepest of the models the plot may take, so none reaches past its cell.+ float cw = 0f, cd = 0f;+ foreach (var cand in once ? new[] { first } : from)+ foreach (bool f in new[] { false, true })+ {+ var probe = Fit(id, cand, p, yaw, w, d, h, top, exactHeight, f, m);+ cw = Mathf.Max(cw, probe.W); cd = Mathf.Max(cd, probe.D);+ }+ float gap = PlotGapShare * Mathf.Min(cw, cd), pu = cw + gap, pv = cd + gap;+ int nu = once ? 1 : Mathf.Clamp(Mathf.FloorToInt((w + gap) / pu), 1, MaxPerSide);+ int nv = once ? 1 : Mathf.Clamp(Mathf.FloorToInt((d + gap) / pv), 1, MaxPerSide);+ float a = yaw * Mathf.Deg2Rad, ca = Mathf.Cos(a), sa = Mathf.Sin(a);+ for (int i = 0; i < nu; i++)+ for (int j = 0; j < nv; j++)+ {+ float u = (i - 0.5f * (nu - 1)) * pu, v = (j - 0.5f * (nv - 1)) * pv;+ var q = p + new Vector2(u * ca - v * sa, u * sa + v * ca);+ var model = i == 0 && j == 0 ? first : TownModels.Pick(from, id, q, out flip);+ models.Add(Fit(id, model, q, yaw, w, d, h, top, exactHeight, flip, m).OnPlot(p));+ }+ if (top - bottom > PlinthRiseM * m)+ km.Plinths.Box(p.x, p.y, yaw, nu * pu - gap, nv * pv - gap, bottom, top, 0f, TerraceStone, TerraceStone, Facade.Plain, m, roofed: true);}static void AddModel(string id, TownModel model, Vector2 p, float yaw, float w, float d, float h, float bottom, float top, KitMesh km,float m, bool exactHeight, bool flip){if (models == null) throw new System.InvalidOperationException("a town model was placed outside SettlementKits.Build");- models.Add(Fit(id, model, p, yaw, w, d, h, top, exactHeight, flip));- if (top - bottom > PlinthRiseM * m) km.Plinths.Box(p.x, p.y, yaw, w, d, bottom, top, 0f, TerraceStone, TerraceStone, Facade.Plain, m, roofed: true);+ var mi = Fit(id, model, p, yaw, w, d, h, top, exactHeight, flip, m);+ models.Add(mi);+ // The plinth under the model itself, not the whole plot.+ if (top - bottom > PlinthRiseM * m) km.Plinths.Box(p.x, p.y, yaw, mi.W, mi.D, bottom, top, 0f, TerraceStone, TerraceStone, Facade.Plain, m, roofed: true);}/// <summary>A town plot's models by its style and its place (issue #659's table).</summary>diff --git a/unity/Assets/Tests/EditMode/TownModelScaleTests.cs b/unity/Assets/Tests/EditMode/TownModelScaleTests.csnew file mode 100644index 000000000..e89689587--- /dev/null+++ b/unity/Assets/Tests/EditMode/TownModelScaleTests.cs@@ -0,0 +1,175 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game.Map;+using Statecraft.Game.Map.Kits;+using Statecraft.Game.Map.Routes;+using UnityEditor.SceneManagement;+using UnityEngine;+using M = Statecraft.Game.Map.Kits.TownModel;++/// <summary>The owner on v0.1.1 (18 October 2026): "the sizes in 0.1.1 dont make any sense - [MATKOT's] buildings are way+/// bigger then the train. this also makes jaffa's buildings be over tel avivs buildings". MATKOT's building models (#700)+/// stand at one world scale, measured against the steam train the map runs (ServiceTrain): a house about one locomotive+/// long, a city block no longer and no taller than the whole train, and no settlement's models over another's.</summary>+public class TownModelScaleTests+{+ [TearDown]+ public void Restore()+ {+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ KitScale.Reset();+ }++ /// <summary>The service train's length on the map (m): MATKOT's locomotive and tender at RouteTrain.Scale times+ /// ServiceTrain.ModelSize, about 816 m, in ServiceTrain.Cars cars of about 204 m: the locomotive's own car.</summary>+ static float TrainM => RouteTrain.ModelRealLengthM * RouteTrain.Scale * ServiceTrain.ModelSize;+ static float LocoM => TrainM / ServiceTrain.Cars;++ /// <summary>The large buildings: the city blocks (Tel Aviv, Jerusalem, Haifa), the barn, the dining hall, the winery and+ /// the port's cargo shed. Every other model is a house (or the water tower).</summary>+ static readonly HashSet<M> Large = new HashSet<M>+ {+ M.B01WhiteCity, M.B02aCornerBlock, M.B02bNarrowBlock, M.B03aArches, M.B03bExternalStair, M.B03cPlain,+ M.B04aStoneBalconies, M.B04bLoadingDoors, M.B07DiningHall, M.B23Winery, M.B24Barn, M.B32CargoShed,+ };++ static List<SettlementKits.ModelInstance> Models(out MapScene map)+ {+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);+ map = UnityEngine.Object.FindFirstObjectByType<MapScene>(); map.Build();+ var g = new KitGround(map.Terrain, map.Frame, map.Hexes, map.ElevMinM);+ foreach (var c in map.RouteCorridors) g.AddCorridor(c.line, c.halfWidth);+ foreach (var c in map.UnitClearings) g.AddCorridor(new List<Vector2> { c.centre, c.centre + Vector2.right }, c.radius);+ var built = SettlementKits.Build(map.Settlements, map.Localities.Select(p => p.Settlement).ToList(), new List<Localities.Area>(), g, out _);+ foreach (var k in built.Towns) UnityEngine.Object.DestroyImmediate(k.mesh);+ foreach (var t in built.Tiles) UnityEngine.Object.DestroyImmediate(t.mesh);+ foreach (var c in built.Close.Values) UnityEngine.Object.DestroyImmediate(c);+ return built.Models;+ }++ /// <summary>A placed model's four ground corners (world x/z) and its height (m): its mesh-space box through its matrix.</summary>+ static (Vector2[] quad, float height) Box(SettlementKits.ModelInstance mi)+ {+ var s = TownModels.Size[(int)mi.Model];+ var quad = new Vector2[4];+ float lo = float.MaxValue, hi = float.MinValue;+ for (int i = 0; i < 8; i++)+ {+ var c = mi.M.MultiplyPoint3x4(new Vector3(((i & 1) - 0.5f) * s.x, (((i >> 1) & 1) - 0.5f) * s.y, ((i >> 2) & 1) * s.z));+ if (i < 4) quad[i == 2 ? 3 : i == 3 ? 2 : i] = new Vector2(c.x, c.z); // 0,1,3,2: around the base+ lo = Mathf.Min(lo, c.y); hi = Mathf.Max(hi, c.y);+ }+ return (quad, hi - lo);+ }++ static float LongSide(Vector2[] q) => Mathf.Max((q[1] - q[0]).magnitude, (q[2] - q[1]).magnitude);++ /// <summary>Two convex quads overlap (separating axis test), by more than <paramref name="slackM"/>.</summary>+ static bool Overlap(Vector2[] a, Vector2[] b, float slackM)+ {+ foreach (var poly in new[] { a, b })+ for (int i = 0; i < 4; i++)+ {+ var e = poly[(i + 1) % 4] - poly[i];+ var n = new Vector2(-e.y, e.x).normalized;+ float amin = a.Min(p => Vector2.Dot(n, p)), amax = a.Max(p => Vector2.Dot(n, p));+ float bmin = b.Min(p => Vector2.Dot(n, p)), bmax = b.Max(p => Vector2.Dot(n, p));+ if (amax - slackM <= bmin || bmax - slackM <= amin) return false;+ }+ return true;+ }++ /// <summary>One world scale, against the locomotive: every house model's long side is between 0.2 and 1.5 of the+ /// locomotive's car (about 41 to 306 m: no house longer than one and a half locomotives; the floor is half the smallest+ /// house the kits lay, Jerusalem's Old City cells of about 2.1 m real, 51 m at the world scale, so a scale that collapsed+ /// by half or more fails),+ /// and every large building's long side and every model's height are within the whole train's length (about 816 m).+ /// On v0.1.1 the models filled the kits' plots at the kits' symbolic 60x (blocks) and 100x (houses): a house of 8 m+ /// was 800 m long and a Tel Aviv block up to 1.6 km.</summary>+ [Test]+ public void EveryBuildingModelIsSizedAgainstTheLocomotive()+ {+ var models = Models(out _);+ Assert.Greater(models.Count, 1000);+ float loco = LocoM, train = TrainM;+ Assert.AreEqual(204f, loco, 1f, "the locomotive's car"); Assert.AreEqual(816f, train, 1f, "the service train");+ var bad = new List<string>();+ var houses = new List<float>(); var large = new List<float>(); var heights = new List<float>();+ foreach (var mi in models)+ {+ var (q, h) = Box(mi);+ float side = LongSide(q);+ heights.Add(h);+ if (Large.Contains(mi.Model))+ {+ large.Add(side);+ if (side > train) bad.Add($"{mi.Id} {mi.Model}: {side:0} m long, longer than the train");+ }+ else+ {+ houses.Add(side);+ if (side > 1.5f * loco || side < 0.2f * loco) bad.Add($"{mi.Id} {mi.Model}: {side:0} m long, {side / loco:0.00} locomotives");+ }+ if (h > train) bad.Add($"{mi.Id} {mi.Model}: {h:0} m tall, taller than the train is long");+ }+ float Median(List<float> l) { var s = l.OrderBy(x => x).ToList(); return s[s.Count / 2]; }+ TestContext.WriteLine($"locomotive {loco:0} m, train {train:0} m; houses: median {Median(houses):0} m ({houses.Min():0}-{houses.Max():0}); " ++ $"large: median {Median(large):0} m ({large.Min():0}-{large.Max():0}); heights: median {Median(heights):0} m (max {heights.Max():0})");+ CollectionAssert.IsEmpty(bad.Take(15), $"{bad.Count} of {models.Count} models off the locomotive's scale");+ }++ /// <summary>"jaffa's buildings be over tel avivs buildings": Jaffa (an Arab town in May 1948) keeps its stone houses+ /// (b17) and Tel Aviv its White City blocks, at one scale: Jaffa's tallest house stands lower than the locomotive's car is+ /// long and lower than Tel Aviv's typical block. On v0.1.1 Jaffa's 100x houses rose up to about 490 m, in front of Tel+ /// Aviv's blocks from the camera's side (it looks north), so they covered them.</summary>+ [Test]+ public void JaffasHousesStandLowerThanTelAvivsBlocks()+ {+ var models = Models(out _);+ bool Port(SettlementKits.ModelInstance m) => m.Model == M.B32CargoShed || m.Model == M.B28WaterTower; // a port's sheds, a water tower+ var jaffa = models.Where(m => m.Id == "jaffa" && !Port(m)).ToList(); var tel = models.Where(m => m.Id == "tel_aviv" && !Port(m)).ToList();+ Assert.Greater(jaffa.Count, 10); Assert.Greater(tel.Count, 20);+ Assert.IsTrue(jaffa.All(m => m.Model == M.B17CourtyardHouse), "Jaffa's stone houses");+ Assert.IsTrue(tel.All(m => m.Model == M.B01WhiteCity || m.Model == M.B02aCornerBlock || m.Model == M.B02bNarrowBlock), "the White City");+ var th = tel.Select(m => Box(m).height).OrderBy(x => x).ToList();+ float jaffaMax = jaffa.Max(m => Box(m).height), telMedian = th[th.Count / 2];+ TestContext.WriteLine($"Jaffa's tallest house {jaffaMax:0} m, Tel Aviv's median block {telMedian:0} m");+ Assert.Less(jaffaMax, LocoM, "Jaffa's tallest house is lower than the locomotive is long");+ Assert.Less(jaffaMax, telMedian, "Jaffa's tallest house is lower than Tel Aviv's median block");+ }++ /// <summary>No settlement's building models stand over another's: no two models of different towns or localities overlap+ /// on the ground (their footprints, by the separating axis test, by more than 1 m).</summary>+ [Test]+ public void NoTwoSettlementsBuildingModelsOverlap()+ {+ var models = Models(out _);+ var boxes = models.Select(m => (m.Id, m.Model, quad: Box(m).quad)).ToList();+ const float cell = 2000f;+ var grid = new Dictionary<(int, int), List<int>>();+ for (int i = 0; i < boxes.Count; i++)+ {+ var q = boxes[i].quad;+ int x0 = Mathf.FloorToInt(q.Min(p => p.x) / cell), x1 = Mathf.FloorToInt(q.Max(p => p.x) / cell);+ int z0 = Mathf.FloorToInt(q.Min(p => p.y) / cell), z1 = Mathf.FloorToInt(q.Max(p => p.y) / cell);+ for (int x = x0; x <= x1; x++) for (int z = z0; z <= z1; z++)+ { if (!grid.TryGetValue((x, z), out var l)) grid[(x, z)] = l = new List<int>(); l.Add(i); }+ }+ var pairs = new HashSet<(int, int)>(); var byTowns = new Dictionary<string, int>();+ foreach (var l in grid.Values)+ for (int a = 0; a < l.Count; a++)+ for (int b = a + 1; b < l.Count; b++)+ {+ int i = Math.Min(l[a], l[b]), j = Math.Max(l[a], l[b]);+ if (boxes[i].Id == boxes[j].Id || !pairs.Add((i, j))) continue;+ if (!Overlap(boxes[i].quad, boxes[j].quad, 1f)) continue;+ var key = string.CompareOrdinal(boxes[i].Id, boxes[j].Id) < 0 ? $"{boxes[i].Id}/{boxes[j].Id}" : $"{boxes[j].Id}/{boxes[i].Id}";+ byTowns[key] = byTowns.TryGetValue(key, out var n) ? n + 1 : 1;+ }+ TestContext.WriteLine(byTowns.Count == 0 ? "no overlaps" : string.Join("; ", byTowns.OrderByDescending(kv => kv.Value).Select(kv => $"{kv.Key}: {kv.Value}")));+ CollectionAssert.IsEmpty(byTowns.Keys.Take(15), $"{byTowns.Values.Sum()} overlapping pairs between settlements");+ }+}diff --git a/unity/Assets/Tests/EditMode/TownModelScaleTests.cs.meta b/unity/Assets/Tests/EditMode/TownModelScaleTests.cs.metanew file mode 100644index 000000000..f46fe4811--- /dev/null+++ b/unity/Assets/Tests/EditMode/TownModelScaleTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ebf46262019a945db8578fcd13246e82\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/TownModelTests.cs b/unity/Assets/Tests/EditMode/TownModelTests.csindex faba9286f..44cd862ad 100644--- a/unity/Assets/Tests/EditMode/TownModelTests.cs+++ b/unity/Assets/Tests/EditMode/TownModelTests.cs@@ -103,10 +103,12 @@ public class TownModelTests// Every farm shed of every kibbutz (#820: the game settlements' and the localities') is a b24 barn, and no kibbutz// house is.var kibbutzim = map.Settlements.Concat(map.Localities.Select(p => p.Settlement)).Where(s => s.Type == "kibbutz").Select(s => s.Id).ToHashSet();+ // At the world scale a shed's plot holds a group of barns (SettlementKits.PlaceModel): one plot of barns per shed.int barns = built.Models.Count(m => kibbutzim.Contains(m.Id) && m.Model == M.B24Barn);- TestContext.WriteLine($"kibbutz sheds {built.FarmSheds}, b24 barns in kibbutzim {barns}, dining halls {built.KibbutzHalls}");+ int barnPlots = built.Models.Where(m => kibbutzim.Contains(m.Id) && m.Model == M.B24Barn).Select(m => (m.Id, m.Plot)).Distinct().Count();+ TestContext.WriteLine($"kibbutz sheds {built.FarmSheds}, b24 barns in kibbutzim {barns} on {barnPlots} plots, dining halls {built.KibbutzHalls}");Assert.Greater(built.FarmSheds, 0, "the kibbutzim have farm sheds");- Assert.AreEqual(built.FarmSheds, barns, "one b24 barn per kibbutz farm shed");+ Assert.AreEqual(built.FarmSheds, barnPlots, "one plot of b24 barns per kibbutz farm shed");CollectionAssert.IsEmpty(bad);}@@ -114,8 +116,10 @@ public class TownModelTestsstatic HashSet<string> Outposts(List<SettlementKits.Placed> placed) =>placed.Where(p => p.Kind == "outpost_yard").Select(p => p.Id).ToHashSet();- /// <summary>Every building the census records (and every water tower and port warehouse) is one model at its plot's- /// centre, filling its footprint; no other model is placed.</summary>+ /// <summary>Every building the census records (and every water tower and port warehouse) is built of models on its plot:+ /// at the world scale (SettlementKits.ModelScale) a kit plot holds a grid of them (a water tower, a warehouse, a dining+ /// hall and a place's one-off building one), each turned with the plot and inside its footprint; no other model is+ /// placed.</summary>[Test]public void EveryPlacedBuildingIsOneModelOnItsPlot(){@@ -128,16 +132,29 @@ public class TownModelTestsAssert.IsTrue(want.Any(p => p.Kind == "dining_hall"), "the kibbutzim's dining halls are in the census (#820)");var got = built.Models.Where(m => towns.Contains(m.Id)).ToList();TestContext.WriteLine($"{want.Count} town buildings in the census, {got.Count} town models, {built.Models.Count} models with the localities");- Assert.AreEqual(want.Count, got.Count, "one model per placed building");- var byKey = got.ToLookup(m => (m.Id, Mathf.RoundToInt(m.C.x), Mathf.RoundToInt(m.C.y)));+ var byKey = got.ToLookup(m => (m.Id, Mathf.RoundToInt(m.Plot.x), Mathf.RoundToInt(m.Plot.y)));+ Assert.AreEqual(want.Count, byKey.Count, "every placed building's plot has its models, and no model stands elsewhere");var bad = new List<string>();+ var corners = new List<Vector3>();foreach (var p in want){var at = byKey[(p.Id, Mathf.RoundToInt(p.C.x), Mathf.RoundToInt(p.C.y))].ToList();- if (at.Count != 1) { bad.Add($"{p.Id} {p.Kind} at {p.C}: {at.Count} models"); continue; }- var mi = at[0];- if (Mathf.Abs(mi.W - p.W) > 0.5f || Mathf.Abs(mi.D - p.D) > 0.5f || Mathf.Abs(mi.Yaw - p.Yaw) > 0.01f) bad.Add($"{p.Id} {p.Kind} at {p.C}: footprint");+ if (at.Count == 0) { bad.Add($"{p.Id} {p.Kind} at {p.C}: no model"); continue; }+ if (p.Kind != "building" && at.Count != 1) bad.Add($"{p.Id} {p.Kind} at {p.C}: {at.Count} models");+ float a = p.Yaw * Mathf.Deg2Rad, ca = Mathf.Cos(a), sa = Mathf.Sin(a);+ foreach (var mi in at)+ {+ if (Mathf.Abs(mi.Yaw - p.Yaw) > 0.01f) bad.Add($"{p.Id} {p.Kind} at {p.C}: turned off its plot");+ corners.Clear(); mi.Corners(corners);+ foreach (var c in corners)+ {+ float dx = c.x - p.C.x, dz = c.z - p.C.y;+ if (Mathf.Abs(dx * ca + dz * sa) > 0.5f * p.W + 0.5f || Mathf.Abs(-dx * sa + dz * ca) > 0.5f * p.D + 0.5f)+ { bad.Add($"{p.Id} {p.Kind} at {p.C}: a model outside its plot"); break; }+ }+ }}+ TestContext.WriteLine($"{got.Count} town models on {byKey.Count} plots");CollectionAssert.IsEmpty(bad.Take(20), $"{bad.Count} mismatches");Assert.Greater(built.Models.Count, got.Count, "the 1948 localities' houses are models too");}@@ -167,7 +184,7 @@ public class TownModelTests};var outposts = Outposts(placed);CollectionAssert.AreEqual(new[] { "revivim" }, outposts.Where(ids.Contains).ToArray(), "the one walled lookout (a listed gap)");- var at = built.Models.ToLookup(m => (m.Id, Mathf.RoundToInt(m.C.x), Mathf.RoundToInt(m.C.y)));+ var at = built.Models.ToLookup(m => (m.Id, Mathf.RoundToInt(m.Plot.x), Mathf.RoundToInt(m.Plot.y)));var bad = new List<string>();int houses = 0;foreach (var p in placed.Where(p => ids.Contains(p.Id) && !outposts.Contains(p.Id)))@@ -185,39 +202,40 @@ public class TownModelTestsCollectionAssert.IsEmpty(bad.Take(20), $"{bad.Count} kit buildings left up close");}- /// <summary>A model fills its plot: its world bounds are the plot's footprint and height (city blocks exactly; a house- /// within its stretch limits), standing on the plot's ground level, at any yaw and with the model's long side turned- /// to the plot's.</summary>+ /// <summary>A model stands on its plot at the world scale (SettlementKits.ModelScale, the owner on v0.1.1: the buildings+ /// were "way bigger then the train"): a plot w x d x h at the kit's scale k stands for a building w/k x d/k x h/k real,+ /// so the model's longer side is max(w, d) / k x ModelScale along the plot's longer side, one scale on both ground axes+ /// (its own proportions, not stretched to the plot), centred on the plot, on the ground, as tall as h / k x ModelScale+ /// (city blocks exactly; a house within its stretch limits), at any yaw, never mirrored.</summary>[Test]- public void AModelFillsItsFootprint([Values(0f, 20f, 90f, 137f)] float yaw, [Values(false, true)] bool flip)+ public void AModelStandsOnItsPlotAtTheWorldScale([Values(0f, 20f, 90f, 137f)] float yaw, [Values(false, true)] bool flip){+ const float kit = 60f;+ float toWorld = SettlementKits.ModelScale / kit;foreach (M model in Enum.GetValues(typeof(M)))foreach (var (w, d) in new[] { (840f, 600f), (500f, 900f) }){- var mi = SettlementKits.Fit("t", model, new Vector2(1000f, 2000f), yaw, w, d, 1200f, 50f, exactHeight: true, flip);+ var mi = SettlementKits.Fit("t", model, new Vector2(1000f, 2000f), yaw, w, d, 1200f, 50f, exactHeight: true, flip, kit);var s = TownModels.Size[(int)model];var lo = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); var hi = -lo;- for (int i = 0; i < 8; i++)- {- var c = mi.M.MultiplyPoint3x4(new Vector3(((i & 1) - 0.5f) * s.x, (((i >> 1) & 1) - 0.5f) * s.y, ((i >> 2) & 1) * s.z));- lo = Vector3.Min(lo, c); hi = Vector3.Max(hi, c);- }- Assert.AreEqual(50f, lo.y, 0.01f, $"{model} stands on the ground"); Assert.AreEqual(1250f, hi.y, 0.05f, $"{model} height");- // In the plot's own frame the box is w x d.float a = yaw * Mathf.Deg2Rad, ca = Mathf.Cos(a), sa = Mathf.Sin(a);float maxU = 0f, maxV = 0f;for (int i = 0; i < 8; i++){var c = mi.M.MultiplyPoint3x4(new Vector3(((i & 1) - 0.5f) * s.x, (((i >> 1) & 1) - 0.5f) * s.y, ((i >> 2) & 1) * s.z));+ lo = Vector3.Min(lo, c); hi = Vector3.Max(hi, c);float dx = c.x - 1000f, dz = c.z - 2000f;maxU = Mathf.Max(maxU, Mathf.Abs(dx * ca + dz * sa)); maxV = Mathf.Max(maxV, Mathf.Abs(-dx * sa + dz * ca));}- Assert.AreEqual(0.5f * w, maxU, 0.05f, $"{model} width at yaw {yaw}"); Assert.AreEqual(0.5f * d, maxV, 0.05f, $"{model} depth at yaw {yaw}");+ Assert.AreEqual(50f, lo.y, 0.01f, $"{model} stands on the ground"); Assert.AreEqual(50f + 1200f * toWorld, hi.y, 0.05f, $"{model} height");+ float along = 2f * (w >= d ? maxU : maxV), across = 2f * (w >= d ? maxV : maxU);+ Assert.AreEqual(Mathf.Max(w, d) * toWorld, along, 0.05f, $"{model}: its longer side at the world scale, yaw {yaw}");+ Assert.AreEqual(Mathf.Min(s.x, s.y) / Mathf.Max(s.x, s.y), across / along, 1e-3f, $"{model} keeps its own proportions");+ Assert.AreEqual(2f * maxU, mi.W, 0.05f, $"{model}: W along the yaw"); Assert.AreEqual(2f * maxV, mi.D, 0.05f, $"{model}: D across");Assert.Greater(mi.M.determinant, 0f, $"{model}: not mirrored (the faces keep their winding)");- var house = SettlementKits.Fit("t", model, Vector2.zero, yaw, w, d, 99999f, 0f, exactHeight: false, flip);+ var house = SettlementKits.Fit("t", model, Vector2.zero, yaw, w, d, 99999f, 0f, exactHeight: false, flip, kit);float natural = house.H / SettlementKits.MaxStretch;- Assert.AreEqual(natural, s.z * Mathf.Sqrt((w >= d) == (s.x >= s.y) ? w / s.x * (d / s.y) : d / s.x * (w / s.y)), natural * 1e-3f,- $"{model}: a house's height stops at its stretch limit");+ Assert.AreEqual(s.z * Mathf.Max(w, d) * toWorld / Mathf.Max(s.x, s.y), natural, natural * 1e-3f, $"{model}: a house's height stops at its stretch limit");}}@@ -434,7 +452,8 @@ public class TownModelTestsvar root = map.transform.Find(KitLayer.RootName);var layer = root.GetComponentInChildren<TownModelLayer>(); Assert.IsNotNull(layer);Assert.Greater(layer.Count, 1000);- Assert.Greater(layer.CountFor("tel_aviv"), layer.CountFor("petah_tikva"), "the big city has more buildings");+ int Plots(string id) => layer.InstancesOf(id).Select(m => m.Plot).Distinct().Count();+ Assert.Greater(Plots("tel_aviv"), Plots("petah_tikva"), "the big city has more building plots");var renderers = root.GetComponentsInChildren<MeshRenderer>(true);var closeRs = renderers.Where(r => r.name.EndsWith(KitLayer.CloseSuffix)).ToList();var kitRs = map.Settlements.Select(s => root.Find(s.Id).GetComponent<MeshRenderer>())