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.

Map: the water in its own pass and one border texel a pixel, out of the terrain's shader (Fixes #195) (#320)

Eyal Golan4abb64f0ac05
diff --git a/ASSETS.yaml b/ASSETS.yaml
index 94cce0efa..c022dd3e8 100644
--- a/ASSETS.yaml
+++ b/ASSETS.yaml
@@ -167,7 +167,7 @@ rules:
note: "Decision D13 (docs/oss/DECISIONS.md): the owner rules the licence of textures derived from DEM, CHELSA, IMS and coordinate inputs."
- glob: "unity/Assets/Textures/*"
licence: Copernicus-DEM
- source: "tools/terrain_bake.py from the Copernicus DEM GLO-30-derived heightmap (unity/Assets/StreamingAssets/map/heightmap.*): AO, curvature, sky-view (Map/terrain_bake.png), coast distance (Map/coast.png) and the AO copy (Map/ao.png); attribution in NOTICE"
+ source: "tools/terrain_bake.py from the Copernicus DEM GLO-30-derived heightmap (unity/Assets/StreamingAssets/map/heightmap.*): AO, curvature, sky-view (Map/terrain_bake.png), coast distance (Map/coast.png) and the AO copy (Map/ao.png); the terrain water's mesh samples (Map/terrain_water.bytes, Editor TerrainWaterBake from the same heightmap); attribution in NOTICE"
status: verified
# --- Event-card header photographs: real archival photos, never AI (docs/event-images.md; owner rulings 2026-10-11) ---
# Licences and artists re-read from each Commons file page on 2026-10-11; CC BY 4.0 credits are the licensor's credit
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d3c769bad..17f27c066 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -256,6 +256,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
It decodes to the same bytes, so the terrain is unchanged (#44).
### Fixed
+- The map draws about four times faster at the gameplay zoom (#195). The water's shading moved out of the terrain's shader
+ into its own pass over the water and the shore, and the region borders read one texel a pixel instead of up to seven.
+ Since the promo sea (#138) and the borders (#206) the terrain's shader had grown large enough to slow every terrain pixel
+ in the browser, even with the water and the borders toggled off. The look is unchanged. Presentation only.
- The four General Zionist ministers (Rokach, Bernstein, Sapir, Serlin) leave office on 25 May 1953 and return on 3
June 1953, and the Prime Minister holds their ministries in between, as he told the Knesset on 25 May. The
Knesset's position records show no break; the plenum record of the resignation and of the new declarations of
diff --git a/docs/visual-v1.md b/docs/visual-v1.md
index 9038e6127..7cc62043f 100644
--- a/docs/visual-v1.md
+++ b/docs/visual-v1.md
@@ -431,7 +431,8 @@ Judean slopes and the Negev (`PromoPose.CloseChecks`, haze off): no AO steps.
## Task 7: sea
One water function (`StatecraftMap.hlsl` `ScWaterShade`) on both sides of the map's edge: the terrain graph outputs it as
emission on a black, fully metallic, fully occluded surface, and the border skirt's `Sea.mat` (`Statecraft/Sea`, passes
-`Sea`, `DepthOnly`, `DepthNormals`) returns it directly. It is driven by Task 5's coast distance: a turquoise -> teal -> navy
+`Sea`, `DepthOnly`, `DepthNormals`) returns it directly. (Since issue #195 the terrain graph outputs only the black surface;
+`MapScene`'s `TerrainWater` mesh adds the water on top with `Sea.mat` in its `_ScTerrainWater` mode. See "Issue #195".) It is driven by Task 5's coast distance: a turquoise -> teal -> navy
ramp over 12 km, foam within 350 m, the Dead Sea pale turquoise with a white salt rim. It samples the main light's shadows
itself, takes the cooler water haze (`ScHazeWater`), and falls back to the flat sea colour under the `water` toggle. WebGL
build: 77.1 MB, no `Shader error`. GLES3: `ShaderChecks.Gles3Errors` is empty for `Statecraft/Sea` and the terrain (no
@@ -988,10 +989,12 @@ Each band lies inside its region, as Civ draws territory, so two outlined region
to red+cream: promo 03 near Tel Aviv). The bands are world-space: they widen towards the camera.
**What is drawn.** `MapBorders` (C#) bakes one texel per hex (`RegionHexes`, RGBA8 linear, point-sampled, 47 x 58: r + 256 g
-the region id, b the style) and sets the globals; `StatecraftBorders.hlsl`'s `ScBorderApply`, called last in the terrain
+the region id, b the style; since issue #195, a's low six bits say which edges border another region) and sets the
+globals; `StatecraftBorders.hlsl`'s `ScBorderApply`, called last in the terrain
function, draws the band along each edge whose neighbour is in another region. A pixel farther from its hex's edges than
the widest band plus wash can reach fetches nothing (exact: a segment is never nearer than its line); one nearer fetches its
-own hex and only the neighbours within reach (one, or two near a corner). The first version fetched all seven texels on
+own hex and only the neighbours within reach (one, or two near a corner); since issue #195 it fetches only its own hex,
+whose edge bits replace the neighbours' fetches. The first version fetched all seven texels on
every land pixel and cost 3.3 ms at gameplay03 (`visual=all` 14.97 against `-borders` 11.64, a loaded machine): over the
2.5 ms budget. The distance is to the edge segment (corners rounded, so bands join without notches), in pixels
across the edge (Task 8's anisotropic filter), box-filtered. Stripes and wash are unlit (they replace BaseColor and go out
@@ -1676,3 +1679,65 @@ place carries on; Lydda and Ramle for the game settlements `lod` and `ramla`; Ne
- History: a first version scanned every lot and footprint linearly, taking 350 ms (kits) and 330 ms (trees) in the
editor. `DiscIndex` (a 4 km grid) brought that to about 30 ms each.
- Build: wasm +111,913 bytes and data +14,441, plus the localities file fetched at boot.
+
+## Issue #195: the water and the border lookups out of the terrain's fragment shader
+- **Why.** promo-sea (#138) put the water shading (`ScWaterShade`, the breakers' `fwidth`, the footprint) in the terrain
+ graph's function, and promo-borders (#206) six neighbour fetches in `ScBorderApply`'s loop. Either one makes the shader
+ big enough to slow every terrain pixel in WebGL, the water and borders toggled off included
+ (`.superpowers/handover-2026-10-11/promo/perf-investigation.md`): none@gameplay03 measured 2.5 ms without both, 7.3 ms
+ with the borders' fetches alone, about 10 ms with both.
+- **Water.** `StatecraftTerrain.hlsl` outputs a black, fully metallic, fully occluded surface with no emission on the water
+ (Lit adds 0 there). `MapBuilder.BuildWaterMesh` copies the terrain's surface wherever the water's coverage can be above
+ 0: wet heightmap samples (the sea within 0.5 m of 0 m, flat rift lakes) and two samples around them, at full resolution,
+ with flat blocks as T-junction-free fans (129,882 vertices, 239,958 triangles). It is drawn with a copy of `Sea.mat` in
+ its `_ScTerrainWater` mode: additive, colour times coverage (the land adds 0: no per-pixel discard to split the shore's 2x2 quads, the lesson of #306), no depth write, its depth pulled two
+ pixels' worth towards the camera (the terrain's LOD splits the surface its own way). The terrain draws one queue earlier
+ (`Terrain.mat` 1998) and the water at 1999, before every other opaque, so boats and harbours cover it.
+- **Borders.** `MapBorders.Use` bakes, per hex, which of its six edges border another region (alpha: 192 plus a bit per
+ edge, `MapBorders.NeighbourSteps` order). `ScBorderApply` reads its own hex's texel only, where it read up to seven, and
+ skips a hex with no border edge (it would draw nothing). Same math, same pixels: `BorderTests` unchanged, and the border
+ pixels of the player's screenshots are identical. An overlay mesh along the bands, like the water's, was the plan; the
+ bake met the target with no mesh, no boot or memory cost and no rebuild hitch, so no mesh was built.
+- **Exactness.** On the water and its shore the sum is what the terrain drew before, except where a border band meets the
+ 140 m coverage ramp at the shore, and the extra rounding of one blend.
+- **Measured** (WebGL, headless, 1920x1080, DPR 1; `PROFILE summary` medians over 3 interleaved rounds, main 1cdb356 and
+ the fix back to back under one exclusive machine lock per round, order rotated; [min-max] across rounds):
+
+ | pose, toggles | main 1cdb356 | fix |
+ |---|---|---|
+ | gameplay03, none | 10.48 [10.29-10.79] | 2.52 [2.44-2.55] |
+ | gameplay03, all | 13.94 [13.85-14.14] | 3.19 [3.16-3.19] |
+ | diorama02, none | 13.56 [12.40-13.78] | 8.18 [8.02-8.33] |
+ | diorama02, all | 18.72 [17.92-19.03] | 12.05 [11.93-12.35] |
+
+- **Baked.** The mesh's samples and triangles are baked into `Assets/Textures/Map/terrain_water.bytes` (3.4 MB;
+ `Statecraft.Game.EditorTools.TerrainWaterBake.Bake`, re-run whenever `heightmap.r16z` changes), referenced by
+ `Map.unity`'s `MapScene`, so a player only places the vertices on the heights it loaded. The file carries the
+ heightmap's resolution and a check of its heights; a stale or missing bake is refused (a warning) and the mesh derived at
+ load as before (22 ms unthrottled, about 87 ms at `--cpu 4`). `SeaTests.TheBakedWaterMeshMatchesTheHeightmap` fails on
+ a stale bake.
+- **Boot** (`tools/headed.py boot --runs 3 --cpu 4`, interleaved under one exclusive lock per round, order rotated; six
+ rounds, 18 runs each, 2026-10-13, main 244723f against the fix merged on it, cc3c954): `map_build_ms` median main 3023
+ [3006-3042] ms, the fix 3039 [3017-3064] ms. `terrain water` takes 19 [17-22] ms, the fix's whole share; `terrain
+ heights set` is 1389 [1374-1411] ms on main and 1397 [1372-1409] ms on the fix.
+- **`SetHeights` moves with the build, not with the fix.** The review measured the fix merged on main 6d439a7 (44e1d63)
+ at about 105 ms over that main, 85 ms of it in `terrain heights set`, and it reproduces here (1473 [1462-1496] ms
+ against 1385 [1375-1418], nine runs each). It is not the 3.4 MB bake, and not the WebGL heap:
+ - The same commit rebuilt without `Map.unity`'s reference to the bake (the same wasm, byte for byte; the water mesh
+ then derived at load) keeps the slow `terrain heights set`: 1487 [1466-1503] ms against 1491 [1463-1499] with it.
+ - With heap probes (a `WebAssembly.Memory.grow` hook and the heap size after every boot phase) in builds of main 244723f
+ and of the fix merged on it, both grow the wasm heap at the same points to the same sizes (286 MB to 343 MB at
+ `new TerrainData`, none inside `SetHeights`); the bake adds 3 MB of reserved native memory and no grow. The
+ `SetHeights` call alone measured 1185-1198 ms on both.
+ - A small C# change that runs only after `SetHeights` (reading the bake through `TextAsset.GetData`, which cut
+ `terrain water` from 20 to 17 ms) made `terrain heights set` 1511 [1489-1530] ms in its build, against the fix's
+ 1397. It was dropped.
+ - With V8's tiering off (`--js-flags=--no-wasm-dynamic-tiering`: every function compiled by TurboFan up front), five
+ builds (both mains, the fix, 44e1d63 and the `GetData` variant) all take 1426-1455 ms in `terrain heights set`.
+ So each wasm binary gets its own `SetHeights` time, about 1390 or about 1490 ms at `--cpu 4`, from when V8 tiers up
+ the code it runs. Any change can move it either way, and the next merge of main draws again. So judge a boot change
+ by its own phases, and read `terrain heights set` apart from them.
+- **A layer change** (`MapBorders.Use`) takes 0.8 ms for the 870-hex 1948 layer, texture upload included: no rebuild, no
+ hitch.
+- **Memory.** The water mesh keeps about 4.5 MB on the GPU (its CPU copy is dropped in players, `UploadMeshData`); placing
+ it from the bake allocates its 3.4 MB of bytes and about 1.5 MB of vertices, short-lived. The borders add nothing (the edge bits ride in the existing texel).
diff --git a/tools/tests/test_terrain_water_bake.py b/tools/tests/test_terrain_water_bake.py
new file mode 100644
index 000000000..aae087178
--- /dev/null
+++ b/tools/tests/test_terrain_water_bake.py
@@ -0,0 +1,54 @@
+"""The terrain water's baked mesh (unity/Assets/Textures/Map/terrain_water.bytes, issue #195) is for the shipped heightmap.
+
+The game refuses a bake whose header does not match the heightmap it loaded (MapBuilder.TryReadWaterMesh: the resolution and
+HeightsCheck, FNV-1a over every 997th height's float bits) and then derives the mesh at boot, which is slower. CI runs no
+Unity, so this checks the same header here: a heightmap change without a re-bake (TerrainWaterBake.Bake) fails CI, as
+localities_bake's does. Unity's SeaTests.TheBakedWaterMeshMatchesTheHeightmap compares the whole mesh."""
+import json
+import struct
+from pathlib import Path
+
+import numpy as np
+
+import heightmap_codec as hc
+
+ROOT = Path(__file__).resolve().parents[2]
+MAP = ROOT / "unity/Assets/StreamingAssets/map"
+BAKE = ROOT / "unity/Assets/Textures/Map/terrain_water.bytes"
+MAGIC = 0x31574353 # "SCW1"
+
+
+def heights_check(heights: np.ndarray) -> int:
+ """MapBuilder.HeightsCheck over Unity's heights[y, x] (float32, y = 0 at the south)."""
+ bits = heights.astype(np.float32).ravel()[::997].view(np.uint32)
+ h = 2166136261
+ for b in bits.tolist():
+ for k in range(4):
+ h = ((h ^ ((b >> (8 * k)) & 0xFF)) * 16777619) & 0xFFFFFFFF
+ return struct.unpack("<i", struct.pack("<I", h))[0]
+
+
+def unity_heights() -> np.ndarray:
+ """HeightmapLoader.ToUnityHeights: raw / 65535f, file row 0 (north) as the last row."""
+ meta = json.loads((MAP / "heightmap.json").read_text())
+ raw = hc.decode((MAP / "heightmap.r16z").read_bytes(), meta["width"], meta["height"])
+ return (raw.astype(np.float32) / np.float32(65535.0))[::-1]
+
+
+def test_the_terrain_water_bake_is_for_the_shipped_heightmap():
+ magic, res, check, nverts, nindices = struct.unpack_from("<5i", BAKE.read_bytes())
+ heights = unity_heights()
+ assert magic == MAGIC
+ assert res == heights.shape[1]
+ assert BAKE.stat().st_size == 20 + 4 * (nverts + nindices)
+ assert check == heights_check(heights), "stale: re-run Statecraft.Game.EditorTools.TerrainWaterBake.Bake"
+
+
+def test_heights_check_reads_every_997th_sample():
+ h = np.zeros((40, 50), np.float32)
+ base = heights_check(h)
+ h[997 // 50, 997 % 50] = 0.5
+ assert heights_check(h) != base
+ h[997 // 50, 997 % 50] = 0.0
+ h[0, 1] = 0.5
+ assert heights_check(h) == base
diff --git a/unity/Assets/Editor/MapMaterials.cs b/unity/Assets/Editor/MapMaterials.cs
index 084c26dcd..d364a7b42 100644
--- a/unity/Assets/Editor/MapMaterials.cs
+++ b/unity/Assets/Editor/MapMaterials.cs
@@ -27,6 +27,8 @@ namespace Statecraft.Game.EditorTools
terrain.SetTexture("_ScCoastTex", Tex(Statecraft.Game.Map.MapTexturePaths.Coast));
terrain.SetTexture("_ScAoTex", Tex(Statecraft.Game.Map.MapTexturePaths.Ao));
terrain.SetTexture("_ScLandTex", Tex(Statecraft.Game.Map.MapTexturePaths.Land)); // land use (tools/land_bake.py)
+ // Before the water drawn on it (issue #195: MapScene.TerrainWaterQueue), which precedes the other opaques.
+ terrain.renderQueue = Statecraft.Game.Map.MapScene.TerrainWaterQueue - 1;
EditorUtility.SetDirty(terrain);
// Settlement boxes: matte URP Lit; SettlementPlacer sets the per-type _BaseColor through a MaterialPropertyBlock.
var marker = Make(MarkerPath, "Universal Render Pipeline/Lit", Color.white);
diff --git a/unity/Assets/Editor/TerrainWaterBake.cs b/unity/Assets/Editor/TerrainWaterBake.cs
new file mode 100644
index 000000000..4deb39aa2
--- /dev/null
+++ b/unity/Assets/Editor/TerrainWaterBake.cs
@@ -0,0 +1,27 @@
+using System.IO;
+using Statecraft.Game.Map;
+using UnityEditor;
+
+namespace Statecraft.Game.EditorTools
+{
+ /// <summary>Bakes the terrain water's mesh (MapBuilder.WaterMeshGrid) from the shipped heightmap into
+ /// MapTexturePaths.WaterMesh, so a player places its vertices instead of deriving it at boot (issue #195). Re-run it
+ /// whenever heightmap.r16z changes (SeaTests fails until then; the map also falls back to deriving it). Run headless:
+ /// Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod
+ /// Statecraft.Game.EditorTools.TerrainWaterBake.Bake</summary>
+ public static class TerrainWaterBake
+ {
+ public static byte[] Bytes()
+ {
+ var (meta, heights) = HeightmapLoader.Load(Paths.StreamingMap);
+ var (grid, indices) = MapBuilder.WaterMeshGrid(meta.width, MapBuilder.TerrainSize(meta), heights, meta.elev_min_m);
+ return MapBuilder.WaterMeshBytes(meta.width, heights, grid, indices);
+ }
+
+ public static void Bake()
+ {
+ File.WriteAllBytes(MapTexturePaths.WaterMesh, Bytes());
+ AssetDatabase.ImportAsset(MapTexturePaths.WaterMesh);
+ }
+ }
+}
diff --git a/unity/Assets/Editor/TerrainWaterBake.cs.meta b/unity/Assets/Editor/TerrainWaterBake.cs.meta
new file mode 100644
index 000000000..5117c369b
--- /dev/null
+++ b/unity/Assets/Editor/TerrainWaterBake.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 9e037fa8a33124a8a9545fed4ff7a090
\ No newline at end of file
diff --git a/unity/Assets/Map.unity b/unity/Assets/Map.unity
index b6900e12d..5ca5daeaf 100644
--- a/unity/Assets/Map.unity
+++ b/unity/Assets/Map.unity
@@ -386,6 +386,7 @@ MonoBehaviour:
borderLandMaterial: {fileID: 2100000, guid: ed41bb6e0c8274066b408da9b1f5bef2, type: 2}
kitMaterial: {fileID: 2100000, guid: 24c1cceae1b22492e9c9f2be7c1a6b5e, type: 2}
treeMaterial: {fileID: 2100000, guid: 2dd15539298814dafa803cdbc57e2426, type: 2}
+ terrainWaterMesh: {fileID: 4900000, guid: 51f85aaa1270842658cbc02738ff8df2, type: 3}
--- !u!4 &1195372453
Transform:
m_ObjectHideFlags: 0
diff --git a/unity/Assets/Materials/Terrain.mat b/unity/Assets/Materials/Terrain.mat
index cca4c9027..5554fc05b 100644
--- a/unity/Assets/Materials/Terrain.mat
+++ b/unity/Assets/Materials/Terrain.mat
@@ -16,7 +16,7 @@ Material:
m_LightmapFlags: 4
m_EnableInstancingVariants: 1
m_DoubleSidedGI: 0
- m_CustomRenderQueue: -1
+ m_CustomRenderQueue: 1998
stringTagMap: {}
disabledShaderPasses: []
m_LockedProperties:
diff --git a/unity/Assets/Scripts/Map/MapBorders.cs b/unity/Assets/Scripts/Map/MapBorders.cs
index dac5f426a..85d1c14bc 100644
--- a/unity/Assets/Scripts/Map/MapBorders.cs
+++ b/unity/Assets/Scripts/Map/MapBorders.cs
@@ -144,7 +144,15 @@ namespace Statecraft.Game.Map
foreach (var (q, r) in layer.Hexes)
{
if (!mapHexes.Contains((q, r))) throw new ArgumentException($"{layer.Name}: hex ({q}, {r}) is not on the map");
- px[(r - rMin) * w + (q - qMin)] = Encode(layer.RegionOf(q, r), layer.StyleOf(layer.RegionOf(q, r)));
+ int id = layer.RegionOf(q, r), edges = 0;
+ // Edge i borders another region when that neighbour is in one (an unlisted hex, on the map or off it,
+ // is 0: the coast and the data's edge get no band) and it is not this one.
+ for (int i = 0; i < NeighbourSteps.Length; i++)
+ {
+ int other = layer.RegionOf(q + NeighbourSteps[i].dq, r + NeighbourSteps[i].dr);
+ if (other > 0 && other != id) edges |= 1 << i;
+ }
+ px[(r - rMin) * w + (q - qMin)] = Encode(id, layer.StyleOf(id), edges);
}
texture.SetPixels32(px); texture.Apply(false, false);
Current = layer; hasLayer = layer != null && layer.Count > 0;
@@ -155,8 +163,15 @@ namespace Statecraft.Game.Map
static void DestroyObject(UnityEngine.Object o) { if (Application.isPlaying) UnityEngine.Object.Destroy(o); else UnityEngine.Object.DestroyImmediate(o); }
- /// <summary>The texel of a hex: r + 256 g the region id, b the style (StatecraftBorders.hlsl, ScRegionAt).</summary>
- public static Color32 Encode(int id, BorderStyle style) => new Color32((byte)(id & 0xFF), (byte)(id >> 8), (byte)style, 255);
+ /// <summary>The texel of a hex: r + 256 g the region id, b the style, a 192 plus a bit per edge that borders another
+ /// region, in <see cref="NeighbourSteps"/> order (StatecraftBorders.hlsl, ScRegionAt). Baked here so the terrain's
+ /// shader reads one texel, not seven (issue #195). The default, every edge, is 255.</summary>
+ public static Color32 Encode(int id, BorderStyle style, int borderEdges = 0x3F) =>
+ new Color32((byte)(id & 0xFF), (byte)(id >> 8), (byte)style, (byte)(0xC0 | (borderEdges & 0x3F)));
+
+ /// <summary>Axial steps to a hex's six neighbours, in tools/hexgrid.py's NEIGHBOURS order: the order of
+ /// StatecraftBorders.hlsl's ScHexNormals, so bit i of the edge mask is the edge shared with neighbour i.</summary>
+ public static readonly (int dq, int dr)[] NeighbourSteps = { (1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1) };
static void SetStyle(int colour, int light, int shape, Style s)
{
diff --git a/unity/Assets/Scripts/Map/MapBuilder.cs b/unity/Assets/Scripts/Map/MapBuilder.cs
index 4bf786040..66580b4bd 100644
--- a/unity/Assets/Scripts/Map/MapBuilder.cs
+++ b/unity/Assets/Scripts/Map/MapBuilder.cs
@@ -284,6 +284,272 @@ namespace Statecraft.Game.Map
return mesh;
}
+ /// <summary>Lakes: flat water (a 3x3 height range within LakeFlatM) below LakeBelowM, tools/terrain_bake.py's rule.</summary>
+ public const float LakeBelowM = -150f, LakeFlatM = 0.25f;
+ /// <summary>The water mesh reaches this many heightmap samples past the last wet one: the shore's coverage ramp (about
+ /// 70 m inland) and the coast texture's own resolution stay inside it.</summary>
+ public const int WaterMeshReach = 2;
+ /// <summary>The largest flat block the water mesh draws as one fan (heightmap cells a side).</summary>
+ public const int WaterMeshBlock = 32;
+
+ /// <summary>The surface the water inside the map is drawn on (issue #195; MapScene.TerrainWaterName): the terrain's own
+ /// heightmap surface wherever the water's coverage can be above 0, so Sea.shader's terrain-water mode can add the water
+ /// on top of the terrain instead of the terrain's own shader carrying it. Wet samples are the sea (within SeaToleranceM
+ /// of 0 m) and flat rift lakes (LakeBelowM, LakeFlatM); every cell within WaterMeshReach samples of one is drawn at
+ /// the heightmap's full resolution, except square blocks whose samples all share one height (the open sea, the lakes'
+ /// flat middles), drawn as fans from the centre to every sample on their edge, so no edge has a T-junction.
+ /// <paramref name="heights"/> are the ones the terrain was given (Unity's [y, x], 0..1): the terrain stores them at
+ /// 16 bits, a few centimetres off, well inside the water's depth pull (Sea.shader).</summary>
+ public static Mesh BuildWaterMesh(TerrainData data, float[,] heights, float elevMinM, MapRuntimeAssets assets)
+ {
+ var (grid, indices) = WaterMeshGrid(data.heightmapResolution, data.size, heights, elevMinM);
+ return assets.Own(WaterMesh(data.heightmapResolution, data.size, heights, grid, indices));
+ }
+
+ /// <summary>The terrain's size (m: width, relief, length) for a heightmap, as Build gives it.</summary>
+ public static Vector3 TerrainSize(HeightmapMeta meta) =>
+ new Vector3(meta.width_km * 1000f, (meta.elev_max_m - meta.elev_min_m) * VerticalExaggeration, meta.length_km * 1000f);
+
+ /// <summary>BuildWaterMesh's geometry as heightmap samples: each vertex is sample (x, y) packed as x | y << 16, and
+ /// the triangles index them (three a triangle, facing up). Baked into terrain_water.bytes (WaterMeshBytes) so a
+ /// player only places the vertices (issue #195: boot time).</summary>
+ public static (int[] grid, int[] indices) WaterMeshGrid(int res, Vector3 size, float[,] heights, float elevMinM)
+ {
+ int cells = res - 1;
+ // Thresholds on the 0..1 heights (one sample is h * size.y / VerticalExaggeration + elevMinM metres): the scan
+ // below runs over every sample (4.2 million), so it stays a compare (boot time, issue #195).
+ float perMetre = VerticalExaggeration / size.y, zero = -elevMinM * perMetre;
+ float seaLo = zero - SeaToleranceM * perMetre, seaHi = zero + SeaToleranceM * perMetre;
+ float lakeBelow = (LakeBelowM - elevMinM) * perMetre, lakeFlat = LakeFlatM * perMetre;
+ // A sample is wet when it is sea, or the flat floor of a rift lake (its 3x3 neighbourhood within LakeFlatM).
+ bool Wet(int x, int y)
+ {
+ float h = heights[y, x];
+ if (h > seaLo && h < seaHi) return true;
+ if (h >= lakeBelow) return false;
+ float lo = h, hi = h;
+ for (int oy = -1; oy <= 1; oy++)
+ for (int ox = -1; ox <= 1; ox++)
+ {
+ float n = heights[Mathf.Clamp(y + oy, 0, cells), Mathf.Clamp(x + ox, 0, cells)];
+ lo = Mathf.Min(lo, n); hi = Mathf.Max(hi, n);
+ }
+ return hi - lo <= lakeFlat;
+ }
+ // One pass over every sample, with no per-sample array (on WebGL a 4 MB allocation at boot costs more than the
+ // scan): which WaterMeshBlock-square blocks hold a wet sample. Only blocks with a wet sample in or beside them
+ // are looked at again (a cell is drawn when a wet sample lies within WaterMeshReach of one of its corners, and
+ // the reach is under a block), so the land away from the water costs a compare or two a sample (boot time,
+ // issue #195).
+ const int B = WaterMeshBlock, R = WaterMeshReach;
+ int blocks = (cells + B - 1) / B;
+ var blockWet = new bool[blocks * blocks];
+ // A row at a time (WebGL: the browser optimises a function after its first calls, not inside one long loop).
+ void ScanRow(int y)
+ {
+ int by = Mathf.Min(y / B, blocks - 1) * blocks;
+ for (int x = 0; x < res; x++)
+ {
+ float h = heights[y, x];
+ if ((h > seaLo && h < seaHi) || (h < lakeBelow && Wet(x, y))) blockWet[by + Mathf.Min(x / B, blocks - 1)] = true;
+ }
+ }
+ for (int y = 0; y < res; y++) ScanRow(y);
+ bool Relevant(int bx, int by)
+ {
+ for (int j = Mathf.Max(0, by - 1); j <= Mathf.Min(blocks - 1, by + 1); j++)
+ for (int i = Mathf.Max(0, bx - 1); i <= Mathf.Min(blocks - 1, bx + 1); i++)
+ if (blockWet[j * blocks + i]) return true;
+ return false;
+ }
+
+ var verts = new List<int>(1 << 17); var tris = new List<int>(3 << 18);
+ // Each sample's vertex is made once: samples on the blocks' grid lines are indexed globally, a block's inner
+ // samples in a block-local table (no dictionary: boot time).
+ var onColumn = new int[(blocks + 1) * res]; var onRow = new int[(blocks + 1) * res];
+ var inner = new int[(B - 1) * (B - 1)];
+ for (int i = 0; i < onColumn.Length; i++) { onColumn[i] = -1; onRow[i] = -1; }
+ int bx0 = 0, by0 = 0;
+ int Vertex(int x, int y)
+ {
+ int[] table; int at;
+ if (x % B == 0) { table = onColumn; at = x / B * res + y; }
+ else if (y % B == 0) { table = onRow; at = y / B * res + x; }
+ else { table = inner; at = (y - by0 - 1) * (B - 1) + (x - bx0 - 1); }
+ if (table[at] < 0) { table[at] = verts.Count; verts.Add(x | y << 16); }
+ return table[at];
+ }
+ // Triangles face up: every cell and fan below is listed anticlockwise seen from above (x east, z north), which
+ // Unity's clockwise front faces take in the reverse order.
+ void Tri(int i, int j, int l) { tris.Add(i); tris.Add(l); tris.Add(j); }
+ // Whether block (x0, y0, s) is all wet and all its samples share one height (bitwise: the sea's 0 m, a lake's
+ // quantised level).
+ bool Flat(int x0, int y0, int s)
+ {
+ float h = heights[y0, x0];
+ for (int y = y0; y <= y0 + s; y++)
+ for (int x = x0; x <= x0 + s; x++)
+ {
+ float v = heights[y, x];
+ if (v != h || !((v > seaLo && v < seaHi) || (v < lakeBelow && Wet(x, y)))) return false;
+ }
+ return true;
+ }
+ // Within the top-level block being drawn: near[] says, per sample of the block (B + 1 a side), whether a wet
+ // sample lies within R: the wetness of the block plus R around it, then a separable dilation (counts of wet
+ // samples in a sliding window of 2 R + 1, along x, then along y).
+ int side = B + 1, span = side + 2 * R;
+ var near = new bool[side * side]; var localWet = new byte[span * span]; var rowNear = new byte[span * side];
+ int nx0 = 0, ny0 = 0;
+ void Dilate(int x0, int y0)
+ {
+ nx0 = x0; ny0 = y0;
+ for (int j = 0; j < span; j++)
+ for (int i = 0; i < span; i++)
+ {
+ int x = x0 - R + i, y = y0 - R + j;
+ bool w = false;
+ if (x >= 0 && y >= 0 && x < res && y < res)
+ {
+ float h = heights[y, x]; // the sea test inline: a call costs (boot time)
+ w = (h > seaLo && h < seaHi) || (h < lakeBelow && Wet(x, y));
+ }
+ localWet[j * span + i] = (byte)(w ? 1 : 0);
+ }
+ for (int j = 0; j < span; j++) // along x: sample i of the block is at i + R
+ {
+ int o = j * span, count = 0;
+ for (int k = 0; k < 2 * R; k++) count += localWet[o + k];
+ for (int i = 0; i < side; i++)
+ {
+ count += localWet[o + i + 2 * R];
+ rowNear[j * side + i] = (byte)(count > 0 ? 1 : 0);
+ count -= localWet[o + i];
+ }
+ }
+ for (int i = 0; i < side; i++) // then along y
+ {
+ int count = 0;
+ for (int k = 0; k < 2 * R; k++) count += rowNear[k * side + i];
+ for (int j = 0; j < side; j++)
+ {
+ count += rowNear[(j + 2 * R) * side + i];
+ near[j * side + i] = count > 0;
+ count -= rowNear[j * side + i];
+ }
+ }
+ }
+ bool Near(int x, int y) => near[(y - ny0) * side + (x - nx0)];
+ bool Drawn(int cx, int cy) => Near(cx, cy) || Near(cx + 1, cy) || Near(cx, cy + 1) || Near(cx + 1, cy + 1);
+ bool AnyDrawn(int x0, int y0, int s)
+ {
+ for (int y = y0; y < y0 + s; y++)
+ for (int x = x0; x < x0 + s; x++)
+ if (Drawn(x, y)) return true;
+ return false;
+ }
+ void Fan(int x0, int y0, int s) // from the centre to every sample on the edge: 4 s triangles
+ {
+ int c = verts.Count;
+ verts.Add((x0 + s / 2) | (y0 + s / 2) << 16); // a sample: s is even, the block level
+ var ring = new List<int>(4 * s);
+ for (int i = 0; i < s; i++) ring.Add(Vertex(x0 + i, y0));
+ for (int i = 0; i < s; i++) ring.Add(Vertex(x0 + s, y0 + i));
+ for (int i = 0; i < s; i++) ring.Add(Vertex(x0 + s - i, y0 + s));
+ for (int i = 0; i < s; i++) ring.Add(Vertex(x0, y0 + s - i));
+ for (int i = 0; i < ring.Count; i++) Tri(c, ring[i], ring[(i + 1) % ring.Count]);
+ }
+ void Block(int x0, int y0, int s) // inside a dilated top-level block
+ {
+ if (x0 >= cells || y0 >= cells || !AnyDrawn(x0, y0, Mathf.Min(s, Mathf.Min(cells - x0, cells - y0)))) return;
+ if (x0 + s <= cells && y0 + s <= cells && s > 1 && Flat(x0, y0, s)) { Fan(x0, y0, s); return; }
+ if (s > 1)
+ {
+ int h = s / 2;
+ Block(x0, y0, h); Block(x0 + h, y0, h); Block(x0, y0 + h, h); Block(x0 + h, y0 + h, h);
+ return;
+ }
+ if (!Drawn(x0, y0)) return;
+ int a = Vertex(x0, y0), b = Vertex(x0 + 1, y0), d = Vertex(x0, y0 + 1), e = Vertex(x0 + 1, y0 + 1);
+ Tri(a, b, e); Tri(a, e, d);
+ }
+ for (int by = 0; by < blocks; by++)
+ for (int bx = 0; bx < blocks; bx++)
+ {
+ if (!Relevant(bx, by)) continue;
+ int x0 = bx * B, y0 = by * B;
+ bx0 = x0; by0 = y0;
+ for (int i = 0; i < inner.Length; i++) inner[i] = -1;
+ if (x0 + B <= cells && y0 + B <= cells && Flat(x0, y0, B)) { Fan(x0, y0, B); continue; }
+ Dilate(x0, y0);
+ Block(x0, y0, B);
+ }
+ return (verts.ToArray(), tris.ToArray());
+ }
+
+ /// <summary>The water mesh from its samples (WaterMeshGrid): every vertex on the terrain's own heightmap sample.</summary>
+ public static Mesh WaterMesh(int res, Vector3 size, float[,] heights, int[] grid, int[] indices)
+ {
+ int cells = res - 1;
+ float stepX = size.x / cells, stepZ = size.z / cells;
+ var verts = new Vector3[grid.Length];
+ for (int i = 0; i < grid.Length; i++)
+ {
+ int x = grid[i] & 0xFFFF, y = grid[i] >> 16;
+ verts[i] = new Vector3(x * stepX, heights[y, x] * size.y, y * stepZ);
+ }
+ var mesh = new Mesh { name = "TerrainWater", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };
+ mesh.SetVertices(verts);
+ mesh.SetIndices(indices, MeshTopology.Triangles, 0, false);
+ mesh.bounds = new Bounds(size * 0.5f, size);
+ if (!Application.isEditor) mesh.UploadMeshData(true); // players keep only the GPU copy (about 4.5 MB less heap)
+ return mesh;
+ }
+
+ /// <summary>terrain_water.bytes (MapTexturePaths.WaterMesh): "SCW1", the heightmap's resolution, a check of its
+ /// heights (HeightsCheck), the vertex and index counts, then WaterMeshGrid's two arrays, all little-endian int32.</summary>
+ const int WaterMagic = 0x31574353;
+ public static byte[] WaterMeshBytes(int res, float[,] heights, int[] grid, int[] indices)
+ {
+ var bytes = new byte[20 + 4 * (grid.Length + indices.Length)];
+ int[] head = { WaterMagic, res, HeightsCheck(heights), grid.Length, indices.Length };
+ Buffer.BlockCopy(head, 0, bytes, 0, 20);
+ Buffer.BlockCopy(grid, 0, bytes, 20, 4 * grid.Length);
+ Buffer.BlockCopy(indices, 0, bytes, 20 + 4 * grid.Length, 4 * indices.Length);
+ return bytes;
+ }
+
+ /// <summary>Reads terrain_water.bytes; false (and the reason) when it is not for this heightmap.</summary>
+ public static bool TryReadWaterMesh(byte[] bytes, int res, float[,] heights, out int[] grid, out int[] indices, out string reason)
+ {
+ grid = indices = Array.Empty<int>();
+ if (bytes == null || bytes.Length < 20) { reason = "missing or short"; return false; }
+ var head = new int[5];
+ Buffer.BlockCopy(bytes, 0, head, 0, 20);
+ if (head[0] != WaterMagic) { reason = "not a water mesh"; return false; }
+ if (head[1] != res) { reason = $"made for a {head[1]} heightmap, this one is {res}"; return false; }
+ if (head[2] != HeightsCheck(heights)) { reason = "made for other heights (re-bake: TerrainWaterBake.Bake)"; return false; }
+ if (bytes.Length != 20 + 4L * (head[3] + head[4])) { reason = "truncated"; return false; }
+ grid = new int[head[3]]; indices = new int[head[4]];
+ Buffer.BlockCopy(bytes, 20, grid, 0, 4 * grid.Length);
+ Buffer.BlockCopy(bytes, 20 + 4 * grid.Length, indices, 0, 4 * indices.Length);
+ reason = "";
+ return true;
+ }
+
+ /// <summary>A cheap check that baked water data still matches the heights: FNV-1a over every 997th sample's bits.</summary>
+ public static int HeightsCheck(float[,] heights)
+ {
+ int res = heights.GetLength(1), n = heights.Length;
+ uint h = 2166136261;
+ for (int i = 0; i < n; i += 997)
+ {
+ uint bits = (uint)BitConverter.SingleToInt32Bits(heights[i / res, i % res]);
+ for (int k = 0; k < 4; k++) { h ^= (bits >> (8 * k)) & 0xFF; h *= 16777619; }
+ }
+ return (int)h;
+ }
+
/// <summary>Vertices of one draped hex ring (<see cref="DrapedRing"/>).</summary>
public const int RingVertices = 6 * OverlaySegmentsPerEdge;
diff --git a/unity/Assets/Scripts/Map/MapScene.cs b/unity/Assets/Scripts/Map/MapScene.cs
index 763051f53..f7da3eae1 100644
--- a/unity/Assets/Scripts/Map/MapScene.cs
+++ b/unity/Assets/Scripts/Map/MapScene.cs
@@ -16,6 +16,9 @@ namespace Statecraft.Game.Map
/// <summary>The art spike's procedural settlement kits and trees (Kit.mat, Tree.mat: Statecraft/Kit). Optional: without
/// them the map keeps the placeholder marker boxes.</summary>
[SerializeField] Material kitMaterial, treeMaterial;
+ /// <summary>The terrain water's mesh, baked (MapTexturePaths.WaterMesh, issue #195). Optional: without it, or when it
+ /// is for other heights, the map derives the mesh at load (about 90 ms at the boot budget's CPU throttling).</summary>
+ [SerializeField] TextAsset terrainWaterMesh;
public GeoFrame Frame { get; private set; }
/// <summary>hexes.json as the last Build read it (bounds, hex size, biomes).</summary>
@@ -40,6 +43,11 @@ namespace Statecraft.Game.Map
public const string SelectionName = "HexSelection";
/// <summary>The land and sea past the map's edge: a child of the terrain (so a rebuild destroys it).</summary>
public const string BorderSkirtName = "BorderSkirt";
+ /// <summary>The water inside the map: a mesh over the water and its shore, a child of the terrain (issue #195).</summary>
+ public const string TerrainWaterName = "TerrainWater";
+ /// <summary>The terrain water's render queue: after the terrain (Terrain.mat, one queue earlier: MapMaterials) and
+ /// before every other opaque, so boats, harbours and units drawn on the water cover it despite its depth pull.</summary>
+ public const int TerrainWaterQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry - 1;
/// <summary>Highlight colour of the selected hex, to read against every biome; MapMaterials bakes it into the
/// editor-made HexSelection.mat. Warm ivory since the visual v1 merge point: the earlier gold (1, 0.84, 0.38) shares
/// the hue of the terrain shader's dry-grass coastal plain (MapPalette), so at gameplay03 it stood out from the land
@@ -229,6 +237,8 @@ namespace Statecraft.Game.Map
var size = Terrain.terrainData.size;
AddBorderSkirt(terrainGo, meta.elev_min_m);
DiagLog.BootPhase("border skirt");
+ AddTerrainWater(terrainGo, heights, meta.elev_min_m);
+ DiagLog.BootPhase("terrain water");
Frame = new GeoFrame(meta.lon0, meta.lon1, meta.lat0, meta.lat1, size.x, size.z);
var markers = SettlementPlacer.Place(list, Frame, Terrain, markerMaterial);
markers.transform.SetParent(transform, true);
@@ -314,6 +324,48 @@ namespace Statecraft.Game.Map
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
}
+ /// <summary>The water inside the map (issue #195): MapBuilder.BuildWaterMesh's copy of the terrain's surface over the
+ /// water and its shore, drawn with a copy of Sea.mat in its terrain-water mode (Sea.shader _ScTerrainWater), which
+ /// adds the water's colour times its coverage on top of the terrain graph (black there); the land adds 0 (no discard: whole quads, #306). Drawn
+ /// right after the terrain, before the other opaques (TerrainWaterQueue); no depth write, no shadow, no collider
+ /// (clicks still pick only the terrain). The water's shading thus stays out of the terrain's fragment shader, whose
+ /// size it had pushed past a WebGL cost cliff (about 3 ms a frame at gameplay03, even with the water toggled
+ /// off).</summary>
+ void AddTerrainWater(GameObject terrainGo, float[,] heights, float elevMinM)
+ {
+ var assets = terrainGo.GetComponent<MapRuntimeAssets>();
+ var material = assets.Own(new Material(seaMaterial) { name = TerrainWaterName });
+ material.SetFloat("_ScTerrainWater", 1f);
+ material.SetFloat("_ScSrcBlend", (float)UnityEngine.Rendering.BlendMode.One);
+ material.SetFloat("_ScDstBlend", (float)UnityEngine.Rendering.BlendMode.One);
+ material.SetFloat("_ScZWrite", 0f);
+ material.SetShaderPassEnabled("DepthOnly", false);
+ material.SetShaderPassEnabled("DepthNormals", false);
+ material.renderQueue = TerrainWaterQueue;
+ var go = new GameObject(TerrainWaterName);
+ go.transform.SetParent(terrainGo.transform, false);
+ go.AddComponent<MeshFilter>().sharedMesh = WaterMesh(heights, elevMinM, assets);
+ var renderer = go.AddComponent<MeshRenderer>();
+ renderer.sharedMaterial = material;
+ renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
+ }
+
+ /// <summary>The baked water mesh when it matches these heights, else the one derived from them.</summary>
+ Mesh WaterMesh(float[,] heights, float elevMinM, MapRuntimeAssets assets)
+ {
+ var data = Terrain.terrainData;
+ if (terrainWaterMesh != null)
+ {
+ if (MapBuilder.TryReadWaterMesh(terrainWaterMesh.bytes, data.heightmapResolution, heights, out var grid, out var indices, out var why))
+ return assets.Own(MapBuilder.WaterMesh(data.heightmapResolution, data.size, heights, grid, indices));
+ Debug.LogWarning($"MAP {MapTexturePaths.WaterMesh}: {why}; deriving the water mesh at load");
+ }
+ return MapBuilder.BuildWaterMesh(data, heights, elevMinM, assets);
+ }
+
+ /// <summary>Test and editor seam: the baked water mesh (null: derived at load).</summary>
+ public void ConfigureWater(TextAsset baked) => terrainWaterMesh = baked;
+
static string MetaPath => "heightmap.json";
static string HexesPath => "hexes.json";
static string SettlementsPath => SettlementPlacer.DefaultFileName;
diff --git a/unity/Assets/Scripts/Map/MapShaderGlobals.cs b/unity/Assets/Scripts/Map/MapShaderGlobals.cs
index ac1196412..e35bf38d4 100644
--- a/unity/Assets/Scripts/Map/MapShaderGlobals.cs
+++ b/unity/Assets/Scripts/Map/MapShaderGlobals.cs
@@ -79,5 +79,8 @@ namespace Statecraft.Game.Map
public const string Ao = "Assets/Textures/Map/ao.png";
/// <summary>The land (tools/land_bake.py, issue #33): rgb its linear colour, a its weight over the biome ground.</summary>
public const string Land = "Assets/Textures/Map/landuse.png";
+ /// <summary>The terrain water's mesh as heightmap samples (MapBuilder.WaterMeshBytes; Editor TerrainWaterBake), so a
+ /// player does not derive it at boot (issue #195).</summary>
+ public const string WaterMesh = "Assets/Textures/Map/terrain_water.bytes";
}
}
diff --git a/unity/Assets/Shaders/Sea.shader b/unity/Assets/Shaders/Sea.shader
index 003ff8c98..9ea2e727a 100644
--- a/unity/Assets/Shaders/Sea.shader
+++ b/unity/Assets/Shaders/Sea.shader
@@ -2,11 +2,21 @@
// (StatecraftMap.hlsl ScWaterShade) and coast texture (clamped at the edge), with the same water haze, so no seam shows. Unlit:
// the function lights itself, as the terrain graph's water (emission only) does. DepthOnly and DepthNormals passes keep it
// in the depth prepass on tiers that make one.
+// It also shades the water inside the map (issue #195): MapScene's TerrainWater (MapBuilder.BuildWaterMesh, the terrain's
+// surface over the water and its shore) is drawn with a copy of Sea.mat that sets _ScTerrainWater, which adds the
+// water's colour times its coverage (ScWater) on top of the terrain (additive, no depth write; the land adds 0). The
+// terrain graph (StatecraftTerrain.hlsl) outputs black on the water, so the sum is what it drew before; the water no
+// longer weighs on the terrain's own fragment shader, whose size cost about 3 ms a frame at gameplay03.
Shader "Statecraft/Sea"
{
Properties
{
[NoScaleOffset] _ScCoastTex ("Coast distance (R)", 2D) = "black" {}
+ // The skirt's defaults; MapScene's TerrainWater material sets 1, One, One and 0.
+ [HideInInspector] _ScTerrainWater ("Terrain water", Float) = 0
+ [HideInInspector] _ScSrcBlend ("Source blend", Float) = 1
+ [HideInInspector] _ScDstBlend ("Destination blend", Float) = 0
+ [HideInInspector] _ScZWrite ("Depth write", Float) = 1
}
SubShader
{
@@ -14,7 +24,7 @@ Shader "Statecraft/Sea"
HLSLINCLUDE
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
CBUFFER_START(UnityPerMaterial)
- float _ScSeaUnused; // the SRP Batcher needs a UnityPerMaterial buffer; the sea has no per-material numbers
+ float _ScTerrainWater; // 1 = the terrain's water (MapScene.TerrainWaterName), 0 = the skirt's sea
CBUFFER_END
struct Attributes { float4 positionOS : POSITION; };
ENDHLSL
@@ -23,6 +33,8 @@ Shader "Statecraft/Sea"
{
Name "Sea"
Tags { "LightMode" = "UniversalForward" }
+ Blend [_ScSrcBlend] [_ScDstBlend]
+ ZWrite [_ScZWrite]
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment Frag
@@ -32,23 +44,51 @@ Shader "Statecraft/Sea"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
#include "Assets/Shaders/StatecraftMap.hlsl"
TEXTURE2D(_ScCoastTex); SAMPLER(sampler_ScCoastTex);
+ // The terrain water's depth pull (pixels' worth of metres towards the camera; see Vert).
+ static const float ScWaterDepthPullPx = 2.0;
struct Varyings { float4 positionCS : SV_POSITION; float3 positionWS : TEXCOORD0; };
Varyings Vert(Attributes input)
{
Varyings o;
VertexPositionInputs p = GetVertexPositionInputs(input.positionOS.xyz);
o.positionCS = p.positionCS; o.positionWS = p.positionWS;
+ // The terrain water (_ScTerrainWater: a uniform, not a keyword, so no extra variants to load). The terrain
+ // draws the same surface split and simplified its own way (its LOD keeps within a pixel), so
+ // the water's depth is pulled ScWaterDepthPullPx pixels' worth of metres towards the camera along the view
+ // ray: the same pixel, never behind the terrain it lies on (a depth offset alone left specks at the
+ // overview). Drawn before every other opaque (MapScene.TerrainWaterQueue), so it covers nothing else.
+ // Shading keeps the true position.
+ // An orthographic camera (MapCapture.TopDown, the top-down sea tests) has parallel rays and pixels the same
+ // size at every distance: the pull goes along its forward axis, by its pixel size, or the water would slide
+ // across the screen towards the camera's axis.
+ float dist = max(length(_WorldSpaceCameraPos - p.positionWS), 1.0);
+ bool perspective = IsPerspectiveProjection();
+ float3 towards = perspective ? (_WorldSpaceCameraPos - p.positionWS) / dist : -GetViewForwardDir();
+ float pixelM = (perspective ? dist : 1.0) * 2.0 / (abs(UNITY_MATRIX_P._m11) * _ScreenParams.y);
+ float pull = _ScTerrainWater * min(ScWaterDepthPullPx * pixelM, 0.5 * dist);
+ o.positionCS = TransformWorldToHClip(p.positionWS + towards * pull);
return o;
}
half4 Frag(Varyings input) : SV_Target
{
float2 mapM = input.positionWS.xz - _ScMapOrigin.xz;
float coast = SAMPLE_TEXTURE2D(_ScCoastTex, sampler_ScCoastTex, saturate(mapM / _ScMap.xy)).r;
- float footprintM = max(length(ddx(mapM)), length(ddy(mapM))); // as the terrain's water takes it
- float3 c = ScHazeWater(ScWaterShade(coast, 0.0, input.positionWS, mapM, footprintM, ScBreakers(coast, mapM)), input.positionWS);
- // The hex lattice runs on past the map's edge, exactly as on the terrain's water (review I3).
- c = lerp(c, SRGBToLinear(ScGridWaterSrgb), ScGridAmount(mapM, input.positionWS) * _ScGrid.y);
- return half4(c, 1.0);
+ // Every derivative in uniform control flow (the derivatives below and ScWaterShade's).
+ float footprintM = max(length(ddx(mapM)), length(ddy(mapM)));
+ float2 breakers = ScBreakers(coast, mapM);
+ // The hex lattice runs on past the map's edge, exactly as on the terrain (review I3).
+ float gridLine = ScGridAmount(mapM, input.positionWS) * _ScGrid.y;
+ bool onTerrain = _ScTerrainWater > 0.5;
+ // The terrain's coverage (0 on land, a ramp about 140 m wide at the shore) and the rift lakes' depth (salt,
+ // fresh); the skirt is all sea at sea level.
+ // No discard on the land: a per-pixel discard splits the 2x2 quads along the shore, where the derivatives
+ // the water needs come from (the lesson of #306); the land's fragments add colour times 0. The mesh holds
+ // only the water and two heightmap samples of shore, so few land fragments run.
+ float water = onTerrain ? ScWater(coast) : 1.0;
+ float elevM = onTerrain ? (input.positionWS.y - _ScMap.z) / _ScMap.w : 0.0;
+ float3 c = ScHazeWater(ScWaterShade(coast, elevM, input.positionWS, mapM, footprintM, breakers), input.positionWS);
+ c = lerp(c, SRGBToLinear(ScGridWaterSrgb), gridLine);
+ return half4(c * water, onTerrain ? 0.0 : 1.0); // the terrain water adds; the target's alpha is left as it is
}
ENDHLSL
}
diff --git a/unity/Assets/Shaders/StatecraftBorders.hlsl b/unity/Assets/Shaders/StatecraftBorders.hlsl
index 49fffc3f4..c0a28c56e 100644
--- a/unity/Assets/Shaders/StatecraftBorders.hlsl
+++ b/unity/Assets/Shaders/StatecraftBorders.hlsl
@@ -6,7 +6,8 @@
// texel per hex (_ScRegionTex) and sets the globals; with no region data, or the "borders" toggle off, _ScBorders.w is 0 and
// nothing is drawn. Included at the end of StatecraftMap.hlsl; the terrain calls ScBorderApply last.
-TEXTURE2D(_ScRegionTex); // one texel per hex, linear RGBA8: r + 256 g the region id (0 = none), b the style (0 = none, 1, 2)
+TEXTURE2D(_ScRegionTex); // one texel per hex, linear RGBA8: r + 256 g the region id (0 = none), b the style (0 = none, 1, 2),
+ // a's low six bits which edges border another region (MapBorders.Use bakes them; issue #195)
float4 _ScRegionInfo; // x q of texel column 0, y r of texel row 0, z width, w height (texels)
float4 _ScBorders; // x least band width (px), y widest band (+ wash) as a share of the hex's inradius,
// z 1 = no early-out (tests prove the early-out exact), w 1 = on
@@ -15,19 +16,18 @@ float4 _ScBorders; // x least band width (px), y widest band (+ wash) as
float4 _ScBorderColour1, _ScBorderLight1, _ScBorderShape1;
float4 _ScBorderColour2, _ScBorderLight2, _ScBorderShape2;
-// Axial neighbour steps and the outward unit normals of the edges shared with them (p space: x east, y south): tools/
-// hexgrid.py's NEIGHBOURS order.
-static const float2 ScHexSteps[6] = { float2(1, 0), float2(1, -1), float2(0, -1), float2(-1, 0), float2(-1, 1), float2(0, 1) };
+// The outward unit normals of a hex's edges (p space: x east, y south), in tools/hexgrid.py's NEIGHBOURS order (axial
+// steps (1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1): MapBorders.NeighbourSteps). Bit i of a hex's edge mask is edge i.
static const float2 ScHexNormals[6] = { float2(1, 0), float2(0.5, -0.8660254), float2(-0.5, -0.8660254), float2(-1, 0),
float2(-0.5, 0.8660254), float2(0.5, 0.8660254) };
-// Region id and style of axial hex (q, r); (0, 0) off the texture.
-float2 ScRegionAt(float2 qr)
+// Region id, style and border-edge mask of axial hex (q, r); (0, 0, 0) off the texture.
+float3 ScRegionAt(float2 qr)
{
int2 t = int2(qr - _ScRegionInfo.xy);
- if (t.x < 0 || t.y < 0 || t.x >= (int)_ScRegionInfo.z || t.y >= (int)_ScRegionInfo.w) return float2(0.0, 0.0);
+ if (t.x < 0 || t.y < 0 || t.x >= (int)_ScRegionInfo.z || t.y >= (int)_ScRegionInfo.w) return float3(0.0, 0.0, 0.0);
float4 v = LOAD_TEXTURE2D(_ScRegionTex, t) * 255.0;
- return float2(round(v.r) + 256.0 * round(v.g), round(v.b));
+ return float3(round(v.r) + 256.0 * round(v.g), round(v.b), (float)((int)round(v.a) & 63));
}
// The axial hex containing p (cube rounding: ScHexEdgeDistance's layout, p.x east and p.y south of the north-west corner)
@@ -68,17 +68,20 @@ void ScBorderApply(float2 mapM, float water, inout float3 baseColor, inout float
float reach = max(max(_ScBorderShape1.x, _ScBorderShape2.x), 1.5 * _ScBorders.x * footprint) * washMul + 1.5 * footprint;
reach = _ScBorders.z > 0.5 ? 1e9 : reach;
float edge = inradius - max(abs(v.x), max(abs(0.5 * v.x + 0.8660254 * v.y), abs(0.5 * v.x - 0.8660254 * v.y)));
- float2 own = edge < reach && water < 1.0 ? ScRegionAt(qr) : float2(0.0, 0.0);
- [branch] if (own.x > 0.5 && own.y > 0.5)
+ float3 own = edge < reach && water < 1.0 ? ScRegionAt(qr) : float3(0.0, 0.0, 0.0);
+ int edges = (int)own.z;
+ // A hex with no border edge draws nothing (the loop below would leave cover 0), so it skips the work.
+ [branch] if (own.x > 0.5 && own.y > 0.5 && edges != 0)
{
float bestPx = 1e9, bestAa = 1.0;
[unroll] for (int i = 0; i < 6; i++)
{
float2 n = ScHexNormals[i];
- // Only the edges within reach are looked up (one, or two near a corner).
+ // Only the edges within reach count (one, or two near a corner). Whether edge i borders another region is
+ // baked into the hex's own texel: the neighbours' six fetches here had pushed the terrain's fragment shader
+ // past a WebGL cost cliff (about 5 ms a frame at gameplay03, borders on or off: issue #195).
if (inradius - dot(v, n) >= reach) continue;
- float2 other = ScRegionAt(qr + ScHexSteps[i]);
- if (other.x > 0.5 && other.x != own.x)
+ if (((edges >> i) & 1) != 0)
{
// Distance to the edge segment (corners rounded, so two border edges join without a notch), in pixels
// along the direction it grows (Task 8's anisotropic filter: metres per pixel across the line).
diff --git a/unity/Assets/Shaders/StatecraftTerrain.hlsl b/unity/Assets/Shaders/StatecraftTerrain.hlsl
index 61411a693..d530ddd0a 100644
--- a/unity/Assets/Shaders/StatecraftTerrain.hlsl
+++ b/unity/Assets/Shaders/StatecraftTerrain.hlsl
@@ -17,9 +17,6 @@ void StatecraftTerrain_float(float2 UV, float3 PositionWS, float3 NormalWS, Unit
bake.r = SAMPLE_TEXTURE2D(Ao.tex, Ao.samplerstate, UV).r;
float coast = SAMPLE_TEXTURE2D(Coast.tex, Coast.samplerstate, UV).r;
float2 mapM = UV * _ScMap.xy;
- // The pixel's footprint (m), for the water's chop and breakers, taken here in uniform
- // control flow (derivatives are undefined inside the water branch).
- float footprintM = max(length(ddx(mapM)), length(ddy(mapM)));
// ScGround with the land use (StatecraftLand.hlsl) laid between its colour and its shading: curvature, AO and breakup
// shade the fields too. The "land" toggle lerps it away (it does not skip the sample: a visual switch, not a price).
float4 land = SAMPLE_TEXTURE2D(Land.tex, Land.samplerstate, UV);
@@ -29,27 +26,23 @@ void StatecraftTerrain_float(float2 UV, float3 PositionWS, float3 NormalWS, Unit
float h = _ScHaze.a * ScHazeAmount(PositionWS); // land haze, applied after lighting via Emission
float ao = bake.r * lerp(0.6, 1.0, bake.b);
float water = ScWater(coast);
- // Water: ScWaterShade's colour (sunlit with its shadows, then the cool water haze) as emission on a black, fully metallic,
- // fully occluded surface, so Lit adds nothing (no diffuse, specular colour 0, indirect light times occlusion 0): exactly
- // what Sea.shader returns past the edge. Land keeps its after-lighting haze through the same Emission.
+ // Water: a black, fully metallic, fully occluded surface with no emission, so Lit outputs 0 there; the water's colour
+ // (ScWaterShade, sunlit with its shadows, then the water haze) is added on top, times the same coverage, by the terrain
+ // water (Sea.shader's _ScTerrainWater, MapScene.TerrainWaterName): the sum is what this function drew before issue
+ // #195. Kept out of here because its size, not its arithmetic, cost about 3 ms a frame at gameplay03 in WebGL even with
+ // the water off (perf-investigation). Land keeps its after-lighting haze through Emission.
float elevM = (PositionWS.y - _ScMap.z) / _ScMap.w;
- // Land pixels (water 0, spatially coherent) skip the water shading: its noise and second shadow lookup would only be
- // multiplied away (Task 7 fix round 1, M3).
- float2 breakers = ScBreakers(coast, mapM);
- float3 waterColour = 0;
- [branch] if (water > 0.0) waterColour = ScHazeWater(ScWaterShade(coast, elevM, PositionWS, mapM, footprintM, breakers), PositionWS);
ground = ScShore(ground, coast, elevM, n, mapM); // the beach and the Dead Sea's salt flats (promo-sea)
- // The hex grid (visual v1 Task 8), light and faint on land and water, thinner towards the overview: the same lines as
- // Sea.shader past the edge. Computed outside the branch: its fwidth needs uniform control flow.
+ // The hex grid (visual v1 Task 8), light and faint on land, thinner towards the overview: the same lines as Sea.shader
+ // draws on the water. Computed in uniform control flow: its fwidth needs it.
float gridLine = ScGridAmount(mapM, PositionWS);
ground = lerp(ground, SRGBToLinear(ScGridLandSrgb), gridLine * _ScGrid.x);
- waterColour = lerp(waterColour, SRGBToLinear(ScGridWaterSrgb), gridLine * _ScGrid.y);
BaseColor = ground * (1.0 - h) * (1.0 - water);
NormalOut = normalize(lerp(n, float3(0, 1, 0), water));
Occlusion = lerp(lerp(1.0, ao, 0.8), 0.0, water);
Smoothness = 0.0;
Metallic = water;
- Emission = lerp(_ScHaze.rgb * h, waterColour, water);
+ Emission = _ScHaze.rgb * h * (1.0 - water);
ScBorderApply(mapM, water, BaseColor, Emission); // region borders (StatecraftBorders.hlsl), last: unlit, on land only
}
diff --git a/unity/Assets/Tests/EditMode/BorderEdgeTests.cs b/unity/Assets/Tests/EditMode/BorderEdgeTests.cs
new file mode 100644
index 000000000..90c120422
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/BorderEdgeTests.cs
@@ -0,0 +1,54 @@
+#nullable enable
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using NUnit.Framework;
+using Statecraft.Game.Map;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+
+/// <summary>Issue #195: which of a hex's edges border another region is baked into its own texel (MapBorders.Use), so the
+/// terrain's shader reads one texel, not seven: the neighbours' six fetches had pushed the terrain's fragment shader past a
+/// WebGL cost cliff (about 5 ms a frame at gameplay03, borders on or off). BorderTests prove the drawing unchanged.</summary>
+public class BorderEdgeTests
+{
+ [TearDown]
+ public void Reset() { EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); VisualToggles.Clear(); }
+
+ [Test]
+ public void UseBakesWhichEdgesBorderAnotherRegion()
+ {
+ EditorSceneManager.OpenScene("Assets/Map.unity", OpenSceneMode.Single);
+ var map = Object.FindFirstObjectByType<MapScene>(); map.Build();
+ // A hex whose six neighbours are on the map: region 1 at the centre and at neighbours 0 and 3, region 2 at
+ // neighbour 1, neighbour 2 in no region (no band against it), neighbours 4 and 5 in region 3 (style none: still
+ // another region).
+ var steps = MapBorders.NeighbourSteps;
+ var onMap = new HashSet<(int q, int r)>(map.Hexes.hexes.Select(h => (h.q, h.r)));
+ var c = map.Hexes.hexes.First(h => steps.All(s => onMap.Contains((h.q + s.dq, h.r + s.dr))));
+ int[] ids = { 1, 2, 0, 1, 3, 3 };
+ var hexes = new Dictionary<(int q, int r), int> { [(c.q, c.r)] = 1 };
+ for (int i = 0; i < 6; i++) if (ids[i] > 0) hexes[(c.q + steps[i].dq, c.r + steps[i].dr)] = ids[i];
+ var styles = new Dictionary<int, BorderStyle> { [1] = BorderStyle.Primary, [2] = BorderStyle.Secondary, [3] = BorderStyle.None };
+ MapBorders.Use(new RegionLayer("edges", hexes, styles));
+ var tex = (Texture2D)Shader.GetGlobalTexture("_ScRegionTex");
+ var info = Shader.GetGlobalVector("_ScRegionInfo");
+ Color32 At(int q, int r) => tex.GetPixel(q - (int)info.x, r - (int)info.y);
+ var centre = At(c.q, c.r);
+ Assert.AreEqual((1, 0, 1), ((int)centre.r, (int)centre.g, (int)centre.b), "region and style as before");
+ Assert.AreEqual(0xC0 | 0b110010, (int)centre.a, "edges 1, 4 and 5 border another region; 0 and 3 are its own, 2 none");
+ Assert.AreEqual(0xC0 | 1 << 4 | 1 << 5, (int)At(c.q + steps[1].dq, c.r + steps[1].dr).a,
+ "neighbour 1 sees the centre across its edge 4 (the opposite of 1) and neighbour 0 across its edge 5");
+ MapBorders.Use(null);
+ Assert.AreEqual(0, (int)At(c.q, c.r).a, "no layer: a cleared texel");
+ }
+
+ [Test]
+ public void TheBordersReadOneTexelAPixel()
+ {
+ var src = Regex.Replace(File.ReadAllText("Assets/Shaders/StatecraftBorders.hlsl"), "//[^\n]*", "");
+ Assert.AreEqual(1, Regex.Matches(src, @"ScRegionAt\(").Count - 1, "ScRegionAt called once (its definition aside)");
+ Assert.AreEqual(1, Regex.Matches(src, "LOAD_TEXTURE2D").Count);
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/BorderEdgeTests.cs.meta b/unity/Assets/Tests/EditMode/BorderEdgeTests.cs.meta
new file mode 100644
index 000000000..c0ec76fd7
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/BorderEdgeTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1a8e629d8f2374d5795851253c048830
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/SeaTests.cs b/unity/Assets/Tests/EditMode/SeaTests.cs
index 0ab1047f5..5a31cb9cc 100644
--- a/unity/Assets/Tests/EditMode/SeaTests.cs
+++ b/unity/Assets/Tests/EditMode/SeaTests.cs
@@ -48,6 +48,97 @@ public class SeaTests
CollectionAssert.IsEmpty(ShaderChecks.Gles3Errors(AssetDatabase.LoadAssetAtPath<Material>("Assets/Materials/Terrain.mat").shader));
}
+ /// <summary>Issue #195: the water inside the map is drawn by MapScene's TerrainWater, the terrain's surface over the
+ /// water and its shore (MapBuilder.BuildWaterMesh) with a copy of Sea.mat in its terrain-water mode: added on top right
+ /// after the terrain and before the other opaques, no depth write, no shadow, no collider. The mesh lies on the
+ /// heightmap (its vertices are heightmap samples or flat fans), reaches the open sea and both rift lakes, and stays off
+ /// inland hills.</summary>
+ [Test]
+ public void TheTerrainWaterLiesOnTheWaterWithTheSeaShader()
+ {
+ var map = OpenMap();
+ var t = map.Terrain.transform.Find(MapScene.TerrainWaterName);
+ Assert.IsNotNull(t, "TerrainWater under the terrain");
+ Assert.AreEqual(map.Terrain.transform.position, t.position);
+ Assert.IsNull(t.GetComponent<Collider>(), "clicks pick the terrain only");
+ var r = t.GetComponent<MeshRenderer>();
+ Assert.AreEqual(UnityEngine.Rendering.ShadowCastingMode.Off, r.shadowCastingMode);
+ var m = r.sharedMaterial;
+ Assert.AreEqual("Statecraft/Sea", m.shader.name);
+ Assert.AreEqual(1f, m.GetFloat("_ScTerrainWater"));
+ Assert.Greater(m.renderQueue, map.Terrain.materialTemplate.renderQueue, "after the terrain");
+ Assert.Less(m.renderQueue, (int)UnityEngine.Rendering.RenderQueue.Geometry, "before boats, harbours and units");
+ Assert.AreEqual(0f, m.GetFloat("_ScZWrite"));
+ Assert.IsFalse(m.GetShaderPassEnabled("DepthOnly")); Assert.IsFalse(m.GetShaderPassEnabled("DepthNormals"));
+ var mesh = t.GetComponent<MeshFilter>().sharedMesh;
+ var verts = mesh.vertices;
+ TestContext.WriteLine($"water mesh: {verts.Length} vertices, {mesh.triangles.Length / 3} triangles");
+ Assert.Less(mesh.triangles.Length / 3, 1_000_000, "a light mesh, not a second terrain");
+ // Every vertex lies on the terrain (a fan's centre on its flat block).
+ var origin = map.Terrain.transform.position;
+ for (int i = 0; i < verts.Length; i += 97)
+ Assert.AreEqual(map.Terrain.SampleHeight(origin + verts[i]), verts[i].y, 0.25f, $"vertex {i} {verts[i]}");
+ // Wet places are covered, an inland hill is not: horizontal hits on the mesh's triangles.
+ bool Covers(double lon, double lat)
+ {
+ var p = map.Frame.ToWorld(lon, lat, 0) - origin;
+ var tri = mesh.triangles;
+ for (int i = 0; i < tri.Length; i += 3)
+ {
+ Vector3 a = verts[tri[i]], b = verts[tri[i + 1]], c = verts[tri[i + 2]];
+ float d = (b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z);
+ float u = ((b.z - c.z) * (p.x - c.x) + (c.x - b.x) * (p.z - c.z)) / d;
+ float v = ((c.z - a.z) * (p.x - c.x) + (a.x - c.x) * (p.z - c.z)) / d;
+ if (u >= 0 && v >= 0 && u + v <= 1) return true;
+ }
+ return false;
+ }
+ Assert.IsTrue(Covers(34.60, 32.08), "the open sea west of Tel Aviv");
+ Assert.IsTrue(Covers(35.50, 31.50), "the Dead Sea");
+ Assert.IsTrue(Covers(35.59, 32.82), "the Sea of Galilee");
+ Assert.IsFalse(Covers(35.21, 31.77), "Jerusalem's hills");
+ }
+
+ /// <summary>Issue #195: the baked water mesh (terrain_water.bytes, Editor TerrainWaterBake.Bake) is what the shipped
+ /// heightmap gives now, byte for byte, and the map scene uses it; a stale bake is refused and the map derives the mesh
+ /// instead, so it is never wrong, only slower to boot.</summary>
+ [Test]
+ public void TheBakedWaterMeshMatchesTheHeightmap()
+ {
+ var (meta, heights) = HeightmapLoader.Load(Statecraft.Game.Paths.StreamingMap);
+ var (grid, indices) = MapBuilder.WaterMeshGrid(meta.width, MapBuilder.TerrainSize(meta), heights, meta.elev_min_m);
+ var baked = AssetDatabase.LoadAssetAtPath<TextAsset>(MapTexturePaths.WaterMesh);
+ Assert.IsNotNull(baked, MapTexturePaths.WaterMesh);
+ CollectionAssert.AreEqual(MapBuilder.WaterMeshBytes(meta.width, heights, grid, indices), baked.bytes,
+ "stale: re-run Statecraft.Game.EditorTools.TerrainWaterBake.Bake");
+ Assert.IsTrue(MapBuilder.TryReadWaterMesh(baked.bytes, meta.width, heights, out _, out _, out var why), why);
+ heights[145, 1995] += 0.001f; // sample 997 x 300, one HeightsCheck reads
+ Assert.IsFalse(MapBuilder.TryReadWaterMesh(baked.bytes, meta.width, heights, out _, out _, out why), "other heights");
+ var derived = new System.Collections.Generic.List<string>();
+ void Watch(string message, string stack, LogType type) { if (message.Contains("deriving the water mesh")) derived.Add(message); }
+ Application.logMessageReceived += Watch;
+ try
+ {
+ var map = OpenMap();
+ var mesh = map.Terrain.transform.Find(MapScene.TerrainWaterName).GetComponent<MeshFilter>().sharedMesh;
+ Assert.AreEqual(grid.Length, mesh.vertexCount);
+ }
+ finally { Application.logMessageReceived -= Watch; }
+ CollectionAssert.IsEmpty(derived, "the scene's map uses the bake");
+ }
+
+ /// <summary>Issue #195: the terrain graph's function carries no water shading. Its size, not its arithmetic, cost about
+ /// 3 ms a frame at gameplay03 in WebGL (even with the water toggled off, so no toggle measures it); the water belongs in
+ /// Sea.shader's terrain-water mode.</summary>
+ [Test]
+ public void TheTerrainFunctionCarriesNoWaterShading()
+ {
+ var src = System.Text.RegularExpressions.Regex.Replace(
+ File.ReadAllText("Assets/Shaders/StatecraftTerrain.hlsl"), "//[^\n]*", ""); // comments may name them
+ foreach (var call in new[] { "ScWaterShade", "ScBreakers", "ScHazeWater", "ddx(", "ddy(" })
+ StringAssert.DoesNotContain(call, src);
+ }
+
/// <summary>The controller's known gap: at the Jordanian plateau the land skirt holds the edge's height for 20 km (at
/// least 80% of its height above the sea) and reaches sea level only at the last ring.</summary>
[Test]
@@ -367,6 +458,31 @@ public class SeaTests
finally { Object.DestroyImmediate(go); }
}
+ /// <summary>Issue #195 review: the terrain water's depth pull follows an orthographic camera's parallel rays. Pulled
+ /// towards the camera's position instead, the water slid towards the view's axis, and the terrain's black water showed
+ /// between it and the shore. Straight down over the coast south of Tel Aviv, 30 km across with the axis 12 km offshore,
+ /// no pixel is black.</summary>
+ [UnityTest]
+ public IEnumerator TheTerrainWaterStaysPutUnderAnOrthographicCamera()
+ {
+ var map = OpenMap();
+ yield return null;
+ var centre = map.Frame.ToWorld(34.62, 32.0, 0); centre.y = 0f;
+ var go = new GameObject("TopCoast"); var cam = go.AddComponent<Camera>();
+ try
+ {
+ const int n = 512;
+ cam.orthographic = true; cam.orthographicSize = 15000f; cam.aspect = 1f;
+ cam.transform.position = centre + Vector3.up * 20000f; cam.transform.rotation = Quaternion.Euler(90, 0, 0);
+ cam.nearClipPlane = 100f; cam.farClipPlane = 60000f;
+ var r = RenderSample.Render(cam, n, n);
+ int black = r.Pixels.Count(c => Mathf.Max(c.r, Mathf.Max(c.g, c.b)) < 0.02f);
+ TestContext.WriteLine($"black pixels: {black} of {n * n}");
+ Assert.AreEqual(0, black, "the water covers the terrain's black water up to the shore");
+ }
+ finally { Object.DestroyImmediate(go); }
+ }
+
/// <summary>Rendered: the Dead Sea is pale turquoise, much lighter than the open Mediterranean.</summary>
[UnityTest]
public IEnumerator TheDeadSeaIsPalerThanTheOpenSea()
diff --git a/unity/Assets/Textures/Map/terrain_water.bytes b/unity/Assets/Textures/Map/terrain_water.bytes
new file mode 100644
index 000000000..0a94f9676
Binary files /dev/null and b/unity/Assets/Textures/Map/terrain_water.bytes differ
diff --git a/unity/Assets/Textures/Map/terrain_water.bytes.meta b/unity/Assets/Textures/Map/terrain_water.bytes.meta
new file mode 100644
index 000000000..c1aa9b6ca
--- /dev/null
+++ b/unity/Assets/Textures/Map/terrain_water.bytes.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 51f85aaa1270842658cbc02738ff8df2
+TextScriptImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant: