A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: bake the route ribbons, so boot places them instead of building them (refs #321) (#436)
Eyal Golan20d34c631067
diff --git a/ASSETS.yaml b/ASSETS.yamlindex 99d993b9d..979767bb0 100644--- a/ASSETS.yaml+++ b/ASSETS.yaml@@ -192,6 +192,11 @@ rules:source: "Railways and main roads of May 1948 (issue #35): traced by tools/routes_1948.py on the Survey of Palestine 1:250,000 map of 1946 (public domain; scans and georeferencing by Palestine Open Maps, https://palopenmaps.org/en/maps?basemap=pal250k1946) between waypoints at Wikipedia API (CC BY-SA) and Wikidata (CC0) coordinates; per-route sources and check dates in routes_1948.yaml"status: verifiednote: "Public domain checked 2026-10-11: PD-UKGov (expired Crown copyright: 50 years from publication for published works, which HMSO treats as worldwide) and PD-scan, as Wikimedia Commons files the 1946 Survey of Palestine sheets (e.g. https://commons.wikimedia.org/wiki/File:Gaza_sh._04,_1946.jpg). Palestine Open Maps' About page calls its maps public domain under the UK Copyright, Designs and Patents Act and publishes no terms of its own for its tiles or georeferencing; the traced lines are our own derivative and copy none of its layers. No OpenStreetMap (ODbL) geometry is copied: OSM and OpenHistoricalMap lines are only measured against (tools/routes_accuracy.py, docs/routes.md)."+ - glob: "unity/Assets/Resources/Routes/RouteRibbons.bytes"+ licence: CC-BY-SA-4.0+ source: "The route ribbons' meshes (issue #321), baked by Editor RouteRibbonBake from content/map/route_paths_1948.yaml (the traced lines above) draped on the Copernicus DEM GLO-30-derived heightmap (unity/Assets/StreamingAssets/map/heightmap.*); no new facts; attribution in NOTICE"+ status: owner-verify+ note: "Decision D13 (docs/oss/DECISIONS.md): the owner rules the licence of data derived from DEM and coordinate inputs."- glob: "content/map/units_1948.yaml"licence: CC-BY-SA-4.0source: "The 1948 brigades, 101 Squadron and the first navy ships, with their dated positions (docs/units.md, Units in play): facts and place coordinates read from English and Hebrew Wikipedia (CC BY-SA; Wikipedia API prop=coordinates) and Wikidata (CC0), and the S-199 markings from Eduard Info 11/2025 pp. 53-54 (facts only, no text or image copied); per-row sources and check dates in the file"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c0c46b8ec..46f1f5bac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -206,6 +206,11 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBreadability choice at map scale; the sourced kit is unchanged (refs #197).- The scenario runner (`Scenario`) and the `mvp-slice` golden's player (`MvpGolden`) move from the tests into `Statecraft.Sim`,next to `GoldenRun`, so Unity can play those goldens too (step 1 of #394). Same code, same hashes; no golden moves.+- The map's railways and roads are placed from a bake at boot instead of being built (refs #321), as the water's+ mesh is since #195. The routes look the same: the bake holds the same meshes, and a stale or missing bake is refused+ with a warning and the routes are built at load as before. `routes built` takes 51 ms at `--cpu 4`, from+ 162 ms. The bake also lists where each route lies in its mesh, for the corridors of GDD Phase 4 (#384).+ Presentation only.- Sea round 2 (refs #388). The sea has texture at the gameplay and overview zooms, where it used to read as a flatsurface: slow wind streaks, ripples from the waves' slope towards the camera (faded out as a pixel grows towards awave's size), and sparse whitecaps on the streaks' bright side, close up only. All three sit behind a new `seatexture`diff --git a/docs/routes.md b/docs/routes.mdindex 0e11b71da..29e1f27b9 100644--- a/docs/routes.md+++ b/docs/routes.md@@ -12,6 +12,7 @@ The map draws the railways and main roads of 1948, each from its sourced date, a| Tracer | `tools/routes_1948.py` (tests: `tools/tests/test_routes_1948.py`) || Map layer | `unity/Assets/Scripts/Map/Routes/` (`RoutePaths`, `RouteLayer`, `RouteTrain`, `TrainModels`) || Shader and materials | `unity/Assets/Shaders/Route.shader`; `Resources/Routes/Rail.mat`, `Road.mat` (`RouteMaterialAssets.Create`) |+| Baked ribbons (generated) | `unity/Assets/Resources/Routes/RouteRibbons.bytes` (`RouteRibbonBake.Bake`; tests: `tools/tests/test_route_ribbon_bake.py`) || Tests | `unity/Assets/Tests/EditMode/RouteTests.cs` |Both route files are map-only. `ContentLoader` never reads them, so the content hash and the goldens do not move@@ -248,6 +249,31 @@ measurement in `docs/units.md`:**Toggles.** `routes` (the ribbons) and `train` (when there is one) are visual toggles, so `?vprofile` prices each one.+**Baked ribbons** (issue #321). Boot places the ribbon meshes from a bake instead of deriving them, as the terrain water+does (#320, docs/visual-v1.md).+- `RouteRibbonFile` (format) and the editor's `RouteRibbonBake` write every mesh `RouteLayer.Build` draws, in its order+ (`RouteLayer.Plan`): vertices, normals, uvs and indices, to `Resources/Routes/RouteRibbons.bytes`.+- The header holds the bake's version, the heightmap's resolution and `HeightsCheck`, FNV-1a checks of `heightmap.json`+ and `route_paths_1948.yaml`, the terrain's size and origin, and the geometry constants (widths, `StepM`, `ClearanceM`,+ the tolerances, the sample counts, `VerticalExaggeration`).+- When any of them differs from what the map loaded, the bake is refused with a warning (`ROUTES ...: deriving the route+ ribbons at load`) and the ribbons are derived as before: the same meshes, only slower.+- **Route index** (for the GDD Phase 4 corridors, #384). Each mesh lists its routes, each with its first vertex, vertex+ count, first index and index count (`RouteSpan`), so a later change can show one route by its construction state.+ Nothing reads it yet; the vertex layout is unchanged.+- **Re-bake** whenever the heightmap, `heightmap.json`, the route file, a constant in the header or the ribbon rule+ (`RouteLayer.Geometry`; bump `RouteRibbonFile.Version` with it) changes:+ `Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod+ Statecraft.Game.EditorTools.RouteRibbonBake.Bake`, under `tools/machine_lock.py` as any Unity run.+- **Checks.** `tools/tests/test_route_ribbon_bake.py` (CI, no Unity) fails on a stale header, reading the constants from+ the C# source, and checks the route index. `RouteTests.TheBakedRibbonsMatchTheRoutes` compares the bake with a fresh+ derivation byte for byte, and with the map's own terrain vertex for vertex; `AStaleRibbonBakeIsDerivedAtLoad` checks+ the fallback. A change to `RouteLayer.Geometry` without a version bump is caught only by the Unity test.+- **Boot** (`tools/headed.py boot --runs 3 --cpu 4`, phase `routes built`, three rounds interleaved with main `bc67247`+ under the exclusive lock, 9 cold loads each, medians, 2026-10-13): 162 ms on main, 51 ms with the bake. The whole map+ build is 3384 ms on main and 3414 ms with the bake, inside the runs' spread (3158-4240 ms); its other phases move by the+ same few tens of milliseconds both ways from run to run.+**Kits keep off the routes** (settlement kits and trees, #179).- `MapScene` reads the routes before building the kits, and hands `KitLayer.Build` every route's corridor(`RouteLayer.Corridors`): half the drawn width plus `CorridorMarginM` (100 m).diff --git a/tools/tests/test_route_ribbon_bake.py b/tools/tests/test_route_ribbon_bake.pynew file mode 100644index 000000000..899b597f4--- /dev/null+++ b/tools/tests/test_route_ribbon_bake.py@@ -0,0 +1,133 @@+"""The route ribbons' bake (unity/Assets/Resources/Routes/RouteRibbons.bytes, issue #321) is for the shipped map and routes.++The game refuses a bake whose header does not match what it loaded (RouteRibbonFile.TryRead: the heightmap's resolution and+HeightsCheck, FNV-1a checks of heightmap.json and route_paths_1948.yaml, the terrain, RouteLayer's geometry constants and+the bake's version) and then derives the ribbons at boot, which is slower. CI runs no Unity, so this checks the same+header here, with the constants read from the C# source: a change to any of them without a re-bake+(RouteRibbonBake.Bake) fails CI, as the water's bake does. It also walks the meshes and their route index (route id, vertex+and index range) for the GDD Phase 4 corridors (#384). Unity's RouteTests.TheBakedRibbonsMatchTheRoutes compares the+whole meshes."""+import codecs+import re+import struct+from pathlib import Path++import numpy as np+import yaml++from test_terrain_water_bake import MAP, heights_check, unity_heights++ROOT = Path(__file__).resolve().parents[2]+BAKE = ROOT / "unity/Assets/Resources/Routes/RouteRibbons.bytes"+ROUTES = ROOT / "content/map/route_paths_1948.yaml"+SCRIPTS = ROOT / "unity/Assets/Scripts/Map"+MAGIC = 0x31524353 # "SCR1"+REBAKE = "run Statecraft.Game.EditorTools.RouteRibbonBake.Bake in Unity (docs/routes.md, Baked ribbons)"++# RouteRibbonFile.Floats and .Ints, in the header's order, with the file that defines each.+FLOATS = [("Routes/RouteLayer.cs", n) for n in ("RailWidthM", "RoadWidthM", "TrackWidthM", "StepM", "ClearanceM",+ "FallToleranceM", "RiseToleranceM", "MinWidthShare", "HalfWidthStepShare", "RailSpanShare", "RailClearanceM")]+FLOATS += [("MapBuilder.cs", "VerticalExaggeration")]+INTS = [("Routes/RouteLayer.cs", n) for n in ("Across", "NarrowSamples", "LiftSamples")]+++def fnv1a(data: bytes) -> int:+ """RouteRibbonFile.Check: FNV-1a over the bytes, as a signed int32."""+ h = 2166136261+ for b in data:+ h = ((h ^ b) * 16777619) & 0xFFFFFFFF+ return struct.unpack("<i", struct.pack("<I", h))[0]+++def text_check(path: Path) -> int:+ """Check over the file as Unity reads it: File.ReadAllText drops a UTF-8 BOM."""+ return fnv1a(path.read_bytes().removeprefix(codecs.BOM_UTF8))+++def csharp_const(rel: str, name: str) -> str:+ m = re.search(rf"\b{name}\s*=\s*([0-9]+(?:\.[0-9]+)?)f?\b", (SCRIPTS / rel).read_text())+ assert m, f"{name} not found in {rel}"+ return m.group(1)+++def bake_version() -> int:+ return int(csharp_const("Routes/RouteRibbonFile.cs", "Version"))+++class Reader:+ def __init__(self, data: bytes):+ self.data, self.at = data, 0++ def take(self, fmt: str):+ size = struct.calcsize(fmt)+ assert self.at + size <= len(self.data), "truncated: " + REBAKE+ values = struct.unpack_from(fmt, self.data, self.at)+ self.at += size+ return values++ def int(self) -> int:+ return self.take("<i")[0]++ def text(self) -> str:+ n = self.int()+ return self.take(f"<{n}s")[0].decode("utf-8")+++def read_header(r: Reader) -> dict:+ head = dict(zip(("magic", "version", "res", "heights", "map", "routes"), r.take("<6i")))+ head["terrain"] = r.take("<6f")+ head["floats"] = r.take(f"<{len(FLOATS)}f")+ head["ints"] = r.take(f"<{len(INTS)}i")+ head["meshes"] = r.int()+ return head+++def bake_bytes() -> bytes:+ assert BAKE.exists(), f"{BAKE.relative_to(ROOT)} is missing: {REBAKE}"+ return BAKE.read_bytes()+++def test_the_route_ribbon_bake_is_for_the_shipped_map_and_routes():+ head = read_header(Reader(bake_bytes()))+ heights = unity_heights()+ assert head["magic"] == MAGIC+ assert head["version"] == bake_version(), "made by another RouteRibbonFile.Version: " + REBAKE+ assert head["res"] == heights.shape[1]+ assert head["heights"] == heights_check(heights), "stale (heightmap): " + REBAKE+ assert head["map"] == text_check(MAP / "heightmap.json"), "stale (heightmap.json): " + REBAKE+ assert head["routes"] == text_check(ROUTES), "stale (route_paths_1948.yaml): " + REBAKE+ want = [np.float32(float(csharp_const(f, n))) for f, n in FLOATS]+ got = [np.float32(v) for v in head["floats"]]+ changed = [n for (_, n), a, b in zip(FLOATS, want, got) if a != b]+ changed += [n for (f, n), v in zip(INTS, head["ints"]) if int(csharp_const(f, n)) != v]+ assert not changed, f"stale (constants {', '.join(changed)}): " + REBAKE+++def test_every_route_is_in_the_index_once_and_its_ranges_tile_its_mesh():+ r = Reader(bake_bytes())+ head = read_header(r)+ ids = []+ for _ in range(head["meshes"]):+ name = r.text()+ nv, ni, nr = r.take("<3i")+ vertex = index = 0+ for _ in range(nr):+ rid = r.text()+ first_v, count_v, first_i, count_i = r.take("<4i")+ assert (first_v, first_i) == (vertex, index), f"{name}: {rid} does not follow the route before it"+ assert count_i % 3 == 0, f"{name}: {rid}"+ vertex, index = first_v + count_v, first_i + count_i+ ids.append(rid)+ assert (vertex, index) == (nv, ni), f"{name}: the routes do not cover the mesh"+ r.take(f"<{8 * nv}f")+ indices = np.array(r.take(f"<{ni}i"), dtype=np.int64)+ assert ni == 0 or (indices.min() >= 0 and indices.max() < nv), name+ assert r.at == len(r.data), "longer than its meshes: " + REBAKE+ shipped = [route["id"] for route in yaml.safe_load(ROUTES.read_text(encoding="utf-8"))["routes"]]+ assert sorted(ids) == sorted(shipped), "stale (route ids): " + REBAKE+++def test_the_check_is_fnv1a():+ assert fnv1a(b"") == struct.unpack("<i", struct.pack("<I", 2166136261))[0]+ assert fnv1a(b"a") == struct.unpack("<i", struct.pack("<I", 0xE40C292C))[0] # the FNV-1a 32-bit test vector+ assert fnv1a(b"ab") != fnv1a(b"ba")diff --git a/unity/Assets/Editor/RouteRibbonBake.cs b/unity/Assets/Editor/RouteRibbonBake.csnew file mode 100644index 000000000..a991f563f--- /dev/null+++ b/unity/Assets/Editor/RouteRibbonBake.cs@@ -0,0 +1,24 @@+using System.IO;+using Statecraft.Game.Boot;+using Statecraft.Game.Map.Routes;+using UnityEditor;++namespace Statecraft.Game.EditorTools+{+ /// <summary>Bakes the route ribbons (RouteLayer.Plan, RouteLayer.Derive) from the shipped heightmap and+ /// route_paths_1948.yaml into RouteRibbonFile.AssetPath, so a player places them instead of deriving them at boot+ /// (issue #321). Re-run it whenever the heightmap, heightmap.json, the route file or RouteLayer's geometry changes+ /// (RouteTests.TheBakedRibbonsMatchTheRoutes and tools/tests/test_route_ribbon_bake.py fail until then; the map also+ /// falls back to deriving them). Run headless: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit+ /// -projectPath unity -executeMethod Statecraft.Game.EditorTools.RouteRibbonBake.Bake</summary>+ public static class RouteRibbonBake+ {+ public static byte[] Bytes() => RouteRibbonFile.Bake(GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap));++ public static void Bake()+ {+ File.WriteAllBytes(RouteRibbonFile.AssetPath, Bytes());+ AssetDatabase.ImportAsset(RouteRibbonFile.AssetPath);+ }+ }+}diff --git a/unity/Assets/Editor/RouteRibbonBake.cs.meta b/unity/Assets/Editor/RouteRibbonBake.cs.metanew file mode 100644index 000000000..f8bc03d8c--- /dev/null+++ b/unity/Assets/Editor/RouteRibbonBake.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 26f78b40f4ec4952ab82c76ff706b079\ No newline at end of filediff --git a/unity/Assets/Resources/Routes/RouteRibbons.bytes b/unity/Assets/Resources/Routes/RouteRibbons.bytesnew file mode 100644index 000000000..c1dd2729fBinary files /dev/null and b/unity/Assets/Resources/Routes/RouteRibbons.bytes differdiff --git a/unity/Assets/Resources/Routes/RouteRibbons.bytes.meta b/unity/Assets/Resources/Routes/RouteRibbons.bytes.metanew file mode 100644index 000000000..724cd4599--- /dev/null+++ b/unity/Assets/Resources/Routes/RouteRibbons.bytes.meta@@ -0,0 +1,7 @@+fileFormatVersion: 2+guid: a47e536b296994548811ee86d8a12438+TextScriptImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex f7da3eae1..8d3b74b15 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -296,8 +296,10 @@ namespace Statecraft.Game.MapDebug.Log(stats.ToString());}// The routes are drawn map-only, as at the game's date (the start until the game sets one); a missing or malformed- // file means no routes and a warning; the train only in screenshots, editor renders and ?train.- Routes.RouteLayer.Build(Terrain, Frame, routes, Routes.RouteLayer.ModeForThisRun(), RouteDate ?? Routes.RouteLayer.DefaultDate);+ // file means no routes and a warning; the train only in screenshots, editor renders and ?train. 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));DiagLog.BootPhase("routes built");if (!cam.TryGetComponent(out CameraRig rig)) rig = cam.gameObject.AddComponent<CameraRig>();diff --git a/unity/Assets/Scripts/Map/Routes/RouteLayer.cs b/unity/Assets/Scripts/Map/Routes/RouteLayer.csindex 9d99864c0..e50aeb6ff 100644--- a/unity/Assets/Scripts/Map/Routes/RouteLayer.cs+++ b/unity/Assets/Scripts/Map/Routes/RouteLayer.cs@@ -89,12 +89,46 @@ namespace Statecraft.Game.Map.Routes_ => throw new ArgumentException($"unknown route kind '{kind}'", nameof(kind)),};+ /// <summary>One ribbon mesh Build draws: the routes of one display window in one look ("Rail", or "Roads" for the+ /// roads and tracks), in the file's order.</summary>+ public sealed class RibbonPlan+ {+ public RouteWindow Window;+ public string Look = "";+ public List<RoutePath> Routes = new List<RoutePath>();+ public bool RailGrade => Look == "Rail";+ public string MeshName => $"Route{Look} {Window}";+ }++ /// <summary>The ribbons Build draws, in its order: the windows in the order they open, and in each the rail, then the+ /// roads, where the window has any. The bake (RouteRibbonFile) stores its meshes in this order.</summary>+ public static List<RibbonPlan> Plan(IReadOnlyList<RoutePath> routes)+ {+ var plans = new List<RibbonPlan>();+ foreach (var group in routes.GroupBy(RoutePaths.WindowOf).OrderBy(g => g.Key.From).ThenBy(g => g.Key.To ?? DateTime.MaxValue))+ foreach (var (kinds, look) in new[] { (new[] { RoutePaths.Rail }, "Rail"), (new[] { RoutePaths.Road, RoutePaths.Track }, "Roads") })+ {+ var members = group.Where(r => kinds.Contains(r.Kind)).ToList();+ if (members.Count > 0) plans.Add(new RibbonPlan { Window = group.Key, Look = look, Routes = members });+ }+ return plans;+ }++ /// <summary>A plan's ribbon, derived from the terrain (what the bake stores).</summary>+ public static RibbonGeometry Derive(RibbonPlan plan, GeoFrame frame, TerrainData data, Vector3 origin) =>+ Geometry(plan.Routes.Select(r => (r.Id, World(frame, r), WidthOf(r.Kind))), data, origin, plan.RailGrade);+/// <summary>Builds the routes under <paramref name="terrain"/> (so a map rebuild destroys them): one group per display/// window (its rail and road ribbons), shown as at <paramref name="date"/>, and, when <paramref name="train"/> is not/// None and the train's route is in <paramref name="routes"/>, the train (still: it stands at its still position, so/// screenshots and editor renders repeat exactly). Meshes, the train's palette and its material copy are owned by- /// the root's own MapRuntimeAssets, which also unregisters the toggles. Returns the root.</summary>- public static GameObject Build(Terrain terrain, GeoFrame frame, IReadOnlyList<RoutePath> routes, TrainMode train, DateTime date)+ /// the root's own MapRuntimeAssets, which also unregisters the toggles. Returns the root.+ /// With <paramref name="baked"/> (the inputs the map read), the ribbons are placed from the bake+ /// (RouteRibbonFile.Resource, Editor RouteRibbonBake) when it was made from the same inputs; a missing or stale bake+ /// 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){if (terrain == null) throw new ArgumentNullException(nameof(terrain));if (routes == null) throw new ArgumentNullException(nameof(routes));@@ -112,30 +146,28 @@ namespace Statecraft.Game.Map.Routesvar data = terrain.terrainData; var origin = terrain.transform.position;// One group per display window, in the order the windows open (deterministic names and draw order).- foreach (var group in routes.GroupBy(RoutePaths.WindowOf).OrderBy(g => g.Key.From).ThenBy(g => g.Key.To ?? DateTime.MaxValue))+ var plans = Plan(routes);+ var geometry = Geometries(plans, frame, data, origin, baked);+ GameObject? holder = null;+ for (int i = 0; i < plans.Count; i++){- var holder = new GameObject($"Window {group.Key}");- holder.transform.SetParent(ribbons.transform, false);- holder.AddComponent<RouteGroup>().Window = group.Key;- foreach (var (kinds, material, name) in new[]- {- (new[] { RoutePaths.Rail }, rail, "Rail"),- (new[] { RoutePaths.Road, RoutePaths.Track }, road, "Roads"),- })+ var plan = plans[i];+ if (holder == null || !plans[i - 1].Window.Equals(plan.Window)){- var lines = group.Where(r => kinds.Contains(r.Kind)).Select(r => (World(frame, r), WidthOf(r.Kind))).ToList();- if (lines.Count == 0) continue;- var mesh = assets.Own(Ribbon(lines, data, origin, $"Route{name} {group.Key}", railGrade: name == "Rail"));- mesh.UploadMeshData(true);- var go = new GameObject(name);- go.transform.SetParent(holder.transform, false);- go.AddComponent<MeshFilter>().sharedMesh = mesh;- var r = go.AddComponent<MeshRenderer>();- r.sharedMaterial = material;- r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;- r.receiveShadows = true;+ holder = new GameObject($"Window {plan.Window}");+ holder.transform.SetParent(ribbons.transform, false);+ holder.AddComponent<RouteGroup>().Window = plan.Window;+ holder.SetActive(plan.Window.Covers(date));}- holder.SetActive(group.Key.Covers(date));+ var mesh = assets.Own(geometry[i].ToMesh(plan.MeshName));+ mesh.UploadMeshData(true);+ var go = new GameObject(plan.Look);+ go.transform.SetParent(holder.transform, false);+ go.AddComponent<MeshFilter>().sharedMesh = mesh;+ var r = go.AddComponent<MeshRenderer>();+ r.sharedMaterial = plan.RailGrade ? rail : road;+ r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;+ r.receiveShadows = true;}assets.OnTeardown(VisualToggles.Register(RoutesToggle, on => { if (ribbons != null) ribbons.SetActive(on); }));@@ -150,6 +182,25 @@ namespace Statecraft.Game.Map.Routesreturn root;}+ /// <summary>The plans' ribbons: from the bake when <paramref name="baked"/> is given and the bake is for those inputs,+ /// else derived.</summary>+ static List<RibbonGeometry> Geometries(List<RibbonPlan> plans, GeoFrame frame, TerrainData data, Vector3 origin, RouteRibbonFile.Source? baked)+ {+ if (baked is { } source && plans.Count > 0)+ {+ var asset = Resources.Load<TextAsset>(RouteRibbonFile.Resource);+ string why = "missing";+ if (asset != null)+ {+ bool ok = RouteRibbonFile.TryRead(asset.bytes, source, data.size, origin, plans, out var read, out why);+ if (!Application.isEditor) Resources.UnloadAsset(asset); // its bytes were copied; drop the native copy+ if (ok) return read;+ }+ Debug.LogWarning($"ROUTES {RouteRibbonFile.AssetPath}: {why}; deriving the route ribbons at load");+ }+ return plans.ConvertAll(p => Derive(p, frame, data, origin));+ }+/// <summary>A route's points in world metres (x east, z north).</summary>public static List<Vector2> World(GeoFrame frame, RoutePath route){@@ -204,7 +255,7 @@ namespace Statecraft.Game.Map.Routes/// <summary>The narrowest a cross-section gets, as a share of the ribbon's width (a gorge floor).</summary>public const float MinWidthShare = 0.25f;/// <summary>Samples per side when a cross-section looks for where it must stop.</summary>- const int NarrowSamples = 8;+ internal const int NarrowSamples = 8;/// <summary>The half-width (m) a cross-section at <paramref name="q"/> (flat at <paramref name="y"/>) may span. A sample/// leaves the tolerance where the ground is more than <see cref="RiseToleranceM"/> above the section or more than@@ -259,7 +310,7 @@ namespace Statecraft.Game.Map.Routes/// <summary>Clearance (m, world) of the rails over the highest ground under them, where a section had to be lifted.</summary>public const float RailClearanceM = 3f;/// <summary>Ground samples each side of the line when a section checks the ground under its rails (<see cref="RailSpanShare"/>).</summary>- const int LiftSamples = 4;+ internal const int LiftSamples = 4;/// <summary>The half-widths of a rail line's sections (centre points <paramref name="pts"/>, unit directions/// <paramref name="dirs"/>, heights <paramref name="ys"/>), smoothed along the line: FlatHalfWidth per section, then@@ -295,14 +346,21 @@ namespace Statecraft.Game.Map.Routes/// rails (<see cref="RailSpanShare"/>; review A-I2). Normal: the terrain's at the line.</item>/// </list></summary>public static Mesh Ribbon(IEnumerable<(List<Vector2> line, float width)> lines, TerrainData data, Vector3 origin, string name,+ bool railGrade = false) =>+ Geometry(lines.Select(l => ("", l.line, l.width)), data, origin, railGrade).ToMesh(name);++ /// <summary><see cref="Ribbon"/>'s arrays before they become a mesh, with each line's vertex and index range under its+ /// route id (<see cref="RibbonGeometry.Routes"/>).</summary>+ public static RibbonGeometry Geometry(IEnumerable<(string id, List<Vector2> line, float width)> lines, TerrainData data, Vector3 origin,bool railGrade = false){var verts = new List<Vector3>(); var normals = new List<Vector3>(); var uvs = new List<Vector2>(); var tris = new List<int>();- foreach (var (line, width) in lines)+ var spans = new List<RouteSpan>();+ foreach (var (id, line, width) in lines){- if (line.Count < 2) continue;+ if (line.Count < 2) { spans.Add(new RouteSpan(id, verts.Count, 0, tris.Count, 0)); continue; }var (pts, along) = Resample(line, StepM);- int n = pts.Count, first = verts.Count;+ int n = pts.Count, first = verts.Count, firstIndex = tris.Count;var dirs = new Vector2[n];for (int i = 0; i < n; i++) dirs[i] = (pts[Math.Min(n - 1, i + 2)] - pts[Math.Max(0, i - 2)]).normalized;if (railGrade)@@ -346,12 +404,9 @@ namespace Statecraft.Game.Map.Routesint a = first + i * Across + j, b = a + 1, c = a + Across, d = c + 1;tris.AddRange(new[] { a, c, b, b, c, d }); // the shader draws both faces}+ spans.Add(new RouteSpan(id, first, verts.Count - first, firstIndex, tris.Count - firstIndex));}- var mesh = new Mesh { name = name };- if (verts.Count > 65535) mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;- mesh.SetVertices(verts); mesh.SetNormals(normals); mesh.SetUVs(0, uvs); mesh.SetTriangles(tris, 0);- mesh.RecalculateBounds();- return mesh;+ return new RibbonGeometry(verts.ToArray(), normals.ToArray(), uvs.ToArray(), tris.ToArray(), spans.ToArray());}}}diff --git a/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs b/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.csnew file mode 100644index 000000000..f37694076--- /dev/null+++ b/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs@@ -0,0 +1,240 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Text;+using Statecraft.Game.Boot;+using UnityEngine;++namespace Statecraft.Game.Map.Routes+{+ /// <summary>One route's share of a ribbon mesh: its first vertex and vertex count, and its first index and index count+ /// (whole triangles). A route whose line is shorter than two points has none.</summary>+ public readonly struct RouteSpan : IEquatable<RouteSpan>+ {+ public readonly string Id;+ public readonly int FirstVertex, VertexCount, FirstIndex, IndexCount;+ public RouteSpan(string id, int firstVertex, int vertexCount, int firstIndex, int indexCount)+ { Id = id; FirstVertex = firstVertex; VertexCount = vertexCount; FirstIndex = firstIndex; IndexCount = indexCount; }+ public bool Equals(RouteSpan o) => Id == o.Id && FirstVertex == o.FirstVertex && VertexCount == o.VertexCount+ && FirstIndex == o.FirstIndex && IndexCount == o.IndexCount;+ public override bool Equals(object? o) => o is RouteSpan s && Equals(s);+ public override int GetHashCode() => HashCode.Combine(Id, FirstVertex, VertexCount, FirstIndex, IndexCount);+ public override string ToString() => $"{Id} v{FirstVertex}+{VertexCount} i{FirstIndex}+{IndexCount}";+ }++ /// <summary>A ribbon mesh's arrays (RouteLayer.Geometry), and which routes it holds where (<see cref="Routes"/>), so a+ /// later change can draw one route on its own (GDD Phase 4 corridors, issue #384).</summary>+ public sealed class RibbonGeometry+ {+ public readonly Vector3[] Vertices, Normals;+ public readonly Vector2[] Uvs;+ public readonly int[] Indices;+ public readonly RouteSpan[] Routes;++ public RibbonGeometry(Vector3[] vertices, Vector3[] normals, Vector2[] uvs, int[] indices, RouteSpan[] routes)+ { Vertices = vertices; Normals = normals; Uvs = uvs; Indices = indices; Routes = routes; }++ public Mesh ToMesh(string name)+ {+ var mesh = new Mesh { name = name };+ if (Vertices.Length > 65535) mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;+ mesh.SetVertices(Vertices); mesh.SetNormals(Normals); mesh.SetUVs(0, Uvs); mesh.SetTriangles(Indices, 0);+ mesh.RecalculateBounds();+ return mesh;+ }+ }++ /// <summary>The route ribbons, baked (Editor RouteRibbonBake, issue #321), so a player places them instead of deriving+ /// them at boot (about 100 ms at the boot budget's CPU throttling). Little-endian throughout:+ /// <list type="bullet">+ /// <item>header: "SCR1", <see cref="Version"/>, the heightmap's resolution and HeightsCheck, checks of heightmap.json+ /// and route_paths_1948.yaml (<see cref="Check"/>), the terrain's size and origin (6 floats), the geometry constants+ /// (<see cref="Floats"/>, then <see cref="Ints"/>), the mesh count;</item>+ /// <item>each mesh, in RouteLayer.Plan's order: its name, its vertex, index and route counts, each route's id and+ /// <see cref="RouteSpan"/>, then the vertices, normals and uvs (floats) and the indices (int32).</item>+ /// </list>+ /// A string is its UTF-8 byte count (int32) and the bytes. tools/tests/test_route_ribbon_bake.py checks the header+ /// against the shipped files without Unity.</summary>+ public static class RouteRibbonFile+ {+ public const string Resource = "Routes/RouteRibbons";+ public const string AssetPath = RouteLayer.Folder + "/RouteRibbons.bytes";+ /// <summary>Bump it when RouteLayer.Geometry's rule changes (the constants are checked on their own), so CI fails a+ /// bake made by the old rule.</summary>+ public const int Version = 1;+ const int Magic = 0x31524353; // "SCR1"++ /// <summary>What the ribbons were made from, as the map read it.</summary>+ public readonly struct Source+ {+ public readonly int Resolution, HeightsCheck, MapCheck, RoutesCheck;+ public Source(int resolution, int heightsCheck, int mapCheck, int routesCheck)+ { Resolution = resolution; HeightsCheck = heightsCheck; MapCheck = mapCheck; RoutesCheck = routesCheck; }++ public static Source Of(float[,] heights, string heightmapJson, string routesYaml) =>+ new Source(heights.GetLength(1), MapBuilder.HeightsCheck(heights), Check(heightmapJson), Check(routesYaml));+ }++ /// <summary>FNV-1a over the text's UTF-8 bytes (the file's bytes: no BOM, LF by .gitattributes).</summary>+ public static int Check(string text)+ {+ uint h = 2166136261;+ foreach (var b in Encoding.UTF8.GetBytes(text ?? "")) { h ^= b; h *= 16777619; }+ return (int)h;+ }++ /// <summary>The constants the ribbons depend on, in the header's order (the Python test reads the same names).</summary>+ static float[] Floats => new[]+ {+ RouteLayer.RailWidthM, RouteLayer.RoadWidthM, RouteLayer.TrackWidthM, RouteLayer.StepM, RouteLayer.ClearanceM,+ RouteLayer.FallToleranceM, RouteLayer.RiseToleranceM, RouteLayer.MinWidthShare, RouteLayer.HalfWidthStepShare,+ RouteLayer.RailSpanShare, RouteLayer.RailClearanceM, MapBuilder.VerticalExaggeration,+ };+ static int[] Ints => new[] { RouteLayer.Across, RouteLayer.NarrowSamples, RouteLayer.LiftSamples };++ /// <summary>The bake of the map's inputs: the terrain as MapBuilder.Build makes it (at the origin, as MapScene's), the+ /// routes as MapScene reads them, every plan derived.</summary>+ public static byte[] Bake(MapInputs inputs)+ {+ var (meta, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16z);+ var data = new TerrainData { heightmapResolution = meta.width };+ try+ {+ data.size = MapBuilder.TerrainSize(meta);+ data.SetHeights(0, 0, heights);+ var frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, data.size.x, data.size.z);+ var routes = RoutePaths.ReadOrNone(inputs.RoutesYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), Debug.LogWarning);+ var plans = RouteLayer.Plan(routes);+ var ribbons = plans.ConvertAll(p => RouteLayer.Derive(p, frame, data, Vector3.zero));+ return Bytes(Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml), data.size, Vector3.zero, plans, ribbons);+ }+ finally { UnityEngine.Object.DestroyImmediate(data); }+ }++ public static byte[] Bytes(Source source, Vector3 size, Vector3 origin, IReadOnlyList<RouteLayer.RibbonPlan> plans,+ IReadOnlyList<RibbonGeometry> ribbons)+ {+ if (plans.Count != ribbons.Count) throw new ArgumentException("one ribbon a plan", nameof(ribbons));+ using var stream = new MemoryStream();+ using var w = new BinaryWriter(stream);+ foreach (var v in new[] { Magic, Version, source.Resolution, source.HeightsCheck, source.MapCheck, source.RoutesCheck }) w.Write(v);+ foreach (var f in new[] { size.x, size.y, size.z, origin.x, origin.y, origin.z }) w.Write(f);+ foreach (var f in Floats) w.Write(f);+ foreach (var i in Ints) w.Write(i);+ w.Write(plans.Count);+ for (int m = 0; m < plans.Count; m++)+ {+ var g = ribbons[m];+ WriteString(w, plans[m].MeshName);+ w.Write(g.Vertices.Length); w.Write(g.Indices.Length); w.Write(g.Routes.Length);+ foreach (var s in g.Routes)+ {+ WriteString(w, s.Id);+ w.Write(s.FirstVertex); w.Write(s.VertexCount); w.Write(s.FirstIndex); w.Write(s.IndexCount);+ }+ var floats = new float[g.Vertices.Length * 8];+ for (int i = 0, n = g.Vertices.Length; i < n; i++)+ {+ floats[3 * i] = g.Vertices[i].x; floats[3 * i + 1] = g.Vertices[i].y; floats[3 * i + 2] = g.Vertices[i].z;+ floats[3 * n + 3 * i] = g.Normals[i].x; floats[3 * n + 3 * i + 1] = g.Normals[i].y; floats[3 * n + 3 * i + 2] = g.Normals[i].z;+ floats[6 * n + 2 * i] = g.Uvs[i].x; floats[6 * n + 2 * i + 1] = g.Uvs[i].y;+ }+ var block = new byte[4 * (floats.Length + g.Indices.Length)];+ Buffer.BlockCopy(floats, 0, block, 0, 4 * floats.Length);+ Buffer.BlockCopy(g.Indices, 0, block, 4 * floats.Length, 4 * g.Indices.Length);+ w.Write(block);+ }+ w.Flush();+ return stream.ToArray();+ }++ static void WriteString(BinaryWriter w, string s)+ {+ var b = Encoding.UTF8.GetBytes(s);+ w.Write(b.Length); w.Write(b);+ }++ /// <summary>Reads the bake; false (and the reason) when it was not made from <paramref name="source"/>, for this+ /// terrain, with these constants and for these <paramref name="plans"/> (the same meshes, routes and order).</summary>+ public static bool TryRead(byte[]? bytes, Source source, Vector3 size, Vector3 origin, IReadOnlyList<RouteLayer.RibbonPlan> plans,+ out List<RibbonGeometry> ribbons, out string reason)+ {+ ribbons = new List<RibbonGeometry>();+ if (bytes == null || bytes.Length == 0) { reason = "missing"; return false; }+ var r = new Reader(bytes);+ try+ {+ if (r.Int() != Magic) { reason = "not a route ribbon bake"; return false; }+ int version = r.Int();+ if (version != Version) { reason = $"made by version {version}, this is {Version} (re-bake: RouteRibbonBake.Bake)"; return false; }+ int res = r.Int();+ if (res != source.Resolution) { reason = $"made for a {res} heightmap, this one is {source.Resolution}"; return false; }+ if (r.Int() != source.HeightsCheck) { reason = "made for other heights (re-bake: RouteRibbonBake.Bake)"; return false; }+ if (r.Int() != source.MapCheck) { reason = "made for another heightmap.json (re-bake: RouteRibbonBake.Bake)"; return false; }+ if (r.Int() != source.RoutesCheck) { reason = $"made for another {RoutePaths.DefaultFileName} (re-bake: RouteRibbonBake.Bake)"; return false; }+ var at = new Vector3(r.Float(), r.Float(), r.Float());+ var o = new Vector3(r.Float(), r.Float(), r.Float());+ if (!Same(at, size) || !Same(o, origin)) { reason = $"made for a terrain of size {at} at {o}, this one is {size} at {origin}"; return false; }+ foreach (var f in Floats)+ if (BitConverter.SingleToInt32Bits(r.Float()) != BitConverter.SingleToInt32Bits(f)) { reason = "made with other widths or spacing (re-bake: RouteRibbonBake.Bake)"; return false; }+ foreach (var i in Ints)+ if (r.Int() != i) { reason = "made with other sample counts (re-bake: RouteRibbonBake.Bake)"; return false; }+ int count = r.Int();+ if (count != plans.Count) { reason = $"holds {count} ribbons, the routes make {plans.Count}"; return false; }+ foreach (var plan in plans)+ {+ var name = r.Text();+ if (name != plan.MeshName) { reason = $"holds '{name}' where the routes make '{plan.MeshName}'"; return false; }+ int nv = r.Count(), ni = r.Count(), nr = r.Count();+ if (nr != plan.Routes.Count) { reason = $"'{name}' holds {nr} routes, the routes make {plan.Routes.Count}"; return false; }+ var spans = new RouteSpan[nr];+ for (int k = 0; k < nr; k++)+ {+ var id = r.Text();+ if (id != plan.Routes[k].Id) { reason = $"'{name}' holds '{id}' where the routes have '{plan.Routes[k].Id}'"; return false; }+ spans[k] = new RouteSpan(id, r.Int(), r.Int(), r.Int(), r.Int());+ }+ var floats = r.Floats(8 * nv);+ var verts = new Vector3[nv]; var normals = new Vector3[nv]; var uvs = new Vector2[nv];+ for (int i = 0; i < nv; i++)+ {+ verts[i] = new Vector3(floats[3 * i], floats[3 * i + 1], floats[3 * i + 2]);+ normals[i] = new Vector3(floats[3 * nv + 3 * i], floats[3 * nv + 3 * i + 1], floats[3 * nv + 3 * i + 2]);+ uvs[i] = new Vector2(floats[6 * nv + 2 * i], floats[6 * nv + 2 * i + 1]);+ }+ var indices = r.Ints(ni);+ foreach (var i in indices)+ if ((uint)i >= (uint)nv) { reason = $"'{name}' indexes a vertex it does not hold"; return false; }+ ribbons.Add(new RibbonGeometry(verts, normals, uvs, indices, spans));+ }+ if (!r.AtEnd) { reason = "longer than its meshes"; return false; }+ }+ catch (EndOfStreamException) { ribbons.Clear(); reason = "truncated"; return false; }+ reason = "";+ return true;+ }++ /// <summary>Equal, bit for bit (-0 and 0 apart: the bake writes what it was given).</summary>+ static bool Same(Vector3 a, Vector3 b) =>+ BitConverter.SingleToInt32Bits(a.x) == BitConverter.SingleToInt32Bits(b.x) && BitConverter.SingleToInt32Bits(a.y) == BitConverter.SingleToInt32Bits(b.y)+ && BitConverter.SingleToInt32Bits(a.z) == BitConverter.SingleToInt32Bits(b.z);++ /// <summary>Reads the file front to back; past its end it throws EndOfStreamException.</summary>+ sealed class Reader+ {+ readonly byte[] bytes; int at;+ public Reader(byte[] bytes) { this.bytes = bytes; }+ public bool AtEnd => at == bytes.Length;++ void Need(long n) { if (n < 0 || at + n > bytes.Length) throw new EndOfStreamException(); }+ public int Int() { Need(4); int v = BitConverter.ToInt32(bytes, at); at += 4; return v; }+ public float Float() { Need(4); float v = BitConverter.ToSingle(bytes, at); at += 4; return v; }+ /// <summary>A count: never negative.</summary>+ public int Count() { int n = Int(); if (n < 0) throw new EndOfStreamException(); return n; }+ public string Text() { int n = Count(); Need(n); var s = Encoding.UTF8.GetString(bytes, at, n); at += n; return s; }+ public float[] Floats(int n) { Need(4L * n); var a = new float[n]; Buffer.BlockCopy(bytes, at, a, 0, 4 * n); at += 4 * n; return a; }+ public int[] Ints(int n) { Need(4L * n); var a = new int[n]; Buffer.BlockCopy(bytes, at, a, 0, 4 * n); at += 4 * n; return a; }+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs.meta b/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs.metanew file mode 100644index 000000000..dae293f05--- /dev/null+++ b/unity/Assets/Scripts/Map/Routes/RouteRibbonFile.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: f334b1be4e704b3ba28044fd623ad62b\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/RouteTests.cs b/unity/Assets/Tests/EditMode/RouteTests.csindex 602e0c093..5d4fe8cc7 100644--- a/unity/Assets/Tests/EditMode/RouteTests.cs+++ b/unity/Assets/Tests/EditMode/RouteTests.cs@@ -825,4 +825,105 @@ public class RouteTests/// <summary>Bounds for the road test, set from its log.</summary>const float VergeStep = 0.04f, VergeBelowGround = 0.01f, PaleReadShare = 0.6f;++ /// <summary>Issue #321: the baked ribbons (RouteRibbonFile.AssetPath, Editor RouteRibbonBake.Bake) are what the shipped+ /// heightmap and route file give now, byte for byte; the map scene places them without deriving; and what it places+ /// equals what the map's own terrain derives, vertex for vertex, with each route's range in the index.</summary>+ [Test]+ public void TheBakedRibbonsMatchTheRoutes()+ {+ var inputs = Statecraft.Game.Boot.GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap);+ var baked = AssetDatabase.LoadAssetAtPath<TextAsset>(RouteRibbonFile.AssetPath);+ Assert.IsNotNull(baked, $"{RouteRibbonFile.AssetPath} is missing: run Statecraft.Game.EditorTools.RouteRibbonBake.Bake");+ CollectionAssert.AreEqual(RouteRibbonFile.Bake(inputs), baked.bytes, "stale: re-run Statecraft.Game.EditorTools.RouteRibbonBake.Bake");++ var derivedAtLoad = new List<string>();+ void Watch(string message, string stack, LogType type) { if (message.Contains("deriving the route ribbons")) derivedAtLoad.Add(message); }+ Application.logMessageReceived += Watch;+ MapScene map;+ try { map = BuildMap(); }+ finally { Application.logMessageReceived -= Watch; }+ try+ {+ CollectionAssert.IsEmpty(derivedAtLoad, "the map places the bake");+ var (_, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16z);+ var source = RouteRibbonFile.Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml);+ var plans = RouteLayer.Plan(RoutePaths.Parse(inputs.RoutesYaml, Bounds));+ var data = map.Terrain.terrainData; var origin = map.Terrain.transform.position;+ Assert.IsTrue(RouteRibbonFile.TryRead(baked.bytes, source, data.size, origin, plans, out var read, out var why), why);+ var placed = Ribbons(RoutesRoot(map), "Rail").Concat(Ribbons(RoutesRoot(map), "Roads"))+ .Select(f => f.sharedMesh).ToDictionary(m => m.name);+ Assert.AreEqual(plans.Count, placed.Count);+ for (int i = 0; i < plans.Count; i++)+ {+ var derived = RouteLayer.Derive(plans[i], map.Frame, data, origin);+ var name = plans[i].MeshName;+ CollectionAssert.AreEqual(derived.Vertices, read[i].Vertices, name);+ CollectionAssert.AreEqual(derived.Normals, read[i].Normals, name);+ CollectionAssert.AreEqual(derived.Uvs, read[i].Uvs, name);+ CollectionAssert.AreEqual(derived.Indices, read[i].Indices, name);+ CollectionAssert.AreEqual(derived.Routes, read[i].Routes, name);+ CollectionAssert.AreEqual(plans[i].Routes.Select(r => r.Id), read[i].Routes.Select(s => s.Id), name);+ Assert.AreEqual(derived.Vertices.Length, placed[name].vertexCount, name);+ Assert.AreEqual((uint)derived.Indices.Length, placed[name].GetIndexCount(0), name);+ }+ // Every route is in the index once, and its ranges tile its mesh.+ CollectionAssert.AreEquivalent(plans.SelectMany(p => p.Routes).Select(r => r.Id), read.SelectMany(g => g.Routes).Select(s => s.Id));+ foreach (var g in read)+ for (int k = 0; k < g.Routes.Length; k++)+ {+ var s = g.Routes[k];+ Assert.AreEqual(k == 0 ? 0 : g.Routes[k - 1].FirstVertex + g.Routes[k - 1].VertexCount, s.FirstVertex, s.Id);+ Assert.AreEqual(k == 0 ? 0 : g.Routes[k - 1].FirstIndex + g.Routes[k - 1].IndexCount, s.FirstIndex, s.Id);+ for (int i = s.FirstIndex; i < s.FirstIndex + s.IndexCount; i++)+ Assert.That(g.Indices[i], Is.InRange(s.FirstVertex, s.FirstVertex + s.VertexCount - 1), s.Id);+ }++ // A bake made from other inputs is refused.+ var other = new[]+ {+ new RouteRibbonFile.Source(source.Resolution, source.HeightsCheck + 1, source.MapCheck, source.RoutesCheck),+ new RouteRibbonFile.Source(source.Resolution, source.HeightsCheck, source.MapCheck + 1, source.RoutesCheck),+ new RouteRibbonFile.Source(source.Resolution, source.HeightsCheck, source.MapCheck, source.RoutesCheck + 1),+ };+ foreach (var s in other) Assert.IsFalse(RouteRibbonFile.TryRead(baked.bytes, s, data.size, origin, plans, out _, out _));+ Assert.IsFalse(RouteRibbonFile.TryRead(baked.bytes, source, data.size + Vector3.up, origin, plans, out _, out _), "another terrain size");+ Assert.IsFalse(RouteRibbonFile.TryRead(baked.bytes.Take(baked.bytes.Length - 1).ToArray(), source, data.size, origin, plans, out _, out why));+ Assert.AreEqual("truncated", why);+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>Issue #321: a stale bake is refused with a warning and the ribbons are derived at load, the same meshes as+ /// a build without the bake.</summary>+ [Test]+ public void AStaleRibbonBakeIsDerivedAtLoad()+ {+ var map = BuildMap();+ try+ {+ var inputs = Statecraft.Game.Boot.GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap);+ var (_, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16z);+ var routes = RoutePaths.Parse(inputs.RoutesYaml, Bounds);+ var stale = RouteRibbonFile.Source.Of(heights, inputs.HeightmapJson, inputs.RoutesYaml + "\n# edited");+ UnityEngine.TestTools.LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("deriving the route ribbons at load"));+ var root = RouteLayer.Build(map.Terrain, map.Frame, routes, RouteLayer.TrainMode.None, RouteLayer.DefaultDate, stale);+ try+ {+ var plans = RouteLayer.Plan(routes);+ var meshes = root.transform.Find(RouteLayer.RibbonsName).GetComponentsInChildren<MeshFilter>(true).Select(f => f.sharedMesh).ToList();+ Assert.AreEqual(plans.Count, meshes.Count);+ var data = map.Terrain.terrainData; var origin = map.Terrain.transform.position;+ for (int i = 0; i < plans.Count; i++)+ {+ var derived = RouteLayer.Derive(plans[i], map.Frame, data, origin);+ Assert.AreEqual(plans[i].MeshName, meshes[i].name);+ Assert.AreEqual(derived.Vertices.Length, meshes[i].vertexCount, plans[i].MeshName);+ Assert.AreEqual((uint)derived.Indices.Length, meshes[i].GetIndexCount(0), plans[i].MeshName);+ }+ }+ finally { Object.DestroyImmediate(root); }+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }}