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.

feat(map): terrain from Copernicus heightmap, biome layers, hex overlay

eyalgolan70e193eefdbd
diff --git a/unity/Assets/Editor/MapMaterials.cs b/unity/Assets/Editor/MapMaterials.cs
new file mode 100644
index 000000000..d6d95e361
--- /dev/null
+++ b/unity/Assets/Editor/MapMaterials.cs
@@ -0,0 +1,35 @@
+using UnityEditor;
+using UnityEngine;
+
+namespace Statecraft.Game.EditorTools
+{
+ /// <summary>Creates the map's material assets (M0 correction 1: Shader.Find returns null in players, so materials are
+ /// editor-made assets passed to MapBuilder.Build through serialized fields). Idempotent.
+ /// Run headless: Unity -batchmode -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.MapMaterials.Create</summary>
+ public static class MapMaterials
+ {
+ public const string Folder = "Assets/Materials";
+ public const string TerrainPath = Folder + "/Terrain.mat";
+ public const string OverlayPath = Folder + "/HexOverlay.mat";
+
+ public static void Create()
+ {
+ if (!AssetDatabase.IsValidFolder(Folder)) AssetDatabase.CreateFolder("Assets", "Materials");
+ Make(TerrainPath, "Universal Render Pipeline/Terrain/Lit", null);
+ Make(OverlayPath, "Universal Render Pipeline/Unlit", new Color(0.15f, 0.12f, 0.08f, 1f));
+ AssetDatabase.SaveAssets();
+ }
+
+ static void Make(string path, string shaderName, Color? colour)
+ {
+ var shader = Shader.Find(shaderName); // editor only: fine here
+ if (shader == null) throw new System.InvalidOperationException($"shader not found: {shaderName}");
+ var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
+ if (mat == null) { mat = new Material(shader); AssetDatabase.CreateAsset(mat, path); }
+ else mat.shader = shader;
+ mat.enableInstancing = true;
+ if (colour.HasValue) mat.color = colour.Value;
+ EditorUtility.SetDirty(mat);
+ }
+ }
+}
diff --git a/unity/Assets/Editor/MapMaterials.cs.meta b/unity/Assets/Editor/MapMaterials.cs.meta
new file mode 100644
index 000000000..6c8476f93
--- /dev/null
+++ b/unity/Assets/Editor/MapMaterials.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 6f0fe9a024ae14aec949594f35bcaa8b
\ No newline at end of file
diff --git a/unity/Assets/Materials.meta b/unity/Assets/Materials.meta
new file mode 100644
index 000000000..0392da22c
--- /dev/null
+++ b/unity/Assets/Materials.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 84aca41f0a37d4628bb184a143bdd488
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Materials/HexOverlay.mat b/unity/Assets/Materials/HexOverlay.mat
new file mode 100644
index 000000000..d1a8a0d1e
--- /dev/null
+++ b/unity/Assets/Materials/HexOverlay.mat
@@ -0,0 +1,71 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-5879377743329346241
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
+ m_Name:
+ m_EditorClassIdentifier: Unity.RenderPipelines.Universal.Editor::UnityEditor.Rendering.Universal.AssetVersion
+ version: 10
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: HexOverlay
+ m_Shader: {fileID: 4800000, guid: 650dd9526735d5b46b79224bc6e94025, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 1
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap:
+ RenderType: Opaque
+ disabledShaderPasses:
+ - MOTIONVECTORS
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _BaseMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _AddPrecomputedVelocity: 0
+ - _AlphaClip: 0
+ - _AlphaToMask: 0
+ - _Blend: 0
+ - _BlendOp: 0
+ - _Cull: 2
+ - _Cutoff: 0.5
+ - _DstBlend: 0
+ - _DstBlendAlpha: 0
+ - _QueueOffset: 0
+ - _SampleGI: 0
+ - _SrcBlend: 1
+ - _SrcBlendAlpha: 1
+ - _Surface: 0
+ - _XRMotionVectorsPass: 1
+ - _ZWrite: 1
+ m_Colors:
+ - _BaseColor: {r: 0.15, g: 0.12, b: 0.08, a: 1}
+ - _Color: {r: 0.14999998, g: 0.11999995, b: 0.07999996, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/unity/Assets/Materials/HexOverlay.mat.meta b/unity/Assets/Materials/HexOverlay.mat.meta
new file mode 100644
index 000000000..cddf1f7d2
--- /dev/null
+++ b/unity/Assets/Materials/HexOverlay.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 29dd83b7b3b1f4a4aa5a710be0078164
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Materials/Terrain.mat b/unity/Assets/Materials/Terrain.mat
new file mode 100644
index 000000000..2a8ad8ce2
--- /dev/null
+++ b/unity/Assets/Materials/Terrain.mat
@@ -0,0 +1,116 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: Terrain
+ m_Shader: {fileID: 4800000, guid: 69c1f799e772cb6438f56c23efccb782, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 1
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap: {}
+ disabledShaderPasses: []
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _Control:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Mask0:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Mask1:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Mask2:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Mask3:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Normal0:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Normal1:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Normal2:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Normal3:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Splat0:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Splat1:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Splat2:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _Splat3:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _TerrainHolesTexture:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _EnableHeightBlend: 0
+ - _EnableInstancedPerPixelNormal: 1
+ - _HeightTransition: 0
+ - _Metallic0: 0
+ - _Metallic1: 0
+ - _Metallic2: 0
+ - _Metallic3: 0
+ - _NumLayersCount: 1
+ - _Smoothness0: 0.5
+ - _Smoothness1: 0.5
+ - _Smoothness2: 0.5
+ - _Smoothness3: 0.5
+ m_Colors:
+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
+--- !u!114 &8557332215924006562
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_GameObject: {fileID: 0}
+ m_Enabled: 1
+ m_EditorHideFlags: 0
+ m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
+ m_Name:
+ m_EditorClassIdentifier: Unity.RenderPipelines.Universal.Editor::UnityEditor.Rendering.Universal.AssetVersion
+ version: 10
diff --git a/unity/Assets/Materials/Terrain.mat.meta b/unity/Assets/Materials/Terrain.mat.meta
new file mode 100644
index 000000000..fb29d950d
--- /dev/null
+++ b/unity/Assets/Materials/Terrain.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: fc63b910005e64adaaa42ba488bcc248
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Scripts/Map.meta b/unity/Assets/Scripts/Map.meta
new file mode 100644
index 000000000..c4e405c67
--- /dev/null
+++ b/unity/Assets/Scripts/Map.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: a88bc13d7281a400ba1b6326e89616cd
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/unity/Assets/Scripts/Map/GeoFrame.cs b/unity/Assets/Scripts/Map/GeoFrame.cs
new file mode 100644
index 000000000..906109e6c
--- /dev/null
+++ b/unity/Assets/Scripts/Map/GeoFrame.cs
@@ -0,0 +1,14 @@
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>Equirectangular lon/lat -> world metres. x = east, z = north, origin = south-west corner.</summary>
+ public readonly struct GeoFrame
+ {
+ public readonly double Lon0, Lon1, Lat0, Lat1; public readonly float WidthM, LengthM;
+ public GeoFrame(double lon0, double lon1, double lat0, double lat1, float widthM, float lengthM)
+ { Lon0 = lon0; Lon1 = lon1; Lat0 = lat0; Lat1 = lat1; WidthM = widthM; LengthM = lengthM; }
+ public Vector3 ToWorld(double lon, double lat, float y) =>
+ new Vector3((float)((lon - Lon0) / (Lon1 - Lon0) * WidthM), y, (float)((lat - Lat0) / (Lat1 - Lat0) * LengthM));
+ }
+}
diff --git a/unity/Assets/Scripts/Map/GeoFrame.cs.meta b/unity/Assets/Scripts/Map/GeoFrame.cs.meta
new file mode 100644
index 000000000..c3ce3a72f
--- /dev/null
+++ b/unity/Assets/Scripts/Map/GeoFrame.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 521dc3fa020054b5eb3a24dca152d5f9
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/HeightmapLoader.cs b/unity/Assets/Scripts/Map/HeightmapLoader.cs
new file mode 100644
index 000000000..8ed04c21e
--- /dev/null
+++ b/unity/Assets/Scripts/Map/HeightmapLoader.cs
@@ -0,0 +1,37 @@
+using System;
+using System.IO;
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ [Serializable]
+ public sealed class HeightmapMeta
+ {
+ public int width, height; public double lon0, lon1, lat0, lat1;
+ public float elev_min_m, elev_max_m, width_km, length_km; public string attribution;
+ }
+
+ public static class HeightmapLoader
+ {
+ public static (HeightmapMeta meta, float[,] heights) Load(string dir)
+ {
+ var meta = JsonUtility.FromJson<HeightmapMeta>(File.ReadAllText(Path.Combine(dir, "heightmap.json")));
+ 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}");
+ var raw = new ushort[meta.width * meta.height];
+ Buffer.BlockCopy(bytes, 0, raw, 0, bytes.Length); // little-endian on all our targets
+ return (meta, ToUnityHeights(raw, meta.width));
+ }
+
+ /// <summary>File row 0 is north; Unity heights[y, x] has y = 0 at south.</summary>
+ public static float[,] ToUnityHeights(ushort[] raw, int n)
+ {
+ var h = new float[n, n];
+ for (int fileRow = 0; fileRow < n; fileRow++)
+ for (int x = 0; x < n; x++)
+ h[n - 1 - fileRow, x] = raw[fileRow * n + x] / 65535f;
+ return h;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/HeightmapLoader.cs.meta b/unity/Assets/Scripts/Map/HeightmapLoader.cs.meta
new file mode 100644
index 000000000..2a8722fb4
--- /dev/null
+++ b/unity/Assets/Scripts/Map/HeightmapLoader.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 99e52e409c5a842529c5c2c09b27912a
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/HexMath.cs b/unity/Assets/Scripts/Map/HexMath.cs
new file mode 100644
index 000000000..285828722
--- /dev/null
+++ b/unity/Assets/Scripts/Map/HexMath.cs
@@ -0,0 +1,14 @@
+using UnityEngine;
+
+namespace Statecraft.Game.Map
+{
+ /// <summary>Pointy-top hex geometry (Red Blob Games): corner i at 60*i - 30 degrees.</summary>
+ public static class HexMath
+ {
+ public static Vector2 Corner(Vector2 center, float sizeM, int i)
+ {
+ float a = Mathf.Deg2Rad * (60f * i - 30f);
+ return new Vector2(center.x + sizeM * Mathf.Cos(a), center.y + sizeM * Mathf.Sin(a));
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/HexMath.cs.meta b/unity/Assets/Scripts/Map/HexMath.cs.meta
new file mode 100644
index 000000000..a10a4fbe2
--- /dev/null
+++ b/unity/Assets/Scripts/Map/HexMath.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 53ae5296413b942758b63cb480ac72e7
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/MapBuilder.cs b/unity/Assets/Scripts/Map/MapBuilder.cs
new file mode 100644
index 000000000..36823c795
--- /dev/null
+++ b/unity/Assets/Scripts/Map/MapBuilder.cs
@@ -0,0 +1,134 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+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; }
+
+ public static class MapBuilder
+ {
+ public const float VerticalExaggeration = 3f; // diorama look; real relief would read flat at 400 km scale
+
+ static readonly Dictionary<string, Color> Biome = new Dictionary<string, Color>
+ {
+ ["sea"] = new Color(0.16f, 0.42f, 0.55f), ["lake"] = new Color(0.20f, 0.50f, 0.62f),
+ ["coastal_plain"] = new Color(0.55f, 0.62f, 0.36f), ["hills"] = new Color(0.62f, 0.58f, 0.40f),
+ ["mountains"] = new Color(0.58f, 0.52f, 0.42f), ["valley"] = new Color(0.50f, 0.56f, 0.38f),
+ ["desert"] = new Color(0.80f, 0.68f, 0.48f),
+ };
+
+ /// <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,
+ /// HexOverlay.mat) passed in by the caller: Shader.Find returns null in players (M0 correction 1).</summary>
+ public static GameObject Build(string mapDir, string hexesJson, Material terrainMaterial, Material overlayMaterial)
+ {
+ if (terrainMaterial == null) throw new ArgumentNullException(nameof(terrainMaterial));
+ if (overlayMaterial == null) throw new ArgumentNullException(nameof(overlayMaterial));
+ var (meta, heights) = HeightmapLoader.Load(mapDir);
+ 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);
+
+ var hexFile = JsonUtility.FromJson<HexFile>(File.ReadAllText(hexesJson));
+ if (hexFile.layout != "pointy") throw new InvalidDataException($"hexes.json: layout '{hexFile.layout}' unsupported");
+
+ var data = new TerrainData { heightmapResolution = meta.width };
+ data.size = new Vector3(widthM, reliefM, lengthM);
+ data.SetHeights(0, 0, heights);
+
+ var terrainGo = Terrain.CreateTerrainGameObject(data);
+ terrainGo.name = "Terrain";
+ terrainGo.GetComponent<Terrain>().materialTemplate = terrainMaterial;
+ ApplyBiomeColours(data, frame, hexFile);
+
+ var overlay = BuildHexOverlay(frame, hexFile, data, overlayMaterial);
+ overlay.transform.SetParent(terrainGo.transform, false);
+ return terrainGo;
+ }
+
+ /// <summary>One terrain layer per biome; each alphamap texel takes the biome of its nearest hex centre.</summary>
+ static void ApplyBiomeColours(TerrainData data, GeoFrame frame, HexFile hexes)
+ {
+ var names = new List<string>(Biome.Keys);
+ var layers = new TerrainLayer[names.Count];
+ for (int i = 0; i < names.Count; i++)
+ {
+ var tex = new Texture2D(1, 1); tex.SetPixel(0, 0, Biome[names[i]]); tex.Apply();
+ layers[i] = new TerrainLayer { diffuseTexture = tex, tileSize = new Vector2(1000, 1000) };
+ }
+ data.terrainLayers = layers;
+ int res = 512; data.alphamapResolution = res;
+ var centres = new List<(Vector2 p, int layer)>();
+ foreach (var h in hexes.hexes)
+ {
+ int idx = names.IndexOf(h.biome);
+ if (idx < 0) throw new InvalidDataException($"hexes.json: unknown biome '{h.biome}' at q={h.q} r={h.r}");
+ var w = frame.ToWorld(h.lon, h.lat, 0); centres.Add((new Vector2(w.x, w.z), idx));
+ }
+ float cell = hexes.hex_size_km * 1000f * 2f;
+ var grid = BucketGrid(centres, cell);
+ var a = new float[res, res, names.Count];
+ for (int y = 0; y < res; y++)
+ for (int x = 0; x < res; x++)
+ {
+ var p = new Vector2((x + 0.5f) / res * frame.WidthM, (y + 0.5f) / res * frame.LengthM);
+ a[y, x, Nearest(grid, p, cell)] = 1f;
+ }
+ data.SetAlphamaps(0, 0, a);
+ }
+
+ static Dictionary<(int, int), List<(Vector2 p, int layer)>> BucketGrid(List<(Vector2 p, int layer)> pts, float cell)
+ {
+ var g = new Dictionary<(int, int), List<(Vector2, int)>>();
+ foreach (var c in pts)
+ {
+ var k = ((int)(c.p.x / cell), (int)(c.p.y / cell));
+ if (!g.TryGetValue(k, out var l)) g[k] = l = new List<(Vector2, int)>();
+ l.Add(c);
+ }
+ return g;
+ }
+
+ static int Nearest(Dictionary<(int, int), List<(Vector2 p, int layer)>> g, Vector2 p, float cell)
+ {
+ int cx = (int)(p.x / cell), cy = (int)(p.y / cell); float best = float.MaxValue; int layer = 0;
+ for (int dx = -1; dx <= 1; dx++)
+ for (int dy = -1; dy <= 1; dy++)
+ if (g.TryGetValue((cx + dx, cy + dy), out var l))
+ foreach (var c in l) { float d = (c.p - p).sqrMagnitude; if (d < best) { best = d; layer = c.layer; } }
+ return layer;
+ }
+
+ /// <summary>Thin line mesh of every land hex outline, draped 30 m above the terrain.</summary>
+ static GameObject BuildHexOverlay(GeoFrame frame, HexFile hexes, TerrainData data, Material material)
+ {
+ float size = hexes.hex_size_km * 1000f;
+ var verts = new List<Vector3>(); var idx = new List<int>();
+ foreach (var h in hexes.hexes)
+ {
+ if (!h.land) continue;
+ var c = frame.ToWorld(h.lon, h.lat, 0);
+ int start = verts.Count;
+ for (int i = 0; i < 6; i++)
+ {
+ var k = HexMath.Corner(new Vector2(c.x, c.z), size, i);
+ float y = data.GetInterpolatedHeight(k.x / frame.WidthM, k.y / frame.LengthM) + 30f;
+ verts.Add(new Vector3(k.x, y, k.y));
+ }
+ for (int i = 0; i < 6; i++) { idx.Add(start + i); idx.Add(start + (i + 1) % 6); }
+ }
+ var mesh = new Mesh { name = "HexOverlay", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };
+ mesh.SetVertices(verts); mesh.SetIndices(idx, MeshTopology.Lines, 0);
+ mesh.RecalculateBounds();
+ var go = new GameObject("HexOverlay");
+ go.AddComponent<MeshFilter>().sharedMesh = mesh;
+ var mr = go.AddComponent<MeshRenderer>();
+ mr.sharedMaterial = material;
+ mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
+ return go;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Map/MapBuilder.cs.meta b/unity/Assets/Scripts/Map/MapBuilder.cs.meta
new file mode 100644
index 000000000..b9cc169a8
--- /dev/null
+++ b/unity/Assets/Scripts/Map/MapBuilder.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 9287512d1c27d482596bf357eaca791b
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/MapTests.cs b/unity/Assets/Tests/EditMode/MapTests.cs
new file mode 100644
index 000000000..a6cbf46fc
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MapTests.cs
@@ -0,0 +1,86 @@
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Map;
+using UnityEditor;
+using UnityEngine;
+
+public class MapTests
+{
+ [Test]
+ public void HeightmapRowZeroIsNorth_SoUnityRowZeroIsSouth()
+ {
+ // 3x3 raster: the north row is all 65535 and the rest 0. After loading, Unity row 2 (north) must be 1.
+ var raw = new ushort[] { 65535, 65535, 65535, 0, 0, 0, 0, 0, 0 };
+ var h = HeightmapLoader.ToUnityHeights(raw, 3);
+ Assert.AreEqual(1f, h[2, 0], 1e-6); Assert.AreEqual(0f, h[0, 0], 1e-6);
+ }
+
+ [Test]
+ public void GeoFrame_MapsCornersAndJerusalemEastOfTelAviv()
+ {
+ var f = new GeoFrame(34.2, 35.9, 29.45, 33.35, 161000f, 433000f);
+ Assert.AreEqual(0f, f.ToWorld(34.2, 29.45, 0).x, 1e-3);
+ Assert.AreEqual(433000f, f.ToWorld(35.9, 33.35, 0).z, 1);
+ var telAviv = f.ToWorld(34.78, 32.08, 0); var jerusalem = f.ToWorld(35.22, 31.78, 0);
+ Assert.Greater(jerusalem.x, telAviv.x); // east
+ Assert.Less(jerusalem.z, telAviv.z); // south
+ }
+
+ [Test]
+ public void PointyTopCornerZeroIsAtMinus30Degrees()
+ {
+ var c = HexMath.Corner(Vector2.zero, 1f, 0); // Red Blob: angle = 60*i - 30 degrees
+ Assert.AreEqual(Mathf.Cos(-30 * Mathf.Deg2Rad), c.x, 1e-5);
+ Assert.AreEqual(Mathf.Sin(-30 * Mathf.Deg2Rad), c.y, 1e-5);
+ }
+
+ [Test]
+ public void TruncatedHeightmapIsRejectedWithExpectedSize()
+ {
+ var dir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "hm_" + System.Guid.NewGuid().ToString("N"));
+ System.IO.Directory.CreateDirectory(dir);
+ System.IO.File.WriteAllText(System.IO.Path.Combine(dir, "heightmap.json"),
+ "{\"width\":3,\"height\":3,\"lon0\":34.2,\"lon1\":35.9,\"lat0\":29.45,\"lat1\":33.35,\"elev_min_m\":-427,\"elev_max_m\":2367,\"width_km\":161.5,\"length_km\":431.2,\"attribution\":\"x\"}");
+ 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);
+ }
+
+ // M0 correction 1: no Shader.Find at runtime. Materials are editor-made assets passed into Build.
+ const string TerrainMatPath = "Assets/Materials/Terrain.mat", OverlayMatPath = "Assets/Materials/HexOverlay.mat";
+
+ static string HexesJson => System.IO.Path.Combine(Paths.Content, "map", "hexes.json");
+
+ [Test]
+ public void BuildUsesThePassedTerrainAndOverlayMaterials()
+ {
+ var terrainMat = AssetDatabase.LoadAssetAtPath<Material>(TerrainMatPath);
+ var overlayMat = AssetDatabase.LoadAssetAtPath<Material>(OverlayMatPath);
+ Assert.IsNotNull(terrainMat, TerrainMatPath); Assert.IsNotNull(overlayMat, OverlayMatPath);
+ Assert.AreEqual("Universal Render Pipeline/Terrain/Lit", terrainMat.shader.name);
+ Assert.AreEqual("Universal Render Pipeline/Unlit", overlayMat.shader.name);
+
+ var go = MapBuilder.Build(Paths.StreamingMap, HexesJson, terrainMat, overlayMat);
+ var terrain = go.GetComponent<Terrain>();
+ try
+ {
+ Assert.AreSame(terrainMat, terrain.materialTemplate);
+ var overlay = go.transform.Find("HexOverlay");
+ Assert.IsNotNull(overlay, "HexOverlay child");
+ Assert.AreSame(overlayMat, overlay.GetComponent<MeshRenderer>().sharedMaterial);
+ Assert.AreEqual(2049, terrain.terrainData.heightmapResolution);
+ Assert.Greater(overlay.GetComponent<MeshFilter>().sharedMesh.vertexCount, 0);
+ }
+ finally
+ {
+ Object.DestroyImmediate(terrain.terrainData);
+ Object.DestroyImmediate(go);
+ }
+ }
+
+ [Test]
+ public void BuildRejectsMissingMaterials()
+ {
+ Assert.Throws<System.ArgumentNullException>(() => MapBuilder.Build(Paths.StreamingMap, HexesJson, null, null));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/MapTests.cs.meta b/unity/Assets/Tests/EditMode/MapTests.cs.meta
new file mode 100644
index 000000000..16c32bb90
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/MapTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 51b1632efe9bf44278171f588b041fe4
\ No newline at end of file