A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Map: Tal's train runs on the 1948 railway in normal play (refs #668, #35) (#771)
Eyal Golana98bd0051348
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d837d3a1a..9f9297cfd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -130,6 +130,14 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBtown's Hebrew name), so the hillside hex's70 m does not read as the town's (refs #204). It is worked out in Unity from the town's own lon/lat and the hex grid(`InfoPanelPresenter.TownHex`), with no new `content/map/` field; an ordinary hex shows no such line.+- A steam train runs on the Jaffa–Jerusalem railway in normal play from 2 March 1950, the date regular service resumed+ (refs #668, #35; maintainer decision on #35, 16 October 2026). It runs from Lod to Jerusalem, sourced in+ `content/map/routes_1948.yaml` (Israel Railways, 1998), with the date awaiting the human check. Tel Aviv South to Lod+ is in the content too. It rests on Wikipedia alone, so it runs only once a person signs it off.+ The model is Tal's (@pixelrenderai-hash) locomotive and tender from The 1948 Collection. It leads three of the+ showcase's coaches, four articulated cars that ride the track (owner, 16 October 2026: "ride the track, cut walls"):+ on the Sorek valley's tightest bends their sides pass into the gorge walls. It streams only once the game date reaches+ the service, never at boot. If it does not stream, the game plays on without it and logs one warning.- Tal's (@pixelrenderai-hash) 23 single-building Tripo models from #507, imported for the strategic map (refs #659, step1): `unity/Assets/Art/Settlements/Prototype/Models/b*`, outside every `Resources/` folder, meshes compressed with noanimation, rig, tangents or Read/Write, colour maps committed and crunched at 512 px; `BuildingModelImportTests` pinsdiff --git a/content/map/route_paths_1948.tsv b/content/map/route_paths_1948.tsvindex d950e8386..042a8f75e 100644--- a/content/map/route_paths_1948.tsv+++ b/content/map/route_paths_1948.tsv@@ -1,7 +1,8 @@-# Generated by tools/route_paths_bake.py from route_paths_1948.yaml. Do not edit: edit the YAML (tools/routes_1948.py)+# Generated by tools/route_paths_bake.py from route_paths_1948.yaml and the services of routes_1948.yaml.+# Do not edit: edit the YAMLs (tools/routes_1948.py writes the first)# and rerun the tool. The runtime form the map reads at boot (map-only, outside the content hash).#route id kind status from to length_km on_symbol max_gap_m point_count points-meta version 2+meta version 3meta yaml_check 254700474meta routes 19route jaffa_jerusalem_railway rail draft 1920-10-05 79.4 1.0 65 113 34.76117 32.05894;34.76409 32.05996;34.76949 32.0605;34.77448 32.0603;34.77742 32.05924;34.78086 32.05571;34.78638 32.04568;34.79255 32.03932;34.81436 32.02349;34.83771 32.00775;34.84893 31.99572;34.8713 31.97509;34.88636 31.95755;34.88673 31.95516;34.88565 31.95368;34.87321 31.94354;34.87112 31.94135;34.86992 31.93914;34.8708 31.93573;34.87298 31.93191;34.87781 31.9283;34.88083 31.9234;34.88626 31.91762;34.88954 31.90869;34.88909 31.90734;34.88636 31.90467;34.87678 31.89781;34.87057 31.88903;34.87168 31.87982;34.87147 31.87482;34.86603 31.86169;34.86775 31.85101;34.87009 31.84463;34.87058 31.84073;34.86979 31.82851;34.86722 31.81997;34.86949 31.81555;34.87025 31.8114;34.87181 31.80857;34.87557 31.80583;34.88764 31.79956;34.89363 31.79506;34.90035 31.78828;34.92253 31.76821;34.92847 31.76507;34.93797 31.75898;34.94668 31.759;34.95347 31.75656;34.95884 31.756;34.97276 31.75634;34.98381 31.75799;35.00674 31.75687;35.01071 31.75768;35.01722 31.76211;35.03203 31.76215;35.03544 31.7646;35.03876 31.7659;35.0477 31.76358;35.05046 31.75846;35.05232 31.75727;35.0651 31.76556;35.0675 31.76593;35.06883 31.76475;35.06934 31.76031;35.06539 31.75626;35.06483 31.75461;35.06613 31.75284;35.06934 31.7512;35.0737 31.75011;35.07778 31.75009;35.08386 31.75723;35.08588 31.75852;35.08703 31.7586;35.08797 31.75729;35.08624 31.75413;35.08606 31.7517;35.08691 31.75108;35.09144 31.7511;35.09289 31.75045;35.09369 31.74963;35.09485 31.74558;35.0958 31.7445;35.10339 31.74279;35.11714 31.73811;35.11861 31.7385;35.12205 31.74277;35.12356 31.74337;35.12516 31.74331;35.12622 31.74156;35.1248 31.73751;35.12586 31.73527;35.12727 31.73454;35.12892 31.73445;35.13344 31.73692;35.13546 31.73692;35.13697 31.73577;35.13836 31.73204;35.13999 31.7312;35.14144 31.73175;35.15582 31.74346;35.16043 31.74566;35.16454 31.74553;35.1731 31.74401;35.17851 31.74412;35.18192 31.74515;35.1869 31.74832;35.19691 31.75147;35.19855 31.75147;35.20436 31.74975;35.20594 31.74999;35.21073 31.75343;35.21583 31.75941;35.22466 31.76678@@ -23,4 +24,5 @@ route jerusalem_jericho_road road draft 1946 32.1 0.96 439 58 35.22569 31.77933route tiberias_metula_road road draft 1946 58.1 0.91 418 68 35.5333 32.79442;35.5347 32.79877;35.53443 32.79938;35.5301 32.80216;35.52206 32.80947;35.51652 32.8195;35.51035 32.82659;35.50947 32.82961;35.5091 32.83631;35.5112 32.84125;35.52729 32.86386;35.53054 32.86931;35.53135 32.87008;35.53704 32.87211;35.54324 32.87688;35.5453 32.88023;35.54743 32.88644;35.54815 32.88771;35.54938 32.88827;35.54938 32.88926;35.54468 32.89726;35.54073 32.90223;35.54129 32.90344;35.54597 32.90579;35.54717 32.908;35.5443 32.91347;35.54335 32.91767;35.54277 32.93459;35.54487 32.94166;35.54313 32.94898;35.54158 32.95958;35.54332 32.96352;35.55158 32.97443;35.55511 32.98097;35.56398 33.00276;35.56361 33.00437;35.56096 33.00866;35.56213 33.0135;35.56791 33.01741;35.5697 33.02098;35.57069 33.02558;35.57107 33.03424;35.57067 33.04831;35.57396 33.0701;35.57266 33.0837;35.57341 33.09084;35.57343 33.09915;35.57092 33.12213;35.56822 33.13337;35.56943 33.14627;35.56953 33.15855;35.56847 33.16965;35.56558 33.17735;35.56508 33.18709;35.56536 33.19029;35.56739 33.19637;35.56935 33.21646;35.57048 33.21911;35.57522 33.22585;35.58054 33.24196;35.58022 33.24335;35.57778 33.24568;35.57213 33.2485;35.56961 33.25645;35.56981 33.26356;35.57424 33.27074;35.57577 33.27765;35.57536 33.27881route gaza_beersheba_road road draft 1946 45.7 0.96 358 55 34.46076 31.50912;34.47082 31.50312;34.47832 31.49745;34.48678 31.48862;34.49413 31.48278;34.50074 31.48077;34.51565 31.47893;34.52217 31.47653;34.53546 31.46778;34.55457 31.4573;34.56223 31.45227;34.57343 31.44743;34.58375 31.44173;34.59115 31.43592;34.59975 31.43088;34.60654 31.42227;34.61073 31.41522;34.61335 31.40248;34.61381 31.39021;34.61443 31.38667;34.61648 31.38162;34.61798 31.37574;34.62574 31.36641;34.64298 31.34962;34.64656 31.34717;34.65213 31.3447;34.65326 31.34334;34.65456 31.3398;34.65938 31.33669;34.67004 31.33302;34.67413 31.33319;34.68023 31.33475;34.68994 31.33366;34.69523 31.33394;34.69658 31.33321;34.70012 31.32881;34.7032 31.32372;34.70385 31.32133;34.70374 31.31355;34.70853 31.30754;34.70998 31.30094;34.71155 31.29774;34.71528 31.29493;34.72196 31.29137;34.72622 31.28793;34.73484 31.27907;34.73726 31.27572;34.73971 31.27084;34.74254 31.26831;34.75433 31.2616;34.76189 31.25557;34.77332 31.25226;34.78395 31.24652;34.78499 31.24626;34.78538 31.24664route beersheba_auja_road road draft 1946 69.9 0.97 261 77 34.78538 31.24664;34.78695 31.24386;34.79402 31.23727;34.79753 31.23201;34.80098 31.22072;34.80203 31.21544;34.80401 31.21001;34.80492 31.20399;34.80684 31.19738;34.80706 31.18043;34.80472 31.164;34.80613 31.15516;34.80491 31.14671;34.80542 31.13519;34.80651 31.1299;34.80798 31.1266;34.81171 31.12141;34.82035 31.11128;34.82177 31.108;34.82207 31.10204;34.82303 31.10092;34.82794 31.09776;34.82993 31.09167;34.83409 31.08549;34.83908 31.07546;34.83842 31.06632;34.83379 31.06149;34.83102 31.0565;34.80519 31.0366;34.79032 31.02098;34.78129 31.01459;34.77774 31.01282;34.77578 31.01246;34.76346 31.01561;34.76158 31.01531;34.7609 31.01406;34.75921 31.00408;34.76199 30.99334;34.76134 30.99179;34.75216 30.98452;34.72421 30.971;34.71105 30.96099;34.70396 30.9572;34.69683 30.95518;34.6775 30.95208;34.67385 30.9485;34.66057 30.94707;34.65502 30.9457;34.65323 30.94433;34.64789 30.93636;34.64092 30.93199;34.6349 30.92653;34.63194 30.92465;34.62888 30.92364;34.62487 30.9232;34.61728 30.92787;34.60679 30.93019;34.60518 30.92916;34.60133 30.92297;34.59443 30.91981;34.58566 30.91813;34.58336 30.91617;34.57899 30.91098;34.57525 30.90814;34.5551 30.90038;34.55032 30.8995;34.54487 30.90086;34.53995 30.90142;34.52619 30.90204;34.52124 30.90158;34.50057 30.89494;34.4856 30.8939;34.48196 30.89325;34.44598 30.88287;34.43721 30.88089;34.43465 30.87916;34.43364 30.8777-meta body_check -352026697+service jaffa_jerusalem_railway 1950-03-02 34.87556 31.94583 35.22471 31.76685+meta body_check -1423678488diff --git a/content/map/routes_1948.yaml b/content/map/routes_1948.yamlindex 6f75eea95..0e2c5356e 100644--- a/content/map/routes_1948.yaml+++ b/content/map/routes_1948.yaml@@ -23,6 +23,11 @@# from / to: the window in which the map draws the route (RouteLayer shows it while the game date is inside it): a year# or a 'YYYY-MM-DD' date, quoted. `from` is the earliest date the cited sources support for the whole line as drawn# (1946, the map's date, where no source gives an earlier one); `to` is left out while the line still exists.+# service (a railway only, optional): the train in normal play, from the sourced date regular service on the line+# resumed (`from`), with its own status, to_verify and sources, and its stretches: in order along the line, each between+# two named stations (start, end: with coordinates and a url, as the waypoints), with a status and sources; a stretch+# with `gated: true` runs only once a person has signed it off. tools/route_paths_bake.py gives the map the span of the+# stretches that run.map_source:name: Survey of Palestine, Palestine 1:250,000, 1946 (three sheets)url: https://palopenmaps.org/en/maps?basemap=pal250k1946@@ -61,6 +66,56 @@ routes:checked: '2026-10-11'- url: https://en.wikipedia.org/wiki/Palestine_Railwayschecked: '2026-10-11'+ # service: the train in normal play (maintainer decision on #35, 16 October 2026; issue #668), from the date regular+ # service resumed after the 1948 war. No train runs on the line before `from`.+ service:+ from: '1950-03-02'+ status: draft+ note: Israel Railways opened a regular passenger service from Haifa to Jerusalem on 2 March 1950, one train a day+ each way, about four hours, by the old Tel Aviv North station (Bnei Brak) on the Eastern Railway (Israel Railways,+ 50 Years of Israel Railways, 1998, p. 15; Jaffa–Jerusalem railway). That service joined this line at Lod, so on this+ line it ran from Lod to Jerusalem. The symbolic first train to Jerusalem, which carried flour and Torah scrolls, was+ not a regular service and is not counted; its date is in to_verify.+ to_verify:+ - The date awaits a human check against the cited sources (CONTENT_POLICY section 2.6). The 1998 booklet is a scan+ with no text layer; its sentence was read from the page image. A contemporary report, Al HaMishmar of 1 March+ 1950 ("tomorrow a passenger train from Haifa and Tel Aviv to Jerusalem"), is cited by he Wikipedia and was not+ opened.+ - The sources disagree on the symbolic first train to Jerusalem, 17 August 1948 in the 1998 booklet (Israel Railways,+ 1998, p. 15, the same page as the 2 March 1950 service) and 7 August 1949 in Jaffa–Jerusalem railway (en+ Wikipedia). The game uses neither date; it is left to the human check.+ sources:+ - url: https://web.archive.org/web/20140327112217/http://www.rail.co.il/HE/Fun/Museum/Documents/50Years.pdf+ checked: '2026-10-16'+ - url: https://en.wikipedia.org/wiki/Jaffa%E2%80%93Jerusalem_railway+ checked: '2026-10-16'+ # stretches: the line's stretches the train may run, in order along it, each ending where the next starts. A gated+ # stretch runs only once a person has signed it off (reviewed_by and reviewed_on beside its status, as every status+ # row; docs/HISTORIAN_REVIEW.md); the others run from `from`. tools/route_paths_bake.py gives the map the span of the+ # stretches that run.+ stretches:+ - start: {name: Tel Aviv South railway station (Beit Hadar, its 1920-1970 site), lon: 34.777, lat: 32.0636, url: 'https://en.wikipedia.org/wiki/Tel_Aviv_South_railway_station'}+ end: {name: Lod railway station, lon: 34.87556, lat: 31.94583, url: 'https://en.wikipedia.org/wiki/Lod_railway_station'}+ gated: true+ status: draft+ note: A connecting train between Tel Aviv South and Lod from 2 March 1950 (he Wikipedia, the Jaffa–Jerusalem+ railway and Israel Railways). The 1998 booklet does not name it, so it rests on Wikipedia alone and runs only+ once a person has checked it. The track from Tel Aviv South to Jaffa station was lifted in September 1949, when+ Tel Aviv South became the terminus (Tel Aviv South railway station), so no train runs to Jaffa.+ sources:+ - url: https://he.wikipedia.org/wiki/%D7%9E%D7%A1%D7%99%D7%9C%D7%AA_%D7%94%D7%A8%D7%9B%D7%91%D7%AA_%D7%99%D7%A4%D7%95%E2%80%93%D7%99%D7%A8%D7%95%D7%A9%D7%9C%D7%99%D7%9D+ checked: '2026-10-16'+ - url: https://he.wikipedia.org/wiki/%D7%A8%D7%9B%D7%91%D7%AA_%D7%99%D7%A9%D7%A8%D7%90%D7%9C+ checked: '2026-10-16'+ - url: https://en.wikipedia.org/wiki/Tel_Aviv_South_railway_station+ checked: '2026-10-16'+ - start: {name: Lod railway station, lon: 34.87556, lat: 31.94583, url: 'https://en.wikipedia.org/wiki/Lod_railway_station'}+ end: {name: Jerusalem (Khan) railway station, lon: 35.22471, lat: 31.76685, url: 'https://www.wikidata.org/wiki/Q2920513'}+ status: draft+ note: The Haifa–Jerusalem service's stretch on this line (Israel Railways, 1998, p. 15).+ sources:+ - url: https://web.archive.org/web/20140327112217/http://www.rail.co.il/HE/Fun/Museum/Documents/50Years.pdf+ checked: '2026-10-16'- id: kantara_main_line_southname: Haifa–El Kantara main line (Lydda to Rafah)kind: raildiff --git a/tools/route_paths_bake.py b/tools/route_paths_bake.pyindex a7b8725c3..179bb06ea 100644--- a/tools/route_paths_bake.py+++ b/tools/route_paths_bake.py@@ -16,10 +16,16 @@ with a warning, when either does not match. Rows, tab-separated:meta routes <number of route rows>route id kind status from to length_km on_symbol max_gap_m point_count points...+ service route_id from start end (one per route with a `service` in routes_1948.yaml, issue #668)+ ...meta body_check <signed int32> (the last row)+A service row is a railway's train service: the date regular service resumed (`from`) and the stretch's two ends as+"lon lat" (start, end), read from routes_1948.yaml (the sourced, hand-written file the map never reads), so the train's+date and stretch come from the content. A service changes neither route_paths_1948.yaml nor the ribbon bake.+`to` is empty when the route has no end; `points` is "lon lat" pairs joined by ';', each number as Python's shortest-round-trip form of the YAML's value. `body_check` is FNV-1a over the UTF-8 bytes of every route row, each with its+round-trip form of the YAML's value. `body_check` is FNV-1a over the UTF-8 bytes of every route and service row, each with its'\n', in order. The reader requires it as the last row and recomputes it, so a file cut anywhere (even inside anumber, review of #547) or edited by hand is refused; the counts give the clearer message for a lost row or point. Lines starting with '#' are comments. No field may hold a tab or a line break.@@ -34,11 +40,13 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.pathimport yaml12 # noqa: E402+import review_record # noqa: E402ROOT = Path(__file__).resolve().parents[1]SOURCE = ROOT / "content" / "map" / "route_paths_1948.yaml"+ROUTES = ROOT / "content" / "map" / "routes_1948.yaml" # the services (issue #668)RUNTIME = ROOT / "content" / "map" / "route_paths_1948.tsv"-VERSION = 2 # RoutePaths.RuntimeVersion (2: the body_check row, review of #547)+VERSION = 3 # RoutePaths.RuntimeVersion (2: the body_check row, review of #547; 3: the service rows, #668)COLUMNS = ["route", "id", "kind", "status", "from", "to", "length_km", "on_symbol", "max_gap_m", "point_count", "points"]@@ -51,7 +59,7 @@ def yaml_check(data: bytes) -> int:def body_check(rows: list[str]) -> int:- """RoutePaths.BodyCheck: FNV-1a over the route rows' UTF-8 bytes, each followed by '\n', as a signed int32."""+ """RoutePaths.BodyCheck: FNV-1a over the route and service rows' UTF-8 bytes, each followed by '\n', as a signed int32."""return yaml_check("".join(r + "\n" for r in rows).encode("utf-8"))@@ -68,11 +76,26 @@ def _field(value, where: str) -> str:return text-def bake(data: bytes) -> str:- """The runtime file for the YAML file's bytes: deterministic, so a fresh bake equals the committed file."""+def running_span(service: dict) -> tuple[dict, dict] | None:+ """The (start, end) stations of the service's stretches that run: every stretch but a gated one a person has not+ signed off. They must be one unbroken run along the line; None when none runs."""+ runs = [not x.get("gated", False) or review_record.signed(x) for x in service["stretches"]]+ if not any(runs):+ return None+ first, last = runs.index(True), len(runs) - 1 - runs[::-1].index(True)+ if not all(runs[first:last + 1]):+ raise ValueError("a gated stretch that does not run lies between two that do: the train's span would jump it")+ return service["stretches"][first]["start"], service["stretches"][last]["end"]+++def bake(data: bytes, routes: bytes) -> str:+ """The runtime file for the YAML file's bytes and routes_1948.yaml's (the services): deterministic, so a fresh bake+ equals the committed file."""doc = yaml12.load(data.decode("utf-8"))+ sourced = yaml12.load(routes.decode("utf-8"))["routes"]out = [- "# Generated by tools/route_paths_bake.py from route_paths_1948.yaml. Do not edit: edit the YAML (tools/routes_1948.py)",+ "# Generated by tools/route_paths_bake.py from route_paths_1948.yaml and the services of routes_1948.yaml.",+ "# Do not edit: edit the YAMLs (tools/routes_1948.py writes the first)","# and rerun the tool. The runtime form the map reads at boot (map-only, outside the content hash).","#" + "\t".join(COLUMNS),f"meta\tversion\t{VERSION}",@@ -86,6 +109,19 @@ def bake(data: bytes) -> str:row = ["route", r["id"], r["kind"], r["status"], r["from"], r.get("to") or "", _number(r["length_km"], where),_number(r["on_symbol"], where), _number(r["max_gap_m"], where), str(len(r["points"]))]rows.append("\t".join(_field(v, where) for v in row) + "\t" + points)+ traced = {r["id"] for r in doc["routes"]}+ for r in sourced:+ s = r.get("service")+ if s is None:+ continue+ where = f"route '{r.get('id')}' service"+ if r["id"] not in traced:+ raise ValueError(f"{ROUTES.name}: {where}: the route is not in {SOURCE.name}")+ span = running_span(s)+ if span is None:+ continue # every stretch is gated and none is signed off: no train+ ends = [f"{_number(w['lon'], where)} {_number(w['lat'], where)}" for w in span]+ rows.append("\t".join(_field(v, where) for v in ["service", r["id"], s["from"], *ends]))out += rowsout.append(f"meta\tbody_check\t{body_check(rows)}")return "\n".join(out) + "\n"@@ -95,7 +131,7 @@ def main() -> int:ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])ap.add_argument("--check", action="store_true", help="fail when the committed runtime file is stale")args = ap.parse_args()- fresh = bake(SOURCE.read_bytes())+ fresh = bake(SOURCE.read_bytes(), ROUTES.read_bytes())if args.check:current = RUNTIME.read_text(encoding="utf-8") if RUNTIME.exists() else ""if current != fresh:diff --git a/tools/routes_1948.py b/tools/routes_1948.pyindex 7a4a0a3ae..08cbb64be 100644--- a/tools/routes_1948.py+++ b/tools/routes_1948.py@@ -488,6 +488,57 @@ def validate_routes(doc: dict, bounds: dict) -> None:srcs = r.get("sources") or []if not srcs or not all(str(s.get("url", "")).startswith("https://") and s.get("checked") for s in srcs):raise ValueError(f"{rid}: every route needs sources with an https url and a checked date")+ if "service" in r:+ _validate_service(rid, r, window[0], bounds)+++def _station_problem(w) -> bool:+ return not (isinstance(w, dict) and w.get("name") and str(w.get("url", "")).startswith("https://"))+++def _validate_service(rid: str, r: dict, route_from: date, bounds: dict) -> None:+ """A railway's train service (issue #668): a sourced start date inside the route's window and its stretches, in order+ along the line, each between two named stations on the map and ending where the next starts. A stretch with+ `gated: true` runs only once a person signs it off (tools/route_paths_bake.py)."""+ s = r["service"]+ if r["kind"] != "rail" or not isinstance(s, dict):+ raise ValueError(f"{rid}: a service only on a railway, as a mapping")+ v = s.get("from")+ if not isinstance(v, str) or not DATE_RULE.fullmatch(v):+ raise ValueError(f"{rid}: service from must be a quoted 'YYYY' or 'YYYY-MM-DD'")+ if _as_date(v) < route_from:+ raise ValueError(f"{rid}: service from ({v}) is before the route's from")+ if s.get("status") not in STATUSES:+ raise ValueError(f"{rid}: service status must be one of {STATUSES}")+ if not _sourced(s):+ raise ValueError(f"{rid}: the service needs sources with an https url and a checked date")+ stretches = s.get("stretches")+ if not isinstance(stretches, list) or not stretches:+ raise ValueError(f"{rid}: the service needs stretches")+ for n, x in enumerate(stretches, 1):+ at = f"{rid}: service stretch {n}"+ for key in ("start", "end"):+ w = x.get(key) if isinstance(x, dict) else None+ lon, lat = (w.get("lon"), w.get("lat")) if isinstance(w, dict) else (None, None)+ if _station_problem(w) or not (isinstance(lon, (int, float)) and isinstance(lat, (int, float))+ and bounds["lon0"] <= lon <= bounds["lon1"] and bounds["lat0"] <= lat <= bounds["lat1"]):+ raise ValueError(f"{at} {key} needs a name, an https url and a lon/lat on the map")+ if not isinstance(x.get("gated", False), bool):+ raise ValueError(f"{at} gated must be true or false")+ if x.get("status") not in STATUSES:+ raise ValueError(f"{at} status must be one of {STATUSES}")+ signoff = review_record.problem(x)+ if signoff:+ raise ValueError(f"{at} {signoff[0]} {signoff[1]}")+ if not _sourced(x):+ raise ValueError(f"{at} needs sources with an https url and a checked date")+ if n > 1 and (x["start"]["lon"], x["start"]["lat"]) != (stretches[n - 2]["end"]["lon"], stretches[n - 2]["end"]["lat"]):+ raise ValueError(f"{rid}: service stretch {n} does not start where stretch {n - 1} ends")+++def _sourced(row: dict) -> bool:+ srcs = row.get("sources") or []+ return bool(srcs) and all(str(x.get("url", "")).startswith("https://") and x.get("checked") for x in srcs)HEADER = """\diff --git a/tools/tests/test_route_paths_bake.py b/tools/tests/test_route_paths_bake.pyindex 6f40bf9c9..aff0f878a 100644--- a/tools/tests/test_route_paths_bake.py+++ b/tools/tests/test_route_paths_bake.py@@ -25,7 +25,7 @@ REBAKE = "run uv run tools/route_paths_bake.py"# The fingerprint of the readers (code_fingerprint). Re-pin only after RoutePathsRuntimeTests passes in Unity, with# RoutePaths.RuntimeVersion and route_paths_bake.VERSION bumped together if the runtime layout changed.-PINNED_CODE = "a7cc9cf147bca7ec7bcf3a769fd86550bd4a92bbcfeea98ab0f74e60908fca00"+PINNED_CODE = "ea5cd1dccf91f9cc5f5824104546f95e2281925c6b7e6bb6f7bfcbd414e2bf8d"def member(text: str, signature: str) -> str:@@ -61,7 +61,7 @@ def code_fingerprint() -> str:def test_the_runtime_file_is_the_bake_of_the_yaml():- assert bake.RUNTIME.read_text(encoding="utf-8") == bake.bake(bake.SOURCE.read_bytes()), f"stale: {REBAKE}"+ assert bake.RUNTIME.read_text(encoding="utf-8") == bake.bake(bake.SOURCE.read_bytes(), bake.ROUTES.read_bytes()), f"stale: {REBAKE}"def test_the_bake_and_the_reader_share_a_version():@@ -82,12 +82,60 @@ def test_the_check_is_the_ribbon_bakes():def test_the_file_ends_with_its_body_check():- """The last row is body_check over the route rows (review of #547, S1): a file cut anywhere, even inside a number,- loses it or no longer matches it, and RoutePaths.RuntimeRows refuses it."""+ """The last row is body_check over the route and service rows (review of #547, S1; #668): a file cut anywhere, even+ inside a number, loses it or no longer matches it, and RoutePaths.RuntimeRows refuses it."""lines = bake.RUNTIME.read_text(encoding="utf-8").rstrip("\n").split("\n")kind, name, value = lines[-1].split("\t")assert (kind, name) == ("meta", "body_check")- rows = [line for line in lines if line.startswith("route\t")]+ rows = [line for line in lines if line.startswith(("route\t", "service\t"))]assert int(value) == bake.body_check(rows)cut = rows[-1][:-1] # the last number a digit shortassert bake.body_check(rows[:-1] + [cut]) != int(value)+++def test_the_runtime_file_carries_the_train_service():+ """Issue #668: the train's date and the span of its stretches that run reach the map through the runtime file (the map+ does not read routes_1948.yaml), one service row per route that has one, after the route rows and inside the body+ check. Tel Aviv South to Lod is gated and not signed off, so the train runs from Lod to Jerusalem."""+ lines = bake.RUNTIME.read_text(encoding="utf-8").rstrip("\n").split("\n")+ services = [line.split("\t") for line in lines if line.startswith("service\t")]+ assert services == [["service", "jaffa_jerusalem_railway", "1950-03-02", "34.87556 31.94583", "35.22471 31.76685"]]+ rows = [line for line in lines if line.startswith(("route\t", "service\t"))]+ assert rows[-1].startswith("service\t"), "the service rows follow the route rows"+ assert int(lines[-1].split("\t")[2]) == bake.body_check(rows), "the body check covers the service rows too"+++def _service_row(routes_text: str) -> list[str] | None:+ tsv = bake.bake(bake.SOURCE.read_bytes(), routes_text.encode("utf-8"))+ rows = [line.split("\t") for line in tsv.split("\n") if line.startswith("service\t")]+ return rows[0] if rows else None+++def _routes_with(edit) -> str:+ import yaml12+ doc = yaml12.load(bake.ROUTES.read_text(encoding="utf-8"))+ edit(next(r for r in doc["routes"] if r["id"] == "jaffa_jerusalem_railway")["service"])+ import yaml+ return yaml.safe_dump(doc, allow_unicode=True, sort_keys=False)+++def test_a_gated_stretch_draws_no_train_until_a_person_signs_it_off():+ """The gate (issue #668): Tel Aviv South to Lod, on Wikipedia alone, is not in the train's span while unsigned..."""+ row = _service_row(_routes_with(lambda s: None))+ assert row[3] == "34.87556 31.94583", "the train starts at Lod"+++def test_once_signed_off_the_gated_stretch_draws():+ """... and once a person signs it off (reviewed_by and reviewed_on, the repository's sign-off), the train runs from+ Tel Aviv South, a content edit only."""+ def sign(s):+ s["stretches"][0].update({"reviewed_by": "a-historian", "reviewed_on": "2026-10-20"})+ row = _service_row(_routes_with(sign))+ assert row[3:] == ["34.777 32.0636", "35.22471 31.76685"], "Tel Aviv South to Jerusalem"+++def test_no_stretch_that_runs_means_no_service_row():+ def gate_all(s):+ for x in s["stretches"]:+ x["gated"] = True+ assert _service_row(_routes_with(gate_all)) is Nonediff --git a/tools/tests/test_routes_1948.py b/tools/tests/test_routes_1948.pyindex d0dc1529d..f5012a920 100644--- a/tools/tests/test_routes_1948.py+++ b/tools/tests/test_routes_1948.py@@ -257,3 +257,77 @@ def test_validate_accepts_a_whole_sign_off():doc = yaml12.load((ROOT / "content" / "map" / "routes_1948.yaml").read_text(encoding="utf-8"))doc["routes"][0].update({"reviewed_by": "eyalgolan", "reviewed_on": "2026-10-15"})rt.validate_routes(doc, BOUNDS)+++def test_the_train_service_is_sourced_and_on_the_line():+ """Issue #668 (maintainer decision on #35, 16 October 2026): a train on the Jaffa-Jerusalem line in normal play only+ from the sourced date regular service resumed, 2 March 1950. Its stretches run in order along the traced line, each+ ending where the next starts; Tel Aviv South to Lod rests on Wikipedia alone, so it is gated on a person's check."""+ src = next(r for r in ROUTES["routes"] if r["id"] == "jaffa_jerusalem_railway")+ service = src["service"]+ assert service["from"] == "1950-03-02"+ assert service["status"] == "draft", "the date awaits the human check (CONTENT_POLICY section 2.6)"+ assert service["to_verify"]+ stretches = service["stretches"]+ assert [(s["start"]["name"].split(" (")[0], s["end"]["name"].split(" (")[0], s.get("gated", False)) for s in stretches] == [+ ("Tel Aviv South railway station", "Lod railway station", True), ("Lod railway station", "Jerusalem", False)]+ assert not any("reviewed_by" in s for s in stretches), "only a person signs a stretch off"+ points = [tuple(p) for p in BY_ID["jaffa_jerusalem_railway"]["points"]]+ for s in stretches:+ assert all(x["url"].startswith("https://") and x["checked"] for x in s["sources"])+ for end in ("start", "end"):+ lonlat = (s[end]["lon"], s[end]["lat"])+ nearest_km = min(rt.km_between(lonlat, p) for p in points)+ assert nearest_km < 1.0, f"{s[end]['name']} is {nearest_km:.2f} km off the traced line"+ assert [r["id"] for r in ROUTES["routes"] if "service" in r] == ["jaffa_jerusalem_railway"], "one train (#668)"+++def _service_doc():+ doc = yaml12.load((ROOT / "content" / "map" / "routes_1948.yaml").read_text(encoding="utf-8"))+ return doc, next(r for r in doc["routes"] if r["id"] == "jaffa_jerusalem_railway")["service"]++[email protected]("change, message", [+ ({"from": "1950-3-2"}, "service from must be a quoted"),+ ({"from": "1900"}, "service from .* is before the route's from"),+ ({"sources": []}, "service needs sources"),+ ({"sources": [{"url": "http://x", "checked": "2026-10-16"}]}, "service needs sources"),+ ({"status": "approved"}, "service status"),+ ({"stretches": []}, "service needs stretches"),+])+def test_validate_rejects_a_bad_service(change, message):+ doc, service = _service_doc()+ service.update(change)+ with pytest.raises(ValueError, match=message):+ rt.validate_routes(doc, BOUNDS)++[email protected]("change, message", [+ ({"start": None}, "stretch 1 start"),+ ({"end": {"name": "x", "lon": 40.0, "lat": 31.7, "url": "https://x"}}, "stretch 1 end"),+ ({"end": {"name": "x", "lon": 35.2, "lat": 31.7, "url": "http://x"}}, "stretch 1 end"),+ ({"gated": "yes"}, "stretch 1 gated"),+ ({"status": "approved"}, "stretch 1 status"),+ ({"sources": []}, "stretch 1 needs sources"),+ ({"reviewed_by": "someone"}, "stretch 1 reviewed_on"),+])+def test_validate_rejects_a_bad_stretch(change, message):+ doc, service = _service_doc()+ service["stretches"][0].update(change)+ with pytest.raises(ValueError, match=message):+ rt.validate_routes(doc, BOUNDS)+++def test_validate_rejects_stretches_that_do_not_meet():+ doc, service = _service_doc()+ service["stretches"][1]["start"] = dict(service["stretches"][1]["start"], lon=34.9)+ with pytest.raises(ValueError, match="stretch 2 does not start where stretch 1 ends"):+ rt.validate_routes(doc, BOUNDS)+++def test_validate_rejects_a_service_on_a_road():+ doc, service = _service_doc()+ road = next(r for r in doc["routes"] if r["kind"] == "road")+ road["service"] = service+ with pytest.raises(ValueError, match="service only on a railway"):+ rt.validate_routes(doc, BOUNDS)diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex 081fa7c44..a67a30b22 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -396,7 +396,8 @@ 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. The ribbons are+ // file means no routes and a warning; the promo's train in screenshots, editor renders and ?train, and in normal play+ // 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));diff --git a/unity/Assets/Scripts/Map/Routes/RouteLayer.cs b/unity/Assets/Scripts/Map/Routes/RouteLayer.csindex 0d8b151be..3d90991a3 100644--- a/unity/Assets/Scripts/Map/Routes/RouteLayer.cs+++ b/unity/Assets/Scripts/Map/Routes/RouteLayer.cs@@ -11,7 +11,8 @@ namespace Statecraft.Game.Map.Routes/// Statecraft/Route materials in Resources (no runtime Shader.Find, no new serialized field on MapScene). Each route/// shows only while the game date is inside its window (RoutePath.From/To; review C1: the Burma Road from 14 June/// 1948): routes are grouped by window, one ribbon pair per group, and <see cref="ShowAt"/> switches the groups. A- /// steam train on the Jaffa–Jerusalem line is a showcase, never normal play (review I1, <see cref="ModeFor"/>). Widths are symbolic, measured on the+ /// steam train runs on the Jaffa–Jerusalem line: in normal play only from the sourced date regular service resumed+ /// (<see cref="ServiceTrain"/>, issue #668), and as the promo's showcase in screenshots and `?train` (<see cref="ModeFor"/>). Widths are symbolic, measured on the/// promo's gameplay frame like the settlements and units (docs/routes.md): a road's pale core about 8 px and the railway/// about 16 px wide at 1920 px (the soft edges take about a sixth of the railway's width, so its bed is drawn 680 m), so they read at the gameplay zoom as the promo draws them. Registers the "routes" (ribbons)/// and "train" visual toggles, so the frame profile prices each. Pure geometry from the data: the same file gives the@@ -35,10 +36,13 @@ namespace Statecraft.Game.Map.Routes/// <summary>Height above the highest ground sampled around each vertex; the shader's depth offset does the rest.</summary>public const float ClearanceM = 20f;- /// <summary>The showcase train's route and stretch: the Jaffa–Jerusalem railway from its Jaffa end to Lydda junction,- /// the stretch the promo's train runs (promo/final/03). It is ambience for the promo frames, not a timetable: no- /// regular trains ran here from the British withdrawal in May 1948 until Lydda was taken in July and service resumed- /// later (Palestine Railways), which is why normal play shows no train (<see cref="ModeFor"/>).</summary>+ /// <summary>The train's route: the Jaffa–Jerusalem railway. The showcase runs from its Jaffa end to Lydda junction+ /// (<see cref="TrainTurnAt"/>), the stretch the promo's train runs (promo/final/03): ambience for the promo frames, not+ /// a timetable. No regular trains ran on the line from the British withdrawal in May 1948 until 2 March 1950, after+ /// Lydda was taken in July 1948 and the 1949 armistice (Israel Railways; routes_1948.yaml), so normal play runs its+ /// train only from then, on the stretches of the route's service that run (Lod to Jerusalem, the 1950 service's+ /// stretch of this line; Tel Aviv South to Lod once a person signs it off): <see cref="ServiceTrain"/>, maintainer+ /// decision on #35, 16 October 2026.</summary>public const string TrainRoute = "jaffa_jerusalem_railway";public static readonly (double lon, double lat) TrainTurnAt = (34.87556, 31.94583); // Lod railway station@@ -46,13 +50,15 @@ namespace Statecraft.Game.Map.Routes/// game's start, 15 May 1948.</summary>public static readonly DateTime DefaultDate = new DateTime(1948, 5, 15);- public enum TrainMode { None, Still, Moving }+ /// <summary>None: no train. Still and Moving: the promo's showcase train. Service: normal play's (issue #668), from+ /// the route's sourced service date only.</summary>+ public enum TrainMode { None, Still, Moving, Service }- /// <summary>Whether there is a train and whether it moves (review I1): editor renders and screenshots (`?shot` /- /// `-shot`) show the promo's still train; `?train` or `?units` (desktop `-train` / `-units`) asks for the moving- /// showcase; normal play has none, as no service is sourced for the line at the game's dates.</summary>+ /// <summary>Which train (review I1; issue #668): editor renders and screenshots (`?shot` / `-shot`) show the promo's+ /// still train; `?train` or `?units` (desktop `-train` / `-units`) asks for the moving showcase; normal play runs the+ /// service train, from the date regular service resumed (<see cref="ServiceTrain"/>).</summary>public static TrainMode ModeFor(bool playing, bool shot, bool requested) =>- !playing || shot ? TrainMode.Still : requested ? TrainMode.Moving : TrainMode.None;+ !playing || shot ? TrainMode.Still : requested ? TrainMode.Moving : TrainMode.Service;public static bool TrainRequested(string? url, string[] args, bool webgl) =>webgl ? Boot.UrlFlags.Has(url, "train") || Boot.UrlFlags.Has(url, "units") : Array.IndexOf(args, "-train") >= 0 || Array.IndexOf(args, "-units") >= 0;@@ -68,6 +74,8 @@ namespace Statecraft.Game.Map.Routesif (map == null) return;map.RouteDate = date; // a later rebuild of this map starts at the game's date (re-review nit 2)if (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 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));@@ -182,7 +190,17 @@ namespace Statecraft.Game.Map.Routesassets.OnTeardown(VisualToggles.Register(RoutesToggle, on => { if (ribbons != null) ribbons.SetActive(on); }));var trainRoute = routes.FirstOrDefault(r => r.Id == TrainRoute);- if (trainRoute != null && train != TrainMode.None)+ if (trainRoute != null && train == TrainMode.Service)+ {+ // Normal play: nothing is built or fetched before the route's service date (issue #668). No service (the YAML+ // fallback carries none, or it was refused with a warning): no train.+ if (trainRoute.Service != null)+ {+ var service = ServiceTrain.Create(root.transform, assets, frame, trainRoute, data, origin, date);+ assets.OnTeardown(VisualToggles.Register(TrainToggle, on => { if (service != null) service.gameObject.SetActive(on); }));+ }+ }+ else if (trainRoute != null && train != TrainMode.None){var go = RouteTrain.Spawn(root.transform, assets, World(frame, trainRoute), data, origin,frame.ToWorld(TrainTurnAt.lon, TrainTurnAt.lat, 0), frame.ToWorld(RouteTrain.StillAt.lon, RouteTrain.StillAt.lat, 0),diff --git a/unity/Assets/Scripts/Map/Routes/RoutePaths.cs b/unity/Assets/Scripts/Map/Routes/RoutePaths.csindex 4d6102497..26223d929 100644--- a/unity/Assets/Scripts/Map/Routes/RoutePaths.cs+++ b/unity/Assets/Scripts/Map/Routes/RoutePaths.cs@@ -28,6 +28,18 @@ namespace Statecraft.Game.Map.Routespublic double MaxGapM { get; set; }/// <summary>[lon, lat] pairs, in order along the route.</summary>public List<List<double>> Points { get; set; } = new List<List<double>>();+ /// <summary>The railway's train service in normal play (issue #668), or null: from the runtime file's service row+ /// (tools/route_paths_bake.py reads it from routes_1948.yaml); route_paths_1948.yaml never carries one.</summary>+ [YamlIgnore] public RouteService? Service { get; set; }+ }++ /// <summary>A railway's train service (issue #668; maintainer decision on #35, 16 October 2026): the date regular+ /// service on it resumed (a quoted 'YYYY-MM-DD', sourced in routes_1948.yaml) and the stretch the train runs, between+ /// the line's points nearest Start and End (lon, lat).</summary>+ public sealed class RouteService+ {+ public string From = "";+ public double StartLon, StartLat, EndLon, EndLat;}public sealed class RoutePathFile { public List<RoutePath> Routes { get; set; } = new List<RoutePath>(); }@@ -54,7 +66,7 @@ namespace Statecraft.Game.Map.Routespublic const string RuntimeFileName = "route_paths_1948.tsv";/// <summary>Bump it, with tools/route_paths_bake.py's VERSION, when the runtime file's layout or its reading/// (ParseRuntime, RuntimeRows) changes; tools/tests/test_route_paths_bake.py pins a fingerprint of that code.</summary>- public const int RuntimeVersion = 2; // 2: the body_check row (review of #547)+ public const int RuntimeVersion = 3; // 2: the body_check row (review of #547); 3: the service rows (#668)public const string Rail = "rail", Road = "road", Track = "track";static readonly HashSet<string> Kinds = new HashSet<string> { Rail, Road, Track };static readonly Regex IdRule = new Regex(@"^[a-z][a-z0-9_]*\z");@@ -121,7 +133,7 @@ namespace Statecraft.Game.Map.Routesreturn new RoutePathFile { Routes = routes };}- /// <summary>The runtime file's body_check: FNV-1a over the UTF-8 bytes of its route rows, each followed by '\n', in+ /// <summary>The runtime file's body_check: FNV-1a over the UTF-8 bytes of its route and service rows, each followed by '\n', in/// order (tools/route_paths_bake.py's body_check).</summary>public static int BodyCheck(IEnumerable<string> routeRows){@@ -157,6 +169,21 @@ namespace Statecraft.Game.Map.Routeselse if (c[0] == "meta" && c.Length == 3 && c[1] == "version") version = Int(c[2], "version", line);else if (c[0] == "meta" && c.Length == 3 && c[1] == "yaml_check") check = Int(c[2], "yaml_check", line);else if (c[0] == "meta" && c.Length == 3 && c[1] == "routes") count = Int(c[2], "routes", line);+ else if (c[0] == "service")+ {+ if (c.Length != 5) throw new InvalidDataException($"{file}:{line}: a service row has {c.Length} fields, not 5");+ rows.Add(text);+ var route = routes.Find(r => r.Id == c[1]) ?? throw new InvalidDataException($"{file}:{line}: a service for '{c[1]}', which no route row before it has");+ if (route.Service != null) throw new InvalidDataException($"{file}:{line}: a second service for '{c[1]}'");+ (double, double) End(string pair, string what)+ {+ int sp = pair.IndexOf(' ');+ if (sp < 0 || pair.IndexOf(' ', sp + 1) >= 0) throw new InvalidDataException($"{file}:{line}: {what} '{pair}' is not 'lon lat'");+ return (Num(pair.Substring(0, sp), what + " lon", line), Num(pair.Substring(sp + 1), what + " lat", line));+ }+ var (startLon, startLat) = End(c[3], "start"); var (endLon, endLat) = End(c[4], "end");+ route.Service = new RouteService { From = c[2], StartLon = startLon, StartLat = startLat, EndLon = endLon, EndLat = endLat };+ }else if (c[0] == "route"){if (c.Length != 11) throw new InvalidDataException($"{file}:{line}: a route row has {c.Length} fields, not 11");@@ -242,11 +269,37 @@ namespace Statecraft.Game.Map.Routesif (bounds is { } b && (p[0] < b.lon0 || p[0] > b.lon1 || p[1] < b.lat0 || p[1] > b.lat1))throw new InvalidDataException(FormattableString.Invariant($"{at} point {i} ({p[0]}, {p[1]}) is outside the map"));}+ if (r.Service != null && !skipped.Contains(r) && ServiceProblem(r, bounds) is { } problem)+ {+ // After the route's own checks, so one cause gives one warning. A bad service never costs the routes+ // (the train is cosmetic): the tolerant read drops the train with a warning; a strict read throws.+ if (skipBadWindow == null) throw new InvalidDataException($"{at} {problem}");+ skipBadWindow($"{at} {problem}; no train runs on it");+ r.Service = null;+ }}doc.Routes.RemoveAll(skipped.Contains);return doc.Routes;}static bool IsFinite(double v) => !double.IsNaN(v) && !double.IsInfinity(v);++ /// <summary>Why the route's service cannot run (issue #668), or null: only on a railway, a 'YYYY-MM-DD' date inside the+ /// route's window, and both ends finite and on the map.</summary>+ static string? ServiceProblem(RoutePath r, (double lon0, double lon1, double lat0, double lat1)? bounds)+ {+ var s = r.Service!;+ if (r.Kind != Rail) return "has a service but is not a railway";+ DateTime from;+ try { from = Bound(s.From); }+ catch (FormatException e) { return $"service from: {e.Message}"; }+ if (s.From.Length != 10) return $"service from '{s.From}' is not a day ('YYYY-MM-DD')";+ try { if (!WindowOf(r).Covers(from)) return $"service from {s.From} is outside the route's window"; }+ catch (FormatException) { return "service on a route with a bad window"; }+ foreach (var (lon, lat, what) in new[] { (s.StartLon, s.StartLat, "start"), (s.EndLon, s.EndLat, "end") })+ if (!IsFinite(lon) || !IsFinite(lat) || bounds is { } b && (lon < b.lon0 || lon > b.lon1 || lat < b.lat0 || lat > b.lat1))+ return FormattableString.Invariant($"service {what} ({lon}, {lat}) is outside the map");+ return null;+ }}}diff --git a/unity/Assets/Scripts/Map/Routes/RouteTrain.cs b/unity/Assets/Scripts/Map/Routes/RouteTrain.csindex 1cf5c8e57..8f6f36d66 100644--- a/unity/Assets/Scripts/Map/Routes/RouteTrain.cs+++ b/unity/Assets/Scripts/Map/Routes/RouteTrain.cs@@ -12,8 +12,11 @@ namespace Statecraft.Game.Map.Routes/// start and the turn point (RouteLayer: Jaffa to Lydda), the locomotive leading each way, with a stop at each end./// A still train (screenshots, editor renders) stands at <see cref="StillAt"/>, heading inland, every run alike. Cheap:/// six transforms set per frame from a precomputed table; no physics, no allocation after Spawn. A showcase for the- /// promo frames and `?train` / `?units`, never normal play (RouteLayer.ModeFor, review I1): the run is ambience, not a- /// sourced timetable.</summary>+ /// promo frames and `?train` / `?units` (RouteLayer.ModeFor, review I1): the run is ambience, not a sourced timetable.+ /// Normal play's train is <see cref="SpawnModel"/>'s (issue #668, <see cref="ServiceTrain"/>): Tal's streamed+ /// locomotive and tender leading three of this showcase's coaches, four articulated cars on the stretch and from the+ /// date the content gives, each riding the line (owner, 16 October 2026: "ride the track, cut walls";+ /// <see cref="MaxLiftM"/>).</summary>public sealed class RouteTrain : MonoBehaviour{/// <summary>Times real size along the line, measured on the promo's gameplay frame: its six-car train is about 250 px@@ -37,6 +40,11 @@ namespace Statecraft.Game.Map.RoutesVector3[] tableP = Array.Empty<Vector3>();float startS, endS, length;float? still;+ // Normal play's model train only (SpawnModel): its body is kept clear of the ground (BodyLift).+ bool clearGround;+ float carHalfWidth;+ TerrainData? terrain;+ Vector3 terrainOrigin;/// <summary>Distance along the line of the head (front of the locomotive) at time <paramref name="t"/>, and the/// direction (+1 towards the turn point, -1 back).</summary>@@ -56,6 +64,8 @@ namespace Statecraft.Game.Map.Routespublic float? StillHead => still;public IReadOnlyList<Transform> Cars => cars;+ /// <summary>Each car's middle, metres behind the head along the line (Place puts car k at head - dir * offset).</summary>+ public IReadOnlyList<float> CarOffsets => carOffset;public float Length => length;public (float start, float end) Stretch => (startS, endS);@@ -77,10 +87,47 @@ namespace Statecraft.Game.Map.Routesvar front = At(c + dir * carHalf[k]); var back = At(c - dir * carHalf[k]);var mid = At(c);var fwd = front - back;- cars[k].SetPositionAndRotation(mid, Quaternion.LookRotation(fwd.sqrMagnitude > 1e-6f ? fwd : Vector3.forward, Vector3.up));+ var axis = fwd.sqrMagnitude > 1e-6f ? fwd.normalized : Vector3.forward;+ if (clearGround) mid.y += Mathf.Min(BodyLift(mid, axis, carHalf[k]), MaxLiftM);+ cars[k].SetPositionAndRotation(mid, Quaternion.LookRotation(axis, Vector3.up));}}+ /// <summary>The most (m) a service-train car is raised off the line to clear the ground under it: 5 m. The owner's+ /// ruling for #668 (16 October 2026: "ride the track, cut walls"): every car rides the line, and where the Sorek+ /// valley's walls rise under a car's sides on the tightest bends, the sides pass into them, as the rail ribbon's+ /// own edges do in a cutting (RouteLayer.RiseToleranceM), instead of the car floating over them.</summary>+ public const float MaxLiftM = 5f;++ /// <summary>Samples along a model car's body (each side of its middle) and across it (each side of its centre line)+ /// where <see cref="BodyLift"/> reads the ground.</summary>+ public const int LiftSamplesAlong = 20, LiftSamplesAcross = 2;++ /// <summary>How far (m) to raise a car whose middle is at <paramref name="mid"/> (on the line, at the ride height) and+ /// whose straight body runs along <paramref name="dir"/> for <paramref name="half"/> each way, so its base stays+ /// <see cref="RideM"/> above the ground everywhere under it: the line's own points carry that height, but a rigid+ /// car cuts across a bend or a rise of the Sorek valley's grade (issue #668). 0 where the ground stays under it.+ /// Place raises a car by at most <see cref="MaxLiftM"/> of it. 205 terrain reads (41 along by 5 across) per car per+ /// frame.</summary>+ public float BodyLift(Vector3 mid, Vector3 dir, float half)+ {+ if (terrain == null) return 0f;+ var right = Vector3.Cross(Vector3.up, dir); right.y = 0f;+ right = right.sqrMagnitude > 1e-6f ? right.normalized : Vector3.right;+ float lift = 0f;+ for (int i = -LiftSamplesAlong; i <= LiftSamplesAlong; i++)+ for (int j = -LiftSamplesAcross; j <= LiftSamplesAcross; j++)+ {+ var p = mid + dir * (half * i / LiftSamplesAlong) + right * (carHalfWidth * j / Mathf.Max(LiftSamplesAcross, 1));+ float need = RouteLayer.Ground(terrain, terrainOrigin, new Vector2(p.x, p.z)) + RideM - p.y;+ if (need > lift) lift = need;+ }+ return lift;+ }++ /// <summary>The half-width (m of map) of a model car's base, which <see cref="BodyLift"/> keeps clear.</summary>+ public float CarHalfWidth => carHalfWidth;+/// <summary>The point of the line (on the ribbon, plus the ride height) at distance s, clamped to the line.</summary>public Vector3 At(float s){@@ -107,18 +154,8 @@ namespace Statecraft.Game.Map.Routesvar paint = assets.Own(new Material(template) { name = "Train (palette)" });paint.SetTexture("_BaseMap", palette);- var go = new GameObject("Train");- go.transform.SetParent(parent, false);- var train = go.AddComponent<RouteTrain>();- var (pts, along) = RouteLayer.Resample(line, TableStepM);- train.tableS = along.ToArray();- train.tableP = new Vector3[pts.Count];- for (int i = 0; i < pts.Count; i++)- {- // The ribbon's own height (its grade, the same rule, review M4) plus the ride height.- var dir = (pts[Math.Min(pts.Count - 1, i + 1)] - pts[Math.Max(0, i - 1)]).normalized;- train.tableP[i] = new Vector3(pts[i].x, RouteLayer.GradeHeight(data, origin, pts[i], dir) + RideM, pts[i].y);- }+ var train = NewTrain(parent, line, data, origin);+ var go = train.gameObject;train.startS = 0f;train.endS = train.Nearest(new Vector2(turnAt.x, turnAt.z));@@ -144,6 +181,130 @@ namespace Statecraft.Game.Map.Routesreturn go;}+ /// <summary>An empty train under <paramref name="parent"/> with its line's table: the ribbon's own height (its grade,+ /// the same rule, review M4) plus the ride height, every <see cref="TableStepM"/>.</summary>+ static RouteTrain NewTrain(Transform parent, IReadOnlyList<Vector2> line, TerrainData data, Vector3 origin)+ {+ var go = new GameObject("Train");+ go.transform.SetParent(parent, false);+ var train = go.AddComponent<RouteTrain>();+ var (pts, along) = RouteLayer.Resample(line, TableStepM);+ train.tableS = along.ToArray();+ train.tableP = new Vector3[pts.Count];+ for (int i = 0; i < pts.Count; i++)+ {+ var dir = (pts[Math.Min(pts.Count - 1, i + 1)] - pts[Math.Max(0, i - 1)]).normalized;+ train.tableP[i] = new Vector3(pts[i].x, RouteLayer.GradeHeight(data, origin, pts[i], dir) + RideM, pts[i].y);+ }+ return train;+ }++ /// <summary>The length (real metres) the streamed locomotive and tender stand for: the showcase's locomotive, the+ /// gap and its tender (TrainModels), so both trains are one size on the map.</summary>+ public const float ModelRealLengthM = TrainModels.LocoLengthM + TrainModels.GapM + TrainModels.TenderLengthM;++ /// <summary>Normal play's train (issue #668): <paramref name="cars"/> articulated cars of equal length, together+ /// <see cref="ModelRealLengthM"/> at <see cref="Scale"/> times <paramref name="sizeShare"/> long and each+ /// <paramref name="carWidthM"/> wide (its height scaled with its width): first an instance of <paramref name="model"/>+ /// (Tal's streamed locomotive and tender, <see cref="ServiceTrain"/>), then this showcase's coaches+ /// (<see cref="TrainModels.Coach"/>, their meshes, palette and material owned by <paramref name="assets"/>). Each car is+ /// placed at its own distance along the line, faces along it and rides it (<see cref="Place"/>, <see cref="MaxLiftM"/>);+ /// the train shuttles, the locomotive leading each way, between the line's points nearest <paramref name="startAt"/>+ /// and <paramref name="endAt"/> (world). The model's own frame is turned so its length runs along +Z+ /// (<paramref name="modelYaw"/>, degrees, then to its long horizontal axis) with its base on the car's origin; its+ /// meshes and materials stay the stream's (shared, not owned).</summary>+ public static RouteTrain SpawnModel(Transform parent, MapRuntimeAssets assets, GameObject model, IReadOnlyList<Vector2> line,+ TerrainData data, Vector3 origin, Vector3 startAt, Vector3 endAt, float modelYaw, float sizeShare, int cars, float carWidthM)+ {+ var train = NewTrain(parent, line, data, origin);+ float a = train.Nearest(new Vector2(startAt.x, startAt.z)), b = train.Nearest(new Vector2(endAt.x, endAt.z));+ train.startS = Mathf.Min(a, b); train.endS = Mathf.Max(a, b);+ float total = ModelRealLengthM * Scale * sizeShare, carLength = total / Mathf.Max(cars, 1);++ // The locomotive: the model turned to +Z, its base on the car's origin, sized to the car.+ var loco = new GameObject("Locomotive");+ loco.transform.SetParent(train.transform, false);+ var body = UnityEngine.Object.Instantiate(model, loco.transform, false);+ body.name = model.name;+ body.transform.localRotation = Quaternion.Euler(0f, modelYaw, 0f) * body.transform.localRotation;+ var size = LocalBounds(loco.transform, body);+ if (size.size.x > size.size.z)+ {+ body.transform.localRotation = Quaternion.Euler(0f, 90f, 0f) * body.transform.localRotation;+ size = LocalBounds(loco.transform, body);+ }+ body.transform.localPosition -= new Vector3(size.center.x, size.min.y, size.center.z);+ loco.transform.localScale = CarScale(size.size, carLength, carWidthM);+ train.AddCar(loco.transform, carLength);++ // The coaches: the showcase's painted miniatures, one mesh per coach as the showcase's own consist.+ if (cars > 1)+ {+ var template = Resources.Load<Material>(UnitMaterials.MiniatureResource)+ ?? throw new InvalidOperationException($"Resources/{UnitMaterials.MiniatureResource}.mat is missing (run UnitMaterialAssets.Create)");+ var palette = assets.Own(UnitPalette.MakeTexture(readable: false));+ var paint = assets.Own(new Material(template) { name = "Service train (palette)" });+ paint.SetTexture("_BaseMap", palette);+ for (int k = 1; k < cars; k++)+ {+ var mesh = assets.Own(TrainModels.Coach($"ServiceCoach{k}"));+ var bounds = mesh.bounds;+ mesh.UploadMeshData(true);+ var coach = new GameObject($"Coach{k}");+ coach.transform.SetParent(train.transform, false);+ var shape = new GameObject("Body");+ shape.transform.SetParent(coach.transform, false);+ shape.transform.localPosition = -new Vector3(bounds.center.x, bounds.min.y, bounds.center.z);+ shape.AddComponent<MeshFilter>().sharedMesh = mesh;+ shape.AddComponent<MeshRenderer>().sharedMaterial = paint;+ coach.transform.localScale = CarScale(bounds.size, carLength, carWidthM);+ train.AddCar(coach.transform, carLength);+ }+ }+ train.length = total;+ train.carHalfWidth = carWidthM / 2f;+ train.terrain = data; train.terrainOrigin = origin; train.clearGround = true;+ var (h, d) = train.HeadAt(0f); train.Place(h, d);+ return train;+ }++ /// <summary>The scale that makes a shape of <paramref name="size"/> (its length along Z) <paramref name="length"/> long+ /// and <paramref name="width"/> wide, its height scaled with its width.</summary>+ static Vector3 CarScale(Vector3 size, float length, float width)+ {+ float across = width / Mathf.Max(size.x, 1e-4f);+ return new Vector3(across, across, length / Mathf.Max(size.z, 1e-4f));+ }++ /// <summary>Adds a car <paramref name="length"/> long behind the cars already in the train, nose to tail.</summary>+ void AddCar(Transform car, float length)+ {+ float offset = carOffset.Count == 0 ? 0f : carOffset[carOffset.Count - 1] + carHalf[carHalf.Count - 1];+ cars.Add(car); carOffset.Add(offset + length / 2f); carHalf.Add(length / 2f);+ }++ /// <summary>The bounds of <paramref name="body"/>'s renderers in <paramref name="frame"/>'s local space.</summary>+ static Bounds LocalBounds(Transform frame, GameObject body)+ {+ var bounds = new Bounds(); bool any = false;+ foreach (var f in body.GetComponentsInChildren<MeshFilter>(true))+ if (f.sharedMesh != null) Add(f.transform, f.sharedMesh.bounds);+ foreach (var s in body.GetComponentsInChildren<SkinnedMeshRenderer>(true))+ if (s.sharedMesh != null) Add(s.transform, s.sharedMesh.bounds);+ return bounds;++ void Add(Transform t, Bounds local)+ {+ var m = frame.worldToLocalMatrix * t.localToWorldMatrix;+ for (int c = 0; c < 8; c++)+ {+ var corner = local.center + Vector3.Scale(local.extents, new Vector3((c & 1) == 0 ? -1 : 1, (c & 2) == 0 ? -1 : 1, (c & 4) == 0 ? -1 : 1));+ var p = m.MultiplyPoint3x4(corner);+ if (!any) { bounds = new Bounds(p, Vector3.zero); any = true; } else bounds.Encapsulate(p);+ }+ }+ }+/// <summary>Distance along the line of its point nearest <paramref name="p"/> (to the table's resolution).</summary>public float Nearest(Vector2 p){diff --git a/unity/Assets/Scripts/Map/Routes/ServiceTrain.cs b/unity/Assets/Scripts/Map/Routes/ServiceTrain.csnew file mode 100644index 000000000..48bb574a3--- /dev/null+++ b/unity/Assets/Scripts/Map/Routes/ServiceTrain.cs@@ -0,0 +1,105 @@+#nullable enable+using System;+using System.Collections.Generic;+using Statecraft.Game.Map.Collection;+using UnityEngine;++namespace Statecraft.Game.Map.Routes+{+ /// <summary>The steam train in normal play (issue #668; maintainer decision on #35, 16 October 2026: "Yes, normal+ /// play", on the Jaffa–Jerusalem line, only from the sourced date regular service resumed). The stretch and the date+ /// come from the content: the route's service (routes_1948.yaml, through the runtime file; RouteService), from 2 March+ /// 1950 on the stretches that run: Lod to Jerusalem (Israel Railways, 1998), and Tel Aviv South to Lod only once a+ /// person signs that stretch off (it rests on Wikipedia alone). Before that date there is no train and nothing is+ /// fetched. The model is Tal's (@pixelrenderai-hash) steam locomotive and tender, H09 of The 1948 Collection (#507,+ /// #680), streamed through+ /// <see cref="CollectionStream"/>: asked for only when the game date first reaches the service, so never for the first+ /// frame (the game starts in May 1948, and the stream serves nothing before the frame after a request). The strategic+ /// zoom's mesh (CollectionDetail.Far) is the one drawn at every zoom: a vehicle has no idle clip, and one model of at+ /// most 4,500 triangles costs nothing worth a swap.+ /// It fails open: when the model does not stream (no bundle, a damaged one, no prefab), one warning, no train, and the+ /// map and the game run on. The train runs on the real clock, as the showcase does, whatever the turn: it is ambience,+ /// not a timetable, and the game has no pause that stops the clock. Unity's culling drops it off screen.</summary>+ public sealed class ServiceTrain : MonoBehaviour+ {+ public const string Name = "ServiceTrain";+ /// <summary>H09 in The 1948 Collection (CollectionCatalog.Vehicles).</summary>+ public const string ModelId = "vehicle-steam-locomotive-1948-v2";+ /// <summary>The yaw (degrees) that turns the model's smokebox to its car's +Z, the way it runs (measured on the far+ /// prefab: ServiceTrainTests.TheLocomotiveLeadsWithItsSmokebox).</summary>+ public const float ModelYaw = 0f;+ /// <summary>The train's length as a share of the showcase's locomotive and tender (RouteTrain.Scale): 0.4, about 816 m+ /// on the map (coordinator, 16 October 2026). At the showcase's own size (about 2 km by 745 m) one rigid body cannot+ /// follow the Sorek valley's bends (issue #668, measured along Lod–Jerusalem).</summary>+ public const float ModelSize = 0.4f;+ /// <summary>The train's articulated cars, Tal's locomotive and three coaches, each a quarter of its length (about+ /// 204 m): the owner's ruling for #668 (16 October 2026, "ride the track, cut walls"), measured against one rigid car.</summary>+ public const int Cars = 4;+ /// <summary>Each car's width: 0.9 of the rail ribbon's narrowest drawn width (RouteLayer.MinWidthShare of+ /// RouteLayer.RailWidthM, 170 m on the Sorek's gorge floor), about 153 m, so a car fits the track it rides.</summary>+ public const float CarWidthM = 0.9f * RouteLayer.MinWidthShare * RouteLayer.RailWidthM;++ /// <summary>How the train asks for its model: the game's stream. A test seam (internal; the tests see it through+ /// InternalsVisibleTo), so the tests can answer with a prefab or with nothing.</summary>+ internal static Action<string, CollectionDetail, Action<GameObject?>> Request = CollectionStream.Request;++ List<Vector2> line = new List<Vector2>();+ MapRuntimeAssets? assets;+ TerrainData? data;+ Vector3 origin, startAt, endAt;+ DateTime shownAt;+ bool requested, failed;++ /// <summary>The first day the train runs.</summary>+ public DateTime From { get; private set; }+ /// <summary>The train, once its model has streamed in; null before, and for good when it did not.</summary>+ public RouteTrain? Train { get; private set; }+ public bool Requested => requested;+ public bool Failed => failed;++ /// <summary>Adds the (empty) service train under <paramref name="parent"/> for <paramref name="route"/>'s service,+ /// shown as at <paramref name="date"/>.</summary>+ public static ServiceTrain Create(Transform parent, MapRuntimeAssets assets, GeoFrame frame, RoutePath route, TerrainData data,+ Vector3 origin, DateTime date)+ {+ var s = route.Service ?? throw new ArgumentException($"'{route.Id}' has no service", nameof(route));+ var go = new GameObject(Name);+ go.transform.SetParent(parent, false);+ var t = go.AddComponent<ServiceTrain>();+ t.line = RouteLayer.World(frame, route);+ t.assets = assets;+ t.data = data; t.origin = origin;+ t.startAt = frame.ToWorld(s.StartLon, s.StartLat, 0);+ t.endAt = frame.ToWorld(s.EndLon, s.EndLat, 0);+ t.From = RoutePaths.Bound(s.From);+ t.ShowAt(date);+ return t;+ }++ /// <summary>Runs the train from its date on and hides it before (a loaded earlier save). The first call at or after+ /// the date asks the stream for the model, once; the rest only switch the train on or off.</summary>+ public void ShowAt(DateTime date)+ {+ shownAt = date;+ bool runs = date >= From;+ if (Train != null) Train.gameObject.SetActive(runs);+ if (!runs || requested) return;+ requested = true;+ Request(ModelId, CollectionDetail.Far, OnModel);+ }++ void OnModel(GameObject? prefab)+ {+ if (this == null) return; // the map was rebuilt before the model came; the new map asks again+ if (prefab == null || data == null || assets == null)+ {+ failed = true;+ Debug.LogWarning($"TRAIN: the locomotive ({ModelId}) did not stream; no train runs on {RouteLayer.TrainRoute}, and the map plays on without it.");+ return;+ }+ Train = RouteTrain.SpawnModel(transform, assets, prefab, line, data, origin, startAt, endAt, ModelYaw, ModelSize, Cars, CarWidthM);+ Train.gameObject.SetActive(shownAt >= From);+ Debug.Log($"TRAIN: the steam train runs on {RouteLayer.TrainRoute} from {From:yyyy-MM-dd} ({ModelId}, {Train.Length:0} m)");+ }+ }+}diff --git a/unity/Assets/Scripts/Map/Routes/ServiceTrain.cs.meta b/unity/Assets/Scripts/Map/Routes/ServiceTrain.cs.metanew file mode 100644index 000000000..177b8b386--- /dev/null+++ b/unity/Assets/Scripts/Map/Routes/ServiceTrain.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: cf80bc3078b8645f38c5896280c0c50b\ No newline at end of filediff --git a/unity/Assets/Tests/EditMode/RoutePathsRuntimeTests.cs b/unity/Assets/Tests/EditMode/RoutePathsRuntimeTests.csindex d12542278..0637d63b1 100644--- a/unity/Assets/Tests/EditMode/RoutePathsRuntimeTests.cs+++ b/unity/Assets/Tests/EditMode/RoutePathsRuntimeTests.cs@@ -77,7 +77,7 @@ public class RoutePathsRuntimeTestspoints[0] = lon.ToString("R", CultureInfo.InvariantCulture) + " " + first[1];c[10] = string.Join(";", points); lines[at] = string.Join("\t", c);int end = lines.FindIndex(l => l.StartsWith("meta\tbody_check\t"));- lines[end] = "meta\tbody_check\t" + RoutePaths.BodyCheck(lines.Where(l => l.StartsWith("route\t"))).ToString(CultureInfo.InvariantCulture);+ lines[end] = "meta\tbody_check\t" + RoutePaths.BodyCheck(lines.Where(l => l.StartsWith("route\t") || l.StartsWith("service\t"))).ToString(CultureInfo.InvariantCulture); // #668: the service rows tooinputs.RoutesTsv = string.Join("\n", lines);var fallbacks = new List<string>();diff --git a/unity/Assets/Tests/EditMode/RouteTests.cs b/unity/Assets/Tests/EditMode/RouteTests.csindex a3b55ee5f..b998771dc 100644--- a/unity/Assets/Tests/EditMode/RouteTests.cs+++ b/unity/Assets/Tests/EditMode/RouteTests.cs@@ -74,7 +74,7 @@ public class RouteTestsfor (int i = 1; i + 1 < along.Count; i++) Assert.AreEqual(120f * i, along[i], 1e-3f);}- static MapScene BuildMap()+ internal static MapScene BuildMap(){EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);var map = new GameObject("MapScene").AddComponent<MapScene>();@@ -85,7 +85,7 @@ public class RouteTestsstatic Material Load(string name) => AssetDatabase.LoadAssetAtPath<Material>($"Assets/Materials/{name}.mat");- static Transform RoutesRoot(MapScene map) => map.Terrain.transform.Find(RouteLayer.RootName);+ internal static Transform RoutesRoot(MapScene map) => map.Terrain.transform.Find(RouteLayer.RootName);static IEnumerable<MeshFilter> Ribbons(Transform root, string name) =>root.Find(RouteLayer.RibbonsName).GetComponentsInChildren<MeshFilter>(true).Where(f => f.name == name);@@ -584,16 +584,17 @@ public class RouteTests}}- /// <summary>I1 and M11: the train is a showcase. Editor renders and `?shot` hold it still (the promo frames); `?train`- /// or `?units` runs it; normal play has none.</summary>+ /// <summary>I1 and M11: the promo's train is a showcase. Editor renders and `?shot` hold it still (the promo frames);+ /// `?train` or `?units` runs it; normal play runs the service train instead, from its sourced date (issue #668,+ /// ServiceTrainTests).</summary>[Test]- public void TheTrainIsAShowcaseOnly()+ public void ThePromosTrainIsAShowcase(){Assert.AreEqual(RouteLayer.TrainMode.Still, RouteLayer.ModeFor(playing: false, shot: false, requested: false), "editor renders");Assert.AreEqual(RouteLayer.TrainMode.Still, RouteLayer.ModeFor(playing: true, shot: true, requested: false), "?shot freezes it");Assert.AreEqual(RouteLayer.TrainMode.Still, RouteLayer.ModeFor(playing: true, shot: true, requested: true));Assert.AreEqual(RouteLayer.TrainMode.Moving, RouteLayer.ModeFor(playing: true, shot: false, requested: true));- Assert.AreEqual(RouteLayer.TrainMode.None, RouteLayer.ModeFor(playing: true, shot: false, requested: false), "normal play: no train");+ Assert.AreEqual(RouteLayer.TrainMode.Service, RouteLayer.ModeFor(playing: true, shot: false, requested: false), "normal play: the service train (#668)");Assert.IsTrue(RouteLayer.TrainRequested("https://x/index.html?train", new string[0], true));Assert.IsTrue(RouteLayer.TrainRequested("https://x/index.html?golden&units", new string[0], true));Assert.IsFalse(RouteLayer.TrainRequested("https://x/index.html?golden&smoke=5", new string[0], true));@@ -608,7 +609,7 @@ public class RouteTestsvar data = map.Terrain.terrainData;var routes = RoutePaths.Parse(CommittedYaml, Bounds);var none = RouteLayer.Build(map.Terrain, map.Frame, routes, RouteLayer.TrainMode.None, RouteLayer.DefaultDate);- Assert.IsNull(none.GetComponentInChildren<RouteTrain>(true), "no train in normal play");+ Assert.IsNull(none.GetComponentInChildren<RouteTrain>(true), "no train");var moving = RouteLayer.Build(map.Terrain, map.Frame, routes, RouteLayer.TrainMode.Moving, RouteLayer.DefaultDate);Assert.IsNull(moving.GetComponentInChildren<RouteTrain>().StillHead, "the showcase runs");Object.DestroyImmediate(none); Object.DestroyImmediate(moving);diff --git a/unity/Assets/Tests/EditMode/ServiceTrainTests.cs b/unity/Assets/Tests/EditMode/ServiceTrainTests.csnew file mode 100644index 000000000..c7bd5921e--- /dev/null+++ b/unity/Assets/Tests/EditMode/ServiceTrainTests.cs@@ -0,0 +1,404 @@+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using System.Text.RegularExpressions;+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 UnityEditor;+using UnityEditor.SceneManagement;+using UnityEngine;+using UnityEngine.TestTools;+using Object = UnityEngine.Object;++/// <summary>Issue #668 (maintainer decision on #35, 16 October 2026: "Yes, normal play", on the Jaffa–Jerusalem line, only+/// from the sourced date regular service resumed): the steam train in normal play. Its date and stretch come from the+/// content (routes_1948.yaml, through the runtime file), its model is Tal's H09, streamed after the first frame through+/// CollectionStream, and it fails open.</summary>+public class ServiceTrainTests+{+ static readonly DateTime ServiceDate = new DateTime(1950, 3, 2);+ static readonly (double lon, double lat) TelAvivSouth = (34.777, 32.0636), Jerusalem = (35.22471, 31.76685);+ static readonly (double lon, double lat) Lod = RouteLayer.TrainTurnAt;++ Action<string, CollectionDetail, Action<GameObject>> saved;+ readonly List<(string id, CollectionDetail detail, Action<GameObject> done)> asked = new List<(string, CollectionDetail, Action<GameObject>)>();++ [SetUp]+ public void Seam()+ {+ saved = ServiceTrain.Request;+ asked.Clear();+ ServiceTrain.Request = (id, detail, done) => asked.Add((id, detail, done));+ }++ [TearDown]+ public void Reset()+ {+ ServiceTrain.Request = saved;+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);+ VisualToggles.Clear();+ }++ static MapInputs Inputs() => GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap);++ static (double, double, double, double) Bounds()+ {+ var b = HeightmapLoader.Load(Paths.StreamingMap).meta;+ return (b.lon0, b.lon1, b.lat0, b.lat1);+ }++ /// <summary>The routes as the player reads them at boot (the runtime file).</summary>+ static List<RoutePath> BootRoutes()+ {+ var inputs = Inputs();+ var warnings = new List<string>();+ var routes = RoutePaths.ReadRuntimeOrYaml(inputs.RoutesTsv, inputs.RoutesYaml, Bounds(), warnings.Add);+ CollectionAssert.IsEmpty(warnings);+ return routes;+ }++ static GameObject FarPrefab() =>+ AssetDatabase.LoadAssetAtPath<GameObject>(CollectionCatalog.PrefabPath(ServiceTrain.ModelId, CollectionDetail.Far));++ /// <summary>A map whose routes are built for normal play (the service train) at <paramref name="date"/>; the editor's+ /// own build (the showcase's still train) is replaced.</summary>+ static (MapScene map, ServiceTrain service) NormalPlayMap(DateTime date)+ {+ var map = RouteTests.BuildMap();+ Object.DestroyImmediate(RouteTests.RoutesRoot(map).gameObject);+ RouteLayer.Build(map.Terrain, map.Frame, BootRoutes(), RouteLayer.TrainMode.Service, date);+ var service = RouteTests.RoutesRoot(map).Find(ServiceTrain.Name).GetComponent<ServiceTrain>();+ return (map, service);+ }++ [Test]+ public void TheRuntimeFileCarriesTheSourcedService()+ {+ var jjr = BootRoutes().Single(r => r.Id == RouteLayer.TrainRoute);+ Assert.IsNotNull(jjr.Service, "content/map/routes_1948.yaml's service reaches the map through the runtime file");+ Assert.AreEqual("1950-03-02", jjr.Service.From);+ Assert.AreEqual(Lod, (jjr.Service.StartLon, jjr.Service.StartLat), "Tel Aviv South to Lod is gated and not signed off");+ Assert.AreEqual(Jerusalem, (jjr.Service.EndLon, jjr.Service.EndLat));+ Assert.AreEqual(1, BootRoutes().Count(r => r.Service != null), "one train (#668)");+ Assert.IsNull(RoutePaths.Parse(Inputs().RoutesYaml, Bounds()).Single(r => r.Id == RouteLayer.TrainRoute).Service,+ "the YAML fallback carries no service: then no train runs");+ }++ [Test]+ public void ABadServiceDropsOnlyTheTrain()+ {+ var inputs = Inputs();+ int count = BootRoutes().Count;+ foreach (var (bad, why) in new[]+ {+ ("1950-3-2", "not a date"), ("1950", "a year, not a day"), ("1900-01-01", "before the route's window"),+ })+ {+ var warnings = new List<string>();+ var tsv = Rebody(inputs.RoutesTsv.Replace("\t1950-03-02\t", $"\t{bad}\t"));+ var routes = RoutePaths.ReadRuntimeOrYaml(tsv, inputs.RoutesYaml, Bounds(), warnings.Add);+ Assert.AreEqual(count, routes.Count, why);+ Assert.IsNull(routes.Single(r => r.Id == RouteLayer.TrainRoute).Service, why);+ Assert.AreEqual(1, warnings.Count, why);+ StringAssert.Contains("no train runs on it", warnings[0], why);+ }+ var orphan = Rebody(inputs.RoutesTsv.Replace("service\tjaffa_jerusalem_railway\t", "service\tno_such_route\t"));+ var e = Assert.Throws<InvalidDataException>(() => RoutePaths.ParseRuntime(orphan, inputs.RoutesYaml, Bounds()));+ StringAssert.Contains("no_such_route", e.Message);+ }++ /// <summary>The runtime file with its body_check recomputed, as the bake writes it after an edit.</summary>+ static string Rebody(string tsv)+ {+ var lines = tsv.TrimEnd('\n').Split('\n').ToList();+ var rows = lines.Where(l => l.StartsWith("route\t") || l.StartsWith("service\t")).ToList();+ lines[lines.Count - 1] = $"meta\tbody_check\t{RoutePaths.BodyCheck(rows)}";+ return string.Join("\n", lines) + "\n";+ }++ [Test]+ public void NormalPlayAsksForTheTrainOnlyFromTheServiceDate()+ {+ Assert.AreEqual(RouteLayer.TrainMode.Service, RouteLayer.ModeFor(playing: true, shot: false, requested: false), "normal play");+ var (map, service) = NormalPlayMap(RouteLayer.DefaultDate);+ try+ {+ Assert.AreEqual(ServiceDate, service.From);+ CollectionAssert.IsEmpty(asked, "the boot (15 May 1948) asks for nothing: no download for the first frame");+ Assert.IsNull(service.Train);+ Assert.IsNull(RouteTests.RoutesRoot(map).GetComponentInChildren<RouteTrain>(true), "no train before the service date");++ RouteLayer.ShowAt(map, ServiceDate.AddDays(-1));+ CollectionAssert.IsEmpty(asked, "1 March 1950: still none");+ RouteLayer.ShowAt(map, ServiceDate);+ Assert.AreEqual(1, asked.Count, "2 March 1950: the model is asked for");+ Assert.AreEqual((ServiceTrain.ModelId, CollectionDetail.Far), (asked[0].id, asked[0].detail));+ Assert.IsNull(service.Train, "nothing drawn until the stream answers (a later frame)");++ LogAssert.Expect(LogType.Log, new Regex("^TRAIN: the steam train runs on jaffa_jerusalem_railway from 1950-03-02"));+ asked[0].done(FarPrefab());+ Assert.IsNotNull(service.Train);+ Assert.IsTrue(service.Train.gameObject.activeInHierarchy);+ Assert.AreEqual(ServiceTrain.Cars, service.Train.Cars.Count, "Tal's locomotive and three coaches (owner, \"ride the track, cut walls\")");+ Assert.AreEqual("Locomotive", service.Train.Cars[0].name, "the locomotive leads");+ Assert.AreEqual(FarPrefab().name, service.Train.Cars[0].GetChild(0).name, "the streamed model is the locomotive");+ foreach (var car in service.Train.Cars) Assert.IsNotNull(car.GetComponentInChildren<Renderer>(), car.name);++ RouteLayer.ShowAt(map, new DateTime(1951, 1, 1));+ Assert.AreEqual(1, asked.Count, "asked for once");+ RouteLayer.ShowAt(map, new DateTime(1949, 1, 1));+ Assert.IsFalse(service.Train.gameObject.activeSelf, "an earlier date (a loaded save) hides it");+ RouteLayer.ShowAt(map, ServiceDate);+ Assert.IsTrue(service.Train.gameObject.activeSelf);+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ [Test]+ public void AGameAlreadyPastTheDateAsksAtOnceAndTheStreamDefersIt()+ {+ var (map, service) = NormalPlayMap(new DateTime(1951, 6, 1));+ try+ {+ Assert.AreEqual(1, asked.Count, "a rebuilt map (or a later save) asks when it is built");+ Assert.IsNull(service.Train);+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The load gate (owner, 15 October 2026): the model is streamed, never in Resources, and the game asks the+ /// stream for it (which serves nothing before the frame after a request: CollectionStreamTests).</summary>+ [Test]+ public void TheModelIsStreamedNeverInResources()+ {+ Assert.AreEqual(typeof(CollectionStream), saved.Method.DeclaringType, "the game's seam is CollectionStream.Request");+ Assert.AreEqual(nameof(CollectionStream.Request), saved.Method.Name);+ Assert.AreEqual(CollectionCatalog.Vehicles, CollectionCatalog.BundleOf(ServiceTrain.ModelId));+ foreach (var detail in new[] { CollectionDetail.Far, CollectionDetail.Near })+ {+ var path = CollectionCatalog.PrefabPath(ServiceTrain.ModelId, detail);+ Assert.IsNotNull(AssetDatabase.LoadAssetAtPath<GameObject>(path), path);+ StringAssert.DoesNotContain("/Resources/", path);+ foreach (var dep in AssetDatabase.GetDependencies(path, true))+ StringAssert.DoesNotContain("/Resources/", dep, $"{path} pulls {dep} into the first download");+ }+ Assert.IsNull(Resources.Load<GameObject>(ServiceTrain.ModelId));+ }++ [Test]+ public void AModelThatDoesNotStreamLeavesNoTrainAndOneWarning()+ {+ var (map, service) = NormalPlayMap(ServiceDate);+ try+ {+ LogAssert.Expect(LogType.Warning, new Regex("^TRAIN: the locomotive \\(vehicle-steam-locomotive-1948-v2\\) did not stream"));+ asked[0].done(null);+ Assert.IsTrue(service.Failed);+ Assert.IsNull(service.Train);+ Assert.IsNull(RouteTests.RoutesRoot(map).GetComponentInChildren<RouteTrain>(true));+ RouteLayer.ShowAt(map, ServiceDate.AddMonths(1));+ Assert.AreEqual(1, asked.Count, "no retry on every turn");+ Assert.IsTrue(RouteTests.RoutesRoot(map).Find(RouteLayer.RibbonsName).GetComponentsInChildren<MeshRenderer>().Length > 0,+ "the railways and roads are still drawn");+ LogAssert.NoUnexpectedReceived();+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ [Test]+ public void AModelArrivingAfterTheMapWasRebuiltIsDropped()+ {+ var (map, service) = NormalPlayMap(ServiceDate);+ try+ {+ Object.DestroyImmediate(RouteTests.RoutesRoot(map).gameObject);+ Assert.DoesNotThrow(() => asked[0].done(FarPrefab()));+ Assert.IsNull(Object.FindFirstObjectByType<RouteTrain>());+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>A normal-play map at the service date with the model streamed in (the far prefab).</summary>+ (MapScene map, RouteTrain train) RunningTrain(List<RoutePath> routes = null)+ {+ var map = RouteTests.BuildMap();+ Object.DestroyImmediate(RouteTests.RoutesRoot(map).gameObject);+ RouteLayer.Build(map.Terrain, map.Frame, routes ?? BootRoutes(), RouteLayer.TrainMode.Service, ServiceDate);+ Assert.AreEqual(1, asked.Count);+ asked[0].done(FarPrefab());+ var service = RouteTests.RoutesRoot(map).Find(ServiceTrain.Name).GetComponent<ServiceTrain>();+ Assert.IsNotNull(service.Train);+ return (map, service.Train);+ }++ static Vector2 W(MapScene map, (double lon, double lat) p) { var v = map.Frame.ToWorld(p.lon, p.lat, 0); return new Vector2(v.x, v.z); }++ static Vector2 Flat(Vector3 v) => new Vector2(v.x, v.z);++ /// <summary>The coordinator's gate for #668: Tel Aviv South to Lod rests on Wikipedia alone, so until a person signs+ /// it off the train runs from Lod and never on that stretch...</summary>+ [Test]+ public void TheGatedStretchDrawsNoTrainUntilSignedOff()+ {+ var (map, train) = RunningTrain();+ try+ {+ var (start, end) = train.Stretch;+ Assert.Less((Flat(train.At(start)) - W(map, Lod)).magnitude, 1000f, "the train starts at Lod");+ float lodToTelAvivSouth = (W(map, Lod) - W(map, TelAvivSouth)).magnitude;+ float leg = (end - start - train.Length) / RouteTrain.SpeedMps + RouteTrain.DwellSeconds;+ for (float t = 0f; t < 2f * leg; t += 2f)+ {+ var (h, d) = train.HeadAt(t); train.Place(h, d);+ float carHalf = train.Length / train.Cars.Count / 2f;+ foreach (var c in train.Cars)+ foreach (var tip in new[] { c.position + c.forward * carHalf, c.position - c.forward * carHalf })+ Assert.Greater((Flat(tip) - W(map, TelAvivSouth)).magnitude, lodToTelAvivSouth - 1500f,+ $"at {t:0} s {c.name} reaches onto Tel Aviv South to Lod");+ }+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>... and once the content is signed off (the bake then writes the span from Tel Aviv South:+ /// tools/tests/test_route_paths_bake.py), the same map code runs it from there.</summary>+ [Test]+ public void OnceSignedOffTheGatedStretchDraws()+ {+ var inputs = Inputs();+ var signed = Rebody(inputs.RoutesTsv.Replace("\t1950-03-02\t34.87556 31.94583\t", "\t1950-03-02\t34.777 32.0636\t"));+ Assert.AreNotEqual(inputs.RoutesTsv, signed);+ var warnings = new List<string>();+ var routes = RoutePaths.ReadRuntimeOrYaml(signed, inputs.RoutesYaml, Bounds(), warnings.Add);+ CollectionAssert.IsEmpty(warnings);+ var (map, train) = RunningTrain(routes);+ try+ {+ var (start, end) = train.Stretch;+ Assert.Less((Flat(train.At(start)) - W(map, TelAvivSouth)).magnitude, 1000f, "from Tel Aviv South");+ Assert.Less((Flat(train.At(end)) - W(map, Jerusalem)).magnitude, 1000f, "to Jerusalem");+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ static float DistanceToLine(Vector2 p, List<Vector2> line)+ {+ float best = float.MaxValue;+ for (int i = 1; i < line.Count; i++)+ {+ var a = line[i - 1]; var ab = line[i] - a;+ float t = Mathf.Clamp01(Vector2.Dot(p - a, ab) / Mathf.Max(ab.sqrMagnitude, 1e-6f));+ best = Mathf.Min(best, (a + ab * t - p).magnitude);+ }+ return best;+ }++ [Test]+ public void TheTrainRunsOnTheRailwayFromLodToJerusalem()+ {+ var (map, train) = RunningTrain();+ try+ {+ var line = RouteLayer.World(map.Frame, BootRoutes().Single(r => r.Id == RouteLayer.TrainRoute));+ var (start, end) = train.Stretch;+ Assert.Less((Flat(train.At(start)) - W(map, Lod)).magnitude, 1000f, "it starts at Lod");+ Assert.Less((Flat(train.At(end)) - W(map, Jerusalem)).magnitude, 1000f, "and ends at Jerusalem");+ Assert.That(end - start, Is.InRange(50000f, 80000f), "Lod to Jerusalem by the Sorek valley, about 65 km of the line");+ Assert.AreEqual(RouteTrain.ModelRealLengthM * RouteTrain.Scale * ServiceTrain.ModelSize, train.Length, 1f, "the showcase's locomotive and tender, at ModelSize");++ // Over a whole run there and back, the car's middle is always on the line, and it passes Lod.+ float leg = (end - start - train.Length) / RouteTrain.SpeedMps + RouteTrain.DwellSeconds;+ int samples = 0; float nearLod = float.MaxValue, worst = 0f;+ for (float t = 0f; t < 2f * leg; t += 2f)+ {+ var (h, d) = train.HeadAt(t); train.Place(h, d);+ var c = train.Cars[0].position;+ worst = Mathf.Max(worst, DistanceToLine(new Vector2(c.x, c.z), line));+ nearLod = Mathf.Min(nearLod, (Flat(c) - W(map, Lod)).magnitude);+ samples++;+ }+ TestContext.WriteLine($"{samples} samples over {2f * leg:0} s; the car's middle at most {worst:0} m off the line; nearest Lod {nearLod:0} m");+ Assert.Greater(samples, 200);+ Assert.Less(worst, 60f, "on the railway (to the 50 m table)");+ Assert.Less(nearLod, train.Length, "it reaches Lod");+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }++ /// <summary>The owner's ruling for #668 (16 October 2026, "ride the track, cut walls"): every car rides the line. Each+ /// car's base stays within <see cref="LineBoundM"/> of the line's height (the rail ribbon plus RouteTrain.RideM) under+ /// the car's middle, at every 25 m of the train from Lod to Jerusalem, both ways; on the Sorek valley's tightest bends+ /// the cars' sides pass into the gorge walls instead of floating over them. How deep they go is reported (not+ /// bounded) along the whole route and on the Artuf–Battir grade. On the coastal plain, west of 34.95 E, the sides may go+ /// no deeper than the rail ribbon's own edges may (<see cref="PlainSinkM"/>).</summary>+ [Test]+ public void EveryCarRidesTheLineAndTheWallsTakeTheRest()+ {+ var (map, train) = RunningTrain();+ try+ {+ var data = map.Terrain.terrainData; var origin = map.Terrain.transform.position;+ var (start, end) = train.Stretch;+ float west = map.Frame.ToWorld(35.00, 31.75, 0).x, east = map.Frame.ToWorld(35.13, 31.75, 0).x; // Artuf to Battir+ float plainEdge = map.Frame.ToWorld(34.95, 31.9, 0).x;+ float half = train.Length / 2f, carHalf = train.Length / train.Cars.Count / 2f, halfWidth = train.CarHalfWidth;+ int placements = 0, onGrade = 0, onPlain = 0; float worstOff = 0f, worstPlainSink = float.MinValue;+ var depthAll = new List<float>(); var depthGrade = new List<float>();+ foreach (int dir in new[] { 1, -1 })+ for (float c = start + half; c <= end - half; c += 25f) // the train's middle, Lod to Jerusalem+ {+ train.Place(c + dir * half, dir);+ placements++;+ for (int k = 0; k < train.Cars.Count; k++)+ {+ var car = train.Cars[k];+ var mid = car.position;+ float line = train.At(c + dir * half - dir * train.CarOffsets[k]).y; // the line under the car's own middle+ worstOff = Mathf.Max(worstOff, Mathf.Abs(mid.y - line));+ float depth = float.MinValue; // > 0: the car's side is this far under the ground+ for (int i = -10; i <= 10; i++)+ foreach (int j in new[] { -1, 1 })+ {+ var p = mid + car.forward * (carHalf * i / 10f) + car.right * (halfWidth * j);+ depth = Mathf.Max(depth, RouteLayer.Ground(data, origin, new Vector2(p.x, p.z)) - p.y);+ }+ depthAll.Add(depth);+ if (mid.x >= west && mid.x <= east) { depthGrade.Add(depth); onGrade++; }+ if (mid.x < plainEdge) { onPlain++; worstPlainSink = Mathf.Max(worstPlainSink, depth); }+ }+ }+ string P(List<float> l) { var x = l.OrderBy(v => v).ToList(); return $"p50 {x[x.Count / 2]:0.0} p90 {x[(int)(x.Count * 0.9f)]:0.0} max {x[x.Count - 1]:0.0}"; }+ TestContext.WriteLine($"{placements} placements of {train.Cars.Count} cars from Lod to Jerusalem ({onGrade} car placements on the Artuf-Battir grade, {onPlain} on the plain); " ++ $"the worst base off the line {worstOff:0.0} m; the sides under the ground (m, per car placement): whole route {P(depthAll)}, Sorek {P(depthGrade)}; on the plain at most {worstPlainSink:0.0} m");+ Assert.Greater(onGrade, 200, "non-vacuous: hundreds of car placements on the grade itself");+ Assert.Greater(onPlain, 200, "and on the plain");+ Assert.LessOrEqual(worstOff, LineBoundM, "every car's base rides the line (no float)");+ Assert.LessOrEqual(worstPlainSink, PlainSinkM, "on the plain no car sinks into the ground");+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }+ /// <summary>How far (m) a car's base may sit off the line's height under its middle: 5 m (the owner's "ride the track";+ /// the coordinator's bound).</summary>+ const float LineBoundM = 5f;+ /// <summary>How far (m) a car's side may pass under the ground on the plain: as far as the rail ribbon's own edges may+ /// (RouteLayer.RiseToleranceM, 40 m: "an edge running under a little higher ground reads as a cutting").</summary>+ const float PlainSinkM = RouteLayer.RiseToleranceM;++ [Test]+ public void TheEditorsShowcaseIsUnchanged()+ {+ var map = RouteTests.BuildMap();+ try+ {+ CollectionAssert.IsEmpty(asked, "the editor build and ?shot show the promo's train and stream nothing");+ Assert.IsNull(RouteTests.RoutesRoot(map).Find(ServiceTrain.Name));+ Assert.AreEqual(2 + TrainModels.Coaches, RouteTests.RoutesRoot(map).GetComponentInChildren<RouteTrain>().Cars.Count);+ }+ finally { Object.DestroyImmediate(map.gameObject); }+ }+}diff --git a/unity/Assets/Tests/EditMode/ServiceTrainTests.cs.meta b/unity/Assets/Tests/EditMode/ServiceTrainTests.cs.metanew file mode 100644index 000000000..be1b6657a--- /dev/null+++ b/unity/Assets/Tests/EditMode/ServiceTrainTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: eba310362c7d64120a0848611dcb364a\ No newline at end of file