BlueGit

timfa questward

Merge branch 'cursor/editor-minimap-tile-colors-a898' into 'master'

Average tile colours and a dimension-aware editor minimap

See merge request Timfa/questward!5

timfa Tim Falken · pushed by timfa

Authored 2026-10-06 · 6 weeks ago

Hash
00e2f16ef76ea4a5f323eb9dee0aee4276594d3b
21 files changed +1437 −9
.gitignore +2 −0
@@ -7,6 +7,8 @@ server/data/
7 7 .DS_Store
8 8 Thumbs.db
9 9 client/frameworkv3/js/framework.js
10 client/assets/.tile-average-colors.json
11 client/assets/.tile-average-colors.json.tmp-*
10 12 client/public/framework.js
11 13 .env
12 14 .env.local
@@ -7,6 +7,8 @@ server/data/
7.DS_Store
7.DS_Store
8Thumbs.db
8Thumbs.db
9client/frameworkv3/js/framework.js
9client/frameworkv3/js/framework.js
10client/assets/.tile-average-colors.json
11client/assets/.tile-average-colors.json.tmp-*
10client/public/framework.js
12client/public/framework.js
11.env
13.env
12.env.local
14.env.local
client/editor.html +6 −1
@@ -19,7 +19,12 @@
19 19 <button id="editor-restart-now" type="button" hidden title="Graceful shutdown; systemd restarts the server">Restart now</button>
20 20 <a id="editor-to-play" class="editor-to-play" href="/">Play</a>
21 21 </header>
22 <aside>
22 <aside id="editor-tools">
23 <div id="editor-minimap-wrap">
24 <p class="editor-minimap-title">Minimap</p>
25 <canvas id="editor-minimap" width="400" height="400" aria-label="Minimap of nearby chunks. Click a chunk to centre the editor there."></canvas>
26 <p id="editor-minimap-caption" class="hint">Chunk 0, 0</p>
27 </div>
23 28 <p>Chunk <strong id="coords">0, 0</strong></p>
24 29 <p id="revision"></p>
25 30 <p id="authored"></p>
@@ -19,7 +19,12 @@
19 <button id="editor-restart-now" type="button" hidden title="Graceful shutdown; systemd restarts the server">Restart now</button>
19 <button id="editor-restart-now" type="button" hidden title="Graceful shutdown; systemd restarts the server">Restart now</button>
20 <a id="editor-to-play" class="editor-to-play" href="/">Play</a>
20 <a id="editor-to-play" class="editor-to-play" href="/">Play</a>
21 </header>
21 </header>
22 <aside>
22 <aside id="editor-tools">
23 <div id="editor-minimap-wrap">
24 <p class="editor-minimap-title">Minimap</p>
25 <canvas id="editor-minimap" width="400" height="400" aria-label="Minimap of nearby chunks. Click a chunk to centre the editor there."></canvas>
26 <p id="editor-minimap-caption" class="hint">Chunk 0, 0</p>
27 </div>
23 <p>Chunk <strong id="coords">0, 0</strong></p>
28 <p>Chunk <strong id="coords">0, 0</strong></p>
24 <p id="revision"></p>
29 <p id="revision"></p>
25 <p id="authored"></p>
30 <p id="authored"></p>
client/src/editor/main.js +41 −1
@@ -50,6 +50,7 @@ import { initQuestsModal } from "./questsModal.js";
50 50 import { initDialoguesModal } from "./dialoguesModal.js";
51 51 import { initGiftsModal } from "./giftsModal.js";
52 52 import { initDimensionPickerModal } from "./dimensionPickerModal.js";
53 import { initEditorMinimap } from "./minimap.js";
53 54 import
54 55 {
55 56 OVERWORLD_ID,
@@ -69,6 +70,8 @@ import
69 70 const game = new Game();
70 71 let socket;
71 72 let scene;
73 let editorMinimap = null;
74 let minimapRequestTimer = 0;
72 75 let view;
73 76 let draft = null;
74 77 /** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
@@ -1319,7 +1322,7 @@ function updateSelectionBorder ()
1319 1322 function layoutScene ()
1320 1323 {
1321 1324 const header = document.querySelector("body > header");
1322 const aside = document.querySelector("body > aside");
1325 const aside = $("editor-tools");
1323 1326 const sidePanels = $("side-panels") || $("changelog-wrap");
1324 1327 const top = header.offsetHeight;
1325 1328 aside.style.top = `${top}px`;
@@ -1393,6 +1396,26 @@ function doLoadNeighborhood (x, y)
1393 1396 chunkY = y;
1394 1397 $("coords").textContent = `${chunkX}, ${chunkY}`;
1395 1398 requestChunks(neighborhoodCoords(x, y));
1399 requestEditorMinimap();
1400 }
1401
1402 function requestEditorMinimap ()
1403 {
1404 editorMinimap?.setCenter();
1405 if (minimapRequestTimer)
1406 { return; }
1407 minimapRequestTimer = setTimeout(() =>
1408 {
1409 minimapRequestTimer = 0;
1410 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
1411 { return; }
1412 socket.send({
1413 type: MessageType.editorRequestMinimap,
1414 chunkX,
1415 chunkY,
1416 dimensionId: selectedDimensionId
1417 });
1418 }, 40);
1396 1419 }
1397 1420
1398 1421 function loadNeighborhood (x, y)
@@ -1518,6 +1541,19 @@ function updateTooltip (local, options = {})
1518 1541
1519 1542 async function main ()
1520 1543 {
1544 editorMinimap = initEditorMinimap({
1545 canvas: $("editor-minimap"),
1546 caption: $("editor-minimap-caption"),
1547 getCenter ()
1548 {
1549 return { chunkX, chunkY, dimensionId: selectedDimensionId };
1550 },
1551 onChunkClick (x, y)
1552 {
1553 loadNeighborhood(x, y);
1554 }
1555 });
1556
1521 1557 const authStatus = await fetchAuthStatus();
1522 1558 const signIn = document.getElementById("auth-sign-in");
1523 1559 const signOut = document.getElementById("auth-sign-out");
@@ -1870,6 +1906,8 @@ async function main ()
1870 1906 { giftsModal?.handleMessage(message); }
1871 1907 else if (message.type === MessageType.editorGlobalChangelog)
1872 1908 { renderGlobalChangelog(message.changelog ?? []); }
1909 else if (message.type === MessageType.editorMinimap)
1910 { editorMinimap?.apply(message); }
1873 1911 else if (message.type === MessageType.editorChunk)
1874 1912 {
1875 1913 const msgDim = normalizeDimensionId(message.dimensionId ?? selectedDimensionId);
@@ -1878,6 +1916,8 @@ async function main ()
1878 1916 const isSaveAck = pendingSaveAcks.delete(
1879 1917 editorChunkSaveKey(msgDim, message.chunkX, message.chunkY)
1880 1918 );
1919 if (isSaveAck)
1920 { requestEditorMinimap(); }
1881 1921 if (message.settings)
1882 1922 { view.setSettings(message.settings); }
1883 1923 if (!inEditorView(message.chunkX, message.chunkY))
@@ -50,6 +50,7 @@ import { initQuestsModal } from "./questsModal.js";
50import { initDialoguesModal } from "./dialoguesModal.js";
50import { initDialoguesModal } from "./dialoguesModal.js";
51import { initGiftsModal } from "./giftsModal.js";
51import { initGiftsModal } from "./giftsModal.js";
52import { initDimensionPickerModal } from "./dimensionPickerModal.js";
52import { initDimensionPickerModal } from "./dimensionPickerModal.js";
53import { initEditorMinimap } from "./minimap.js";
53import
54import
54{
55{
55 OVERWORLD_ID,
56 OVERWORLD_ID,
@@ -69,6 +70,8 @@ import
69const game = new Game();
70const game = new Game();
70let socket;
71let socket;
71let scene;
72let scene;
73let editorMinimap = null;
74let minimapRequestTimer = 0;
72let view;
75let view;
73let draft = null;
76let draft = null;
74/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
77/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
@@ -1319,7 +1322,7 @@ function updateSelectionBorder ()
1319function layoutScene ()
1322function layoutScene ()
1320{
1323{
1321 const header = document.querySelector("body > header");
1324 const header = document.querySelector("body > header");
1322 const aside = document.querySelector("body > aside");
1325 const aside = $("editor-tools");
1323 const sidePanels = $("side-panels") || $("changelog-wrap");
1326 const sidePanels = $("side-panels") || $("changelog-wrap");
1324 const top = header.offsetHeight;
1327 const top = header.offsetHeight;
1325 aside.style.top = `${top}px`;
1328 aside.style.top = `${top}px`;
@@ -1393,6 +1396,26 @@ function doLoadNeighborhood (x, y)
1393 chunkY = y;
1396 chunkY = y;
1394 $("coords").textContent = `${chunkX}, ${chunkY}`;
1397 $("coords").textContent = `${chunkX}, ${chunkY}`;
1395 requestChunks(neighborhoodCoords(x, y));
1398 requestChunks(neighborhoodCoords(x, y));
1399 requestEditorMinimap();
1400}
1401
1402function requestEditorMinimap ()
1403{
1404 editorMinimap?.setCenter();
1405 if (minimapRequestTimer)
1406 { return; }
1407 minimapRequestTimer = setTimeout(() =>
1408 {
1409 minimapRequestTimer = 0;
1410 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
1411 { return; }
1412 socket.send({
1413 type: MessageType.editorRequestMinimap,
1414 chunkX,
1415 chunkY,
1416 dimensionId: selectedDimensionId
1417 });
1418 }, 40);
1396}
1419}
1397
1420
1398function loadNeighborhood (x, y)
1421function loadNeighborhood (x, y)
@@ -1518,6 +1541,19 @@ function updateTooltip (local, options = {})
1518
1541
1519async function main ()
1542async function main ()
1520{
1543{
1544 editorMinimap = initEditorMinimap({
1545 canvas: $("editor-minimap"),
1546 caption: $("editor-minimap-caption"),
1547 getCenter ()
1548 {
1549 return { chunkX, chunkY, dimensionId: selectedDimensionId };
1550 },
1551 onChunkClick (x, y)
1552 {
1553 loadNeighborhood(x, y);
1554 }
1555 });
1556
1521 const authStatus = await fetchAuthStatus();
1557 const authStatus = await fetchAuthStatus();
1522 const signIn = document.getElementById("auth-sign-in");
1558 const signIn = document.getElementById("auth-sign-in");
1523 const signOut = document.getElementById("auth-sign-out");
1559 const signOut = document.getElementById("auth-sign-out");
@@ -1870,6 +1906,8 @@ async function main ()
1870 { giftsModal?.handleMessage(message); }
1906 { giftsModal?.handleMessage(message); }
1871 else if (message.type === MessageType.editorGlobalChangelog)
1907 else if (message.type === MessageType.editorGlobalChangelog)
1872 { renderGlobalChangelog(message.changelog ?? []); }
1908 { renderGlobalChangelog(message.changelog ?? []); }
1909 else if (message.type === MessageType.editorMinimap)
1910 { editorMinimap?.apply(message); }
1873 else if (message.type === MessageType.editorChunk)
1911 else if (message.type === MessageType.editorChunk)
1874 {
1912 {
1875 const msgDim = normalizeDimensionId(message.dimensionId ?? selectedDimensionId);
1913 const msgDim = normalizeDimensionId(message.dimensionId ?? selectedDimensionId);
@@ -1878,6 +1916,8 @@ async function main ()
1878 const isSaveAck = pendingSaveAcks.delete(
1916 const isSaveAck = pendingSaveAcks.delete(
1879 editorChunkSaveKey(msgDim, message.chunkX, message.chunkY)
1917 editorChunkSaveKey(msgDim, message.chunkX, message.chunkY)
1880 );
1918 );
1919 if (isSaveAck)
1920 { requestEditorMinimap(); }
1881 if (message.settings)
1921 if (message.settings)
1882 { view.setSettings(message.settings); }
1922 { view.setSettings(message.settings); }
1883 if (!inEditorView(message.chunkX, message.chunkY))
1923 if (!inEditorView(message.chunkX, message.chunkY))
client/src/editor/minimap.js added +203 −0
@@ -0,0 +1,203 @@
1 import { STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2 import { normalizeDimensionId } from "/shared/world/dimensions.js";
3 import
4 {
5 MINIMAP_CHUNK_PIXELS,
6 MINIMAP_EMPTY_COLOR,
7 MINIMAP_SPAN_CHUNKS,
8 minimapChunkAtPixel,
9 minimapRadius
10 } from "/shared/render/chunkMinimap.js";
11
12 const VIEWPORT_STROKE = "#d5dbe6";
13 const CURRENT_STROKE = "#e23d3d";
14
15 /**
16 * Editor minimap. Chunk images are cached in memory after the server sends them
17 * and redrawn locally. The durable cache is the server's per-dimension RGBA files.
18 */
19 export function initEditorMinimap ({ canvas, caption, getCenter, onChunkClick })
20 {
21 const context = canvas.getContext("2d", { alpha: false });
22 const radius = minimapRadius(MINIMAP_SPAN_CHUNKS);
23 const size = MINIMAP_SPAN_CHUNKS * MINIMAP_CHUNK_PIXELS;
24 canvas.width = size;
25 canvas.height = size;
26 /** @type {Map<string, Uint8ClampedArray>} */
27 const images = new Map();
28
29 function cacheKey (dimensionId, chunkX, chunkY)
30 {
31 return `${normalizeDimensionId(dimensionId)}:${chunkX | 0},${chunkY | 0}`;
32 }
33
34 function captionFor (chunkX, chunkY, hovering)
35 {
36 if (!caption)
37 { return; }
38 const where = `Chunk ${chunkX}, ${chunkY}`;
39 caption.textContent = hovering ? where : `${where} · click to centre`;
40 }
41
42 function draw ()
43 {
44 const center = getCenter();
45 const dimensionId = normalizeDimensionId(center.dimensionId);
46 const image = context.createImageData(size, size);
47 const empty = MINIMAP_EMPTY_COLOR;
48 for (let i = 0; i < image.data.length; i += 4)
49 {
50 image.data[i] = empty.r;
51 image.data[i + 1] = empty.g;
52 image.data[i + 2] = empty.b;
53 image.data[i + 3] = 255;
54 }
55 for (let dy = -radius; dy <= radius; dy++)
56 {
57 for (let dx = -radius; dx <= radius; dx++)
58 {
59 const chunkX = (center.chunkX | 0) + dx;
60 const chunkY = (center.chunkY | 0) + dy;
61 const pixels = images.get(cacheKey(dimensionId, chunkX, chunkY));
62 if (!pixels || pixels.length !== MINIMAP_CHUNK_PIXELS * MINIMAP_CHUNK_PIXELS * 4)
63 { continue; }
64 blit(image.data, size, pixels, (dx + radius) * MINIMAP_CHUNK_PIXELS, (dy + radius) * MINIMAP_CHUNK_PIXELS);
65 }
66 }
67 context.putImageData(image, 0, 0);
68 strokeViewport();
69 strokeCurrentChunk();
70 captionFor(center.chunkX | 0, center.chunkY | 0, false);
71 }
72
73 function strokeViewport ()
74 {
75 const view = Math.max(0, STATIC_CHUNK_RADIUS | 0);
76 const origin = (radius - view) * MINIMAP_CHUNK_PIXELS;
77 const extent = (view * 2 + 1) * MINIMAP_CHUNK_PIXELS;
78 context.strokeStyle = VIEWPORT_STROKE;
79 context.lineWidth = 1;
80 context.strokeRect(origin + 0.5, origin + 0.5, extent - 1, extent - 1);
81 }
82
83 function strokeCurrentChunk ()
84 {
85 const origin = radius * MINIMAP_CHUNK_PIXELS;
86 context.strokeStyle = CURRENT_STROKE;
87 context.lineWidth = 2;
88 context.strokeRect(origin + 1, origin + 1, MINIMAP_CHUNK_PIXELS - 2, MINIMAP_CHUNK_PIXELS - 2);
89 }
90
91 function eventPixel (event)
92 {
93 const rect = canvas.getBoundingClientRect();
94 if (rect.width <= 0 || rect.height <= 0)
95 { return null; }
96 return {
97 x: (event.clientX - rect.left) * (canvas.width / rect.width),
98 y: (event.clientY - rect.top) * (canvas.height / rect.height)
99 };
100 }
101
102 function chunkAtEvent (event)
103 {
104 const pixel = eventPixel(event);
105 if (!pixel)
106 { return null; }
107 const center = getCenter();
108 return minimapChunkAtPixel(pixel.x, pixel.y, center.chunkX, center.chunkY);
109 }
110
111 canvas.addEventListener("click", (event) =>
112 {
113 const hit = chunkAtEvent(event);
114 if (!hit)
115 { return; }
116 onChunkClick(hit.chunkX, hit.chunkY);
117 });
118 canvas.addEventListener("mousemove", (event) =>
119 {
120 const hit = chunkAtEvent(event);
121 if (!hit)
122 { return; }
123 captionFor(hit.chunkX, hit.chunkY, true);
124 });
125 canvas.addEventListener("mouseleave", () =>
126 {
127 const center = getCenter();
128 captionFor(center.chunkX | 0, center.chunkY | 0, false);
129 });
130
131 draw();
132
133 return {
134 setCenter ()
135 {
136 draw();
137 },
138 apply (message)
139 {
140 const center = getCenter();
141 const dimensionId = normalizeDimensionId(message?.dimensionId);
142 if (dimensionId !== normalizeDimensionId(center.dimensionId))
143 { return; }
144 if ((message.chunkX | 0) !== (center.chunkX | 0) || (message.chunkY | 0) !== (center.chunkY | 0))
145 { return; }
146 const present = new Set();
147 for (const [key, encoded] of Object.entries(message.chunks ?? {}))
148 {
149 const pixels = rgbaFromBase64(encoded);
150 if (!pixels)
151 { continue; }
152 const [x, y] = key.split(",");
153 const chunkX = Number(x);
154 const chunkY = Number(y);
155 if (!Number.isInteger(chunkX) || !Number.isInteger(chunkY))
156 { continue; }
157 images.set(cacheKey(dimensionId, chunkX, chunkY), pixels);
158 present.add(`${chunkX},${chunkY}`);
159 }
160 for (let dy = -radius; dy <= radius; dy++)
161 {
162 for (let dx = -radius; dx <= radius; dx++)
163 {
164 const chunkX = (message.chunkX | 0) + dx;
165 const chunkY = (message.chunkY | 0) + dy;
166 const key = `${chunkX},${chunkY}`;
167 if (!present.has(key))
168 { images.delete(cacheKey(dimensionId, chunkX, chunkY)); }
169 }
170 }
171 draw();
172 }
173 };
174 }
175
176 function blit (dest, destWidth, src, destX, destY)
177 {
178 const span = MINIMAP_CHUNK_PIXELS;
179 for (let row = 0; row < span; row++)
180 {
181 const srcStart = row * span * 4;
182 const destStart = ((destY + row) * destWidth + destX) * 4;
183 dest.set(src.subarray(srcStart, srcStart + span * 4), destStart);
184 }
185 }
186
187 function rgbaFromBase64 (encoded)
188 {
189 if (typeof encoded !== "string" || !encoded)
190 { return null; }
191 let binary;
192 try
193 { binary = atob(encoded); }
194 catch
195 { return null; }
196 const expected = MINIMAP_CHUNK_PIXELS * MINIMAP_CHUNK_PIXELS * 4;
197 if (binary.length !== expected)
198 { return null; }
199 const out = new Uint8ClampedArray(expected);
200 for (let i = 0; i < expected; i++)
201 { out[i] = binary.charCodeAt(i); }
202 return out;
203 }
@@ -0,0 +1,203 @@
1import { STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { normalizeDimensionId } from "/shared/world/dimensions.js";
3import
4{
5 MINIMAP_CHUNK_PIXELS,
6 MINIMAP_EMPTY_COLOR,
7 MINIMAP_SPAN_CHUNKS,
8 minimapChunkAtPixel,
9 minimapRadius
10} from "/shared/render/chunkMinimap.js";
11
12const VIEWPORT_STROKE = "#d5dbe6";
13const CURRENT_STROKE = "#e23d3d";
14
15/**
16 * Editor minimap. Chunk images are cached in memory after the server sends them
17 * and redrawn locally. The durable cache is the server's per-dimension RGBA files.
18 */
19export function initEditorMinimap ({ canvas, caption, getCenter, onChunkClick })
20{
21 const context = canvas.getContext("2d", { alpha: false });
22 const radius = minimapRadius(MINIMAP_SPAN_CHUNKS);
23 const size = MINIMAP_SPAN_CHUNKS * MINIMAP_CHUNK_PIXELS;
24 canvas.width = size;
25 canvas.height = size;
26 /** @type {Map<string, Uint8ClampedArray>} */
27 const images = new Map();
28
29 function cacheKey (dimensionId, chunkX, chunkY)
30 {
31 return `${normalizeDimensionId(dimensionId)}:${chunkX | 0},${chunkY | 0}`;
32 }
33
34 function captionFor (chunkX, chunkY, hovering)
35 {
36 if (!caption)
37 { return; }
38 const where = `Chunk ${chunkX}, ${chunkY}`;
39 caption.textContent = hovering ? where : `${where} · click to centre`;
40 }
41
42 function draw ()
43 {
44 const center = getCenter();
45 const dimensionId = normalizeDimensionId(center.dimensionId);
46 const image = context.createImageData(size, size);
47 const empty = MINIMAP_EMPTY_COLOR;
48 for (let i = 0; i < image.data.length; i += 4)
49 {
50 image.data[i] = empty.r;
51 image.data[i + 1] = empty.g;
52 image.data[i + 2] = empty.b;
53 image.data[i + 3] = 255;
54 }
55 for (let dy = -radius; dy <= radius; dy++)
56 {
57 for (let dx = -radius; dx <= radius; dx++)
58 {
59 const chunkX = (center.chunkX | 0) + dx;
60 const chunkY = (center.chunkY | 0) + dy;
61 const pixels = images.get(cacheKey(dimensionId, chunkX, chunkY));
62 if (!pixels || pixels.length !== MINIMAP_CHUNK_PIXELS * MINIMAP_CHUNK_PIXELS * 4)
63 { continue; }
64 blit(image.data, size, pixels, (dx + radius) * MINIMAP_CHUNK_PIXELS, (dy + radius) * MINIMAP_CHUNK_PIXELS);
65 }
66 }
67 context.putImageData(image, 0, 0);
68 strokeViewport();
69 strokeCurrentChunk();
70 captionFor(center.chunkX | 0, center.chunkY | 0, false);
71 }
72
73 function strokeViewport ()
74 {
75 const view = Math.max(0, STATIC_CHUNK_RADIUS | 0);
76 const origin = (radius - view) * MINIMAP_CHUNK_PIXELS;
77 const extent = (view * 2 + 1) * MINIMAP_CHUNK_PIXELS;
78 context.strokeStyle = VIEWPORT_STROKE;
79 context.lineWidth = 1;
80 context.strokeRect(origin + 0.5, origin + 0.5, extent - 1, extent - 1);
81 }
82
83 function strokeCurrentChunk ()
84 {
85 const origin = radius * MINIMAP_CHUNK_PIXELS;
86 context.strokeStyle = CURRENT_STROKE;
87 context.lineWidth = 2;
88 context.strokeRect(origin + 1, origin + 1, MINIMAP_CHUNK_PIXELS - 2, MINIMAP_CHUNK_PIXELS - 2);
89 }
90
91 function eventPixel (event)
92 {
93 const rect = canvas.getBoundingClientRect();
94 if (rect.width <= 0 || rect.height <= 0)
95 { return null; }
96 return {
97 x: (event.clientX - rect.left) * (canvas.width / rect.width),
98 y: (event.clientY - rect.top) * (canvas.height / rect.height)
99 };
100 }
101
102 function chunkAtEvent (event)
103 {
104 const pixel = eventPixel(event);
105 if (!pixel)
106 { return null; }
107 const center = getCenter();
108 return minimapChunkAtPixel(pixel.x, pixel.y, center.chunkX, center.chunkY);
109 }
110
111 canvas.addEventListener("click", (event) =>
112 {
113 const hit = chunkAtEvent(event);
114 if (!hit)
115 { return; }
116 onChunkClick(hit.chunkX, hit.chunkY);
117 });
118 canvas.addEventListener("mousemove", (event) =>
119 {
120 const hit = chunkAtEvent(event);
121 if (!hit)
122 { return; }
123 captionFor(hit.chunkX, hit.chunkY, true);
124 });
125 canvas.addEventListener("mouseleave", () =>
126 {
127 const center = getCenter();
128 captionFor(center.chunkX | 0, center.chunkY | 0, false);
129 });
130
131 draw();
132
133 return {
134 setCenter ()
135 {
136 draw();
137 },
138 apply (message)
139 {
140 const center = getCenter();
141 const dimensionId = normalizeDimensionId(message?.dimensionId);
142 if (dimensionId !== normalizeDimensionId(center.dimensionId))
143 { return; }
144 if ((message.chunkX | 0) !== (center.chunkX | 0) || (message.chunkY | 0) !== (center.chunkY | 0))
145 { return; }
146 const present = new Set();
147 for (const [key, encoded] of Object.entries(message.chunks ?? {}))
148 {
149 const pixels = rgbaFromBase64(encoded);
150 if (!pixels)
151 { continue; }
152 const [x, y] = key.split(",");
153 const chunkX = Number(x);
154 const chunkY = Number(y);
155 if (!Number.isInteger(chunkX) || !Number.isInteger(chunkY))
156 { continue; }
157 images.set(cacheKey(dimensionId, chunkX, chunkY), pixels);
158 present.add(`${chunkX},${chunkY}`);
159 }
160 for (let dy = -radius; dy <= radius; dy++)
161 {
162 for (let dx = -radius; dx <= radius; dx++)
163 {
164 const chunkX = (message.chunkX | 0) + dx;
165 const chunkY = (message.chunkY | 0) + dy;
166 const key = `${chunkX},${chunkY}`;
167 if (!present.has(key))
168 { images.delete(cacheKey(dimensionId, chunkX, chunkY)); }
169 }
170 }
171 draw();
172 }
173 };
174}
175
176function blit (dest, destWidth, src, destX, destY)
177{
178 const span = MINIMAP_CHUNK_PIXELS;
179 for (let row = 0; row < span; row++)
180 {
181 const srcStart = row * span * 4;
182 const destStart = ((destY + row) * destWidth + destX) * 4;
183 dest.set(src.subarray(srcStart, srcStart + span * 4), destStart);
184 }
185}
186
187function rgbaFromBase64 (encoded)
188{
189 if (typeof encoded !== "string" || !encoded)
190 { return null; }
191 let binary;
192 try
193 { binary = atob(encoded); }
194 catch
195 { return null; }
196 const expected = MINIMAP_CHUNK_PIXELS * MINIMAP_CHUNK_PIXELS * 4;
197 if (binary.length !== expected)
198 { return null; }
199 const out = new Uint8ClampedArray(expected);
200 for (let i = 0; i < expected; i++)
201 { out[i] = binary.charCodeAt(i); }
202 return out;
203}
client/src/render/sprites.js +4 −1
@@ -1,5 +1,6 @@
1 1 import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2 2 import { applyMagentaTintToImageData } from "/shared/render/tint.js";
3 import { installTileAverageColors } from "/shared/render/tileAverageColors.js";
3 4
4 5 export const UTILITY_IMAGES = [
5 6 { name: "night-shade", url: shadeDataUrl("#000000") },
@@ -22,7 +23,9 @@ export async function loadSpriteCatalog ()
22 23 const response = await fetch("/assets/catalog.json");
23 24 if (!response.ok)
24 25 { throw new Error("Failed to load sprite catalog."); }
25 return response.json();
26 const catalog = await response.json();
27 installTileAverageColors(catalog);
28 return catalog;
26 29 }
27 30
28 31 /**
@@ -1,5 +1,6 @@
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { applyMagentaTintToImageData } from "/shared/render/tint.js";
2import { applyMagentaTintToImageData } from "/shared/render/tint.js";
3import { installTileAverageColors } from "/shared/render/tileAverageColors.js";
3
4
4export const UTILITY_IMAGES = [
5export const UTILITY_IMAGES = [
5 { name: "night-shade", url: shadeDataUrl("#000000") },
6 { name: "night-shade", url: shadeDataUrl("#000000") },
@@ -22,7 +23,9 @@ export async function loadSpriteCatalog ()
22 const response = await fetch("/assets/catalog.json");
23 const response = await fetch("/assets/catalog.json");
23 if (!response.ok)
24 if (!response.ok)
24 { throw new Error("Failed to load sprite catalog."); }
25 { throw new Error("Failed to load sprite catalog."); }
25 return response.json();
26 const catalog = await response.json();
27 installTileAverageColors(catalog);
28 return catalog;
26}
29}
27
30
28/**
31/**
client/ui/editor.css +36 −3
@@ -73,19 +73,52 @@ body>header {
73 73 display: none !important;
74 74 }
75 75
76 body>aside {
76 #editor-tools {
77 77 position: absolute;
78 78 left: 0;
79 79 top: 56px;
80 width: 250px;
80 width: 424px;
81 81 bottom: 0;
82 82 overflow: auto;
83 padding: 0.75rem;
83 padding: 0 0.75rem 0.75rem;
84 84 box-sizing: border-box;
85 85 background: #1a1e26;
86 86 border-right: 1px solid #2c3340;
87 87 }
88 88
89 #editor-minimap-wrap {
90 position: sticky;
91 top: 0;
92 z-index: 2;
93 margin: 0 -0.75rem 0.75rem;
94 padding: 0.55rem 0.75rem 0.4rem;
95 background: #1a1e26;
96 border-bottom: 1px solid #2c3340;
97 }
98
99 .editor-minimap-title {
100 margin: 0 0 0.35rem;
101 font-size: 0.78rem;
102 letter-spacing: 0.04em;
103 text-transform: uppercase;
104 color: #9aa3b2;
105 }
106
107 #editor-minimap {
108 display: block;
109 width: 100%;
110 height: auto;
111 aspect-ratio: 1;
112 cursor: pointer;
113 background: #1a1e26;
114 image-rendering: pixelated;
115 image-rendering: crisp-edges;
116 }
117
118 #editor-minimap-caption {
119 margin: 0.35rem 0 0;
120 }
121
89 122 #side-panels {
90 123 position: absolute;
91 124 right: 0;
@@ -73,19 +73,52 @@ body>header {
73 display: none !important;
73 display: none !important;
74}
74}
75
75
76body>aside {
76#editor-tools {
77 position: absolute;
77 position: absolute;
78 left: 0;
78 left: 0;
79 top: 56px;
79 top: 56px;
80 width: 250px;
80 width: 424px;
81 bottom: 0;
81 bottom: 0;
82 overflow: auto;
82 overflow: auto;
83 padding: 0.75rem;
83 padding: 0 0.75rem 0.75rem;
84 box-sizing: border-box;
84 box-sizing: border-box;
85 background: #1a1e26;
85 background: #1a1e26;
86 border-right: 1px solid #2c3340;
86 border-right: 1px solid #2c3340;
87}
87}
88
88
89#editor-minimap-wrap {
90 position: sticky;
91 top: 0;
92 z-index: 2;
93 margin: 0 -0.75rem 0.75rem;
94 padding: 0.55rem 0.75rem 0.4rem;
95 background: #1a1e26;
96 border-bottom: 1px solid #2c3340;
97}
98
99.editor-minimap-title {
100 margin: 0 0 0.35rem;
101 font-size: 0.78rem;
102 letter-spacing: 0.04em;
103 text-transform: uppercase;
104 color: #9aa3b2;
105}
106
107#editor-minimap {
108 display: block;
109 width: 100%;
110 height: auto;
111 aspect-ratio: 1;
112 cursor: pointer;
113 background: #1a1e26;
114 image-rendering: pixelated;
115 image-rendering: crisp-edges;
116}
117
118#editor-minimap-caption {
119 margin: 0.35rem 0 0;
120}
121
89#side-panels {
122#side-panels {
90 position: absolute;
123 position: absolute;
91 right: 0;
124 right: 0;
server/src/assets/pngRgba.js added +115 −0
@@ -0,0 +1,115 @@
1 import { inflateSync } from "node:zlib";
2
3 const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
4
5 /**
6 * Decode an 8-bit RGB or RGBA PNG (no interlacing) into straight RGBA.
7 * @param {Buffer} buffer
8 * @param {string} [label]
9 * @returns {{ width: number, height: number, rgba: Uint8ClampedArray }}
10 */
11 export function decodePngRgba (buffer, label = "png")
12 {
13 if (!Buffer.isBuffer(buffer) || buffer.length < 8 || !buffer.subarray(0, 8).equals(PNG_SIGNATURE))
14 { throw new Error(`${label}: not a PNG`); }
15
16 let offset = 8;
17 let width = 0;
18 let height = 0;
19 let colorType = -1;
20 const idat = [];
21 while (offset + 8 <= buffer.length)
22 {
23 const length = buffer.readUInt32BE(offset);
24 const type = buffer.toString("ascii", offset + 4, offset + 8);
25 const dataStart = offset + 8;
26 const dataEnd = dataStart + length;
27 if (dataEnd + 4 > buffer.length)
28 { throw new Error(`${label}: truncated PNG chunk`); }
29 const data = buffer.subarray(dataStart, dataEnd);
30 if (type === "IHDR")
31 {
32 width = data.readUInt32BE(0);
33 height = data.readUInt32BE(4);
34 const bitDepth = data[8];
35 colorType = data[9];
36 const interlace = data[12];
37 if (bitDepth !== 8 || (colorType !== 2 && colorType !== 6) || interlace !== 0)
38 {
39 throw new Error(
40 `${label}: expected 8-bit RGB or RGBA without interlacing (bit ${bitDepth}, color ${colorType}, interlace ${interlace})`
41 );
42 }
43 }
44 else if (type === "IDAT")
45 { idat.push(data); }
46 else if (type === "IEND")
47 { break; }
48 offset = dataEnd + 4;
49 }
50 if (width <= 0 || height <= 0 || colorType < 0)
51 { throw new Error(`${label}: missing IHDR`); }
52 if (idat.length === 0)
53 { throw new Error(`${label}: missing IDAT`); }
54
55 const raw = inflateSync(Buffer.concat(idat));
56 const channels = colorType === 6 ? 4 : 3;
57 const stride = width * channels;
58 const expected = (stride + 1) * height;
59 if (raw.length < expected)
60 { throw new Error(`${label}: inflated PNG is short (${raw.length} < ${expected})`); }
61
62 const decoded = Buffer.allocUnsafe(stride * height);
63 const previous = Buffer.alloc(stride);
64 const current = Buffer.alloc(stride);
65 let source = 0;
66 for (let y = 0; y < height; y++)
67 {
68 const filter = raw[source++];
69 raw.copy(current, 0, source, source + stride);
70 source += stride;
71 for (let i = 0; i < stride; i++)
72 {
73 const left = i >= channels ? current[i - channels] : 0;
74 const up = previous[i];
75 const upLeft = i >= channels ? previous[i - channels] : 0;
76 let value = current[i];
77 if (filter === 1)
78 { value = (value + left) & 255; }
79 else if (filter === 2)
80 { value = (value + up) & 255; }
81 else if (filter === 3)
82 { value = (value + ((left + up) >> 1)) & 255; }
83 else if (filter === 4)
84 {
85 const estimate = left + up - upLeft;
86 const pa = Math.abs(estimate - left);
87 const pb = Math.abs(estimate - up);
88 const pc = Math.abs(estimate - upLeft);
89 const predictor = (pa <= pb && pa <= pc) ? left : (pb <= pc ? up : upLeft);
90 value = (value + predictor) & 255;
91 }
92 else if (filter !== 0)
93 { throw new Error(`${label}: unsupported PNG filter ${filter}`); }
94 current[i] = value;
95 }
96 current.copy(decoded, y * stride);
97 current.copy(previous);
98 }
99
100 const rgba = new Uint8ClampedArray(width * height * 4);
101 if (channels === 4)
102 { rgba.set(decoded); }
103 else
104 {
105 for (let i = 0, out = 0; i < width * height; i++)
106 {
107 const sourceOffset = i * 3;
108 rgba[out++] = decoded[sourceOffset];
109 rgba[out++] = decoded[sourceOffset + 1];
110 rgba[out++] = decoded[sourceOffset + 2];
111 rgba[out++] = 255;
112 }
113 }
114 return { width, height, rgba };
115 }
@@ -0,0 +1,115 @@
1import { inflateSync } from "node:zlib";
2
3const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
4
5/**
6 * Decode an 8-bit RGB or RGBA PNG (no interlacing) into straight RGBA.
7 * @param {Buffer} buffer
8 * @param {string} [label]
9 * @returns {{ width: number, height: number, rgba: Uint8ClampedArray }}
10 */
11export function decodePngRgba (buffer, label = "png")
12{
13 if (!Buffer.isBuffer(buffer) || buffer.length < 8 || !buffer.subarray(0, 8).equals(PNG_SIGNATURE))
14 { throw new Error(`${label}: not a PNG`); }
15
16 let offset = 8;
17 let width = 0;
18 let height = 0;
19 let colorType = -1;
20 const idat = [];
21 while (offset + 8 <= buffer.length)
22 {
23 const length = buffer.readUInt32BE(offset);
24 const type = buffer.toString("ascii", offset + 4, offset + 8);
25 const dataStart = offset + 8;
26 const dataEnd = dataStart + length;
27 if (dataEnd + 4 > buffer.length)
28 { throw new Error(`${label}: truncated PNG chunk`); }
29 const data = buffer.subarray(dataStart, dataEnd);
30 if (type === "IHDR")
31 {
32 width = data.readUInt32BE(0);
33 height = data.readUInt32BE(4);
34 const bitDepth = data[8];
35 colorType = data[9];
36 const interlace = data[12];
37 if (bitDepth !== 8 || (colorType !== 2 && colorType !== 6) || interlace !== 0)
38 {
39 throw new Error(
40 `${label}: expected 8-bit RGB or RGBA without interlacing (bit ${bitDepth}, color ${colorType}, interlace ${interlace})`
41 );
42 }
43 }
44 else if (type === "IDAT")
45 { idat.push(data); }
46 else if (type === "IEND")
47 { break; }
48 offset = dataEnd + 4;
49 }
50 if (width <= 0 || height <= 0 || colorType < 0)
51 { throw new Error(`${label}: missing IHDR`); }
52 if (idat.length === 0)
53 { throw new Error(`${label}: missing IDAT`); }
54
55 const raw = inflateSync(Buffer.concat(idat));
56 const channels = colorType === 6 ? 4 : 3;
57 const stride = width * channels;
58 const expected = (stride + 1) * height;
59 if (raw.length < expected)
60 { throw new Error(`${label}: inflated PNG is short (${raw.length} < ${expected})`); }
61
62 const decoded = Buffer.allocUnsafe(stride * height);
63 const previous = Buffer.alloc(stride);
64 const current = Buffer.alloc(stride);
65 let source = 0;
66 for (let y = 0; y < height; y++)
67 {
68 const filter = raw[source++];
69 raw.copy(current, 0, source, source + stride);
70 source += stride;
71 for (let i = 0; i < stride; i++)
72 {
73 const left = i >= channels ? current[i - channels] : 0;
74 const up = previous[i];
75 const upLeft = i >= channels ? previous[i - channels] : 0;
76 let value = current[i];
77 if (filter === 1)
78 { value = (value + left) & 255; }
79 else if (filter === 2)
80 { value = (value + up) & 255; }
81 else if (filter === 3)
82 { value = (value + ((left + up) >> 1)) & 255; }
83 else if (filter === 4)
84 {
85 const estimate = left + up - upLeft;
86 const pa = Math.abs(estimate - left);
87 const pb = Math.abs(estimate - up);
88 const pc = Math.abs(estimate - upLeft);
89 const predictor = (pa <= pb && pa <= pc) ? left : (pb <= pc ? up : upLeft);
90 value = (value + predictor) & 255;
91 }
92 else if (filter !== 0)
93 { throw new Error(`${label}: unsupported PNG filter ${filter}`); }
94 current[i] = value;
95 }
96 current.copy(decoded, y * stride);
97 current.copy(previous);
98 }
99
100 const rgba = new Uint8ClampedArray(width * height * 4);
101 if (channels === 4)
102 { rgba.set(decoded); }
103 else
104 {
105 for (let i = 0, out = 0; i < width * height; i++)
106 {
107 const sourceOffset = i * 3;
108 rgba[out++] = decoded[sourceOffset];
109 rgba[out++] = decoded[sourceOffset + 1];
110 rgba[out++] = decoded[sourceOffset + 2];
111 rgba[out++] = 255;
112 }
113 }
114 return { width, height, rgba };
115}
server/src/assets/spriteCatalog.js +4 −1
@@ -27,6 +27,7 @@ import
27 27 palettePreviewImageName,
28 28 spriteImageName
29 29 } from "../../../shared/definitions/tileSprites.js";
30 import { attachTileAverageColors } from "./tileAverageColors.js";
30 31 import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
31 32 import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT, definitionUsesMaterialNeighborConnect } from "../../../shared/world/neighborConnect.js";
32 33 import
@@ -56,7 +57,7 @@ export function buildSpriteCatalog (assetRoot)
56 57 const fx = scanFx(join(assetRoot, "fx"));
57 58 const containers = scanContainerSprites(join(assetRoot, "blocks", ITEM_SPAWNER_CONTAINER_ASSET_KEY));
58 59 Object.assign(blocks.types, containers.blockTypes);
59 return {
60 const catalog = {
60 61 grounds: grounds.types,
61 62 blocks: blocks.types,
62 63 items: items.types,
@@ -74,6 +75,8 @@ export function buildSpriteCatalog (assetRoot)
74 75 ...containers.images
75 76 ]
76 77 };
78 attachTileAverageColors(catalog, assetRoot);
79 return catalog;
77 80 }
78 81
79 82 /**
@@ -27,6 +27,7 @@ import
27 palettePreviewImageName,
27 palettePreviewImageName,
28 spriteImageName
28 spriteImageName
29 } from "../../../shared/definitions/tileSprites.js";
29 } from "../../../shared/definitions/tileSprites.js";
30import { attachTileAverageColors } from "./tileAverageColors.js";
30import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
31import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
31import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT, definitionUsesMaterialNeighborConnect } from "../../../shared/world/neighborConnect.js";
32import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT, definitionUsesMaterialNeighborConnect } from "../../../shared/world/neighborConnect.js";
32import
33import
@@ -56,7 +57,7 @@ export function buildSpriteCatalog (assetRoot)
56 const fx = scanFx(join(assetRoot, "fx"));
57 const fx = scanFx(join(assetRoot, "fx"));
57 const containers = scanContainerSprites(join(assetRoot, "blocks", ITEM_SPAWNER_CONTAINER_ASSET_KEY));
58 const containers = scanContainerSprites(join(assetRoot, "blocks", ITEM_SPAWNER_CONTAINER_ASSET_KEY));
58 Object.assign(blocks.types, containers.blockTypes);
59 Object.assign(blocks.types, containers.blockTypes);
59 return {
60 const catalog = {
60 grounds: grounds.types,
61 grounds: grounds.types,
61 blocks: blocks.types,
62 blocks: blocks.types,
62 items: items.types,
63 items: items.types,
@@ -74,6 +75,8 @@ export function buildSpriteCatalog (assetRoot)
74 ...containers.images
75 ...containers.images
75 ]
76 ]
76 };
77 };
78 attachTileAverageColors(catalog, assetRoot);
79 return catalog;
77}
80}
78
81
79/**
82/**
server/src/assets/tileAverageColors.js added +245 −0
@@ -0,0 +1,245 @@
1 import { createHash } from "node:crypto";
2 import { readdirSync, readFileSync, writeFileSync, renameSync, statSync } from "node:fs";
3 import { join, relative, sep } from "node:path";
4 import { groundDefinition } from "../../../shared/definitions/tiles.js";
5 import { palettePreviewImageName, spriteImageName } from "../../../shared/definitions/tileSprites.js";
6 import { isSeasonalOverlayVariant } from "../../../shared/world/season.js";
7 import { applyMagentaTintToImageData } from "../../../shared/render/tint.js";
8 import { averageOpaqueColor } from "../../../shared/render/averageSpriteColor.js";
9 import { installTileAverageColors } from "../../../shared/render/tileAverageColors.js";
10 import { decodePngRgba } from "./pngRgba.js";
11
12 /**
13 * Bump when the averaging rules change so on-disk colour and minimap caches rebuild.
14 * Sprites changing already busts the stamp via file size and mtime.
15 */
16 const COLOR_CACHE_VERSION = 1;
17 const CACHE_FILE = ".tile-average-colors.json";
18
19 /** @type {{ stamp: string, colors: Record<string, { r: number, g: number, b: number }> } | null} */
20 let memory = null;
21
22 /**
23 * Sample every ground and block state from the sprites the catalog actually
24 * registers, then publish the results on the catalog and into the shared registry.
25 *
26 * Procedural wave grounds (water, deep water, lava) do not display their noise
27 * PNG — that texture feeds the shader. Their visible colour is taken from the
28 * palette preview sprite (`*-preview.png`), which is art, not a hand-entered
29 * swatch. Seasonal overlays such as ice (`water-winter`) still use their own sprite.
30 *
31 * @param {object} catalog
32 * @param {string} assetRoot `client/assets`
33 */
34 export function attachTileAverageColors (catalog, assetRoot)
35 {
36 const stamp = colorStamp(assetRoot);
37 let colors = memory?.stamp === stamp ? memory.colors : null;
38 if (!colors)
39 { colors = readDiskCache(assetRoot, stamp); }
40 if (!colors)
41 {
42 colors = computeColors(catalog, assetRoot);
43 memory = { stamp, colors };
44 writeDiskCache(assetRoot, stamp, colors);
45 }
46 else
47 { memory = { stamp, colors }; }
48
49 applyColors(catalog, colors);
50 catalog.tileColorStamp = stamp;
51 installTileAverageColors(catalog);
52 return catalog;
53 }
54
55 function applyColors (catalog, colors)
56 {
57 applyGroup(catalog?.grounds, "ground", colors);
58 applyGroup(catalog?.blocks, "block", colors);
59 }
60
61 function applyGroup (types, layer, colors)
62 {
63 for (const type of Object.values(types ?? {}))
64 {
65 const stateColors = {};
66 for (const state of type?.states ?? [])
67 {
68 const color = colors[spriteImageName(layer, type.key, state)];
69 if (color)
70 { stateColors[state] = color; }
71 }
72 type.stateColors = stateColors;
73 type.averageColor = stateColors[type.defaultState] ?? firstColor(stateColors);
74 }
75 }
76
77 function computeColors (catalog, assetRoot)
78 {
79 const imagesByName = new Map();
80 for (const image of catalog?.images ?? [])
81 { imagesByName.set(image.name, image); }
82
83 const decoded = new Map();
84 const tinted = new Map();
85 const colors = {};
86 sampleGroup(catalog?.grounds, "ground", imagesByName, colors, decoded, tinted, assetRoot);
87 sampleGroup(catalog?.blocks, "block", imagesByName, colors, decoded, tinted, assetRoot);
88 return colors;
89 }
90
91 function sampleGroup (types, layer, imagesByName, colors, decoded, tinted, assetRoot)
92 {
93 for (const type of Object.values(types ?? {}))
94 {
95 const procedural = layer === "ground" && !!groundDefinition(type.typeId)?.proceduralWaves;
96 const preview = imagesByName.get(palettePreviewImageName(layer, type.key)) ?? null;
97 for (const state of type?.states ?? [])
98 {
99 const name = spriteImageName(layer, type.key, state);
100 let image = imagesByName.get(name) ?? null;
101 if (procedural && preview && !isSeasonalOverlayVariant(state))
102 { image = preview; }
103 if (!image)
104 { continue; }
105 const color = colorForImage(image, assetRoot, decoded, tinted);
106 if (color)
107 { colors[name] = color; }
108 }
109 }
110 }
111
112 function colorForImage (image, assetRoot, decoded, tinted)
113 {
114 const tintKey = image.tint
115 ? `${image.tint.r},${image.tint.g},${image.tint.b}`
116 : "";
117 const key = `${image.url}|${tintKey}`;
118 if (tinted.has(key))
119 { return tinted.get(key); }
120
121 const bitmap = decodeUrl(image.url, assetRoot, decoded);
122 let pixels = bitmap.rgba;
123 if (image.tint)
124 {
125 pixels = new Uint8ClampedArray(bitmap.rgba);
126 applyMagentaTintToImageData({ data: pixels }, image.tint);
127 }
128 const color = averageOpaqueColor(pixels, bitmap.width, bitmap.height);
129 tinted.set(key, color);
130 return color;
131 }
132
133 function decodeUrl (url, assetRoot, decoded)
134 {
135 const filePath = assetFile(assetRoot, url);
136 const cached = decoded.get(filePath);
137 if (cached)
138 { return cached; }
139 const bitmap = decodePngRgba(readFileSync(filePath), filePath);
140 decoded.set(filePath, bitmap);
141 return bitmap;
142 }
143
144 function assetFile (assetRoot, url)
145 {
146 const prefix = "/assets/";
147 if (typeof url !== "string" || !url.startsWith(prefix))
148 { throw new Error(`Sprite URL is not under /assets/: ${url}`); }
149 const root = assetRoot.endsWith(sep) ? assetRoot : assetRoot + sep;
150 const resolved = join(assetRoot, url.slice(prefix.length));
151 if (resolved !== assetRoot && !resolved.startsWith(root))
152 { throw new Error(`Sprite URL escapes the asset root: ${url}`); }
153 return resolved;
154 }
155
156 function colorStamp (assetRoot)
157 {
158 const hash = createHash("sha1");
159 hash.update(String(COLOR_CACHE_VERSION));
160 hash.update("\0");
161 const files = [];
162 for (const folder of ["grounds", "blocks", "herbs"])
163 { collectPngs(join(assetRoot, folder), assetRoot, files); }
164 files.sort((a, b) => a.rel.localeCompare(b.rel, "en"));
165 for (const file of files)
166 {
167 hash.update(file.rel);
168 hash.update("\0");
169 hash.update(String(file.size));
170 hash.update("\0");
171 hash.update(String(file.mtimeMs));
172 hash.update("\0");
173 }
174 return hash.digest("hex");
175 }
176
177 function collectPngs (folder, assetRoot, out)
178 {
179 let entries;
180 try
181 { entries = readdirSync(folder, { withFileTypes: true }); }
182 catch (error)
183 {
184 if (error.code === "ENOENT")
185 { return; }
186 throw error;
187 }
188 for (const entry of entries)
189 {
190 const path = join(folder, entry.name);
191 if (entry.isDirectory())
192 { collectPngs(path, assetRoot, out); }
193 else if (entry.isFile() && entry.name.toLowerCase().endsWith(".png"))
194 {
195 const stat = statSync(path);
196 out.push({
197 rel: relative(assetRoot, path),
198 size: stat.size,
199 mtimeMs: Math.round(stat.mtimeMs)
200 });
201 }
202 }
203 }
204
205 function readDiskCache (assetRoot, stamp)
206 {
207 try
208 {
209 const parsed = JSON.parse(readFileSync(join(assetRoot, CACHE_FILE), "utf8"));
210 if (parsed?.version !== COLOR_CACHE_VERSION || parsed?.stamp !== stamp || !parsed.colors)
211 { return null; }
212 return parsed.colors;
213 }
214 catch
215 { return null; }
216 }
217
218 function writeDiskCache (assetRoot, stamp, colors)
219 {
220 const path = join(assetRoot, CACHE_FILE);
221 const tmp = `${path}.tmp-${process.pid}`;
222 try
223 {
224 writeFileSync(tmp, JSON.stringify({
225 version: COLOR_CACHE_VERSION,
226 stamp,
227 colors
228 }));
229 renameSync(tmp, path);
230 }
231 catch (error)
232 {
233 console.error("[tile-colors] failed to write colour cache:", error.message ?? error);
234 }
235 }
236
237 function firstColor (stateColors)
238 {
239 for (const color of Object.values(stateColors))
240 {
241 if (color)
242 { return color; }
243 }
244 return null;
245 }
@@ -0,0 +1,245 @@
1import { createHash } from "node:crypto";
2import { readdirSync, readFileSync, writeFileSync, renameSync, statSync } from "node:fs";
3import { join, relative, sep } from "node:path";
4import { groundDefinition } from "../../../shared/definitions/tiles.js";
5import { palettePreviewImageName, spriteImageName } from "../../../shared/definitions/tileSprites.js";
6import { isSeasonalOverlayVariant } from "../../../shared/world/season.js";
7import { applyMagentaTintToImageData } from "../../../shared/render/tint.js";
8import { averageOpaqueColor } from "../../../shared/render/averageSpriteColor.js";
9import { installTileAverageColors } from "../../../shared/render/tileAverageColors.js";
10import { decodePngRgba } from "./pngRgba.js";
11
12/**
13 * Bump when the averaging rules change so on-disk colour and minimap caches rebuild.
14 * Sprites changing already busts the stamp via file size and mtime.
15 */
16const COLOR_CACHE_VERSION = 1;
17const CACHE_FILE = ".tile-average-colors.json";
18
19/** @type {{ stamp: string, colors: Record<string, { r: number, g: number, b: number }> } | null} */
20let memory = null;
21
22/**
23 * Sample every ground and block state from the sprites the catalog actually
24 * registers, then publish the results on the catalog and into the shared registry.
25 *
26 * Procedural wave grounds (water, deep water, lava) do not display their noise
27 * PNG — that texture feeds the shader. Their visible colour is taken from the
28 * palette preview sprite (`*-preview.png`), which is art, not a hand-entered
29 * swatch. Seasonal overlays such as ice (`water-winter`) still use their own sprite.
30 *
31 * @param {object} catalog
32 * @param {string} assetRoot `client/assets`
33 */
34export function attachTileAverageColors (catalog, assetRoot)
35{
36 const stamp = colorStamp(assetRoot);
37 let colors = memory?.stamp === stamp ? memory.colors : null;
38 if (!colors)
39 { colors = readDiskCache(assetRoot, stamp); }
40 if (!colors)
41 {
42 colors = computeColors(catalog, assetRoot);
43 memory = { stamp, colors };
44 writeDiskCache(assetRoot, stamp, colors);
45 }
46 else
47 { memory = { stamp, colors }; }
48
49 applyColors(catalog, colors);
50 catalog.tileColorStamp = stamp;
51 installTileAverageColors(catalog);
52 return catalog;
53}
54
55function applyColors (catalog, colors)
56{
57 applyGroup(catalog?.grounds, "ground", colors);
58 applyGroup(catalog?.blocks, "block", colors);
59}
60
61function applyGroup (types, layer, colors)
62{
63 for (const type of Object.values(types ?? {}))
64 {
65 const stateColors = {};
66 for (const state of type?.states ?? [])
67 {
68 const color = colors[spriteImageName(layer, type.key, state)];
69 if (color)
70 { stateColors[state] = color; }
71 }
72 type.stateColors = stateColors;
73 type.averageColor = stateColors[type.defaultState] ?? firstColor(stateColors);
74 }
75}
76
77function computeColors (catalog, assetRoot)
78{
79 const imagesByName = new Map();
80 for (const image of catalog?.images ?? [])
81 { imagesByName.set(image.name, image); }
82
83 const decoded = new Map();
84 const tinted = new Map();
85 const colors = {};
86 sampleGroup(catalog?.grounds, "ground", imagesByName, colors, decoded, tinted, assetRoot);
87 sampleGroup(catalog?.blocks, "block", imagesByName, colors, decoded, tinted, assetRoot);
88 return colors;
89}
90
91function sampleGroup (types, layer, imagesByName, colors, decoded, tinted, assetRoot)
92{
93 for (const type of Object.values(types ?? {}))
94 {
95 const procedural = layer === "ground" && !!groundDefinition(type.typeId)?.proceduralWaves;
96 const preview = imagesByName.get(palettePreviewImageName(layer, type.key)) ?? null;
97 for (const state of type?.states ?? [])
98 {
99 const name = spriteImageName(layer, type.key, state);
100 let image = imagesByName.get(name) ?? null;
101 if (procedural && preview && !isSeasonalOverlayVariant(state))
102 { image = preview; }
103 if (!image)
104 { continue; }
105 const color = colorForImage(image, assetRoot, decoded, tinted);
106 if (color)
107 { colors[name] = color; }
108 }
109 }
110}
111
112function colorForImage (image, assetRoot, decoded, tinted)
113{
114 const tintKey = image.tint
115 ? `${image.tint.r},${image.tint.g},${image.tint.b}`
116 : "";
117 const key = `${image.url}|${tintKey}`;
118 if (tinted.has(key))
119 { return tinted.get(key); }
120
121 const bitmap = decodeUrl(image.url, assetRoot, decoded);
122 let pixels = bitmap.rgba;
123 if (image.tint)
124 {
125 pixels = new Uint8ClampedArray(bitmap.rgba);
126 applyMagentaTintToImageData({ data: pixels }, image.tint);
127 }
128 const color = averageOpaqueColor(pixels, bitmap.width, bitmap.height);
129 tinted.set(key, color);
130 return color;
131}
132
133function decodeUrl (url, assetRoot, decoded)
134{
135 const filePath = assetFile(assetRoot, url);
136 const cached = decoded.get(filePath);
137 if (cached)
138 { return cached; }
139 const bitmap = decodePngRgba(readFileSync(filePath), filePath);
140 decoded.set(filePath, bitmap);
141 return bitmap;
142}
143
144function assetFile (assetRoot, url)
145{
146 const prefix = "/assets/";
147 if (typeof url !== "string" || !url.startsWith(prefix))
148 { throw new Error(`Sprite URL is not under /assets/: ${url}`); }
149 const root = assetRoot.endsWith(sep) ? assetRoot : assetRoot + sep;
150 const resolved = join(assetRoot, url.slice(prefix.length));
151 if (resolved !== assetRoot && !resolved.startsWith(root))
152 { throw new Error(`Sprite URL escapes the asset root: ${url}`); }
153 return resolved;
154}
155
156function colorStamp (assetRoot)
157{
158 const hash = createHash("sha1");
159 hash.update(String(COLOR_CACHE_VERSION));
160 hash.update("\0");
161 const files = [];
162 for (const folder of ["grounds", "blocks", "herbs"])
163 { collectPngs(join(assetRoot, folder), assetRoot, files); }
164 files.sort((a, b) => a.rel.localeCompare(b.rel, "en"));
165 for (const file of files)
166 {
167 hash.update(file.rel);
168 hash.update("\0");
169 hash.update(String(file.size));
170 hash.update("\0");
171 hash.update(String(file.mtimeMs));
172 hash.update("\0");
173 }
174 return hash.digest("hex");
175}
176
177function collectPngs (folder, assetRoot, out)
178{
179 let entries;
180 try
181 { entries = readdirSync(folder, { withFileTypes: true }); }
182 catch (error)
183 {
184 if (error.code === "ENOENT")
185 { return; }
186 throw error;
187 }
188 for (const entry of entries)
189 {
190 const path = join(folder, entry.name);
191 if (entry.isDirectory())
192 { collectPngs(path, assetRoot, out); }
193 else if (entry.isFile() && entry.name.toLowerCase().endsWith(".png"))
194 {
195 const stat = statSync(path);
196 out.push({
197 rel: relative(assetRoot, path),
198 size: stat.size,
199 mtimeMs: Math.round(stat.mtimeMs)
200 });
201 }
202 }
203}
204
205function readDiskCache (assetRoot, stamp)
206{
207 try
208 {
209 const parsed = JSON.parse(readFileSync(join(assetRoot, CACHE_FILE), "utf8"));
210 if (parsed?.version !== COLOR_CACHE_VERSION || parsed?.stamp !== stamp || !parsed.colors)
211 { return null; }
212 return parsed.colors;
213 }
214 catch
215 { return null; }
216}
217
218function writeDiskCache (assetRoot, stamp, colors)
219{
220 const path = join(assetRoot, CACHE_FILE);
221 const tmp = `${path}.tmp-${process.pid}`;
222 try
223 {
224 writeFileSync(tmp, JSON.stringify({
225 version: COLOR_CACHE_VERSION,
226 stamp,
227 colors
228 }));
229 renameSync(tmp, path);
230 }
231 catch (error)
232 {
233 console.error("[tile-colors] failed to write colour cache:", error.message ?? error);
234 }
235}
236
237function firstColor (stateColors)
238{
239 for (const color of Object.values(stateColors))
240 {
241 if (color)
242 { return color; }
243 }
244 return null;
245}
server/src/editor/minimapCache.js added +176 −0
@@ -0,0 +1,176 @@
1 import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
2 import { dirname, join } from "node:path";
3 import { normalizeDimensionId } from "../../../shared/world/dimensions.js";
4 import
5 {
6 MINIMAP_CHUNK_PIXELS,
7 MINIMAP_SPAN_CHUNKS,
8 minimapRadius,
9 renderChunkMinimapRgba
10 } from "../../../shared/render/chunkMinimap.js";
11 import { decodeChunkBlob } from "../world/chunkData.js";
12
13 const RGBA_BYTES = MINIMAP_CHUNK_PIXELS * MINIMAP_CHUNK_PIXELS * 4;
14
15 /**
16 * Per-dimension minimap images, one uncompressed RGBA file per saved chunk.
17 *
18 * Lives under the server data directory next to `world.sqlite`:
19 * `minimap/<dimensionId>/<chunkX>_<chunkY>.rgba`
20 * (16×16×4 bytes while chunks are 16 tiles square).
21 *
22 * A file is written when that chunk is saved, and created on read when it is
23 * missing but the chunk exists. Chunks with no row are drawn as empty by the
24 * client and any stale file for them is removed. Changing sprite colours
25 * (see `color-stamp.txt`) deletes every cached image so the next read rebuilds
26 * them. The editor asks for a window of chunks; only cache misses load the
27 * chunk blob.
28 */
29 export class MinimapCache
30 {
31 constructor (rootDir, worldDb)
32 {
33 this.rootDir = rootDir;
34 this.worldDb = worldDb;
35 }
36
37 pathFor (dimensionId, chunkX, chunkY)
38 {
39 const dim = normalizeDimensionId(dimensionId);
40 return join(this.rootDir, dim, `${chunkX | 0}_${chunkY | 0}.rgba`);
41 }
42
43 /**
44 * Drop cached images when the sprite-colour stamp changes (new or edited art).
45 * @param {string} stamp
46 */
47 syncColorStamp (stamp)
48 {
49 mkdirSync(this.rootDir, { recursive: true });
50 const file = join(this.rootDir, "color-stamp.txt");
51 const next = String(stamp ?? "");
52 let previous = null;
53 try
54 { previous = readFileSync(file, "utf8"); }
55 catch
56 { previous = null; }
57 if (previous === next)
58 { return; }
59 let entries = [];
60 try
61 { entries = readdirSync(this.rootDir, { withFileTypes: true }); }
62 catch
63 { entries = []; }
64 for (const entry of entries)
65 {
66 if (!entry.isDirectory())
67 { continue; }
68 rmSync(join(this.rootDir, entry.name), { recursive: true, force: true });
69 }
70 writeFileSync(file, next);
71 }
72
73 removeDimensions (dimensionIds)
74 {
75 for (const dimensionId of dimensionIds ?? [])
76 {
77 rmSync(join(this.rootDir, normalizeDimensionId(dimensionId)), { recursive: true, force: true });
78 }
79 }
80
81 /**
82 * @param {string} dimensionId
83 * @param {number} chunkX
84 * @param {number} chunkY
85 * @param {object} chunkData
86 * @param {number} defaultGroundTypeId
87 * @returns {Buffer}
88 */
89 write (dimensionId, chunkX, chunkY, chunkData, defaultGroundTypeId)
90 {
91 const rgba = renderChunkMinimapRgba(chunkData, defaultGroundTypeId);
92 const file = this.pathFor(dimensionId, chunkX, chunkY);
93 mkdirSync(dirname(file), { recursive: true });
94 const buffer = Buffer.from(rgba.buffer, rgba.byteOffset, rgba.byteLength);
95 writeFileSync(file, buffer);
96 return buffer;
97 }
98
99 /**
100 * @returns {Buffer | null} cached or freshly built image, or null when the chunk is not saved
101 */
102 readOrCreate (dimensionId, chunkX, chunkY, revisionId, defaultGroundTypeId)
103 {
104 const file = this.pathFor(dimensionId, chunkX, chunkY);
105 const cached = this.#readValid(file);
106 const saved = this.worldDb.hasChunkVersion(chunkX, chunkY, revisionId, dimensionId);
107 if (!saved)
108 {
109 if (cached)
110 { unlinkSync(file); }
111 return null;
112 }
113 if (cached)
114 { return cached; }
115 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimensionId);
116 if (!row)
117 { return null; }
118 const data = decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY);
119 return this.write(dimensionId, chunkX, chunkY, data, defaultGroundTypeId);
120 }
121
122 /**
123 * 25×25 chunk window centred on `centerChunkX` / `centerChunkY`.
124 * Present chunks are raw RGBA, base64. Missing chunks are omitted.
125 */
126 window (dimensionId, centerChunkX, centerChunkY, revisionId, defaultGroundTypeId)
127 {
128 const dim = normalizeDimensionId(dimensionId);
129 const centerX = centerChunkX | 0;
130 const centerY = centerChunkY | 0;
131 const radius = minimapRadius(MINIMAP_SPAN_CHUNKS);
132 const chunks = {};
133 for (let dy = -radius; dy <= radius; dy++)
134 {
135 for (let dx = -radius; dx <= radius; dx++)
136 {
137 const chunkX = centerX + dx;
138 const chunkY = centerY + dy;
139 try
140 {
141 const image = this.readOrCreate(dim, chunkX, chunkY, revisionId, defaultGroundTypeId);
142 if (image)
143 { chunks[`${chunkX},${chunkY}`] = image.toString("base64"); }
144 }
145 catch (error)
146 {
147 console.error(
148 `[minimap] skipped ${dim} ${chunkX},${chunkY}:`,
149 error?.message ?? error
150 );
151 }
152 }
153 }
154 return {
155 dimensionId: dim,
156 chunkX: centerX,
157 chunkY: centerY,
158 chunkPixels: MINIMAP_CHUNK_PIXELS,
159 span: MINIMAP_SPAN_CHUNKS,
160 chunks
161 };
162 }
163
164 #readValid (file)
165 {
166 if (!existsSync(file))
167 { return null; }
168 const buffer = readFileSync(file);
169 if (buffer.length !== RGBA_BYTES)
170 {
171 unlinkSync(file);
172 return null;
173 }
174 return buffer;
175 }
176 }
@@ -0,0 +1,176 @@
1import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
2import { dirname, join } from "node:path";
3import { normalizeDimensionId } from "../../../shared/world/dimensions.js";
4import
5{
6 MINIMAP_CHUNK_PIXELS,
7 MINIMAP_SPAN_CHUNKS,
8 minimapRadius,
9 renderChunkMinimapRgba
10} from "../../../shared/render/chunkMinimap.js";
11import { decodeChunkBlob } from "../world/chunkData.js";
12
13const RGBA_BYTES = MINIMAP_CHUNK_PIXELS * MINIMAP_CHUNK_PIXELS * 4;
14
15/**
16 * Per-dimension minimap images, one uncompressed RGBA file per saved chunk.
17 *
18 * Lives under the server data directory next to `world.sqlite`:
19 * `minimap/<dimensionId>/<chunkX>_<chunkY>.rgba`
20 * (16×16×4 bytes while chunks are 16 tiles square).
21 *
22 * A file is written when that chunk is saved, and created on read when it is
23 * missing but the chunk exists. Chunks with no row are drawn as empty by the
24 * client and any stale file for them is removed. Changing sprite colours
25 * (see `color-stamp.txt`) deletes every cached image so the next read rebuilds
26 * them. The editor asks for a window of chunks; only cache misses load the
27 * chunk blob.
28 */
29export class MinimapCache
30{
31 constructor (rootDir, worldDb)
32 {
33 this.rootDir = rootDir;
34 this.worldDb = worldDb;
35 }
36
37 pathFor (dimensionId, chunkX, chunkY)
38 {
39 const dim = normalizeDimensionId(dimensionId);
40 return join(this.rootDir, dim, `${chunkX | 0}_${chunkY | 0}.rgba`);
41 }
42
43 /**
44 * Drop cached images when the sprite-colour stamp changes (new or edited art).
45 * @param {string} stamp
46 */
47 syncColorStamp (stamp)
48 {
49 mkdirSync(this.rootDir, { recursive: true });
50 const file = join(this.rootDir, "color-stamp.txt");
51 const next = String(stamp ?? "");
52 let previous = null;
53 try
54 { previous = readFileSync(file, "utf8"); }
55 catch
56 { previous = null; }
57 if (previous === next)
58 { return; }
59 let entries = [];
60 try
61 { entries = readdirSync(this.rootDir, { withFileTypes: true }); }
62 catch
63 { entries = []; }
64 for (const entry of entries)
65 {
66 if (!entry.isDirectory())
67 { continue; }
68 rmSync(join(this.rootDir, entry.name), { recursive: true, force: true });
69 }
70 writeFileSync(file, next);
71 }
72
73 removeDimensions (dimensionIds)
74 {
75 for (const dimensionId of dimensionIds ?? [])
76 {
77 rmSync(join(this.rootDir, normalizeDimensionId(dimensionId)), { recursive: true, force: true });
78 }
79 }
80
81 /**
82 * @param {string} dimensionId
83 * @param {number} chunkX
84 * @param {number} chunkY
85 * @param {object} chunkData
86 * @param {number} defaultGroundTypeId
87 * @returns {Buffer}
88 */
89 write (dimensionId, chunkX, chunkY, chunkData, defaultGroundTypeId)
90 {
91 const rgba = renderChunkMinimapRgba(chunkData, defaultGroundTypeId);
92 const file = this.pathFor(dimensionId, chunkX, chunkY);
93 mkdirSync(dirname(file), { recursive: true });
94 const buffer = Buffer.from(rgba.buffer, rgba.byteOffset, rgba.byteLength);
95 writeFileSync(file, buffer);
96 return buffer;
97 }
98
99 /**
100 * @returns {Buffer | null} cached or freshly built image, or null when the chunk is not saved
101 */
102 readOrCreate (dimensionId, chunkX, chunkY, revisionId, defaultGroundTypeId)
103 {
104 const file = this.pathFor(dimensionId, chunkX, chunkY);
105 const cached = this.#readValid(file);
106 const saved = this.worldDb.hasChunkVersion(chunkX, chunkY, revisionId, dimensionId);
107 if (!saved)
108 {
109 if (cached)
110 { unlinkSync(file); }
111 return null;
112 }
113 if (cached)
114 { return cached; }
115 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimensionId);
116 if (!row)
117 { return null; }
118 const data = decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY);
119 return this.write(dimensionId, chunkX, chunkY, data, defaultGroundTypeId);
120 }
121
122 /**
123 * 25×25 chunk window centred on `centerChunkX` / `centerChunkY`.
124 * Present chunks are raw RGBA, base64. Missing chunks are omitted.
125 */
126 window (dimensionId, centerChunkX, centerChunkY, revisionId, defaultGroundTypeId)
127 {
128 const dim = normalizeDimensionId(dimensionId);
129 const centerX = centerChunkX | 0;
130 const centerY = centerChunkY | 0;
131 const radius = minimapRadius(MINIMAP_SPAN_CHUNKS);
132 const chunks = {};
133 for (let dy = -radius; dy <= radius; dy++)
134 {
135 for (let dx = -radius; dx <= radius; dx++)
136 {
137 const chunkX = centerX + dx;
138 const chunkY = centerY + dy;
139 try
140 {
141 const image = this.readOrCreate(dim, chunkX, chunkY, revisionId, defaultGroundTypeId);
142 if (image)
143 { chunks[`${chunkX},${chunkY}`] = image.toString("base64"); }
144 }
145 catch (error)
146 {
147 console.error(
148 `[minimap] skipped ${dim} ${chunkX},${chunkY}:`,
149 error?.message ?? error
150 );
151 }
152 }
153 }
154 return {
155 dimensionId: dim,
156 chunkX: centerX,
157 chunkY: centerY,
158 chunkPixels: MINIMAP_CHUNK_PIXELS,
159 span: MINIMAP_SPAN_CHUNKS,
160 chunks
161 };
162 }
163
164 #readValid (file)
165 {
166 if (!existsSync(file))
167 { return null; }
168 const buffer = readFileSync(file);
169 if (buffer.length !== RGBA_BYTES)
170 {
171 unlinkSync(file);
172 return null;
173 }
174 return buffer;
175 }
176}
server/src/editor/service.js +52 −1
@@ -34,13 +34,15 @@ import {
34 34 normalizeLightingMode,
35 35 normalizeSeasonMode
36 36 } from "../../../shared/world/dimensions.js";
37 import { MINIMAP_CHUNK_PIXELS, MINIMAP_SPAN_CHUNKS } from "../../../shared/render/chunkMinimap.js";
37 38
38 39 export class EditorService
39 40 {
40 constructor (worldDb, stateDb = null)
41 constructor (worldDb, stateDb = null, minimapCache = null)
41 42 {
42 43 this.worldDb = worldDb;
43 44 this.stateDb = stateDb;
45 this.minimapCache = minimapCache;
44 46 }
45 47
46 48 #editorDisplayName (editorAdminId)
@@ -169,6 +171,9 @@ export class EditorService
169 171 encodeChunkBlob(result.data),
170 172 dimId
171 173 );
174 // Cache is derived from the blob just stored. A failure here must not
175 // fail the save or rewrite chunk rows.
176 this.#cacheMinimap(result.chunkX, result.chunkY, result.data, dimId, defaultGroundTypeId);
172 177 }
173 178
174 179 if (diffEntries.length > 0)
@@ -177,6 +182,52 @@ export class EditorService
177 182 return this.loadChunk(chunkX, chunkY, dimId);
178 183 }
179 184
185 /**
186 * Minimap images for the 25×25 chunk window centred on this chunk.
187 * Empty when no cache is configured (tests that do not exercise the minimap).
188 */
189 minimapWindow (chunkX, chunkY, dimensionId = OVERWORLD_ID)
190 {
191 const dimId = normalizeDimensionId(dimensionId);
192 const centerX = chunkX | 0;
193 const centerY = chunkY | 0;
194 if (!this.minimapCache)
195 {
196 return {
197 dimensionId: dimId,
198 chunkX: centerX,
199 chunkY: centerY,
200 chunkPixels: MINIMAP_CHUNK_PIXELS,
201 span: MINIMAP_SPAN_CHUNKS,
202 chunks: {}
203 };
204 }
205 return this.minimapCache.window(
206 dimId,
207 centerX,
208 centerY,
209 this.worldDb.getEditorRevisionId(),
210 this.#defaultGroundForDimension(dimId)
211 );
212 }
213
214 #cacheMinimap (chunkX, chunkY, data, dimensionId, defaultGroundTypeId)
215 {
216 if (!this.minimapCache)
217 { return; }
218 try
219 {
220 this.minimapCache.write(dimensionId, chunkX, chunkY, data, defaultGroundTypeId);
221 }
222 catch (error)
223 {
224 console.error(
225 `[minimap] cache write failed for ${dimensionId} ${chunkX},${chunkY}:`,
226 error?.message ?? error
227 );
228 }
229 }
230
180 231 listDimensions ()
181 232 {
182 233 const revisionId = this.worldDb.getEditorRevisionId();
@@ -34,13 +34,15 @@ import {
34 normalizeLightingMode,
34 normalizeLightingMode,
35 normalizeSeasonMode
35 normalizeSeasonMode
36} from "../../../shared/world/dimensions.js";
36} from "../../../shared/world/dimensions.js";
37import { MINIMAP_CHUNK_PIXELS, MINIMAP_SPAN_CHUNKS } from "../../../shared/render/chunkMinimap.js";
37
38
38export class EditorService
39export class EditorService
39{
40{
40 constructor (worldDb, stateDb = null)
41 constructor (worldDb, stateDb = null, minimapCache = null)
41 {
42 {
42 this.worldDb = worldDb;
43 this.worldDb = worldDb;
43 this.stateDb = stateDb;
44 this.stateDb = stateDb;
45 this.minimapCache = minimapCache;
44 }
46 }
45
47
46 #editorDisplayName (editorAdminId)
48 #editorDisplayName (editorAdminId)
@@ -169,6 +171,9 @@ export class EditorService
169 encodeChunkBlob(result.data),
171 encodeChunkBlob(result.data),
170 dimId
172 dimId
171 );
173 );
174 // Cache is derived from the blob just stored. A failure here must not
175 // fail the save or rewrite chunk rows.
176 this.#cacheMinimap(result.chunkX, result.chunkY, result.data, dimId, defaultGroundTypeId);
172 }
177 }
173
178
174 if (diffEntries.length > 0)
179 if (diffEntries.length > 0)
@@ -177,6 +182,52 @@ export class EditorService
177 return this.loadChunk(chunkX, chunkY, dimId);
182 return this.loadChunk(chunkX, chunkY, dimId);
178 }
183 }
179
184
185 /**
186 * Minimap images for the 25×25 chunk window centred on this chunk.
187 * Empty when no cache is configured (tests that do not exercise the minimap).
188 */
189 minimapWindow (chunkX, chunkY, dimensionId = OVERWORLD_ID)
190 {
191 const dimId = normalizeDimensionId(dimensionId);
192 const centerX = chunkX | 0;
193 const centerY = chunkY | 0;
194 if (!this.minimapCache)
195 {
196 return {
197 dimensionId: dimId,
198 chunkX: centerX,
199 chunkY: centerY,
200 chunkPixels: MINIMAP_CHUNK_PIXELS,
201 span: MINIMAP_SPAN_CHUNKS,
202 chunks: {}
203 };
204 }
205 return this.minimapCache.window(
206 dimId,
207 centerX,
208 centerY,
209 this.worldDb.getEditorRevisionId(),
210 this.#defaultGroundForDimension(dimId)
211 );
212 }
213
214 #cacheMinimap (chunkX, chunkY, data, dimensionId, defaultGroundTypeId)
215 {
216 if (!this.minimapCache)
217 { return; }
218 try
219 {
220 this.minimapCache.write(dimensionId, chunkX, chunkY, data, defaultGroundTypeId);
221 }
222 catch (error)
223 {
224 console.error(
225 `[minimap] cache write failed for ${dimensionId} ${chunkX},${chunkY}:`,
226 error?.message ?? error
227 );
228 }
229 }
230
180 listDimensions ()
231 listDimensions ()
181 {
232 {
182 const revisionId = this.worldDb.getEditorRevisionId();
233 const revisionId = this.worldDb.getEditorRevisionId();
server/src/gateway/websocket.js +7 −0
@@ -970,6 +970,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
970 970 )
971 971 });
972 972 break;
973 case MessageType.editorRequestMinimap:
974 requireAdmin(session);
975 send(session, {
976 type: MessageType.editorMinimap,
977 ...editor.minimapWindow(message.chunkX | 0, message.chunkY | 0, message.dimensionId)
978 });
979 break;
973 980 case MessageType.editorListDimensions:
974 981 case "EDITOR_LIST_DIMENSIONS":
975 982 requireAdmin(session);
@@ -970,6 +970,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
970 )
970 )
971 });
971 });
972 break;
972 break;
973 case MessageType.editorRequestMinimap:
974 requireAdmin(session);
975 send(session, {
976 type: MessageType.editorMinimap,
977 ...editor.minimapWindow(message.chunkX | 0, message.chunkY | 0, message.dimensionId)
978 });
979 break;
973 case MessageType.editorListDimensions:
980 case MessageType.editorListDimensions:
974 case "EDITOR_LIST_DIMENSIONS":
981 case "EDITOR_LIST_DIMENSIONS":
975 requireAdmin(session);
982 requireAdmin(session);
server/src/index.js +7 −1
@@ -2,6 +2,8 @@ import { join } from "node:path";
2 2 import { WorldDatabase } from "./persistence/worldDb.js";
3 3 import { StateDatabase } from "./persistence/stateDb.js";
4 4 import { EditorService } from "./editor/service.js";
5 import { MinimapCache } from "./editor/minimapCache.js";
6 import { buildSpriteCatalog } from "./assets/spriteCatalog.js";
5 7 import { CharacterService } from "./characters/service.js";
6 8 import { FriendService } from "./friends/service.js";
7 9 import { GiftService } from "./gifts/service.js";
@@ -23,7 +25,11 @@ const port = Number(process.env.PORT ?? 8080);
23 25
24 26 const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
25 27 const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
26 const editor = new EditorService(worldDb, stateDb);
28 const spriteCatalog = buildSpriteCatalog(join(rootDir, "client", "assets"));
29 const minimapCache = new MinimapCache(join(dataDir, "minimap"), worldDb);
30 minimapCache.syncColorStamp(spriteCatalog.tileColorStamp ?? "");
31 worldDb.onDimensionsPurged = (ids) => minimapCache.removeDimensions(ids);
32 const editor = new EditorService(worldDb, stateDb, minimapCache);
27 33 const characters = new CharacterService(stateDb, console);
28 34 const friends = new FriendService(stateDb);
29 35 const simulation = new Simulation(worldDb, stateDb);
@@ -2,6 +2,8 @@ import { join } from "node:path";
2import { WorldDatabase } from "./persistence/worldDb.js";
2import { WorldDatabase } from "./persistence/worldDb.js";
3import { StateDatabase } from "./persistence/stateDb.js";
3import { StateDatabase } from "./persistence/stateDb.js";
4import { EditorService } from "./editor/service.js";
4import { EditorService } from "./editor/service.js";
5import { MinimapCache } from "./editor/minimapCache.js";
6import { buildSpriteCatalog } from "./assets/spriteCatalog.js";
5import { CharacterService } from "./characters/service.js";
7import { CharacterService } from "./characters/service.js";
6import { FriendService } from "./friends/service.js";
8import { FriendService } from "./friends/service.js";
7import { GiftService } from "./gifts/service.js";
9import { GiftService } from "./gifts/service.js";
@@ -23,7 +25,11 @@ const port = Number(process.env.PORT ?? 8080);
23
25
24const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
26const worldDb = new WorldDatabase(join(dataDir, "world.sqlite"));
25const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
27const stateDb = new StateDatabase(join(dataDir, "state.sqlite"));
26const editor = new EditorService(worldDb, stateDb);
28const spriteCatalog = buildSpriteCatalog(join(rootDir, "client", "assets"));
29const minimapCache = new MinimapCache(join(dataDir, "minimap"), worldDb);
30minimapCache.syncColorStamp(spriteCatalog.tileColorStamp ?? "");
31worldDb.onDimensionsPurged = (ids) => minimapCache.removeDimensions(ids);
32const editor = new EditorService(worldDb, stateDb, minimapCache);
27const characters = new CharacterService(stateDb, console);
33const characters = new CharacterService(stateDb, console);
28const friends = new FriendService(stateDb);
34const friends = new FriendService(stateDb);
29const simulation = new Simulation(worldDb, stateDb);
35const simulation = new Simulation(worldDb, stateDb);
server/src/persistence/worldDb.js +22 −0
@@ -553,6 +553,7 @@ export class WorldDatabase
553 553 WHERE purge_after IS NOT NULL AND purge_after <= ? AND dimension_id != ?
554 554 `).all(now, OVERWORLD_ID);
555 555 let purged = 0;
556 const purgedIds = [];
556 557 for (const row of rows)
557 558 {
558 559 const id = row.dimension_id;
@@ -562,11 +563,32 @@ export class WorldDatabase
562 563 this.db.prepare("DELETE FROM world_chunk_edit_log WHERE dimension_id = ?").run(id);
563 564 this.db.prepare("DELETE FROM world_dimensions WHERE dimension_id = ?").run(id);
564 565 });
566 purgedIds.push(id);
565 567 purged += 1;
566 568 }
569 if (purgedIds.length > 0 && typeof this.onDimensionsPurged === "function")
570 {
571 try
572 { this.onDimensionsPurged(purgedIds); }
573 catch (error)
574 { console.error("onDimensionsPurged failed:", error?.message ?? error); }
575 }
567 576 return purged;
568 577 }
569 578
579 hasChunkVersion (chunkX, chunkY, revisionId, dimensionId = OVERWORLD_ID)
580 {
581 const dim = normalizeDimensionId(dimensionId);
582 const row = this.db.prepare(`
583 SELECT revision_id
584 FROM world_chunk_versions
585 WHERE dimension_id = ? AND chunk_x = ? AND chunk_y = ? AND revision_id <= ?
586 ORDER BY revision_id DESC
587 LIMIT 1
588 `).get(dim, chunkX, chunkY, revisionId);
589 return !!row;
590 }
591
570 592 getChunkVersion (chunkX, chunkY, revisionId, dimensionId = OVERWORLD_ID)
571 593 {
572 594 const dim = normalizeDimensionId(dimensionId);
@@ -553,6 +553,7 @@ export class WorldDatabase
553 WHERE purge_after IS NOT NULL AND purge_after <= ? AND dimension_id != ?
553 WHERE purge_after IS NOT NULL AND purge_after <= ? AND dimension_id != ?
554 `).all(now, OVERWORLD_ID);
554 `).all(now, OVERWORLD_ID);
555 let purged = 0;
555 let purged = 0;
556 const purgedIds = [];
556 for (const row of rows)
557 for (const row of rows)
557 {
558 {
558 const id = row.dimension_id;
559 const id = row.dimension_id;
@@ -562,11 +563,32 @@ export class WorldDatabase
562 this.db.prepare("DELETE FROM world_chunk_edit_log WHERE dimension_id = ?").run(id);
563 this.db.prepare("DELETE FROM world_chunk_edit_log WHERE dimension_id = ?").run(id);
563 this.db.prepare("DELETE FROM world_dimensions WHERE dimension_id = ?").run(id);
564 this.db.prepare("DELETE FROM world_dimensions WHERE dimension_id = ?").run(id);
564 });
565 });
566 purgedIds.push(id);
565 purged += 1;
567 purged += 1;
566 }
568 }
569 if (purgedIds.length > 0 && typeof this.onDimensionsPurged === "function")
570 {
571 try
572 { this.onDimensionsPurged(purgedIds); }
573 catch (error)
574 { console.error("onDimensionsPurged failed:", error?.message ?? error); }
575 }
567 return purged;
576 return purged;
568 }
577 }
569
578
579 hasChunkVersion (chunkX, chunkY, revisionId, dimensionId = OVERWORLD_ID)
580 {
581 const dim = normalizeDimensionId(dimensionId);
582 const row = this.db.prepare(`
583 SELECT revision_id
584 FROM world_chunk_versions
585 WHERE dimension_id = ? AND chunk_x = ? AND chunk_y = ? AND revision_id <= ?
586 ORDER BY revision_id DESC
587 LIMIT 1
588 `).get(dim, chunkX, chunkY, revisionId);
589 return !!row;
590 }
591
570 getChunkVersion (chunkX, chunkY, revisionId, dimensionId = OVERWORLD_ID)
592 getChunkVersion (chunkX, chunkY, revisionId, dimensionId = OVERWORLD_ID)
571 {
593 {
572 const dim = normalizeDimensionId(dimensionId);
594 const dim = normalizeDimensionId(dimensionId);
server/tests/minimap-cache.test.js added +119 −0
@@ -0,0 +1,119 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mkdtempSync, readFileSync, rmSync, existsSync, unlinkSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { WorldDatabase } from "../src/persistence/worldDb.js";
7 import { EditorService } from "../src/editor/service.js";
8 import { MinimapCache } from "../src/editor/minimapCache.js";
9 import { BlockType, GroundType, installTileAverageColors } from "../../shared/definitions/tiles.js";
10 import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
11 import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
12
13 const GRASS = Object.freeze({ r: 10, g: 200, b: 20 });
14 const DIRT = Object.freeze({ r: 140, g: 80, b: 30 });
15 const WATER = Object.freeze({ r: 20, g: 60, b: 180 });
16 const FLOWER = Object.freeze({ r: 200, g: 20, b: 40 });
17
18 function installFixtureColors ()
19 {
20 installTileAverageColors({
21 grounds: {
22 grass: { typeId: GroundType.grass, averageColor: GRASS, stateColors: {} },
23 dirt: { typeId: GroundType.dirt, averageColor: DIRT, stateColors: {} },
24 water: { typeId: GroundType.water, averageColor: WATER, stateColors: {} }
25 },
26 blocks: {
27 flower: {
28 typeId: BlockType.flower,
29 averageColor: FLOWER,
30 stateColors: { red: FLOWER }
31 }
32 }
33 });
34 }
35
36 function pixel (buffer, index)
37 {
38 const offset = index * 4;
39 return { r: buffer[offset], g: buffer[offset + 1], b: buffer[offset + 2], a: buffer[offset + 3] };
40 }
41
42 test("minimap cache is per dimension, regenerates when missing, and skips chunk blobs when present", () =>
43 {
44 installFixtureColors();
45 const dir = mkdtempSync(join(tmpdir(), "questward-minimap-"));
46 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
47 const cache = new MinimapCache(join(dir, "minimap"), worldDb);
48 cache.syncColorStamp("stamp-a");
49 const editor = new EditorService(worldDb, null, cache);
50 try
51 {
52 const loaded = editor.loadChunk(0, 0, OVERWORLD_ID);
53 const grounds = loaded.data.grounds.map((ground) => ({ typeId: ground.typeId, state: ground.state }));
54 grounds[0] = { typeId: GroundType.dirt, state: null };
55 const blocks = loaded.data.blocks.slice();
56 blocks[1] = { typeId: BlockType.flower, state: "red", config: null };
57 editor.saveChunk(0, 0, {
58 open: true,
59 grounds,
60 blocks,
61 spawners: []
62 }, "auth:test", OVERWORLD_ID);
63
64 const overworldFile = cache.pathFor(OVERWORLD_ID, 0, 0);
65 assert.equal(existsSync(overworldFile), true);
66 const saved = readFileSync(overworldFile);
67 assert.equal(saved.length, CHUNK_SIZE * CHUNK_SIZE * 4);
68 assert.deepEqual(pixel(saved, 0), { ...DIRT, a: 255 });
69 assert.deepEqual(pixel(saved, 1), { ...FLOWER, a: 255 });
70 assert.deepEqual(pixel(saved, 2), { ...GRASS, a: 255 });
71
72 const windowed = editor.minimapWindow(0, 0, OVERWORLD_ID);
73 assert.equal(windowed.span, 25);
74 assert.equal(windowed.chunkPixels, 16);
75 assert.equal(windowed.dimensionId, OVERWORLD_ID);
76 assert.ok(windowed.chunks["0,0"]);
77 assert.equal(windowed.chunks["4,4"], undefined);
78 assert.equal(Object.keys(windowed.chunks).length, 1);
79
80 unlinkSync(overworldFile);
81 const rebuilt = Buffer.from(editor.minimapWindow(0, 0, OVERWORLD_ID).chunks["0,0"], "base64");
82 assert.equal(existsSync(overworldFile), true);
83 assert.deepEqual(pixel(rebuilt, 0), { ...DIRT, a: 255 });
84 assert.deepEqual(pixel(rebuilt, 1), { ...FLOWER, a: 255 });
85
86 editor.createDimension("cave", "Cave", "auth:test");
87 const caveLoaded = editor.loadChunk(0, 0, "cave");
88 const caveGrounds = caveLoaded.data.grounds.map(() => ({ typeId: GroundType.water, state: null }));
89 editor.saveChunk(0, 0, {
90 open: true,
91 grounds: caveGrounds,
92 blocks: caveLoaded.data.blocks,
93 spawners: []
94 }, "auth:test", "cave");
95 const caveFile = cache.pathFor("cave", 0, 0);
96 assert.notEqual(caveFile, overworldFile);
97 assert.deepEqual(pixel(readFileSync(caveFile), 0), { ...WATER, a: 255 });
98 const caveWindow = editor.minimapWindow(0, 0, "Cave");
99 assert.ok(caveWindow.chunks["0,0"]);
100 assert.equal(caveWindow.chunks["4,4"], undefined);
101 assert.ok(editor.minimapWindow(0, 0, OVERWORLD_ID).chunks["0,0"]);
102
103 worldDb.db.prepare(`
104 UPDATE world_chunk_versions SET data_blob = ? WHERE dimension_id = ? AND chunk_x = 0 AND chunk_y = 0
105 `).run("not-json", OVERWORLD_ID);
106 const fromCache = Buffer.from(editor.minimapWindow(0, 0, OVERWORLD_ID).chunks["0,0"], "base64");
107 assert.deepEqual(pixel(fromCache, 0), { ...DIRT, a: 255 });
108
109 cache.syncColorStamp("stamp-b");
110 assert.equal(existsSync(caveFile), false);
111 assert.equal(existsSync(join(dir, "minimap", "color-stamp.txt")), true);
112 assert.equal(readFileSync(join(dir, "minimap", "color-stamp.txt"), "utf8"), "stamp-b");
113 }
114 finally
115 {
116 worldDb.close();
117 rmSync(dir, { recursive: true, force: true });
118 }
119 });
@@ -0,0 +1,119 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mkdtempSync, readFileSync, rmSync, existsSync, unlinkSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { WorldDatabase } from "../src/persistence/worldDb.js";
7import { EditorService } from "../src/editor/service.js";
8import { MinimapCache } from "../src/editor/minimapCache.js";
9import { BlockType, GroundType, installTileAverageColors } from "../../shared/definitions/tiles.js";
10import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
11import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
12
13const GRASS = Object.freeze({ r: 10, g: 200, b: 20 });
14const DIRT = Object.freeze({ r: 140, g: 80, b: 30 });
15const WATER = Object.freeze({ r: 20, g: 60, b: 180 });
16const FLOWER = Object.freeze({ r: 200, g: 20, b: 40 });
17
18function installFixtureColors ()
19{
20 installTileAverageColors({
21 grounds: {
22 grass: { typeId: GroundType.grass, averageColor: GRASS, stateColors: {} },
23 dirt: { typeId: GroundType.dirt, averageColor: DIRT, stateColors: {} },
24 water: { typeId: GroundType.water, averageColor: WATER, stateColors: {} }
25 },
26 blocks: {
27 flower: {
28 typeId: BlockType.flower,
29 averageColor: FLOWER,
30 stateColors: { red: FLOWER }
31 }
32 }
33 });
34}
35
36function pixel (buffer, index)
37{
38 const offset = index * 4;
39 return { r: buffer[offset], g: buffer[offset + 1], b: buffer[offset + 2], a: buffer[offset + 3] };
40}
41
42test("minimap cache is per dimension, regenerates when missing, and skips chunk blobs when present", () =>
43{
44 installFixtureColors();
45 const dir = mkdtempSync(join(tmpdir(), "questward-minimap-"));
46 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
47 const cache = new MinimapCache(join(dir, "minimap"), worldDb);
48 cache.syncColorStamp("stamp-a");
49 const editor = new EditorService(worldDb, null, cache);
50 try
51 {
52 const loaded = editor.loadChunk(0, 0, OVERWORLD_ID);
53 const grounds = loaded.data.grounds.map((ground) => ({ typeId: ground.typeId, state: ground.state }));
54 grounds[0] = { typeId: GroundType.dirt, state: null };
55 const blocks = loaded.data.blocks.slice();
56 blocks[1] = { typeId: BlockType.flower, state: "red", config: null };
57 editor.saveChunk(0, 0, {
58 open: true,
59 grounds,
60 blocks,
61 spawners: []
62 }, "auth:test", OVERWORLD_ID);
63
64 const overworldFile = cache.pathFor(OVERWORLD_ID, 0, 0);
65 assert.equal(existsSync(overworldFile), true);
66 const saved = readFileSync(overworldFile);
67 assert.equal(saved.length, CHUNK_SIZE * CHUNK_SIZE * 4);
68 assert.deepEqual(pixel(saved, 0), { ...DIRT, a: 255 });
69 assert.deepEqual(pixel(saved, 1), { ...FLOWER, a: 255 });
70 assert.deepEqual(pixel(saved, 2), { ...GRASS, a: 255 });
71
72 const windowed = editor.minimapWindow(0, 0, OVERWORLD_ID);
73 assert.equal(windowed.span, 25);
74 assert.equal(windowed.chunkPixels, 16);
75 assert.equal(windowed.dimensionId, OVERWORLD_ID);
76 assert.ok(windowed.chunks["0,0"]);
77 assert.equal(windowed.chunks["4,4"], undefined);
78 assert.equal(Object.keys(windowed.chunks).length, 1);
79
80 unlinkSync(overworldFile);
81 const rebuilt = Buffer.from(editor.minimapWindow(0, 0, OVERWORLD_ID).chunks["0,0"], "base64");
82 assert.equal(existsSync(overworldFile), true);
83 assert.deepEqual(pixel(rebuilt, 0), { ...DIRT, a: 255 });
84 assert.deepEqual(pixel(rebuilt, 1), { ...FLOWER, a: 255 });
85
86 editor.createDimension("cave", "Cave", "auth:test");
87 const caveLoaded = editor.loadChunk(0, 0, "cave");
88 const caveGrounds = caveLoaded.data.grounds.map(() => ({ typeId: GroundType.water, state: null }));
89 editor.saveChunk(0, 0, {
90 open: true,
91 grounds: caveGrounds,
92 blocks: caveLoaded.data.blocks,
93 spawners: []
94 }, "auth:test", "cave");
95 const caveFile = cache.pathFor("cave", 0, 0);
96 assert.notEqual(caveFile, overworldFile);
97 assert.deepEqual(pixel(readFileSync(caveFile), 0), { ...WATER, a: 255 });
98 const caveWindow = editor.minimapWindow(0, 0, "Cave");
99 assert.ok(caveWindow.chunks["0,0"]);
100 assert.equal(caveWindow.chunks["4,4"], undefined);
101 assert.ok(editor.minimapWindow(0, 0, OVERWORLD_ID).chunks["0,0"]);
102
103 worldDb.db.prepare(`
104 UPDATE world_chunk_versions SET data_blob = ? WHERE dimension_id = ? AND chunk_x = 0 AND chunk_y = 0
105 `).run("not-json", OVERWORLD_ID);
106 const fromCache = Buffer.from(editor.minimapWindow(0, 0, OVERWORLD_ID).chunks["0,0"], "base64");
107 assert.deepEqual(pixel(fromCache, 0), { ...DIRT, a: 255 });
108
109 cache.syncColorStamp("stamp-b");
110 assert.equal(existsSync(caveFile), false);
111 assert.equal(existsSync(join(dir, "minimap", "color-stamp.txt")), true);
112 assert.equal(readFileSync(join(dir, "minimap", "color-stamp.txt"), "utf8"), "stamp-b");
113 }
114 finally
115 {
116 worldDb.close();
117 rmSync(dir, { recursive: true, force: true });
118 }
119});
server/tests/tile-average-colors.test.js added +137 −0
@@ -0,0 +1,137 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { fileURLToPath } from "node:url";
4 import { join } from "node:path";
5 import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
6 import { AVERAGE_COLOR_ALPHA_THRESHOLD, averageOpaqueColor } from "../../shared/render/averageSpriteColor.js";
7 import
8 {
9 BlockType,
10 GroundType,
11 BLOCK_DEFINITIONS,
12 GROUND_DEFINITIONS,
13 blockAverageColor,
14 groundAverageColor,
15 installTileAverageColors
16 } from "../../shared/definitions/tiles.js";
17 import { minimapChunkAtPixel, renderChunkMinimapRgba } from "../../shared/render/chunkMinimap.js";
18 import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
19
20 const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
21
22 test("average colour ignores pixels at or below the alpha threshold", () =>
23 {
24 assert.equal(AVERAGE_COLOR_ALPHA_THRESHOLD, 16);
25 const rgba = new Uint8ClampedArray([
26 255, 0, 0, 16,
27 0, 0, 255, 17,
28 0, 255, 0, 255
29 ]);
30 assert.deepEqual(averageOpaqueColor(rgba, 3, 1), { r: 0, g: 128, b: 128 });
31 assert.equal(averageOpaqueColor(new Uint8ClampedArray([0, 0, 0, 0, 1, 2, 3, 16]), 2, 1), null);
32 });
33
34 test("registry falls back from an unknown state to the type colour", () =>
35 {
36 installTileAverageColors({
37 grounds: {
38 grass: {
39 typeId: GroundType.grass,
40 averageColor: { r: 1, g: 2, b: 3 },
41 stateColors: { summer: { r: 4, g: 5, b: 6 } }
42 }
43 },
44 blocks: {
45 flower: {
46 typeId: BlockType.flower,
47 averageColor: { r: 9, g: 0, b: 0 },
48 stateColors: { blue: { r: 0, g: 0, b: 9 } }
49 }
50 }
51 });
52 assert.deepEqual(groundAverageColor(GroundType.grass), { r: 1, g: 2, b: 3 });
53 assert.deepEqual(groundAverageColor(GroundType.grass, "summer"), { r: 4, g: 5, b: 6 });
54 assert.deepEqual(groundAverageColor(GroundType.grass, "missing"), { r: 1, g: 2, b: 3 });
55 assert.deepEqual(blockAverageColor(BlockType.flower, "blue"), { r: 0, g: 0, b: 9 });
56 assert.deepEqual(blockAverageColor(BlockType.flower, "nope"), { r: 9, g: 0, b: 0 });
57 assert.equal(blockAverageColor(9999), null);
58 assert.equal(groundAverageColor(null), null);
59 });
60
61 test("minimap pixels prefer the block colour and map clicks onto chunks", () =>
62 {
63 installTileAverageColors({
64 grounds: {
65 grass: {
66 typeId: GroundType.grass,
67 averageColor: { r: 10, g: 200, b: 20 },
68 stateColors: {}
69 }
70 },
71 blocks: {
72 flower: {
73 typeId: BlockType.flower,
74 averageColor: { r: 200, g: 20, b: 40 },
75 stateColors: { red: { r: 200, g: 20, b: 40 } }
76 }
77 }
78 });
79 const grounds = new Array(CHUNK_SIZE * CHUNK_SIZE).fill({ typeId: GroundType.grass, state: null });
80 const blocks = new Array(CHUNK_SIZE * CHUNK_SIZE).fill(null);
81 blocks[0] = { typeId: BlockType.flower, state: "red" };
82 const rgba = renderChunkMinimapRgba({ grounds, blocks });
83 assert.equal(rgba[0], 200);
84 assert.equal(rgba[1], 20);
85 assert.equal(rgba[4], 10);
86 assert.equal(rgba[5], 200);
87
88 assert.equal(CHUNK_SIZE, 16);
89 assert.deepEqual(minimapChunkAtPixel(0, 0, 5, -3), { chunkX: 5 - 12, chunkY: -3 - 12 });
90 assert.deepEqual(minimapChunkAtPixel(12 * 16, 12 * 16, 5, -3), { chunkX: 5, chunkY: -3 });
91 assert.deepEqual(minimapChunkAtPixel(24 * 16, 24 * 16, 0, 0), { chunkX: 12, chunkY: 12 });
92 assert.equal(minimapChunkAtPixel(25 * 16, 0, 0, 0), null);
93 assert.equal(minimapChunkAtPixel(-1, 0, 0, 0), null);
94 });
95
96 test("every ground and block colour comes from its sprites", () =>
97 {
98 const catalog = buildSpriteCatalog(ASSET_ROOT);
99 for (const def of Object.values(GROUND_DEFINITIONS))
100 {
101 const color = groundAverageColor(def.id);
102 assert.ok(color, `missing ground colour for ${def.key}`);
103 assert.deepEqual(color, catalog.grounds[def.key].averageColor);
104 for (const state of catalog.grounds[def.key].states)
105 {
106 assert.ok(groundAverageColor(def.id, state), `${def.key}:${state}`);
107 }
108 }
109 for (const def of Object.values(BLOCK_DEFINITIONS))
110 {
111 const color = blockAverageColor(def.id);
112 assert.ok(color, `missing block colour for ${def.key}`);
113 const entry = catalog.blocks[def.key];
114 assert.ok(entry, def.key);
115 assert.deepEqual(color, entry.averageColor);
116 for (const state of entry.states)
117 { assert.ok(blockAverageColor(def.id, state), `${def.key}:${state}`); }
118 }
119
120 const summer = groundAverageColor(GroundType.grass, "summer");
121 const winter = groundAverageColor(GroundType.grass, "winter");
122 assert.ok(summer.g > summer.r && summer.g > summer.b, JSON.stringify(summer));
123 assert.notDeepEqual(summer, winter);
124 assert.deepEqual(groundAverageColor(GroundType.grass), summer);
125
126 const water = groundAverageColor(GroundType.water);
127 const lava = groundAverageColor(GroundType.lava);
128 const ice = groundAverageColor(GroundType.water, "water-winter");
129 assert.ok(water.b > water.r + 20, JSON.stringify(water));
130 assert.ok(lava.r > lava.g && lava.r > lava.b, JSON.stringify(lava));
131 assert.notDeepEqual(water, ice);
132
133 const red = blockAverageColor(BlockType.flower, "red");
134 const blue = blockAverageColor(BlockType.flower, "blue");
135 assert.ok(red.r > blue.r, JSON.stringify({ red, blue }));
136 assert.ok(blue.b > red.b, JSON.stringify({ red, blue }));
137 });
@@ -0,0 +1,137 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { fileURLToPath } from "node:url";
4import { join } from "node:path";
5import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
6import { AVERAGE_COLOR_ALPHA_THRESHOLD, averageOpaqueColor } from "../../shared/render/averageSpriteColor.js";
7import
8{
9 BlockType,
10 GroundType,
11 BLOCK_DEFINITIONS,
12 GROUND_DEFINITIONS,
13 blockAverageColor,
14 groundAverageColor,
15 installTileAverageColors
16} from "../../shared/definitions/tiles.js";
17import { minimapChunkAtPixel, renderChunkMinimapRgba } from "../../shared/render/chunkMinimap.js";
18import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
19
20const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
21
22test("average colour ignores pixels at or below the alpha threshold", () =>
23{
24 assert.equal(AVERAGE_COLOR_ALPHA_THRESHOLD, 16);
25 const rgba = new Uint8ClampedArray([
26 255, 0, 0, 16,
27 0, 0, 255, 17,
28 0, 255, 0, 255
29 ]);
30 assert.deepEqual(averageOpaqueColor(rgba, 3, 1), { r: 0, g: 128, b: 128 });
31 assert.equal(averageOpaqueColor(new Uint8ClampedArray([0, 0, 0, 0, 1, 2, 3, 16]), 2, 1), null);
32});
33
34test("registry falls back from an unknown state to the type colour", () =>
35{
36 installTileAverageColors({
37 grounds: {
38 grass: {
39 typeId: GroundType.grass,
40 averageColor: { r: 1, g: 2, b: 3 },
41 stateColors: { summer: { r: 4, g: 5, b: 6 } }
42 }
43 },
44 blocks: {
45 flower: {
46 typeId: BlockType.flower,
47 averageColor: { r: 9, g: 0, b: 0 },
48 stateColors: { blue: { r: 0, g: 0, b: 9 } }
49 }
50 }
51 });
52 assert.deepEqual(groundAverageColor(GroundType.grass), { r: 1, g: 2, b: 3 });
53 assert.deepEqual(groundAverageColor(GroundType.grass, "summer"), { r: 4, g: 5, b: 6 });
54 assert.deepEqual(groundAverageColor(GroundType.grass, "missing"), { r: 1, g: 2, b: 3 });
55 assert.deepEqual(blockAverageColor(BlockType.flower, "blue"), { r: 0, g: 0, b: 9 });
56 assert.deepEqual(blockAverageColor(BlockType.flower, "nope"), { r: 9, g: 0, b: 0 });
57 assert.equal(blockAverageColor(9999), null);
58 assert.equal(groundAverageColor(null), null);
59});
60
61test("minimap pixels prefer the block colour and map clicks onto chunks", () =>
62{
63 installTileAverageColors({
64 grounds: {
65 grass: {
66 typeId: GroundType.grass,
67 averageColor: { r: 10, g: 200, b: 20 },
68 stateColors: {}
69 }
70 },
71 blocks: {
72 flower: {
73 typeId: BlockType.flower,
74 averageColor: { r: 200, g: 20, b: 40 },
75 stateColors: { red: { r: 200, g: 20, b: 40 } }
76 }
77 }
78 });
79 const grounds = new Array(CHUNK_SIZE * CHUNK_SIZE).fill({ typeId: GroundType.grass, state: null });
80 const blocks = new Array(CHUNK_SIZE * CHUNK_SIZE).fill(null);
81 blocks[0] = { typeId: BlockType.flower, state: "red" };
82 const rgba = renderChunkMinimapRgba({ grounds, blocks });
83 assert.equal(rgba[0], 200);
84 assert.equal(rgba[1], 20);
85 assert.equal(rgba[4], 10);
86 assert.equal(rgba[5], 200);
87
88 assert.equal(CHUNK_SIZE, 16);
89 assert.deepEqual(minimapChunkAtPixel(0, 0, 5, -3), { chunkX: 5 - 12, chunkY: -3 - 12 });
90 assert.deepEqual(minimapChunkAtPixel(12 * 16, 12 * 16, 5, -3), { chunkX: 5, chunkY: -3 });
91 assert.deepEqual(minimapChunkAtPixel(24 * 16, 24 * 16, 0, 0), { chunkX: 12, chunkY: 12 });
92 assert.equal(minimapChunkAtPixel(25 * 16, 0, 0, 0), null);
93 assert.equal(minimapChunkAtPixel(-1, 0, 0, 0), null);
94});
95
96test("every ground and block colour comes from its sprites", () =>
97{
98 const catalog = buildSpriteCatalog(ASSET_ROOT);
99 for (const def of Object.values(GROUND_DEFINITIONS))
100 {
101 const color = groundAverageColor(def.id);
102 assert.ok(color, `missing ground colour for ${def.key}`);
103 assert.deepEqual(color, catalog.grounds[def.key].averageColor);
104 for (const state of catalog.grounds[def.key].states)
105 {
106 assert.ok(groundAverageColor(def.id, state), `${def.key}:${state}`);
107 }
108 }
109 for (const def of Object.values(BLOCK_DEFINITIONS))
110 {
111 const color = blockAverageColor(def.id);
112 assert.ok(color, `missing block colour for ${def.key}`);
113 const entry = catalog.blocks[def.key];
114 assert.ok(entry, def.key);
115 assert.deepEqual(color, entry.averageColor);
116 for (const state of entry.states)
117 { assert.ok(blockAverageColor(def.id, state), `${def.key}:${state}`); }
118 }
119
120 const summer = groundAverageColor(GroundType.grass, "summer");
121 const winter = groundAverageColor(GroundType.grass, "winter");
122 assert.ok(summer.g > summer.r && summer.g > summer.b, JSON.stringify(summer));
123 assert.notDeepEqual(summer, winter);
124 assert.deepEqual(groundAverageColor(GroundType.grass), summer);
125
126 const water = groundAverageColor(GroundType.water);
127 const lava = groundAverageColor(GroundType.lava);
128 const ice = groundAverageColor(GroundType.water, "water-winter");
129 assert.ok(water.b > water.r + 20, JSON.stringify(water));
130 assert.ok(lava.r > lava.g && lava.r > lava.b, JSON.stringify(lava));
131 assert.notDeepEqual(water, ice);
132
133 const red = blockAverageColor(BlockType.flower, "red");
134 const blue = blockAverageColor(BlockType.flower, "blue");
135 assert.ok(red.r > blue.r, JSON.stringify({ red, blue }));
136 assert.ok(blue.b > red.b, JSON.stringify({ red, blue }));
137});
shared/definitions/tiles.js +12 −0
@@ -35,6 +35,18 @@ import {
35 35 isDoorPassageOpen
36 36 } from "../world/doors.js";
37 37
38 /**
39 * Average sprite colour for a ground or block, including per-state colours when
40 * states use different art. Populated from the sprite catalog at load.
41 * Pixels with alpha <= AVERAGE_COLOR_ALPHA_THRESHOLD (16) are ignored.
42 */
43 export {
44 AVERAGE_COLOR_ALPHA_THRESHOLD,
45 installTileAverageColors,
46 groundAverageColor,
47 blockAverageColor
48 } from "../render/tileAverageColors.js";
49
38 50 export const GroundType = Object.freeze({
39 51 grass: 1,
40 52 wood: 2,
@@ -35,6 +35,18 @@ import {
35 isDoorPassageOpen
35 isDoorPassageOpen
36} from "../world/doors.js";
36} from "../world/doors.js";
37
37
38/**
39 * Average sprite colour for a ground or block, including per-state colours when
40 * states use different art. Populated from the sprite catalog at load.
41 * Pixels with alpha <= AVERAGE_COLOR_ALPHA_THRESHOLD (16) are ignored.
42 */
43export {
44 AVERAGE_COLOR_ALPHA_THRESHOLD,
45 installTileAverageColors,
46 groundAverageColor,
47 blockAverageColor
48} from "../render/tileAverageColors.js";
49
38export const GroundType = Object.freeze({
50export const GroundType = Object.freeze({
39 grass: 1,
51 grass: 1,
40 wood: 2,
52 wood: 2,
shared/protocol/constants.js +2 −0
@@ -116,6 +116,8 @@ export const MessageType = Object.freeze({
116 116 editorLoadChunk: "EDITOR_LOAD_CHUNK",
117 117 editorChunk: "EDITOR_CHUNK",
118 118 editorSaveChunk: "EDITOR_SAVE_CHUNK",
119 editorRequestMinimap: "EDITOR_REQUEST_MINIMAP",
120 editorMinimap: "EDITOR_MINIMAP",
119 121 editorSaveSettings: "EDITOR_SAVE_SETTINGS",
120 122 editorLoadSettings: "EDITOR_LOAD_SETTINGS",
121 123 editorSettings: "EDITOR_SETTINGS",
@@ -116,6 +116,8 @@ export const MessageType = Object.freeze({
116 editorLoadChunk: "EDITOR_LOAD_CHUNK",
116 editorLoadChunk: "EDITOR_LOAD_CHUNK",
117 editorChunk: "EDITOR_CHUNK",
117 editorChunk: "EDITOR_CHUNK",
118 editorSaveChunk: "EDITOR_SAVE_CHUNK",
118 editorSaveChunk: "EDITOR_SAVE_CHUNK",
119 editorRequestMinimap: "EDITOR_REQUEST_MINIMAP",
120 editorMinimap: "EDITOR_MINIMAP",
119 editorSaveSettings: "EDITOR_SAVE_SETTINGS",
121 editorSaveSettings: "EDITOR_SAVE_SETTINGS",
120 editorLoadSettings: "EDITOR_LOAD_SETTINGS",
122 editorLoadSettings: "EDITOR_LOAD_SETTINGS",
121 editorSettings: "EDITOR_SETTINGS",
123 editorSettings: "EDITOR_SETTINGS",
shared/render/averageSpriteColor.js added +48 −0
@@ -0,0 +1,48 @@
1 /**
2 * Average colour of a sprite's visible pixels.
3 *
4 * Pixels with alpha less than or equal to {@link AVERAGE_COLOR_ALPHA_THRESHOLD}
5 * are treated as transparent and do not affect the average. That drops fully
6 * transparent texels and the faintest antialias fringe (~6% opacity), while
7 * still counting visibly translucent pixels.
8 *
9 * Surviving pixels are weighted equally: alpha is a mask, not a weight.
10 * Callers pass the whole texture, so every frame of a spritesheet is included.
11 */
12 export const AVERAGE_COLOR_ALPHA_THRESHOLD = 16;
13
14 /**
15 * Arithmetic mean RGB of pixels whose alpha is above the threshold.
16 * @param {Uint8Array | Uint8ClampedArray} rgba
17 * @param {number} width
18 * @param {number} height
19 * @param {{ alphaThreshold?: number }} [options]
20 * @returns {{ r: number, g: number, b: number } | null} 0–255 channels, or null when nothing is visible
21 */
22 export function averageOpaqueColor (rgba, width, height, options = {})
23 {
24 const threshold = options.alphaThreshold ?? AVERAGE_COLOR_ALPHA_THRESHOLD;
25 const pixels = Math.max(0, width | 0) * Math.max(0, height | 0);
26 let red = 0;
27 let green = 0;
28 let blue = 0;
29 let count = 0;
30 for (let i = 0; i < pixels; i++)
31 {
32 const offset = i * 4;
33 const alpha = rgba[offset + 3] ?? 0;
34 if (alpha <= threshold)
35 { continue; }
36 red += rgba[offset] ?? 0;
37 green += rgba[offset + 1] ?? 0;
38 blue += rgba[offset + 2] ?? 0;
39 count += 1;
40 }
41 if (count === 0)
42 { return null; }
43 return {
44 r: Math.round(red / count),
45 g: Math.round(green / count),
46 b: Math.round(blue / count)
47 };
48 }
@@ -0,0 +1,48 @@
1/**
2 * Average colour of a sprite's visible pixels.
3 *
4 * Pixels with alpha less than or equal to {@link AVERAGE_COLOR_ALPHA_THRESHOLD}
5 * are treated as transparent and do not affect the average. That drops fully
6 * transparent texels and the faintest antialias fringe (~6% opacity), while
7 * still counting visibly translucent pixels.
8 *
9 * Surviving pixels are weighted equally: alpha is a mask, not a weight.
10 * Callers pass the whole texture, so every frame of a spritesheet is included.
11 */
12export const AVERAGE_COLOR_ALPHA_THRESHOLD = 16;
13
14/**
15 * Arithmetic mean RGB of pixels whose alpha is above the threshold.
16 * @param {Uint8Array | Uint8ClampedArray} rgba
17 * @param {number} width
18 * @param {number} height
19 * @param {{ alphaThreshold?: number }} [options]
20 * @returns {{ r: number, g: number, b: number } | null} 0–255 channels, or null when nothing is visible
21 */
22export function averageOpaqueColor (rgba, width, height, options = {})
23{
24 const threshold = options.alphaThreshold ?? AVERAGE_COLOR_ALPHA_THRESHOLD;
25 const pixels = Math.max(0, width | 0) * Math.max(0, height | 0);
26 let red = 0;
27 let green = 0;
28 let blue = 0;
29 let count = 0;
30 for (let i = 0; i < pixels; i++)
31 {
32 const offset = i * 4;
33 const alpha = rgba[offset + 3] ?? 0;
34 if (alpha <= threshold)
35 { continue; }
36 red += rgba[offset] ?? 0;
37 green += rgba[offset + 1] ?? 0;
38 blue += rgba[offset + 2] ?? 0;
39 count += 1;
40 }
41 if (count === 0)
42 { return null; }
43 return {
44 r: Math.round(red / count),
45 g: Math.round(green / count),
46 b: Math.round(blue / count)
47 };
48}
shared/render/chunkMinimap.js added +86 −0
@@ -0,0 +1,86 @@
1 import { CHUNK_SIZE } from "../protocol/constants.js";
2 import
3 {
4 GroundType,
5 normalizeGround,
6 normalizeBlock,
7 groundAverageColor,
8 blockAverageColor
9 } from "../definitions/tiles.js";
10
11 /** Odd span so one chunk sits in the centre of the editor minimap. */
12 export const MINIMAP_SPAN_CHUNKS = 25;
13
14 /**
15 * One minimap pixel per tile. Chunks are {@link CHUNK_SIZE} tiles on a side
16 * (16 today), so each cached chunk image is that many pixels square.
17 */
18 export const MINIMAP_CHUNK_PIXELS = CHUNK_SIZE;
19
20 /** Unauthored / missing chunks. Matches the editor sidebar (`#1a1e26`). */
21 export const MINIMAP_EMPTY_COLOR = Object.freeze({ r: 0x1a, g: 0x1e, b: 0x26 });
22
23 /** Saved tile whose sprite has no computed colour. */
24 export const MINIMAP_MISSING_COLOR = Object.freeze({ r: 0x3a, g: 0x42, b: 0x50 });
25
26 export function minimapRadius (span = MINIMAP_SPAN_CHUNKS)
27 {
28 return (span - 1) >> 1;
29 }
30
31 /**
32 * Chunk under a minimap pixel. Coordinates are in the bitmap's pixel space
33 * (top-left of the whole minimap is 0, 0), not CSS pixels.
34 * @returns {{ chunkX: number, chunkY: number } | null}
35 */
36 export function minimapChunkAtPixel (
37 pixelX,
38 pixelY,
39 centerChunkX,
40 centerChunkY,
41 span = MINIMAP_SPAN_CHUNKS,
42 chunkPixels = MINIMAP_CHUNK_PIXELS
43 )
44 {
45 if (!Number.isFinite(pixelX) || !Number.isFinite(pixelY) || chunkPixels <= 0)
46 { return null; }
47 const col = Math.floor(pixelX / chunkPixels);
48 const row = Math.floor(pixelY / chunkPixels);
49 if (col < 0 || row < 0 || col >= span || row >= span)
50 { return null; }
51 const radius = minimapRadius(span);
52 return {
53 chunkX: (centerChunkX | 0) + col - radius,
54 chunkY: (centerChunkY | 0) + row - radius
55 };
56 }
57
58 /**
59 * 16×16 (or chunk-sized) RGBA image for one saved chunk.
60 * A block colour wins where a block is present; otherwise the ground colour.
61 * Uses the authored state when that state has its own colour, else the type default.
62 * @param {{ grounds?: unknown[], blocks?: unknown[] } | null | undefined} chunkData
63 * @param {number} [fallbackGroundTypeId]
64 * @returns {Uint8ClampedArray}
65 */
66 export function renderChunkMinimapRgba (chunkData, fallbackGroundTypeId = GroundType.grass)
67 {
68 const tileCount = MINIMAP_CHUNK_PIXELS * MINIMAP_CHUNK_PIXELS;
69 const rgba = new Uint8ClampedArray(tileCount * 4);
70 const grounds = chunkData?.grounds ?? [];
71 const blocks = chunkData?.blocks ?? [];
72 for (let index = 0; index < tileCount; index++)
73 {
74 const block = normalizeBlock(blocks[index]);
75 const ground = normalizeGround(grounds[index], fallbackGroundTypeId);
76 const color = (block && blockAverageColor(block.typeId, block.state))
77 || groundAverageColor(ground.typeId, ground.state)
78 || MINIMAP_MISSING_COLOR;
79 const offset = index * 4;
80 rgba[offset] = color.r;
81 rgba[offset + 1] = color.g;
82 rgba[offset + 2] = color.b;
83 rgba[offset + 3] = 255;
84 }
85 return rgba;
86 }
@@ -0,0 +1,86 @@
1import { CHUNK_SIZE } from "../protocol/constants.js";
2import
3{
4 GroundType,
5 normalizeGround,
6 normalizeBlock,
7 groundAverageColor,
8 blockAverageColor
9} from "../definitions/tiles.js";
10
11/** Odd span so one chunk sits in the centre of the editor minimap. */
12export const MINIMAP_SPAN_CHUNKS = 25;
13
14/**
15 * One minimap pixel per tile. Chunks are {@link CHUNK_SIZE} tiles on a side
16 * (16 today), so each cached chunk image is that many pixels square.
17 */
18export const MINIMAP_CHUNK_PIXELS = CHUNK_SIZE;
19
20/** Unauthored / missing chunks. Matches the editor sidebar (`#1a1e26`). */
21export const MINIMAP_EMPTY_COLOR = Object.freeze({ r: 0x1a, g: 0x1e, b: 0x26 });
22
23/** Saved tile whose sprite has no computed colour. */
24export const MINIMAP_MISSING_COLOR = Object.freeze({ r: 0x3a, g: 0x42, b: 0x50 });
25
26export function minimapRadius (span = MINIMAP_SPAN_CHUNKS)
27{
28 return (span - 1) >> 1;
29}
30
31/**
32 * Chunk under a minimap pixel. Coordinates are in the bitmap's pixel space
33 * (top-left of the whole minimap is 0, 0), not CSS pixels.
34 * @returns {{ chunkX: number, chunkY: number } | null}
35 */
36export function minimapChunkAtPixel (
37 pixelX,
38 pixelY,
39 centerChunkX,
40 centerChunkY,
41 span = MINIMAP_SPAN_CHUNKS,
42 chunkPixels = MINIMAP_CHUNK_PIXELS
43)
44{
45 if (!Number.isFinite(pixelX) || !Number.isFinite(pixelY) || chunkPixels <= 0)
46 { return null; }
47 const col = Math.floor(pixelX / chunkPixels);
48 const row = Math.floor(pixelY / chunkPixels);
49 if (col < 0 || row < 0 || col >= span || row >= span)
50 { return null; }
51 const radius = minimapRadius(span);
52 return {
53 chunkX: (centerChunkX | 0) + col - radius,
54 chunkY: (centerChunkY | 0) + row - radius
55 };
56}
57
58/**
59 * 16×16 (or chunk-sized) RGBA image for one saved chunk.
60 * A block colour wins where a block is present; otherwise the ground colour.
61 * Uses the authored state when that state has its own colour, else the type default.
62 * @param {{ grounds?: unknown[], blocks?: unknown[] } | null | undefined} chunkData
63 * @param {number} [fallbackGroundTypeId]
64 * @returns {Uint8ClampedArray}
65 */
66export function renderChunkMinimapRgba (chunkData, fallbackGroundTypeId = GroundType.grass)
67{
68 const tileCount = MINIMAP_CHUNK_PIXELS * MINIMAP_CHUNK_PIXELS;
69 const rgba = new Uint8ClampedArray(tileCount * 4);
70 const grounds = chunkData?.grounds ?? [];
71 const blocks = chunkData?.blocks ?? [];
72 for (let index = 0; index < tileCount; index++)
73 {
74 const block = normalizeBlock(blocks[index]);
75 const ground = normalizeGround(grounds[index], fallbackGroundTypeId);
76 const color = (block && blockAverageColor(block.typeId, block.state))
77 || groundAverageColor(ground.typeId, ground.state)
78 || MINIMAP_MISSING_COLOR;
79 const offset = index * 4;
80 rgba[offset] = color.r;
81 rgba[offset + 1] = color.g;
82 rgba[offset + 2] = color.b;
83 rgba[offset + 3] = 255;
84 }
85 return rgba;
86}
shared/render/tileAverageColors.js added +113 −0
@@ -0,0 +1,113 @@
1 /**
2 * Registry of average sprite colours for grounds and blocks.
3 *
4 * Filled by {@link installTileAverageColors} from a sprite catalog that already
5 * carries `averageColor` / `stateColors` (the server computes those from PNGs
6 * when it builds the catalog). Game code asks {@link groundAverageColor} or
7 * {@link blockAverageColor} rather than sampling textures itself.
8 *
9 * A missing state falls back to the type's default-state colour. A missing
10 * type returns null.
11 */
12
13 const groundColors = new Map();
14 const blockColors = new Map();
15
16 /**
17 * @param {object | null | undefined} catalog
18 */
19 export function installTileAverageColors (catalog)
20 {
21 groundColors.clear();
22 blockColors.clear();
23 installGroup(groundColors, catalog?.grounds);
24 installGroup(blockColors, catalog?.blocks);
25 }
26
27 /**
28 * @param {number | string | null | undefined} typeId
29 * @param {string | null | undefined} [state]
30 * @returns {{ r: number, g: number, b: number } | null}
31 */
32 export function groundAverageColor (typeId, state = null)
33 {
34 return lookupAverageColor(groundColors, typeId, state);
35 }
36
37 /**
38 * @param {number | string | null | undefined} typeId
39 * @param {string | null | undefined} [state]
40 * @returns {{ r: number, g: number, b: number } | null}
41 */
42 export function blockAverageColor (typeId, state = null)
43 {
44 return lookupAverageColor(blockColors, typeId, state);
45 }
46
47 export { AVERAGE_COLOR_ALPHA_THRESHOLD } from "./averageSpriteColor.js";
48
49 function installGroup (target, types)
50 {
51 for (const type of Object.values(types ?? {}))
52 {
53 if (type?.typeId == null)
54 { continue; }
55 const stateColors = {};
56 for (const [state, color] of Object.entries(type.stateColors ?? {}))
57 {
58 const stored = freezeColor(color);
59 if (stored)
60 { stateColors[state] = stored; }
61 }
62 target.set(type.typeId, {
63 averageColor: freezeColor(type.averageColor) ?? firstColor(stateColors),
64 stateColors
65 });
66 }
67 }
68
69 function lookupAverageColor (groups, typeId, state)
70 {
71 if (typeId == null)
72 { return null; }
73 const entry = groups.get(typeId);
74 if (!entry)
75 { return null; }
76 if (state != null && state !== "")
77 {
78 const specific = entry.stateColors[state];
79 if (specific)
80 { return specific; }
81 }
82 return entry.averageColor ?? null;
83 }
84
85 function firstColor (stateColors)
86 {
87 for (const color of Object.values(stateColors))
88 {
89 if (color)
90 { return color; }
91 }
92 return null;
93 }
94
95 function freezeColor (color)
96 {
97 if (!color)
98 { return null; }
99 const r = clampByte(color.r);
100 const g = clampByte(color.g);
101 const b = clampByte(color.b);
102 if (r == null || g == null || b == null)
103 { return null; }
104 return Object.freeze({ r, g, b });
105 }
106
107 function clampByte (value)
108 {
109 const number = Number(value);
110 if (!Number.isFinite(number))
111 { return null; }
112 return Math.max(0, Math.min(255, Math.round(number)));
113 }
@@ -0,0 +1,113 @@
1/**
2 * Registry of average sprite colours for grounds and blocks.
3 *
4 * Filled by {@link installTileAverageColors} from a sprite catalog that already
5 * carries `averageColor` / `stateColors` (the server computes those from PNGs
6 * when it builds the catalog). Game code asks {@link groundAverageColor} or
7 * {@link blockAverageColor} rather than sampling textures itself.
8 *
9 * A missing state falls back to the type's default-state colour. A missing
10 * type returns null.
11 */
12
13const groundColors = new Map();
14const blockColors = new Map();
15
16/**
17 * @param {object | null | undefined} catalog
18 */
19export function installTileAverageColors (catalog)
20{
21 groundColors.clear();
22 blockColors.clear();
23 installGroup(groundColors, catalog?.grounds);
24 installGroup(blockColors, catalog?.blocks);
25}
26
27/**
28 * @param {number | string | null | undefined} typeId
29 * @param {string | null | undefined} [state]
30 * @returns {{ r: number, g: number, b: number } | null}
31 */
32export function groundAverageColor (typeId, state = null)
33{
34 return lookupAverageColor(groundColors, typeId, state);
35}
36
37/**
38 * @param {number | string | null | undefined} typeId
39 * @param {string | null | undefined} [state]
40 * @returns {{ r: number, g: number, b: number } | null}
41 */
42export function blockAverageColor (typeId, state = null)
43{
44 return lookupAverageColor(blockColors, typeId, state);
45}
46
47export { AVERAGE_COLOR_ALPHA_THRESHOLD } from "./averageSpriteColor.js";
48
49function installGroup (target, types)
50{
51 for (const type of Object.values(types ?? {}))
52 {
53 if (type?.typeId == null)
54 { continue; }
55 const stateColors = {};
56 for (const [state, color] of Object.entries(type.stateColors ?? {}))
57 {
58 const stored = freezeColor(color);
59 if (stored)
60 { stateColors[state] = stored; }
61 }
62 target.set(type.typeId, {
63 averageColor: freezeColor(type.averageColor) ?? firstColor(stateColors),
64 stateColors
65 });
66 }
67}
68
69function lookupAverageColor (groups, typeId, state)
70{
71 if (typeId == null)
72 { return null; }
73 const entry = groups.get(typeId);
74 if (!entry)
75 { return null; }
76 if (state != null && state !== "")
77 {
78 const specific = entry.stateColors[state];
79 if (specific)
80 { return specific; }
81 }
82 return entry.averageColor ?? null;
83}
84
85function firstColor (stateColors)
86{
87 for (const color of Object.values(stateColors))
88 {
89 if (color)
90 { return color; }
91 }
92 return null;
93}
94
95function freezeColor (color)
96{
97 if (!color)
98 { return null; }
99 const r = clampByte(color.r);
100 const g = clampByte(color.g);
101 const b = clampByte(color.b);
102 if (r == null || g == null || b == null)
103 { return null; }
104 return Object.freeze({ r, g, b });
105}
106
107function clampByte (value)
108{
109 const number = Number(value);
110 if (!Number.isFinite(number))
111 { return null; }
112 return Math.max(0, Math.min(255, Math.round(number)));
113}