A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(unity): content manifest in StreamingAssets, UnityWebRequest loader, GameBoot
eyalgolan57d28a5be326
diff --git a/.gitignore b/.gitignoreindex 443dfcb0c..d03d2c567 100644--- a/.gitignore+++ b/.gitignore@@ -34,3 +34,5 @@ unity/*.slnxunity-*.xmlunity-*.logcaptures/+unity/Assets/StreamingAssets/content/+unity/Assets/StreamingAssets/content.metadiff --git a/unity/Assets/Editor/ContentSync.cs b/unity/Assets/Editor/ContentSync.csnew file mode 100644index 000000000..e209e4ca2--- /dev/null+++ b/unity/Assets/Editor/ContentSync.cs@@ -0,0 +1,26 @@+using System.IO;+using Statecraft.Game.Boot;+using UnityEditor;+using UnityEditor.Build;+using UnityEditor.Build.Reporting;++namespace Statecraft.Game.EditorTools+{+ /// <summary>Copies the repository's content/ into Assets/StreamingAssets/content with a manifest.json before every+ /// player build (git-ignored output), so players read the same content the editor reads from the repo.+ /// Run alone: Unity -batchmode -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.ContentSync.Sync</summary>+ public sealed class ContentSync : IPreprocessBuildWithReport+ {+ public const string Target = "Assets/StreamingAssets/content";++ public int callbackOrder => 0;++ public void OnPreprocessBuild(BuildReport report) => Sync();++ public static void Sync()+ {+ var files = ContentManifest.Copy(Path.Combine(Paths.RepoRoot, "content"), Target);+ UnityEngine.Debug.Log($"ContentSync: {files.Count} files to {Target}");+ }+ }+}diff --git a/unity/Assets/Editor/ContentSync.cs.meta b/unity/Assets/Editor/ContentSync.cs.metanew file mode 100644index 000000000..42bcea5b2--- /dev/null+++ b/unity/Assets/Editor/ContentSync.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 83da074a785594f71ae88895b59ff966\ No newline at end of filediff --git a/unity/Assets/Editor/MapCapture.cs b/unity/Assets/Editor/MapCapture.csindex dfe1df0bf..3e2ec1179 100644--- a/unity/Assets/Editor/MapCapture.cs+++ b/unity/Assets/Editor/MapCapture.cs@@ -15,13 +15,15 @@ public static class MapCapturestatic string CaptureDir => Path.Combine(Paths.RepoRoot, "captures");- /// <summary>Creates and saves Assets/Map.unity: default camera and light plus a MapScene wired to the material assets.</summary>+ /// <summary>Creates and saves Assets/Map.unity: default camera and light, a MapScene wired to the material assets, and+ /// the GameBoot that loads the inputs and builds the map in play mode and in players.</summary>public static void MakeScene(){MapMaterials.Create();var scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);- new GameObject("MapScene").AddComponent<MapScene>().Configure(- Load(MapMaterials.TerrainPath), Load(MapMaterials.OverlayPath), Load(MapMaterials.MarkerPath));+ var map = new GameObject("MapScene").AddComponent<MapScene>();+ map.Configure(Load(MapMaterials.TerrainPath), Load(MapMaterials.OverlayPath), Load(MapMaterials.MarkerPath));+ new GameObject("Boot").AddComponent<Statecraft.Game.Boot.GameBoot>().Configure(map);EditorSceneManager.SaveScene(scene, ScenePath);}diff --git a/unity/Assets/Map.unity b/unity/Assets/Map.unityindex 231c97bba..911034c94 100644--- a/unity/Assets/Map.unity+++ b/unity/Assets/Map.unity@@ -119,7 +119,7 @@ NavMeshSettings:debug:m_Flags: 0m_NavMeshData: {fileID: 0}---- !u!1 &375413292+--- !u!1 &1171856989GameObject:m_ObjectHideFlags: 0m_CorrespondingSourceObject: {fileID: 0}@@ -127,9 +127,101 @@ GameObject:m_PrefabAsset: {fileID: 0}serializedVersion: 6m_Component:- - component: {fileID: 375413295}- - component: {fileID: 375413294}- - component: {fileID: 375413293}+ - component: {fileID: 1171856991}+ - component: {fileID: 1171856990}+ m_Layer: 0+ m_Name: Boot+ m_TagString: Untagged+ m_Icon: {fileID: 0}+ m_NavMeshLayer: 0+ m_StaticEditorFlags: 0+ m_IsActive: 1+--- !u!114 &1171856990+MonoBehaviour:+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_GameObject: {fileID: 1171856989}+ m_Enabled: 1+ m_EditorHideFlags: 0+ m_Script: {fileID: 11500000, guid: 9dba4dacfc46b405a9260a42b3b83be4, type: 3}+ m_Name:+ m_EditorClassIdentifier: Statecraft.Game::Statecraft.Game.Boot.GameBoot+ map: {fileID: 1239438371}+--- !u!4 &1171856991+Transform:+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_GameObject: {fileID: 1171856989}+ serializedVersion: 2+ m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}+ m_LocalPosition: {x: 0, y: 0, z: 0}+ m_LocalScale: {x: 1, y: 1, z: 1}+ m_ConstrainProportionsScale: 0+ m_Children: []+ m_Father: {fileID: 0}+ m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}+--- !u!1 &1239438370+GameObject:+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ serializedVersion: 6+ m_Component:+ - component: {fileID: 1239438372}+ - component: {fileID: 1239438371}+ m_Layer: 0+ m_Name: MapScene+ m_TagString: Untagged+ m_Icon: {fileID: 0}+ m_NavMeshLayer: 0+ m_StaticEditorFlags: 0+ m_IsActive: 1+--- !u!114 &1239438371+MonoBehaviour:+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_GameObject: {fileID: 1239438370}+ m_Enabled: 1+ m_EditorHideFlags: 0+ m_Script: {fileID: 11500000, guid: f7b27c26d62c5400c99c12b492a87a6d, type: 3}+ m_Name:+ m_EditorClassIdentifier: Statecraft.Game::Statecraft.Game.Map.MapScene+ terrainMaterial: {fileID: 2100000, guid: fc63b910005e64adaaa42ba488bcc248, type: 2}+ overlayMaterial: {fileID: 2100000, guid: 29dd83b7b3b1f4a4aa5a710be0078164, type: 2}+ markerMaterial: {fileID: 2100000, guid: 7c65bbd4355344f1990495c458323a4e, type: 2}+--- !u!4 &1239438372+Transform:+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ m_GameObject: {fileID: 1239438370}+ serializedVersion: 2+ m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}+ m_LocalPosition: {x: 0, y: 0, z: 0}+ m_LocalScale: {x: 1, y: 1, z: 1}+ m_ConstrainProportionsScale: 0+ m_Children: []+ m_Father: {fileID: 0}+ m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}+--- !u!1 &1924070566+GameObject:+ m_ObjectHideFlags: 0+ m_CorrespondingSourceObject: {fileID: 0}+ m_PrefabInstance: {fileID: 0}+ m_PrefabAsset: {fileID: 0}+ serializedVersion: 6+ m_Component:+ - component: {fileID: 1924070569}+ - component: {fileID: 1924070568}+ - component: {fileID: 1924070567}m_Layer: 0m_Name: Main Cameram_TagString: MainCamera@@ -137,21 +229,21 @@ GameObject:m_NavMeshLayer: 0m_StaticEditorFlags: 0m_IsActive: 1---- !u!81 &375413293+--- !u!81 &1924070567AudioListener:m_ObjectHideFlags: 0m_CorrespondingSourceObject: {fileID: 0}m_PrefabInstance: {fileID: 0}m_PrefabAsset: {fileID: 0}- m_GameObject: {fileID: 375413292}+ m_GameObject: {fileID: 1924070566}m_Enabled: 1---- !u!20 &375413294+--- !u!20 &1924070568Camera:m_ObjectHideFlags: 0m_CorrespondingSourceObject: {fileID: 0}m_PrefabInstance: {fileID: 0}m_PrefabAsset: {fileID: 0}- m_GameObject: {fileID: 375413292}+ m_GameObject: {fileID: 1924070566}m_Enabled: 1serializedVersion: 2m_ClearFlags: 1@@ -196,13 +288,13 @@ Camera:m_OcclusionCulling: 1m_StereoConvergence: 10m_StereoSeparation: 0.022---- !u!4 &375413295+--- !u!4 &1924070569Transform:m_ObjectHideFlags: 0m_CorrespondingSourceObject: {fileID: 0}m_PrefabInstance: {fileID: 0}m_PrefabAsset: {fileID: 0}- m_GameObject: {fileID: 375413292}+ m_GameObject: {fileID: 1924070566}serializedVersion: 2m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}m_LocalPosition: {x: 0, y: 1, z: -10}@@ -211,54 +303,7 @@ Transform:m_Children: []m_Father: {fileID: 0}m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}---- !u!1 &632313118-GameObject:- m_ObjectHideFlags: 0- m_CorrespondingSourceObject: {fileID: 0}- m_PrefabInstance: {fileID: 0}- m_PrefabAsset: {fileID: 0}- serializedVersion: 6- m_Component:- - component: {fileID: 632313120}- - component: {fileID: 632313119}- m_Layer: 0- m_Name: MapScene- m_TagString: Untagged- m_Icon: {fileID: 0}- m_NavMeshLayer: 0- m_StaticEditorFlags: 0- m_IsActive: 1---- !u!114 &632313119-MonoBehaviour:- m_ObjectHideFlags: 0- m_CorrespondingSourceObject: {fileID: 0}- m_PrefabInstance: {fileID: 0}- m_PrefabAsset: {fileID: 0}- m_GameObject: {fileID: 632313118}- m_Enabled: 1- m_EditorHideFlags: 0- m_Script: {fileID: 11500000, guid: f7b27c26d62c5400c99c12b492a87a6d, type: 3}- m_Name:- m_EditorClassIdentifier: Statecraft.Game::Statecraft.Game.Map.MapScene- terrainMaterial: {fileID: 2100000, guid: fc63b910005e64adaaa42ba488bcc248, type: 2}- overlayMaterial: {fileID: 2100000, guid: 29dd83b7b3b1f4a4aa5a710be0078164, type: 2}- markerMaterial: {fileID: 2100000, guid: 7c65bbd4355344f1990495c458323a4e, type: 2}---- !u!4 &632313120-Transform:- m_ObjectHideFlags: 0- m_CorrespondingSourceObject: {fileID: 0}- m_PrefabInstance: {fileID: 0}- m_PrefabAsset: {fileID: 0}- m_GameObject: {fileID: 632313118}- serializedVersion: 2- m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}- m_LocalPosition: {x: 0, y: 0, z: 0}- m_LocalScale: {x: 1, y: 1, z: 1}- m_ConstrainProportionsScale: 0- m_Children: []- m_Father: {fileID: 0}- m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}---- !u!1 &1720501430+--- !u!1 &1964867373GameObject:m_ObjectHideFlags: 0m_CorrespondingSourceObject: {fileID: 0}@@ -266,8 +311,8 @@ GameObject:m_PrefabAsset: {fileID: 0}serializedVersion: 6m_Component:- - component: {fileID: 1720501432}- - component: {fileID: 1720501431}+ - component: {fileID: 1964867375}+ - component: {fileID: 1964867374}m_Layer: 0m_Name: Directional Lightm_TagString: Untagged@@ -275,13 +320,13 @@ GameObject:m_NavMeshLayer: 0m_StaticEditorFlags: 0m_IsActive: 1---- !u!108 &1720501431+--- !u!108 &1964867374Light:m_ObjectHideFlags: 0m_CorrespondingSourceObject: {fileID: 0}m_PrefabInstance: {fileID: 0}m_PrefabAsset: {fileID: 0}- m_GameObject: {fileID: 1720501430}+ m_GameObject: {fileID: 1964867373}m_Enabled: 1serializedVersion: 12m_Type: 1@@ -340,13 +385,13 @@ Light:m_LightUnit: 1m_LuxAtDistance: 1m_EnableSpotReflector: 1---- !u!4 &1720501432+--- !u!4 &1964867375Transform:m_ObjectHideFlags: 0m_CorrespondingSourceObject: {fileID: 0}m_PrefabInstance: {fileID: 0}m_PrefabAsset: {fileID: 0}- m_GameObject: {fileID: 1720501430}+ m_GameObject: {fileID: 1964867373}serializedVersion: 2m_LocalRotation: {x: 0.40821788, y: -0.23456968, z: 0.10938163, w: 0.8754261}m_LocalPosition: {x: 0, y: 3, z: 0}@@ -359,6 +404,7 @@ Transform:SceneRoots:m_ObjectHideFlags: 0m_Roots:- - {fileID: 375413295}- - {fileID: 1720501432}- - {fileID: 632313120}+ - {fileID: 1924070569}+ - {fileID: 1964867375}+ - {fileID: 1239438372}+ - {fileID: 1171856991}diff --git a/unity/Assets/Scripts/Boot.meta b/unity/Assets/Scripts/Boot.metanew file mode 100644index 000000000..4e240a157--- /dev/null+++ b/unity/Assets/Scripts/Boot.meta@@ -0,0 +1,8 @@+fileFormatVersion: 2+guid: 414272d0f3070444abec82a5ef7d1e7d+folderAsset: yes+DefaultImporter:+ externalObjects: {}+ userData:+ assetBundleName:+ assetBundleVariant:diff --git a/unity/Assets/Scripts/Boot/ContentManifest.cs b/unity/Assets/Scripts/Boot/ContentManifest.csnew file mode 100644index 000000000..35d89b36d--- /dev/null+++ b/unity/Assets/Scripts/Boot/ContentManifest.cs@@ -0,0 +1,59 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using UnityEngine;++namespace Statecraft.Game.Boot+{+ /// <summary>The list of content files a player needs, so a WebGL build (no directory listing over HTTP) can fetch+ /// them: content/manifest.json in StreamingAssets, {"files": [...]} with paths relative to content/, '/' separated,+ /// ordinal order. The editor build step (ContentSync) copies the files and writes the manifest.</summary>+ public static class ContentManifest+ {+ public const string FileName = "manifest.json";+ /// <summary>The map files players read: hexes.json and every map/*.yaml (settlements; settlement hexes for the sim).+ /// The precipitation files are tool inputs only.</summary>+ public const string HexesJson = "map/hexes.json";++ [Serializable] sealed class ManifestJson { public string[] files = new string[0]; }++ /// <summary>Every *.yaml in <paramref name="contentDir"/>, events/ and map/, plus map/hexes.json; ordinal order.</summary>+ public static List<string> Collect(string contentDir)+ {+ IEnumerable<string> Yaml(string sub) => Directory.GetFiles(Path.Combine(contentDir, sub), "*.yaml")+ .Select(f => (sub == "" ? "" : sub + "/") + Path.GetFileName(f));+ if (!File.Exists(Path.Combine(contentDir, HexesJson))) throw new FileNotFoundException("content file missing", HexesJson);+ return Yaml("").Concat(Yaml("events")).Concat(Yaml("map")).Append(HexesJson)+ .OrderBy(f => f, StringComparer.Ordinal).ToList();+ }++ public static string Write(IEnumerable<string> files) => JsonUtility.ToJson(new ManifestJson { files = files.ToArray() }, true);++ /// <summary>Parses manifest.json; throws InvalidDataException when it is not a manifest.</summary>+ public static List<string> Parse(string json)+ {+ ManifestJson? m;+ try { m = JsonUtility.FromJson<ManifestJson>(json); }+ catch (ArgumentException e) { throw new InvalidDataException($"{FileName}: malformed JSON ({e.Message})", e); }+ if (m?.files == null || m.files.Length == 0) throw new InvalidDataException($"{FileName}: no files");+ return m.files.ToList();+ }++ /// <summary>Replaces <paramref name="targetDir"/> with a copy of the collected files plus manifest.json.</summary>+ public static List<string> Copy(string contentDir, string targetDir)+ {+ var files = Collect(contentDir);+ if (Directory.Exists(targetDir)) Directory.Delete(targetDir, true);+ foreach (var f in files)+ {+ var to = Path.Combine(targetDir, f);+ Directory.CreateDirectory(Path.GetDirectoryName(to)!);+ File.Copy(Path.Combine(contentDir, f), to);+ }+ File.WriteAllText(Path.Combine(targetDir, FileName), Write(files));+ return files;+ }+ }+}diff --git a/unity/Assets/Scripts/Boot/ContentManifest.cs.meta b/unity/Assets/Scripts/Boot/ContentManifest.cs.metanew file mode 100644index 000000000..261da3ffe--- /dev/null+++ b/unity/Assets/Scripts/Boot/ContentManifest.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 5ca4c8b9980404c79afb97b83169ab6f\ No newline at end of filediff --git a/unity/Assets/Scripts/Boot/GameBoot.cs b/unity/Assets/Scripts/Boot/GameBoot.csnew file mode 100644index 000000000..e5979f143--- /dev/null+++ b/unity/Assets/Scripts/Boot/GameBoot.cs@@ -0,0 +1,39 @@+#nullable enable+using System;+using Statecraft.Game.Map;+using UnityEngine;++namespace Statecraft.Game.Boot+{+ /// <summary>The first thing Map.unity runs: loads the game inputs (fetched on WebGL, read from disk elsewhere), builds+ /// the map, then raises Ready for the game (GameRoot) to start. A failure is logged ("BOOT FAIL ...") and kept in Error.</summary>+ public sealed class GameBoot : MonoBehaviour+ {+ [SerializeField] MapScene map = null!;++ public GameInputs? Inputs { get; private set; }+ public string? Error { get; private set; }+ public event Action<GameInputs>? Ready;++ public void Configure(MapScene mapScene) => map = mapScene;++ async void Start()+ {+ try+ {+ Inputs = Application.platform == RuntimePlatform.WebGLPlayer+ ? await GameInputs.FetchAsync(GameInputs.StreamingUrl())+ : GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);+ map.Build(Inputs.Map);+ Debug.Log($"BOOT OK {Inputs.Content.Events.Count} events");+ Ready?.Invoke(Inputs);+ }+ catch (Exception e)+ {+ Error = e.Message;+ Debug.LogError("BOOT FAIL " + e.Message);+ Debug.LogException(e);+ }+ }+ }+}diff --git a/unity/Assets/Scripts/Boot/GameBoot.cs.meta b/unity/Assets/Scripts/Boot/GameBoot.cs.metanew file mode 100644index 000000000..257365ae7--- /dev/null+++ b/unity/Assets/Scripts/Boot/GameBoot.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 9dba4dacfc46b405a9260a42b3b83be4\ No newline at end of filediff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.csnew file mode 100644index 000000000..794a6bad6--- /dev/null+++ b/unity/Assets/Scripts/Boot/GameInputs.cs@@ -0,0 +1,100 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using Statecraft.Game.Map;+using Statecraft.Sim;+using UnityEngine;+using UnityEngine.Networking;++namespace Statecraft.Game.Boot+{+ /// <summary>The map's raw inputs, already read (no System.IO needed afterwards).</summary>+ public sealed class MapInputs+ {+ public string HeightmapJson = "", HexesJson = "", SettlementsYaml = "";+ public byte[] HeightmapR16 = new byte[0];+ }++ /// <summary>Everything the game loads at start: the sim content and the map inputs. Desktop and the editor read+ /// files (FromDisk); WebGL cannot read StreamingAssets with System.IO, so it fetches them with UnityWebRequest from+ /// the manifest (FetchAsync, tech notes section 2).</summary>+ public sealed class GameInputs+ {+ public Content Content = null!;+ public MapInputs Map = null!;++ public static MapInputs MapFromDisk(string contentDir, string mapDir) => new MapInputs+ {+ HeightmapJson = File.ReadAllText(Path.Combine(mapDir, "heightmap.json")),+ HeightmapR16 = File.ReadAllBytes(Path.Combine(mapDir, "heightmap.r16")),+ HexesJson = File.ReadAllText(Path.Combine(contentDir, "map", "hexes.json")),+ SettlementsYaml = File.ReadAllText(Path.Combine(contentDir, "map", SettlementPlacer.DefaultFileName)),+ };++ public static GameInputs FromDisk(string contentDir, string mapDir) =>+ new GameInputs { Content = ContentLoader.Load(contentDir), Map = MapFromDisk(contentDir, mapDir) };++ /// <summary>Builds the inputs from fetched texts (keys are manifest paths) and heightmap bytes.</summary>+ public static GameInputs FromTexts(IReadOnlyDictionary<string, string> texts, IEnumerable<string> manifest, string heightmapJson, byte[] r16)+ {+ var events = manifest.Where(f => f.StartsWith("events/", StringComparison.Ordinal)).ToList();+ var content = ContentLoader.Load(rel => texts.TryGetValue(rel, out var t) ? t : null, events);+ return new GameInputs+ {+ Content = content,+ Map = new MapInputs+ {+ HeightmapJson = heightmapJson, HeightmapR16 = r16,+ HexesJson = texts["map/hexes.json"], SettlementsYaml = texts["map/" + SettlementPlacer.DefaultFileName],+ },+ };+ }++ /// <summary>StreamingAssets as a URL: the page-relative URL on WebGL, a file:// URI elsewhere.</summary>+ public static string StreamingUrl() =>+ Application.streamingAssetsPath.Contains("://") ? Application.streamingAssetsPath : new Uri(Application.streamingAssetsPath).AbsoluteUri;++ static UnityWebRequest Start(string url)+ {+ var r = UnityWebRequest.Get(url);+ r.SendWebRequest();+ return r;+ }++ /// <summary>Waits a frame at a time (no threads on WebGL; an Awaitable is never awaited twice).</summary>+ static async Awaitable<UnityWebRequest> Done(UnityWebRequest r, string name)+ {+ while (!r.isDone) await Awaitable.NextFrameAsync();+ if (r.result != UnityWebRequest.Result.Success)+ {+ var error = $"{name}: {r.error} ({r.url})";+ r.Dispose();+ throw new IOException(error);+ }+ return r;+ }++ static async Awaitable<string> Text(UnityWebRequest r, string name)+ {+ using var done = await Done(r, name);+ return done.downloadHandler.text;+ }++ /// <summary>Fetches the manifest, then starts every download before awaiting any (parallel), then loads.</summary>+ public static async Awaitable<GameInputs> FetchAsync(string baseUrl)+ {+ var manifest = ContentManifest.Parse(await Text(Start(baseUrl + "/content/" + ContentManifest.FileName), ContentManifest.FileName));+ var requests = manifest.Select(f => (file: f, request: Start(baseUrl + "/content/" + f))).ToList();+ var meta = Start(baseUrl + "/map/heightmap.json");+ var r16 = Start(baseUrl + "/map/heightmap.r16");+ var texts = new Dictionary<string, string>();+ foreach (var (file, request) in requests) texts[file] = await Text(request, file);+ var metaText = await Text(meta, "heightmap.json");+ byte[] bytes;+ using (var done = await Done(r16, "heightmap.r16")) bytes = done.downloadHandler.data;+ return FromTexts(texts, manifest, metaText, bytes);+ }+ }+}diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs.meta b/unity/Assets/Scripts/Boot/GameInputs.cs.metanew file mode 100644index 000000000..f67716bad--- /dev/null+++ b/unity/Assets/Scripts/Boot/GameInputs.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 167dadd9a17f74bdb9a1fcb8536bcafd\ No newline at end of filediff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.csindex 87377e391..a583911f8 100644--- a/unity/Assets/Scripts/Map/MapScene.cs+++ b/unity/Assets/Scripts/Map/MapScene.cs@@ -1,25 +1,30 @@using System;using System.IO;+using Statecraft.Game.Boot;using UnityEngine;namespace Statecraft.Game.Map{- /// <summary>Builds the whole map at runtime: terrain, hexes, 1948 settlements, camera. Materials are editor-made assets- /// (M0 correction 1). Build is idempotent: it destroys what the previous Build made first.</summary>+ /// <summary>Builds the whole map: terrain, hexes, 1948 settlements, camera. Materials are editor-made assets+ /// (M0 correction 1). Build is idempotent: it destroys what the previous Build made first. In play mode the Boot+ /// component calls Build(inputs) once the inputs are loaded (fetched on WebGL); editor tools call Build().</summary>public sealed class MapScene : MonoBehaviour{[SerializeField] Material terrainMaterial, overlayMaterial, markerMaterial;public GeoFrame Frame { get; private set; }public Terrain Terrain { get; private set; }-- void Awake() => Build();+ public Material MarkerMaterial => markerMaterial;public void Configure(Material terrain, Material overlay, Material marker){ terrainMaterial = terrain; overlayMaterial = overlay; markerMaterial = marker; }- public void Build()+ /// <summary>Builds from the repository files with System.IO (editor and desktop only).</summary>+ public void Build() => Build(GameInputs.MapFromDisk(Paths.Content, Paths.StreamingMap));++ public void Build(MapInputs inputs){+ if (inputs == null) throw new ArgumentNullException(nameof(inputs));if (terrainMaterial == null) throw new InvalidOperationException("MapScene: terrainMaterial is not assigned");if (overlayMaterial == null) throw new InvalidOperationException("MapScene: overlayMaterial is not assigned");if (markerMaterial == null) throw new InvalidOperationException("MapScene: markerMaterial is not assigned");@@ -27,14 +32,13 @@ namespace Statecraft.Game.Mapif (cam == null) throw new InvalidOperationException("MapScene needs a camera tagged MainCamera");Clear();- var (metaJson, r16, hexesJson, settlementsYaml) = ReadInputs();- var (meta, heights) = HeightmapLoader.Load(metaJson, r16, MetaPath);- var terrainGo = MapBuilder.Build(meta, heights, MapBuilder.LoadHexes(hexesJson, HexesPath), terrainMaterial, overlayMaterial);+ var (meta, heights) = HeightmapLoader.Load(inputs.HeightmapJson, inputs.HeightmapR16, MetaPath);+ var terrainGo = MapBuilder.Build(meta, heights, MapBuilder.LoadHexes(inputs.HexesJson, HexesPath), terrainMaterial, overlayMaterial);terrainGo.transform.SetParent(transform, true);Terrain = terrainGo.GetComponent<Terrain>();var size = Terrain.terrainData.size;Frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, size.x, size.z);- var list = SettlementPlacer.Parse(settlementsYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), SettlementsPath);+ var list = SettlementPlacer.Parse(inputs.SettlementsYaml, (meta.lon0, meta.lon1, meta.lat0, meta.lat1), SettlementsPath);SettlementPlacer.Place(list, Frame, Terrain, markerMaterial).transform.SetParent(transform, true);if (!cam.TryGetComponent(out CameraRig rig)) rig = cam.gameObject.AddComponent<CameraRig>();@@ -46,16 +50,9 @@ namespace Statecraft.Game.Mapassets.Own(rig.Volume.profile);}- static string MetaPath => Path.Combine(Paths.StreamingMap, "heightmap.json");- static string R16Path => Path.Combine(Paths.StreamingMap, "heightmap.r16");- static string HexesPath => Path.Combine(Paths.Content, "map", "hexes.json");- static string SettlementsPath => Path.Combine(Paths.Content, "map", SettlementPlacer.DefaultFileName);-- /// <summary>Every map input, read once. This uses System.IO, which works in the editor (and desktop players) only:- /// M3 (first player build) replaces it with UnityWebRequest for WebGL, which cannot read streamingAssetsPath with- /// System.IO, and copies content/map into StreamingAssets.</summary>- static (string metaJson, byte[] r16, string hexesJson, string settlementsYaml) ReadInputs() =>- (File.ReadAllText(MetaPath), File.ReadAllBytes(R16Path), File.ReadAllText(HexesPath), File.ReadAllText(SettlementsPath));+ static string MetaPath => "heightmap.json";+ static string HexesPath => "hexes.json";+ static string SettlementsPath => SettlementPlacer.DefaultFileName;/// <summary>Destroys every child: all of them are things Build made (terrain, Settlements, PostFX). Walking the/// hierarchy rather than remembered fields keeps Build idempotent after a domain reload (R2). The VolumeProfile isdiff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.csnew file mode 100644index 000000000..9dbfdd110--- /dev/null+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs@@ -0,0 +1,70 @@+using System.Collections;+using System.IO;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.Boot;+using Statecraft.Sim;+using UnityEngine;+using UnityEngine.TestTools;++public class GameInputsTests+{+ [Test]+ public void TheManifestListsEveryContentFileThePlayerNeeds()+ {+ var files = ContentManifest.Collect(Paths.Content);+ CollectionAssert.Contains(files, "people.yaml");+ CollectionAssert.Contains(files, "events/armistice_egypt.yaml");+ CollectionAssert.Contains(files, "map/hexes.json");+ CollectionAssert.Contains(files, "map/settlements_1948.yaml");+ CollectionAssert.DoesNotContain(files, "map/precip_bio12.u16"); // tool input only+ CollectionAssert.AreEqual(files.OrderBy(f => f, System.StringComparer.Ordinal).ToList(), files);+ Assert.AreEqual(files, ContentManifest.Parse(ContentManifest.Write(files)));+ }++ [Test]+ public void ABrokenManifestIsAClearError()+ {+ var ex = Assert.Throws<InvalidDataException>(() => ContentManifest.Parse("{\"files\": []}"));+ Assert.AreEqual("manifest.json: no files", ex.Message);+ }++ static string StagedSite()+ {+ var site = Path.Combine(Path.GetTempPath(), "statecraft-site-" + System.Guid.NewGuid().ToString("N"));+ ContentManifest.Copy(Paths.Content, Path.Combine(site, "content"));+ Directory.CreateDirectory(Path.Combine(site, "map"));+ foreach (var f in new[] { "heightmap.json", "heightmap.r16" }) File.Copy(Path.Combine(Paths.StreamingMap, f), Path.Combine(site, "map", f));+ return site;+ }++ [UnityTest]+ public IEnumerator FetchingOverUrlsLoadsTheSameContentAsTheDisk()+ {+ var site = StagedSite();+ var fetch = GameInputs.FetchAsync(new System.Uri(site).AbsoluteUri.TrimEnd('/')).GetAwaiter();+ for (int i = 0; i < 600 && !fetch.IsCompleted; i++) yield return null;+ Assert.IsTrue(fetch.IsCompleted, "fetch did not finish in 600 editor frames");+ var fetched = fetch.GetResult();+ var disk = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);+ Assert.AreEqual(disk.Map.HeightmapR16.Length, fetched.Map.HeightmapR16.Length);+ Assert.AreEqual(disk.Map.HexesJson, fetched.Map.HexesJson);+ Assert.AreEqual(disk.Content.Events.Count, fetched.Content.Events.Count);+ Assert.AreEqual(Simulation.NewGame(disk.Content, 7, Mode.Historical).Hash(), Simulation.NewGame(fetched.Content, 7, Mode.Historical).Hash());+ Directory.Delete(site, true);+ }++ [UnityTest]+ public IEnumerator AMissingFileNamesTheFile()+ {+ var site = StagedSite();+ File.Delete(Path.Combine(site, "content", "people.yaml"));+ var fetch = GameInputs.FetchAsync(new System.Uri(site).AbsoluteUri.TrimEnd('/')).GetAwaiter();+ for (int i = 0; i < 600 && !fetch.IsCompleted; i++) yield return null;+ Assert.IsTrue(fetch.IsCompleted, "fetch did not finish in 600 editor frames");+ var ex = Assert.Throws<IOException>(() => fetch.GetResult());+ StringAssert.StartsWith("people.yaml: ", ex.Message);+ Directory.Delete(site, true);+ }+}diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs.meta b/unity/Assets/Tests/EditMode/GameInputsTests.cs.metanew file mode 100644index 000000000..9be82ae2c--- /dev/null+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 0d96b3d4eb8f84f6789c6d4a503b1777\ No newline at end of file