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.

Hex tiles: paint the ground in 256-pixel tiles so ?hex-tiles=israel no longer runs out of memory; WebGL cap 4096 MB (#3166)

Eyal Goland6ee8c3c310f
diff --git a/changelog.d/hex-ground-oom.md b/changelog.d/hex-ground-oom.md
new file mode 100644
index 000000000..d6b85d0d4
--- /dev/null
+++ b/changelog.d/hex-ground-oom.md
@@ -0,0 +1,5 @@
+### Fixed
+- The hex-tile board (`?hex-tiles=israel`) no longer runs out of memory at the first End turn on the web. It paints its
+ ground 256 pixels square at a time through one reused buffer, instead of building the whole 2048 x 2048 alphamap at
+ once (184 MB of floats that the WebGL heap kept for the whole session). The WebGL heap cap goes from 2048 MB to
+ 4096 MB, so there is room for all of Tal Heuberger's models on that board (Refs #3164).
diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexBoard.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexBoard.cs
index b2e37fb6f..1515da604 100644
--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexBoard.cs
+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexBoard.cs
@@ -144,15 +144,18 @@ namespace Statecraft.HexTiles
public static float DistanceToLine(Vector3 p, IReadOnlyList<Vector3> line)
{
float best = float.MaxValue;
- for (int i = 0; i + 1 < line.Count; i++)
- {
- Vector2 a = new Vector2(line[i].x, line[i].z), b = new Vector2(line[i + 1].x, line[i + 1].z), q = new Vector2(p.x, p.z);
- var ab = b - a; float t = Mathf.Clamp01(Vector2.Dot(q - a, ab) / Mathf.Max(ab.sqrMagnitude, 1e-4f));
- best = Mathf.Min(best, (q - (a + ab * t)).magnitude);
- }
+ for (int i = 0; i + 1 < line.Count; i++) best = Mathf.Min(best, DistanceToSegment(p, line[i], line[i + 1]));
return best;
}
+ /// <summary>Distance on the ground (x, z) from p to the segment a-b.</summary>
+ public static float DistanceToSegment(Vector3 p, Vector3 a3, Vector3 b3)
+ {
+ Vector2 a = new Vector2(a3.x, a3.z), b = new Vector2(b3.x, b3.z), q = new Vector2(p.x, p.z);
+ var ab = b - a; float t = Mathf.Clamp01(Vector2.Dot(q - a, ab) / Mathf.Max(ab.sqrMagnitude, 1e-4f));
+ return (q - (a + ab * t)).magnitude;
+ }
+
float Terrain(Vector3 p)
{
var (q0, r0) = HexGeometry.Axial(p, size);
diff --git a/unity/Assets/Scripts/Map/HexTiles/Core/HexBoardBuilder.cs b/unity/Assets/Scripts/Map/HexTiles/Core/HexBoardBuilder.cs
index 83d1edf28..700677ef1 100644
--- a/unity/Assets/Scripts/Map/HexTiles/Core/HexBoardBuilder.cs
+++ b/unity/Assets/Scripts/Map/HexTiles/Core/HexBoardBuilder.cs
@@ -216,7 +216,7 @@ namespace Statecraft.HexTiles
return layer;
}).ToArray();
data.alphamapResolution = AlphaRes;
- data.SetAlphamaps(0, 0, Splat(board, surface, rect, paints, 0, 0, AlphaRes, AlphaRes));
+ PaintGround(data, board, surface, rect, paints);
if (holesOutsideLand)
{
// Holes everywhere but the board's land (and a sliver of shore), so the real map shows around it.
@@ -243,13 +243,44 @@ namespace Statecraft.HexTiles
return (data, rect);
}
+ /// <summary>Side of the square of alphamap pixels PaintGround splats at a time (AlphaRes is a multiple of it).</summary>
+ const int SplatTile = 256;
+
+ /// <summary>Writes the board's whole ground splat into <paramref name="data"/> (alphamap AlphaRes, one layer per
+ /// HexGround id), SplatTile pixels square at a time through one reused buffer: the whole 2048 x 2048 x 11 alphamap
+ /// is 184 MB of floats, and in WebGL the heap never shrinks. Test seam (internal; the tests see it through
+ /// InternalsVisibleTo).</summary>
+ internal static void PaintGround(TerrainData data, HexBoard board, HexBoardSurface surface, Rect rect, IReadOnlyList<(HexPaint paint, int q, int r)> paints)
+ {
+ var ids = HexGround.Ids;
+ var tile = new float[SplatTile, SplatTile, ids.Count];
+ var wt = new float[ids.Count];
+ var roads = RoadPaints(board);
+ for (int z0 = 0; z0 < AlphaRes; z0 += SplatTile)
+ for (int x0 = 0; x0 < AlphaRes; x0 += SplatTile)
+ {
+ SplatInto(tile, wt, ids, surface, rect, paints, roads, x0, z0);
+ data.SetAlphamaps(x0, z0, tile);
+ }
+ }
+
/// <summary>The ground splat over alphamap pixels [x0, x0 + w) x [z0, z0 + h): each hex's layer blended across
- /// edges (HexBoardSurface.GroundWeights), then the tiles' paints, each clipped to its own hex, then the roads.</summary>
- static float[,,] Splat(HexBoard board, HexBoardSurface surface, Rect rect, IEnumerable<(HexPaint paint, int q, int r)> paints, int x0, int z0, int w, int h)
+ /// edges (HexBoardSurface.GroundWeights), then the tiles' paints, each clipped to its own hex, then the roads.
+ /// Internal so the tests can compare PaintGround with it.</summary>
+ internal static float[,,] Splat(HexBoard board, HexBoardSurface surface, Rect rect, IEnumerable<(HexPaint paint, int q, int r)> paints, int x0, int z0, int w, int h)
{
var ids = HexGround.Ids;
var alpha = new float[h, w, ids.Count];
- var wt = new float[ids.Count];
+ SplatInto(alpha, new float[ids.Count], ids, surface, rect, paints.ToList(), RoadPaints(board), x0, z0);
+ return alpha;
+ }
+
+ /// <summary>Fills <paramref name="alpha"/> with the splat from alphamap pixel (<paramref name="x0"/>,
+ /// <paramref name="z0"/>), overwriting it all. <paramref name="wt"/> is scratch, one float per layer.</summary>
+ static void SplatInto(float[,,] alpha, float[] wt, IReadOnlyList<string> ids, HexBoardSurface surface, Rect rect,
+ IReadOnlyList<(HexPaint paint, int q, int r)> paints, IReadOnlyList<HexPaint> roads, int x0, int z0)
+ {
+ int h = alpha.GetLength(0), w = alpha.GetLength(1);
for (int z = 0; z < h; z++)
for (int x = 0; x < w; x++)
{
@@ -257,11 +288,22 @@ namespace Statecraft.HexTiles
for (int l = 0; l < ids.Count; l++) alpha[z, x, l] = wt[l];
}
// Paints, clipped to their own hex (a tile owns its ground), then roads, which run across hexes.
- foreach (var (paint, q, r) in paints) Paint(alpha, rect, ids, paint, HexGeometry.Centre(q, r, HexScale.HexM), surface, x0, z0);
+ for (int i = 0; i < paints.Count; i++)
+ {
+ var (paint, q, r) = paints[i];
+ Paint(alpha, rect, ids, paint, HexGeometry.Centre(q, r, HexScale.HexM), surface, x0, z0);
+ }
+ for (int i = 0; i < roads.Count; i++) Paint(alpha, rect, ids, roads[i], null, surface, x0, z0);
+ }
+
+ /// <summary>The board's roads as dirt line paints, one per road segment.</summary>
+ static List<HexPaint> RoadPaints(HexBoard board)
+ {
+ var roads = new List<HexPaint>();
foreach (var line in board.RoadLines())
for (int i = 0; i + 1 < line.Length; i++)
- Paint(alpha, rect, ids, new HexPaint("dirt", line[i], line[i + 1], RoadM, 0f, 0f, 0.5f, 1f, true), null, surface, x0, z0);
- return alpha;
+ roads.Add(new HexPaint("dirt", line[i], line[i + 1], RoadM, 0f, 0f, 0.5f, 1f, true));
+ return roads;
}
/// <summary>Recomputes the splat round <paramref name="centre"/>: the hex and as far as its ground blends into its
@@ -299,7 +341,7 @@ namespace Statecraft.HexTiles
float k;
if (p.Line)
{
- float d = HexBoardSurface.DistanceToLine(w, new[] { p.A, p.B });
+ float d = HexBoardSurface.DistanceToSegment(w, p.A, p.B);
k = Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(p.Width * 0.5f, p.Width * 0.5f * (1f - p.Soft), d));
}
else
diff --git a/unity/Assets/Scripts/Map/WheelInput.jslib b/unity/Assets/Scripts/Map/WheelInput.jslib
index 9fd8658b6..8af58cfdb 100644
--- a/unity/Assets/Scripts/Map/WheelInput.jslib
+++ b/unity/Assets/Scripts/Map/WheelInput.jslib
@@ -10,8 +10,8 @@
// It only reads (passive, no preventDefault) and ignores events whose target is not Unity's canvas.
//
// The listener is never removed: Unity's Quit() removes only the handlers Emscripten registered. This game creates
-// the player once, and the queue is capped, so nothing grows. The HEAPF32/HEAP32 indexing assumes wasm32 pointers
-// (Unity 6000.3's WebGL target).
+// the player once, and the queue is capped, so nothing grows. The HEAPF32/HEAP32 indexing assumes wasm32 pointers,
+// read unsigned (>>>) because the heap can grow past 2 GB (Unity 6000.3's WebGL target).
mergeInto(LibraryManager.library, {
$StatecraftWheel: { queue: [], listening: false },
@@ -29,8 +29,8 @@ mergeInto(LibraryManager.library, {
}
var n = Math.min(capacity, w.queue.length / 2);
for (var i = 0; i < n; i++) {
- HEAPF32[(deltaY >> 2) + i] = w.queue[2 * i];
- HEAP32[(mode >> 2) + i] = w.queue[2 * i + 1];
+ HEAPF32[(deltaY >>> 2) + i] = w.queue[2 * i];
+ HEAP32[(mode >>> 2) + i] = w.queue[2 * i + 1];
}
w.queue.splice(0, 2 * n);
return n;
diff --git a/unity/Assets/Scripts/UI/SafeArea.jslib b/unity/Assets/Scripts/UI/SafeArea.jslib
index 1a656b9ca..ae588d65c 100644
--- a/unity/Assets/Scripts/UI/SafeArea.jslib
+++ b/unity/Assets/Scripts/UI/SafeArea.jslib
@@ -1,7 +1,7 @@
// The browser's safe-area insets in CSS pixels (the notch, the home indicator), for SafeAreaFit: a probe element reads
// the env(safe-area-inset-*) values, which iOS Safari and Chrome on Android expose; everywhere else they are 0, so the
// UI is padded only where hardware eats the screen. Writes top, right, bottom, left. The HEAPF32 indexing assumes
-// wasm32 pointers (Unity 6000.3's WebGL target), as WheelInput.jslib.
+// wasm32 pointers read unsigned, as WheelInput.jslib (Unity 6000.3's WebGL target).
mergeInto(LibraryManager.library, {
StatecraftSafeAreaInsets: function (out) {
var v = [0, 0, 0, 0];
@@ -16,6 +16,6 @@ mergeInto(LibraryManager.library, {
parseFloat(cs.paddingBottom) || 0, parseFloat(cs.paddingLeft) || 0];
document.body.removeChild(probe);
}
- for (var i = 0; i < 4; i++) HEAPF32[(out >> 2) + i] = v[i];
+ for (var i = 0; i < 4; i++) HEAPF32[(out >>> 2) + i] = v[i];
},
});
diff --git a/unity/Assets/Scripts/UI/ShareShot.jslib b/unity/Assets/Scripts/UI/ShareShot.jslib
index dda4d764c..3dc08447e 100644
--- a/unity/Assets/Scripts/UI/ShareShot.jslib
+++ b/unity/Assets/Scripts/UI/ShareShot.jslib
@@ -91,6 +91,7 @@ mergeInto(LibraryManager.library, {
StatecraftShareKeep: function (pngPtr, length, namePtr) {
StatecraftInvalidateShareAttempt();
window.statecraftShareCopied = 0;
+ pngPtr >>>= 0; // unsigned: with a heap over 2 GB the pointer can be 2^31 or more
var bytes = HEAPU8.slice(pngPtr, pngPtr + length);
window.statecraftShareFile = new File([bytes], UTF8ToString(namePtr), { type: "image/png" });
},
diff --git a/unity/Assets/Tests/EditMode/HexGroundPaintTests.cs b/unity/Assets/Tests/EditMode/HexGroundPaintTests.cs
new file mode 100644
index 000000000..00214ab92
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/HexGroundPaintTests.cs
@@ -0,0 +1,113 @@
+#nullable enable
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using Statecraft.HexTiles;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+using UnityEngine.Profiling;
+using UnityEngine.TestTools.Constraints;
+using Is = UnityEngine.TestTools.Constraints.Is;
+using Object = UnityEngine.Object;
+
+/// <summary>The hex board's ground paint (the israel board's 2048 x 2048 x 11 alphamap) must not allocate the whole
+/// alphamap or garbage per pixel: in WebGL the GC runs only between frames and the heap never shrinks, so one build
+/// frame's garbage stays reserved for the rest of the game.</summary>
+public class HexGroundPaintTests
+{
+ const string IsraelBoard = "israel";
+ GameObject? root;
+ HexBoardState state = null!;
+ List<(HexPaint paint, int q, int r)> paints = null!;
+
+ [OneTimeSetUp]
+ public void BuildTheIsraelBoardPerHex()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ root = HexBoardBuilder.Build(HexBoard.Load(IsraelBoard), null, options: new HexBoardBuilder.Options { PerHex = true }).root;
+ state = root.GetComponent<HexBoardState>();
+ // Build's order: hexes by q then r, each tile's paints in its own order (as Repaint rebuilds them).
+ paints = state.Paints.OrderBy(kv => kv.Key.q).ThenBy(kv => kv.Key.r).SelectMany(kv => kv.Value.Select(p => (p, kv.Key.q, kv.Key.r))).ToList();
+ Assert.That(paints, Is.Not.Empty, "fixture: the israel board has tile paints");
+ Assert.That(state.Board.RoadLines(), Is.Not.Empty, "fixture: the israel board has roads");
+ }
+
+ [OneTimeTearDown]
+ public void Destroy() { if (root != null) Object.DestroyImmediate(root); }
+
+ [Test]
+ public void TheGroundIsBitIdenticalToTheOnePieceSplat()
+ {
+ var data = state.Terrain;
+ int n = data.alphamapResolution, layers = data.alphamapLayers, differing = 0;
+ Assert.That(n, Is.EqualTo(2048));
+ Assert.That(layers, Is.EqualTo(HexGround.Ids.Count));
+ // The reference goes through SetAlphamaps/GetAlphamaps too, so both sides carry the same storage rounding.
+ var reference = NewGround();
+ try
+ {
+ reference.SetAlphamaps(0, 0, HexBoardBuilder.Splat(state.Board, state.Surface, state.Rect, paints, 0, 0, n, n));
+ float maxSeen = 0f;
+ for (int z0 = 0; z0 < n; z0 += 128)
+ {
+ var band = data.GetAlphamaps(0, z0, n, 128);
+ var want = reference.GetAlphamaps(0, z0, n, 128);
+ for (int z = 0; z < 128; z++)
+ for (int x = 0; x < n; x++)
+ for (int l = 0; l < layers; l++)
+ {
+ if (band[z, x, l] != want[z, x, l]) differing++;
+ maxSeen = Mathf.Max(maxSeen, band[z, x, l]);
+ }
+ }
+ Assert.That(maxSeen, Is.GreaterThan(0.5f), "the alphamap was painted");
+ Assert.That(differing, Is.EqualTo(0), "alphamap values that differ from the one-piece splat");
+ }
+ finally { DestroyGround(reference); }
+ }
+
+ // As Build sets it up: the layers first, then the resolution.
+ static TerrainData NewGround()
+ {
+ var data = new TerrainData { terrainLayers = HexGround.Ids.Select(_ => new TerrainLayer()).ToArray() };
+ data.alphamapResolution = 2048;
+ return data;
+ }
+
+ static void DestroyGround(TerrainData data)
+ {
+ foreach (var l in data.terrainLayers) Object.DestroyImmediate(l);
+ Object.DestroyImmediate(data);
+ }
+
+ [Test]
+ public void PaintingTheGroundAllocatesNoWholeAlphamapAndNoGarbagePerPixel()
+ {
+ var data = NewGround();
+ try
+ {
+ void PaintOnce() => HexBoardBuilder.PaintGround(data, state.Board, state.Surface, state.Rect, paints);
+ PaintOnce(); // warm up: the first call JIT-compiles and allocates
+
+ System.GC.Collect();
+ long before = Profiler.GetMonoUsedSizeLong();
+ PaintOnce();
+ long grewMB = (Profiler.GetMonoUsedSizeLong() - before) >> 20;
+
+ Assert.That(() => new int[8], Is.AllocatingGCMemory(), "control: the recorder sees an allocation");
+ // Read as Unity's AllocatingGCMemory constraint reads it: this thread only, collected after the call.
+ var recorder = Recorder.Get("GC.Alloc");
+ recorder.enabled = false;
+ recorder.FilterToCurrentThread();
+ recorder.enabled = true;
+ PaintOnce();
+ recorder.enabled = false;
+ recorder.CollectFromAllThreads();
+ int allocations = recorder.sampleBlockCount;
+
+ Assert.That(grewMB, Is.LessThan(32), $"Mono heap grew {grewMB} MB (the whole alphamap alone is 184 MB)");
+ Assert.That(allocations, Is.LessThan(1000), $"{allocations} managed allocations in one ground paint");
+ }
+ finally { DestroyGround(data); }
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/HexGroundPaintTests.cs.meta b/unity/Assets/Tests/EditMode/HexGroundPaintTests.cs.meta
new file mode 100644
index 000000000..3b5f7ab01
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/HexGroundPaintTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8dd126475b944bc184400b7af9ee6bd6
diff --git a/unity/ProjectSettings/ProjectSettings.asset b/unity/ProjectSettings/ProjectSettings.asset
index 2991a7434..5b18a0a20 100644
--- a/unity/ProjectSettings/ProjectSettings.asset
+++ b/unity/ProjectSettings/ProjectSettings.asset
@@ -818,7 +818,7 @@ PlayerSettings:
webGLThreadsSupport: 0
webGLDecompressionFallback: 0
webGLInitialMemorySize: 32
- webGLMaximumMemorySize: 2048
+ webGLMaximumMemorySize: 4096
webGLMemoryGrowthMode: 2
webGLMemoryLinearGrowthStep: 16
webGLMemoryGeometricGrowthStep: 0.2