Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

fix(map): text/bytes loader overloads, one input read in MapScene, hexes/heightmap bounds check, real spacing comment

eyalgolan1ce729e4f175
diff --git a/unity/Assets/Scripts/Map/HeightmapLoader.cs b/unity/Assets/Scripts/Map/HeightmapLoader.cs
index 27a8c89a1..46f0a9300 100644
--- a/unity/Assets/Scripts/Map/HeightmapLoader.cs
+++ b/unity/Assets/Scripts/Map/HeightmapLoader.cs
@@ -13,15 +13,23 @@ namespace Statecraft.Game.Map
public static class HeightmapLoader
{
+ /// <summary>Reads heightmap.json and heightmap.r16 from <paramref name="dir"/> with System.IO (editor and desktop).</summary>
public static (HeightmapMeta meta, float[,] heights) Load(string dir)
{
var metaPath = Path.Combine(dir, "heightmap.json");
- var meta = ParseMeta(metaPath, File.ReadAllText(metaPath));
+ return Load(File.ReadAllText(metaPath), File.ReadAllBytes(Path.Combine(dir, "heightmap.r16")), metaPath);
+ }
+
+ /// <summary>Parses already-read heightmap inputs (no System.IO, so a WebGL build can pass what UnityWebRequest
+ /// fetched). Errors name <paramref name="metaSource"/> for the meta, as the path overload names the file.</summary>
+ public static (HeightmapMeta meta, float[,] heights) Load(string metaJson, byte[] r16, string metaSource = "heightmap.json")
+ {
+ var meta = ParseMeta(metaSource, metaJson);
if (meta.width != meta.height) throw new InvalidDataException($"heightmap.json: width {meta.width} != height {meta.height}");
- var bytes = File.ReadAllBytes(Path.Combine(dir, "heightmap.r16"));
- if (bytes.Length != meta.width * meta.height * 2) throw new InvalidDataException($"heightmap.r16: {bytes.Length} bytes, expected {meta.width * meta.height * 2}");
+ if (r16 == null) throw new ArgumentNullException(nameof(r16));
+ if (r16.Length != meta.width * meta.height * 2) throw new InvalidDataException($"heightmap.r16: {r16.Length} bytes, expected {meta.width * meta.height * 2}");
var raw = new ushort[meta.width * meta.height];
- Buffer.BlockCopy(bytes, 0, raw, 0, bytes.Length); // little-endian on all our targets
+ Buffer.BlockCopy(r16, 0, raw, 0, r16.Length); // little-endian on all our targets
return (meta, ToUnityHeights(raw, meta.width));
}
diff --git a/unity/Assets/Scripts/Map/MapBuilder.cs b/unity/Assets/Scripts/Map/MapBuilder.cs
index c06cc8184..a7e0ecccb 100644
--- a/unity/Assets/Scripts/Map/MapBuilder.cs
+++ b/unity/Assets/Scripts/Map/MapBuilder.cs
@@ -6,7 +6,8 @@ using UnityEngine;
namespace Statecraft.Game.Map
{
[Serializable] public sealed class HexJson { public int q, r; public double lon, lat; public float elev_m; public bool land; public string biome; }
- [Serializable] public sealed class HexFile { public float hex_size_km; public string layout; public HexJson[] hexes; }
+ [Serializable] public sealed class HexBounds { public double lon0, lon1, lat0, lat1; }
+ [Serializable] public sealed class HexFile { public HexBounds bounds; public float hex_size_km; public string layout; public HexJson[] hexes; }
public static class MapBuilder
{
@@ -15,7 +16,9 @@ namespace Statecraft.Game.Map
public const float BiomeLayerTileSizeM = 1000f; // layers are flat colours, so the tiling only needs to be finite
public const int OverlaySegmentsPerEdge = 10; // ~500 m sub-segments on a 5 km hex edge, each draped on the terrain
public const float OverlayClearanceM = 40f * VerticalExaggeration; // above the (exaggerated) terrain surface
- public const int OverlaySamplesPerSegment = 16; // ~31 m steps, finer than the ~79 m heightmap spacing
+ // ~31 m steps, finer than the heightmap spacing on both axes: 78.9 m E-W x 210.6 m N-S
+ // (heightmap.json: 2049 samples, so 2048 intervals, over width_km 161.53 x length_km 431.22).
+ public const int OverlaySamplesPerSegment = 16;
/// <summary>Terrain LOD screen-space error in pixels. Unity's default (5) gives distant cameras (the top-down
/// capture, the 90 km flythrough) a coarse surface that rises above the draped hex outlines in valleys (K2).</summary>
public const float TerrainPixelError = 1f;
@@ -29,7 +32,7 @@ namespace Statecraft.Game.Map
};
/// <summary>Builds the terrain (with a "HexOverlay" child) from the heightmap in <paramref name="mapDir"/> and the
- /// hexes in <paramref name="hexesJson"/>. Materials are editor-made assets (Assets/Materials/Terrain.mat,
+ /// hexes in <paramref name="hexesJson"/>, both read with System.IO. Materials are editor-made assets (Assets/Materials/Terrain.mat,
/// HexOverlay.mat) passed in by the caller: Shader.Find returns null in players (M0 correction 1).
/// Runtime-created objects are owned by a <see cref="MapRuntimeAssets"/> on the returned GameObject and destroyed with it.</summary>
public static GameObject Build(string mapDir, string hexesJson, Material terrainMaterial, Material overlayMaterial)
@@ -37,7 +40,20 @@ namespace Statecraft.Game.Map
if (terrainMaterial == null) throw new ArgumentNullException(nameof(terrainMaterial));
if (overlayMaterial == null) throw new ArgumentNullException(nameof(overlayMaterial));
var (meta, heights) = HeightmapLoader.Load(mapDir);
- var hexFile = LoadHexes(hexesJson);
+ return Build(meta, heights, LoadHexes(hexesJson), terrainMaterial, overlayMaterial);
+ }
+
+ /// <summary>Builds the map from already-read inputs (HeightmapLoader.Load and LoadHexes over text and bytes), so a
+ /// WebGL build needs no System.IO. Throws InvalidDataException, before creating any object, when the hexes' bounds
+ /// differ from the heightmap's by more than <see cref="BoundsTolerance"/>.</summary>
+ public static GameObject Build(HeightmapMeta meta, float[,] heights, HexFile hexFile, Material terrainMaterial, Material overlayMaterial)
+ {
+ if (meta == null) throw new ArgumentNullException(nameof(meta));
+ if (heights == null) throw new ArgumentNullException(nameof(heights));
+ if (hexFile == null) throw new ArgumentNullException(nameof(hexFile));
+ if (terrainMaterial == null) throw new ArgumentNullException(nameof(terrainMaterial));
+ if (overlayMaterial == null) throw new ArgumentNullException(nameof(overlayMaterial));
+ CheckSameArea(meta, hexFile.bounds);
float widthM = meta.width_km * 1000f, lengthM = meta.length_km * 1000f;
float reliefM = (meta.elev_max_m - meta.elev_min_m) * VerticalExaggeration;
var frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, widthM, lengthM);
@@ -62,9 +78,11 @@ namespace Statecraft.Game.Map
/// <summary>Reads and validates hexes.json (non-empty, hex_size_km > 0, pointy layout, known biomes); problems throw
/// InvalidDataException naming the file. Build calls this before creating any object.</summary>
- public static HexFile LoadHexes(string path)
+ public static HexFile LoadHexes(string path) => LoadHexes(File.ReadAllText(path), path);
+
+ /// <summary>Parses already-read hexes.json text; errors name <paramref name="path"/>, as the path overload does.</summary>
+ public static HexFile LoadHexes(string text, string path)
{
- var text = File.ReadAllText(path);
if (string.IsNullOrWhiteSpace(text)) throw new InvalidDataException($"{path}: empty file");
HexFile f;
try { f = JsonUtility.FromJson<HexFile>(text); }
@@ -79,6 +97,18 @@ namespace Statecraft.Game.Map
return f;
}
+ public const double BoundsTolerance = 1e-9; // degrees
+
+ /// <summary>hexes.json and the heightmap must describe the same lon/lat rectangle, or hexes and settlements land
+ /// in the wrong place on the terrain.</summary>
+ static void CheckSameArea(HeightmapMeta meta, HexBounds b)
+ {
+ if (b == null || Math.Abs(b.lon0 - meta.lon0) > BoundsTolerance || Math.Abs(b.lon1 - meta.lon1) > BoundsTolerance
+ || Math.Abs(b.lat0 - meta.lat0) > BoundsTolerance || Math.Abs(b.lat1 - meta.lat1) > BoundsTolerance)
+ throw new InvalidDataException(FormattableString.Invariant(
+ $"hexes.json bounds (lon {b?.lon0}..{b?.lon1}, lat {b?.lat0}..{b?.lat1}) differ from heightmap.json (lon {meta.lon0}..{meta.lon1}, lat {meta.lat0}..{meta.lat1}) by more than {BoundsTolerance}"));
+ }
+
/// <summary>One terrain layer per biome; each alphamap texel blends the biomes of nearby hex centres (BiomeBlender).</summary>
static void ApplyBiomeColours(TerrainData data, GeoFrame frame, HexFile hexes, MapRuntimeAssets assets)
{
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 0c91952f6..87377e391 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -27,14 +27,14 @@ namespace Statecraft.Game.Map
if (cam == null) throw new InvalidOperationException("MapScene needs a camera tagged MainCamera");
Clear();
- var terrainGo = MapBuilder.Build(Paths.StreamingMap, Path.Combine(Paths.Content, "map", "hexes.json"), terrainMaterial, overlayMaterial);
+ 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);
terrainGo.transform.SetParent(transform, true);
Terrain = terrainGo.GetComponent<Terrain>();
var size = Terrain.terrainData.size;
- var (meta, _) = HeightmapLoader.Load(Paths.StreamingMap);
Frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, size.x, size.z);
- var yamlPath = Path.Combine(Paths.Content, "map", SettlementPlacer.DefaultFileName);
- var list = SettlementPlacer.Parse(File.ReadAllText(yamlPath), (meta.lon0, meta.lon1, meta.lat0, meta.lat1), yamlPath);
+ var list = SettlementPlacer.Parse(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,6 +46,17 @@ namespace Statecraft.Game.Map
assets.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));
+
/// <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 is
/// owned by the terrain's MapRuntimeAssets, so destroying the terrain destroys it.</summary>
diff --git a/unity/Assets/Tests/EditMode/MapTests.cs b/unity/Assets/Tests/EditMode/MapTests.cs
index d02268090..21365d04f 100644
--- a/unity/Assets/Tests/EditMode/MapTests.cs
+++ b/unity/Assets/Tests/EditMode/MapTests.cs
@@ -44,6 +44,9 @@ public class MapTests
System.IO.File.WriteAllBytes(System.IO.Path.Combine(dir, "heightmap.r16"), new byte[10]); // 3x3 needs 18 bytes
var ex = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(dir));
StringAssert.Contains("expected 18", ex.Message);
+ var metaPath = System.IO.Path.Combine(dir, "heightmap.json");
+ var fromBytes = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(System.IO.File.ReadAllText(metaPath), new byte[10], metaPath));
+ Assert.AreEqual(ex.Message, fromBytes.Message);
}
// M0 correction 1: no Shader.Find at runtime. Materials are editor-made assets passed into Build.
@@ -281,6 +284,8 @@ public class MapTests
var path = TempFile("hexes.json", json);
var ex = Assert.Throws<System.IO.InvalidDataException>(() => MapBuilder.LoadHexes(path));
StringAssert.Contains(path, ex.Message); StringAssert.Contains(problem, ex.Message);
+ var fromText = Assert.Throws<System.IO.InvalidDataException>(() => MapBuilder.LoadHexes(json, path));
+ Assert.AreEqual(ex.Message, fromText.Message);
}
const string GoodMeta = "\"lon0\":34.2,\"lon1\":35.9,\"lat0\":29.45,\"lat1\":33.35,\"elev_min_m\":-427,\"elev_max_m\":2367";
@@ -305,6 +310,8 @@ public class MapTests
System.IO.File.WriteAllBytes(System.IO.Path.Combine(dir, "heightmap.r16"), new byte[18]);
var ex = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(dir));
StringAssert.Contains("heightmap.json", ex.Message); StringAssert.Contains(problem, ex.Message);
+ var fromText = Assert.Throws<System.IO.InvalidDataException>(() => HeightmapLoader.Load(json, new byte[18], meta));
+ Assert.AreEqual(ex.Message, fromText.Message);
}
[Test]
@@ -319,4 +326,75 @@ public class MapTests
Assert.AreEqual(terrainsBefore, Object.FindObjectsByType<Terrain>(FindObjectsSortMode.None).Length, "orphan Terrain left behind");
Assert.AreEqual(dataBefore, Resources.FindObjectsOfTypeAll<TerrainData>().Length, "orphan TerrainData left behind");
}
+
+ // --- Text/bytes inputs, for the WebGL build that cannot use System.IO on streamingAssetsPath (final fix 3, I2) ---
+
+ static string MetaPath => System.IO.Path.Combine(Paths.StreamingMap, "heightmap.json");
+ static string R16Path => System.IO.Path.Combine(Paths.StreamingMap, "heightmap.r16");
+
+ [Test]
+ public void HeightmapFromBytesMatchesHeightmapFromPath()
+ {
+ var (pm, ph) = HeightmapLoader.Load(Paths.StreamingMap);
+ var (bm, bh) = HeightmapLoader.Load(System.IO.File.ReadAllText(MetaPath), System.IO.File.ReadAllBytes(R16Path), MetaPath);
+ Assert.AreEqual(JsonUtility.ToJson(pm), JsonUtility.ToJson(bm));
+ Assert.AreEqual(ph.GetLength(0), bh.GetLength(0)); Assert.AreEqual(ph.GetLength(1), bh.GetLength(1));
+ int differ = 0;
+ for (int y = 0; y < ph.GetLength(0); y++) for (int x = 0; x < ph.GetLength(1); x++) if (ph[y, x] != bh[y, x]) differ++;
+ Assert.AreEqual(0, differ, "height samples that differ");
+ }
+
+ [Test]
+ public void HexesFromTextMatchHexesFromPath()
+ {
+ var fromPath = MapBuilder.LoadHexes(HexesJson);
+ var fromText = MapBuilder.LoadHexes(System.IO.File.ReadAllText(HexesJson), HexesJson);
+ Assert.AreEqual(JsonUtility.ToJson(fromPath), JsonUtility.ToJson(fromText));
+ }
+
+ [Test]
+ public void BuildFromReadInputsMatchesBuildFromPaths()
+ {
+ var (terrainMat, overlayMat) = Materials();
+ var a = MapBuilder.Build(Paths.StreamingMap, HexesJson, terrainMat, overlayMat);
+ var (meta, heights) = HeightmapLoader.Load(System.IO.File.ReadAllText(MetaPath), System.IO.File.ReadAllBytes(R16Path), MetaPath);
+ var b = MapBuilder.Build(meta, heights, MapBuilder.LoadHexes(System.IO.File.ReadAllText(HexesJson), HexesJson), terrainMat, overlayMat);
+ try
+ {
+ var ta = a.GetComponent<Terrain>().terrainData; var tb = b.GetComponent<Terrain>(); Assert.IsNotNull(tb, "terrain from read inputs");
+ Assert.AreEqual(ta.size, tb.terrainData.size);
+ Assert.AreEqual(ta.heightmapResolution, tb.terrainData.heightmapResolution);
+ Assert.AreEqual(ta.GetHeights(0, 0, ta.heightmapResolution, ta.heightmapResolution), tb.terrainData.GetHeights(0, 0, ta.heightmapResolution, ta.heightmapResolution));
+ Assert.AreEqual(a.transform.Find("HexOverlay").GetComponent<MeshFilter>().sharedMesh.vertices,
+ b.transform.Find("HexOverlay").GetComponent<MeshFilter>().sharedMesh.vertices);
+ }
+ finally { Object.DestroyImmediate(a); Object.DestroyImmediate(b); }
+ }
+
+ // --- hexes.json and the heightmap must cover the same area (final fix 3, M3) ---
+
+ [TestCase(1e-6, 0, 0, 0)]
+ [TestCase(0, -1e-6, 0, 0)]
+ [TestCase(0, 0, 1e-6, 0)]
+ [TestCase(0, 0, 0, -1e-6)]
+ public void HexBoundsThatDifferFromTheHeightmapAreRejectedBeforeAnyObjectIsCreated(double dLon0, double dLon1, double dLat0, double dLat1)
+ {
+ var (terrainMat, overlayMat) = Materials();
+ var meta = HeightmapLoader.Load(Paths.StreamingMap).meta;
+ string D(double v) => v.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
+ var json = "{\"bounds\":{\"lon0\":" + D(meta.lon0 + dLon0) + ",\"lon1\":" + D(meta.lon1 + dLon1) + ",\"lat0\":" + D(meta.lat0 + dLat0) + ",\"lat1\":" + D(meta.lat1 + dLat1)
+ + "},\"hex_size_km\":5,\"layout\":\"pointy\",\"hexes\":[{\"q\":0,\"r\":0,\"lon\":35,\"lat\":32,\"land\":true,\"biome\":\"hills\"}]}";
+ var path = TempFile("hexes.json", json);
+ int terrainsBefore = Object.FindObjectsByType<Terrain>(FindObjectsSortMode.None).Length;
+ var ex = Assert.Throws<System.IO.InvalidDataException>(() => MapBuilder.Build(Paths.StreamingMap, path, terrainMat, overlayMat));
+ StringAssert.Contains("hexes.json", ex.Message); StringAssert.Contains("heightmap.json", ex.Message); StringAssert.Contains("bounds", ex.Message);
+ Assert.AreEqual(terrainsBefore, Object.FindObjectsByType<Terrain>(FindObjectsSortMode.None).Length, "orphan Terrain left behind");
+ }
+
+ [Test]
+ public void RealHexesJsonCarriesTheHeightmapBounds()
+ {
+ var b = MapBuilder.LoadHexes(HexesJson).bounds; var meta = HeightmapLoader.Load(Paths.StreamingMap).meta;
+ Assert.AreEqual(meta.lon0, b.lon0); Assert.AreEqual(meta.lon1, b.lon1); Assert.AreEqual(meta.lat0, b.lat0); Assert.AreEqual(meta.lat1, b.lat1);
+ }
}