Merge branch 'master' of git@gitlab.com:Timfa/questward.git
@@ -22,6 +22,8 @@ npm start
22
22
23
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
24
24
25
The world editor keeps an in-memory (and `sessionStorage`) draft across brief WebSocket drops: the gateway sends protocol pings ~every 25s, and the editor client auto-reconnects with backoff without wiping unsaved paint.
26
25
27
Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `QUESTWARD_AUTH_CLIENT_SECRET`, local dev uses stub admins (`admin-1`, …). A fresh world is infinite closed grass: open chunk `0,0` in the [world editor](http://localhost:8080/editor), save, then **Apply now** before a character can walk.
26
28
27
29
### Auth env (production)
@@ -22,6 +22,8 @@ npm start22
22
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
24
24
25
The world editor keeps an in-memory (and `sessionStorage`) draft across brief WebSocket drops: the gateway sends protocol pings ~every 25s, and the editor client auto-reconnects with backoff without wiping unsaved paint.
26
25
Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `QUESTWARD_AUTH_CLIENT_SECRET`, local dev uses stub admins (`admin-1`, …). A fresh world is infinite closed grass: open chunk `0,0` in the [world editor](http://localhost:8080/editor), save, then **Apply now** before a character can walk.
27
Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `QUESTWARD_AUTH_CLIENT_SECRET`, local dev uses stub admins (`admin-1`, …). A fresh world is infinite closed grass: open chunk `0,0` in the [world editor](http://localhost:8080/editor), save, then **Apply now** before a character can walk.
26
28
27
### Auth env (production)
29
### Auth env (production)
The contents of this binary file are not shown.
@@ -48,6 +48,7 @@ import
48
48
isOverworld
49
49
} from "/shared/world/dimensions.js";
50
50
import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";
51
import { editorChunkSaveKey, shouldApplySelectedEditorChunk } from "./saveAck.js";
51
52
52
53
const game = new Game();
53
54
let socket;
@@ -70,6 +71,8 @@ let neighborSpawnersByChunk = new Map();
70
71
let pendingNavigate = null;
71
72
/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
72
73
let navigateAfterSave = false;
74
/** Keys (`dimensionId:chunkX,chunkY`) for in-flight `EDITOR_SAVE_CHUNK` acks. */
75
const pendingSaveAcks = new Set();
73
76
let chunkX = 0;
74
77
let chunkY = 0;
75
78
let selectedDimensionId = OVERWORLD_ID;
@@ -95,6 +98,11 @@ let pendingRevisionId = null;
95
98
let applyInFlight = false;
96
99
/** @type {string|null} */
97
100
let sessionAuthSubject = null;
101
/** True after the first successful SESSION message for this page load. */
102
let sessionReady = false;
103
/** Display label for #who while reconnecting. */
104
let accountWhoLabel = "Editor";
105
const EDITOR_DRAFT_STORAGE_PREFIX = "questward-editor-draft:";
98
106
const EDITOR_ZOOM_MIN = 0.25;
99
107
const EDITOR_ZOOM_MAX = 8;
100
108
const EDITOR_ZOOM_STEP = 1.12;
@@ -272,6 +280,7 @@ function snapshotFromPayload (payload)
272
280
grounds: payload.data.grounds,
273
281
blocks: payload.data.blocks,
274
282
light: payload.data.light,
283
enclosed: payload.data.enclosed,
275
284
entities: []
276
285
};
277
286
}
@@ -298,6 +307,137 @@ function draftPersistable ()
298
307
};
299
308
}
300
309
310
function isSelectedChunkDirty ()
311
{
312
if (!draft || draftBaseline == null)
313
{ return false; }
314
return JSON.stringify(draftPersistable()) !== draftBaseline;
315
}
316
317
function draftStorageKey (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId, subject = sessionAuthSubject)
318
{
319
const who = subject ?? "anon";
320
return `${EDITOR_DRAFT_STORAGE_PREFIX}${who}:${normalizeDimensionId(dimensionId)}:${cx},${cy}`;
321
}
322
323
function persistDirtyDraftBackup ()
324
{
325
if (!draft || !isSelectedChunkDirty())
326
{ return; }
327
try
328
{
329
const payload = {
330
savedAt: Date.now(),
331
dimensionId: selectedDimensionId,
332
chunkX,
333
chunkY,
334
authSubject: sessionAuthSubject,
335
open: !!draft.open,
336
grounds: draft.grounds,
337
blocks: draft.blocks,
338
spawners: draft.spawners ?? [],
339
light: draft.light,
340
enclosed: draft.enclosed,
341
baseline: draftBaseline
342
};
343
sessionStorage.setItem(draftStorageKey(), JSON.stringify(payload));
344
}
345
catch
346
{ /* quota / private mode */ }
347
}
348
349
function clearDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
350
{
351
try
352
{ sessionStorage.removeItem(draftStorageKey(cx, cy, dimensionId)); }
353
catch
354
{ /* ignore */ }
355
}
356
357
function readDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)
358
{
359
try
360
{
361
const raw = sessionStorage.getItem(draftStorageKey(cx, cy, dimensionId));
362
if (!raw)
363
{ return null; }
364
const parsed = JSON.parse(raw);
365
if (!parsed || !Array.isArray(parsed.grounds) || !Array.isArray(parsed.blocks))
366
{ return null; }
367
return parsed;
368
}
369
catch
370
{ return null; }
371
}
372
373
function applyRestoredDraftBackup (backup)
374
{
375
if (!backup || !draft)
376
{ return false; }
377
draft.open = !!backup.open;
378
draft.grounds = backup.grounds.map((ground) => normalizeGround(ground));
379
draft.blocks = backup.blocks.map((block) => (block
380
? { ...block, config: block.config ?? null }
381
: null));
382
const tileCount = CHUNK_SIZE * CHUNK_SIZE;
383
draft.light = Array.isArray(backup.light) && backup.light.length === tileCount
384
? backup.light.slice()
385
: (draft.light ?? new Array(tileCount).fill(0));
386
draft.enclosed = Array.isArray(backup.enclosed) && backup.enclosed.length === tileCount
387
? backup.enclosed.slice().map((v) => (v ? 1 : 0))
388
: (draft.enclosed ?? new Array(tileCount).fill(0));
389
draft.spawners = (backup.spawners ?? []).map((entry) => ({
390
localX: entry.localX | 0,
391
localY: entry.localY | 0,
392
config: { ...(entry.config ?? {}) }
393
}));
394
if (typeof backup.baseline === "string")
395
{ draftBaseline = backup.baseline; }
396
$("open").checked = draft.open;
397
const existing = view?.chunks.get(chunkKey(chunkX, chunkY));
398
view.applySnapshot({
399
chunkX,
400
chunkY,
401
open: draft.open,
402
closedEdges: existing?.closedEdges,
403
grounds: draft.grounds,
404
blocks: draft.blocks,
405
light: draft.light,
406
enclosed: draft.enclosed,
407
entities: []
408
});
409
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
410
syncSaveButton();
411
return true;
412
}
413
414
function tryRestoreDraftBackupAfterServerLoad (payload)
415
{
416
const backup = readDraftBackup(payload.chunkX, payload.chunkY, selectedDimensionId);
417
if (!backup)
418
{ return false; }
419
const serverPersistable = {
420
open: !!payload.data.open,
421
grounds: payload.data.grounds,
422
blocks: payload.data.blocks,
423
spawners: payload.data.spawners ?? []
424
};
425
const backupPersistable = {
426
open: !!backup.open,
427
grounds: backup.grounds,
428
blocks: backup.blocks,
429
spawners: backup.spawners ?? []
430
};
431
if (JSON.stringify(serverPersistable) === JSON.stringify(backupPersistable))
432
{
433
clearDraftBackup(payload.chunkX, payload.chunkY, selectedDimensionId);
434
return false;
435
}
436
// Treat server payload as the clean baseline so the restored paint stays dirty.
437
draftBaseline = JSON.stringify(serverPersistable);
438
return applyRestoredDraftBackup(backup);
439
}
440
301
441
function cloneDraftContents (source)
302
442
{
303
443
if (!source)
@@ -348,6 +488,9 @@ function applyDraftContents (next)
348
488
? { ...block, config: block.config ?? null }
349
489
: null));
350
490
draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
491
draft.enclosed = Array.isArray(next.enclosed)
492
? next.enclosed.slice().map((v) => (v ? 1 : 0))
493
: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
351
494
draft.spawners = (next.spawners ?? []).map((entry) => ({
352
495
localX: entry.localX | 0,
353
496
localY: entry.localY | 0,
@@ -363,6 +506,7 @@ function applyDraftContents (next)
363
506
grounds: draft.grounds,
364
507
blocks: draft.blocks,
365
508
light: draft.light,
509
enclosed: draft.enclosed,
366
510
entities: []
367
511
});
368
512
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -437,6 +581,7 @@ function captureDraftBaseline ()
437
581
{
438
582
const payload = draftPersistable();
439
583
draftBaseline = payload ? JSON.stringify(payload) : null;
584
clearDraftBackup();
440
585
syncSaveButton();
441
586
}
442
587
@@ -449,9 +594,7 @@ function isDraftDirty ()
449
594
{
450
595
if (dirtyNeighborChunks.size > 0)
451
596
{ return true; }
452
if (!draft || draftBaseline == null)
453
{ return false; }
454
return JSON.stringify(draftPersistable()) !== draftBaseline;
597
return isSelectedChunkDirty();
455
598
}
456
599
457
600
function syncSaveButton ()
@@ -474,6 +617,10 @@ function syncSaveButton ()
474
617
function afterDraftMutation ()
475
618
{
476
619
syncSaveButton();
620
if (isSelectedChunkDirty())
621
{ persistDirtyDraftBackup(); }
622
else
623
{ clearDraftBackup(); }
477
624
}
478
625
479
626
function clearNeighborEditState ()
@@ -675,6 +822,7 @@ function saveSelectedChunk ()
675
822
const neighborSaves = [...dirtyNeighborChunks.entries()];
676
823
clearNeighborEditState();
677
824
const savedChunks = [{ chunkX, chunkY }];
825
pendingSaveAcks.add(editorChunkSaveKey(selectedDimensionId, chunkX, chunkY));
678
826
socket.send({
679
827
type: MessageType.editorSaveChunk,
680
828
chunkX,
@@ -691,6 +839,7 @@ function saveSelectedChunk ()
691
839
{
692
840
const [cx, cy] = key.split(",").map(Number);
693
841
savedChunks.push({ chunkX: cx, chunkY: cy });
842
pendingSaveAcks.add(editorChunkSaveKey(selectedDimensionId, cx, cy));
694
843
socket.send({
695
844
type: MessageType.editorSaveChunk,
696
845
chunkX: cx,
@@ -963,14 +1112,35 @@ function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pendin
963
1112
updateRevisionUI();
964
1113
}
965
1114
966
function showSelectedChunk (payload)
1115
function showSelectedChunk (payload, { isSaveAck = false } = {})
967
1116
{
968
clearNeighborEditState();
1117
const keepDirtyDraft = !shouldApplySelectedEditorChunk({
1118
isSaveAck,
1119
isDirty: !!draft
1120
&& payload.chunkX === chunkX
1121
&& payload.chunkY === chunkY
1122
&& isSelectedChunkDirty()
1123
});
1124
if (!keepDirtyDraft)
1125
{ clearNeighborEditState(); }
1126
if (keepDirtyDraft)
1127
{
1128
setRevisionState({
1129
activeRevisionId: payload.activeRevisionId,
1130
pendingRevisionId: payload.pendingRevisionId
1131
});
1132
$("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
1133
syncSaveButton();
1134
return;
1135
}
969
1136
draft = {
970
1137
open: payload.data.open,
971
1138
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
972
1139
blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
973
1140
light: payload.data.light.slice(),
1141
enclosed: Array.isArray(payload.data.enclosed)
1142
? payload.data.enclosed.slice().map((v) => (v ? 1 : 0))
1143
: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0),
974
1144
spawners: (payload.data.spawners ?? []).map((entry) => ({
975
1145
localX: entry.localX,
976
1146
localY: entry.localY,
@@ -1002,8 +1172,11 @@ function showSelectedChunk (payload)
1002
1172
}
1003
1173
view.applySnapshot(snapshotFromPayload(payload));
1004
1174
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);
1005
captureDraftBaseline();
1006
syncSaveButton();
1175
const restored = isSaveAck ? false : tryRestoreDraftBackupAfterServerLoad(payload);
1176
if (!restored)
1177
{ captureDraftBaseline(); }
1178
else
1179
{ syncSaveButton(); }
1007
1180
if (navigateAfterSave && pendingNavigate)
1008
1181
{
1009
1182
const next = pendingNavigate;
@@ -1513,15 +1686,46 @@ async function main ()
1513
1686
scene.addObject(ticker);
1514
1687
window.addEventListener("resize", layoutScene);
1515
1688
1689
accountWhoLabel = accountLabel;
1516
1690
$("who").textContent = `${accountLabel} · connecting…`;
1517
1691
1692
function setWhoConnected (label, isAdmin)
1693
{
1694
accountWhoLabel = label;
1695
$("who").textContent = `${label}${isAdmin ? " · admin" : " · not admin"}`;
1696
}
1697
1698
function resubscribeEditorSession ({ reloadMap })
1699
{
1700
socket.send({ type: MessageType.editorLoadSettings });
1701
socket.send({ type: MessageType.editorLoadGameAdmins });
1702
socket.send({ type: MessageType.editorConsoleSubscribe });
1703
requestDimensions();
1704
if (reloadMap)
1705
{
1706
loadNeighborhood(chunkX, chunkY);
1707
return;
1708
}
1709
const coords = neighborhoodCoords(chunkX, chunkY).filter((coord) =>
1710
{
1711
if (coord.chunkX === chunkX && coord.chunkY === chunkY)
1712
{ return !draft || !isSelectedChunkDirty(); }
1713
return !dirtyNeighborChunks.has(chunkKey(coord.chunkX, coord.chunkY));
1714
});
1715
requestChunks(coords);
1716
syncSaveButton();
1717
}
1718
1518
1719
socket = new GameSocket(defaultSocketUrl(), (message) =>
1519
1720
{
1520
1721
if (message.type === MessageType.session)
1521
1722
{
1723
const wasReady = sessionReady;
1522
1724
sessionAuthSubject = message.authSubject ?? null;
1725
sessionReady = true;
1726
socket.notifySessionEstablished();
1523
1727
const label = message.username ?? message.authSubject ?? "Unknown";
1524
$("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1728
setWhoConnected(label, !!message.isAdmin);
1525
1729
if (!message.isAdmin)
1526
1730
{
1527
1731
$("error").textContent = "Admin access required.";
@@ -1534,11 +1738,7 @@ async function main ()
1534
1738
restartBtn.hidden = false;
1535
1739
restartBtn.disabled = false;
1536
1740
}
1537
socket.send({ type: MessageType.editorLoadSettings });
1538
socket.send({ type: MessageType.editorLoadGameAdmins });
1539
socket.send({ type: MessageType.editorConsoleSubscribe });
1540
requestDimensions();
1541
loadNeighborhood(0, 0);
1741
resubscribeEditorSession({ reloadMap: !wasReady });
1542
1742
}
1543
1743
else if (message.type === MessageType.editorSettings
1544
1744
|| message.type === MessageType.editorGameAdmins)
@@ -1571,15 +1771,18 @@ async function main ()
1571
1771
{ renderGlobalChangelog(message.changelog ?? []); }
1572
1772
else if (message.type === MessageType.editorChunk)
1573
1773
{
1574
const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
1774
const msgDim = normalizeDimensionId(message.dimensionId ?? selectedDimensionId);
1575
1775
if (msgDim !== selectedDimensionId)
1576
1776
{ return; }
1777
const isSaveAck = pendingSaveAcks.delete(
1778
editorChunkSaveKey(msgDim, message.chunkX, message.chunkY)
1779
);
1577
1780
if (message.settings)
1578
1781
{ view.setSettings(message.settings); }
1579
1782
if (!inEditorView(message.chunkX, message.chunkY))
1580
1783
{ return; }
1581
1784
if (message.chunkX === chunkX && message.chunkY === chunkY)
1582
{ showSelectedChunk(message); }
1785
{ showSelectedChunk(message, { isSaveAck }); }
1583
1786
else
1584
1787
{
1585
1788
const key = chunkKey(message.chunkX, message.chunkY);
@@ -1616,6 +1819,7 @@ async function main ()
1616
1819
if (giftsModal?.isOpen())
1617
1820
{ giftsModal.handleError?.(message.message); }
1618
1821
pendingCreatedDimensionId = null;
1822
pendingSaveAcks.clear();
1619
1823
navigateAfterSave = false;
1620
1824
dimensionPicker?.setValue(selectedDimensionId);
1621
1825
if (applyInFlight)
@@ -1627,22 +1831,59 @@ async function main ()
1627
1831
}
1628
1832
}
1629
1833
}, {
1834
autoReconnect: true,
1835
onOpen ()
1836
{
1837
if (sessionReady)
1838
{ $("who").textContent = `${accountWhoLabel} · reconnected, waiting for session…`; }
1839
},
1840
onReconnecting ({ attempt, delayMs })
1841
{
1842
$("who").textContent = `${accountWhoLabel} · reconnecting…`;
1843
if (sessionReady)
1844
{
1845
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept."
1846
+ ` (attempt ${attempt}, retry in ${Math.round(delayMs / 100) / 10}s)`;
1847
}
1848
},
1630
1849
onClose (event)
1631
1850
{
1632
1851
if (event.code === 1000)
1633
1852
{ return; }
1634
const reasons = {
1853
const authOrRestart = {
1635
1854
4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1636
1855
1011: "Server could not verify your account with auth.timfalken.com.",
1637
1006: "Connection dropped before the editor session started.",
1638
1856
1001: "Server is restarting. Reload this page in a moment."
1639
1857
};
1858
if (authOrRestart[event.code])
1859
{
1860
sessionReady = false;
1861
$("who").textContent = "Connection failed";
1862
$("error").textContent = authOrRestart[event.code];
1863
return;
1864
}
1865
if (sessionReady)
1866
{
1867
$("who").textContent = `${accountWhoLabel} · reconnecting…`;
1868
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
1869
persistDirtyDraftBackup();
1870
return;
1871
}
1872
const reasons = {
1873
1006: "Connection dropped before the editor session started."
1874
};
1640
1875
const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1641
1876
$("who").textContent = "Connection failed";
1642
1877
$("error").textContent = detail;
1643
1878
},
1644
1879
onError ()
1645
1880
{
1881
if (sessionReady)
1882
{
1883
$("who").textContent = `${accountWhoLabel} · reconnecting…`;
1884
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";
1885
return;
1886
}
1646
1887
$("who").textContent = "Connection failed";
1647
1888
$("error").textContent = "Could not open a live connection to the server.";
1648
1889
}
@@ -1721,7 +1962,17 @@ async function main ()
1721
1962
initSidePanelTabs();
1722
1963
game.startGame();
1723
1964
useNearestNeighbour(scene, game.images);
1724
await socket.connect();
1965
try
1966
{ await socket.connect(); }
1967
catch (error)
1968
{
1969
// autoReconnect keeps retrying; surface the first failure without aborting the editor UI
1970
if (!sessionReady)
1971
{
1972
$("who").textContent = "Connection failed";
1973
$("error").textContent = error?.message || "Could not open a live connection to the server.";
1974
}
1975
}
1725
1976
}
1726
1977
1727
1978
$("tool").textContent = selectedToolLabel();
@@ -48,6 +48,7 @@ import48
isOverworld48
isOverworld49
} from "/shared/world/dimensions.js";49
} from "/shared/world/dimensions.js";50
import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";50
import { normalizeDoorConfig } from "/shared/world/doorRequirements.js";51
import { editorChunkSaveKey, shouldApplySelectedEditorChunk } from "./saveAck.js";51
52
52
const game = new Game();53
const game = new Game();53
let socket;54
let socket;@@ -70,6 +71,8 @@ let neighborSpawnersByChunk = new Map();70
let pendingNavigate = null;71
let pendingNavigate = null;71
/** When true, next matching editorChunk after save should navigate to pendingNavigate. */72
/** When true, next matching editorChunk after save should navigate to pendingNavigate. */72
let navigateAfterSave = false;73
let navigateAfterSave = false;74
/** Keys (`dimensionId:chunkX,chunkY`) for in-flight `EDITOR_SAVE_CHUNK` acks. */75
const pendingSaveAcks = new Set();73
let chunkX = 0;76
let chunkX = 0;74
let chunkY = 0;77
let chunkY = 0;75
let selectedDimensionId = OVERWORLD_ID;78
let selectedDimensionId = OVERWORLD_ID;@@ -95,6 +98,11 @@ let pendingRevisionId = null;95
let applyInFlight = false;98
let applyInFlight = false;96
/** @type {string|null} */99
/** @type {string|null} */97
let sessionAuthSubject = null;100
let sessionAuthSubject = null;101
/** True after the first successful SESSION message for this page load. */102
let sessionReady = false;103
/** Display label for #who while reconnecting. */104
let accountWhoLabel = "Editor";105
const EDITOR_DRAFT_STORAGE_PREFIX = "questward-editor-draft:";98
const EDITOR_ZOOM_MIN = 0.25;106
const EDITOR_ZOOM_MIN = 0.25;99
const EDITOR_ZOOM_MAX = 8;107
const EDITOR_ZOOM_MAX = 8;100
const EDITOR_ZOOM_STEP = 1.12;108
const EDITOR_ZOOM_STEP = 1.12;@@ -272,6 +280,7 @@ function snapshotFromPayload (payload)272
grounds: payload.data.grounds,280
grounds: payload.data.grounds,273
blocks: payload.data.blocks,281
blocks: payload.data.blocks,274
light: payload.data.light,282
light: payload.data.light,283
enclosed: payload.data.enclosed,275
entities: []284
entities: []276
};285
};277
}286
}@@ -298,6 +307,137 @@ function draftPersistable ()298
};307
};299
}308
}300
309
310
function isSelectedChunkDirty ()311
{312
if (!draft || draftBaseline == null)313
{ return false; }314
return JSON.stringify(draftPersistable()) !== draftBaseline;315
}316
317
function draftStorageKey (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId, subject = sessionAuthSubject)318
{319
const who = subject ?? "anon";320
return `${EDITOR_DRAFT_STORAGE_PREFIX}${who}:${normalizeDimensionId(dimensionId)}:${cx},${cy}`;321
}322
323
function persistDirtyDraftBackup ()324
{325
if (!draft || !isSelectedChunkDirty())326
{ return; }327
try328
{329
const payload = {330
savedAt: Date.now(),331
dimensionId: selectedDimensionId,332
chunkX,333
chunkY,334
authSubject: sessionAuthSubject,335
open: !!draft.open,336
grounds: draft.grounds,337
blocks: draft.blocks,338
spawners: draft.spawners ?? [],339
light: draft.light,340
enclosed: draft.enclosed,341
baseline: draftBaseline342
};343
sessionStorage.setItem(draftStorageKey(), JSON.stringify(payload));344
}345
catch346
{ /* quota / private mode */ }347
}348
349
function clearDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)350
{351
try352
{ sessionStorage.removeItem(draftStorageKey(cx, cy, dimensionId)); }353
catch354
{ /* ignore */ }355
}356
357
function readDraftBackup (cx = chunkX, cy = chunkY, dimensionId = selectedDimensionId)358
{359
try360
{361
const raw = sessionStorage.getItem(draftStorageKey(cx, cy, dimensionId));362
if (!raw)363
{ return null; }364
const parsed = JSON.parse(raw);365
if (!parsed || !Array.isArray(parsed.grounds) || !Array.isArray(parsed.blocks))366
{ return null; }367
return parsed;368
}369
catch370
{ return null; }371
}372
373
function applyRestoredDraftBackup (backup)374
{375
if (!backup || !draft)376
{ return false; }377
draft.open = !!backup.open;378
draft.grounds = backup.grounds.map((ground) => normalizeGround(ground));379
draft.blocks = backup.blocks.map((block) => (block380
? { ...block, config: block.config ?? null }381
: null));382
const tileCount = CHUNK_SIZE * CHUNK_SIZE;383
draft.light = Array.isArray(backup.light) && backup.light.length === tileCount384
? backup.light.slice()385
: (draft.light ?? new Array(tileCount).fill(0));386
draft.enclosed = Array.isArray(backup.enclosed) && backup.enclosed.length === tileCount387
? backup.enclosed.slice().map((v) => (v ? 1 : 0))388
: (draft.enclosed ?? new Array(tileCount).fill(0));389
draft.spawners = (backup.spawners ?? []).map((entry) => ({390
localX: entry.localX | 0,391
localY: entry.localY | 0,392
config: { ...(entry.config ?? {}) }393
}));394
if (typeof backup.baseline === "string")395
{ draftBaseline = backup.baseline; }396
$("open").checked = draft.open;397
const existing = view?.chunks.get(chunkKey(chunkX, chunkY));398
view.applySnapshot({399
chunkX,400
chunkY,401
open: draft.open,402
closedEdges: existing?.closedEdges,403
grounds: draft.grounds,404
blocks: draft.blocks,405
light: draft.light,406
enclosed: draft.enclosed,407
entities: []408
});409
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);410
syncSaveButton();411
return true;412
}413
414
function tryRestoreDraftBackupAfterServerLoad (payload)415
{416
const backup = readDraftBackup(payload.chunkX, payload.chunkY, selectedDimensionId);417
if (!backup)418
{ return false; }419
const serverPersistable = {420
open: !!payload.data.open,421
grounds: payload.data.grounds,422
blocks: payload.data.blocks,423
spawners: payload.data.spawners ?? []424
};425
const backupPersistable = {426
open: !!backup.open,427
grounds: backup.grounds,428
blocks: backup.blocks,429
spawners: backup.spawners ?? []430
};431
if (JSON.stringify(serverPersistable) === JSON.stringify(backupPersistable))432
{433
clearDraftBackup(payload.chunkX, payload.chunkY, selectedDimensionId);434
return false;435
}436
// Treat server payload as the clean baseline so the restored paint stays dirty.437
draftBaseline = JSON.stringify(serverPersistable);438
return applyRestoredDraftBackup(backup);439
}440
301
function cloneDraftContents (source)441
function cloneDraftContents (source)302
{442
{303
if (!source)443
if (!source)@@ -348,6 +488,9 @@ function applyDraftContents (next)348
? { ...block, config: block.config ?? null }488
? { ...block, config: block.config ?? null }349
: null));489
: null));350
draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);490
draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);491
draft.enclosed = Array.isArray(next.enclosed)492
? next.enclosed.slice().map((v) => (v ? 1 : 0))493
: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);351
draft.spawners = (next.spawners ?? []).map((entry) => ({494
draft.spawners = (next.spawners ?? []).map((entry) => ({352
localX: entry.localX | 0,495
localX: entry.localX | 0,353
localY: entry.localY | 0,496
localY: entry.localY | 0,@@ -363,6 +506,7 @@ function applyDraftContents (next)363
grounds: draft.grounds,506
grounds: draft.grounds,364
blocks: draft.blocks,507
blocks: draft.blocks,365
light: draft.light,508
light: draft.light,509
enclosed: draft.enclosed,366
entities: []510
entities: []367
});511
});368
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);512
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);@@ -437,6 +581,7 @@ function captureDraftBaseline ()437
{581
{438
const payload = draftPersistable();582
const payload = draftPersistable();439
draftBaseline = payload ? JSON.stringify(payload) : null;583
draftBaseline = payload ? JSON.stringify(payload) : null;584
clearDraftBackup();440
syncSaveButton();585
syncSaveButton();441
}586
}442
587
@@ -449,9 +594,7 @@ function isDraftDirty ()449
{594
{450
if (dirtyNeighborChunks.size > 0)595
if (dirtyNeighborChunks.size > 0)451
{ return true; }596
{ return true; }452
if (!draft || draftBaseline == null)597
return isSelectedChunkDirty();453
{ return false; }454
return JSON.stringify(draftPersistable()) !== draftBaseline;455
}598
}456
599
457
function syncSaveButton ()600
function syncSaveButton ()@@ -474,6 +617,10 @@ function syncSaveButton ()474
function afterDraftMutation ()617
function afterDraftMutation ()475
{618
{476
syncSaveButton();619
syncSaveButton();620
if (isSelectedChunkDirty())621
{ persistDirtyDraftBackup(); }622
else623
{ clearDraftBackup(); }477
}624
}478
625
479
function clearNeighborEditState ()626
function clearNeighborEditState ()@@ -675,6 +822,7 @@ function saveSelectedChunk ()675
const neighborSaves = [...dirtyNeighborChunks.entries()];822
const neighborSaves = [...dirtyNeighborChunks.entries()];676
clearNeighborEditState();823
clearNeighborEditState();677
const savedChunks = [{ chunkX, chunkY }];824
const savedChunks = [{ chunkX, chunkY }];825
pendingSaveAcks.add(editorChunkSaveKey(selectedDimensionId, chunkX, chunkY));678
socket.send({826
socket.send({679
type: MessageType.editorSaveChunk,827
type: MessageType.editorSaveChunk,680
chunkX,828
chunkX,@@ -691,6 +839,7 @@ function saveSelectedChunk ()691
{839
{692
const [cx, cy] = key.split(",").map(Number);840
const [cx, cy] = key.split(",").map(Number);693
savedChunks.push({ chunkX: cx, chunkY: cy });841
savedChunks.push({ chunkX: cx, chunkY: cy });842
pendingSaveAcks.add(editorChunkSaveKey(selectedDimensionId, cx, cy));694
socket.send({843
socket.send({695
type: MessageType.editorSaveChunk,844
type: MessageType.editorSaveChunk,696
chunkX: cx,845
chunkX: cx,@@ -963,14 +1112,35 @@ function setRevisionState ({ activeRevisionId: active, pendingRevisionId: pendin963
updateRevisionUI();1112
updateRevisionUI();964
}1113
}965
1114
966
function showSelectedChunk (payload)1115
function showSelectedChunk (payload, { isSaveAck = false } = {})967
{1116
{968
clearNeighborEditState();1117
const keepDirtyDraft = !shouldApplySelectedEditorChunk({1118
isSaveAck,1119
isDirty: !!draft1120
&& payload.chunkX === chunkX1121
&& payload.chunkY === chunkY1122
&& isSelectedChunkDirty()1123
});1124
if (!keepDirtyDraft)1125
{ clearNeighborEditState(); }1126
if (keepDirtyDraft)1127
{1128
setRevisionState({1129
activeRevisionId: payload.activeRevisionId,1130
pendingRevisionId: payload.pendingRevisionId1131
});1132
$("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";1133
syncSaveButton();1134
return;1135
}969
draft = {1136
draft = {970
open: payload.data.open,1137
open: payload.data.open,971
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),1138
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),972
blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),1139
blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),973
light: payload.data.light.slice(),1140
light: payload.data.light.slice(),1141
enclosed: Array.isArray(payload.data.enclosed)1142
? payload.data.enclosed.slice().map((v) => (v ? 1 : 0))1143
: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0),974
spawners: (payload.data.spawners ?? []).map((entry) => ({1144
spawners: (payload.data.spawners ?? []).map((entry) => ({975
localX: entry.localX,1145
localX: entry.localX,976
localY: entry.localY,1146
localY: entry.localY,@@ -1002,8 +1172,11 @@ function showSelectedChunk (payload)1002
}1172
}1003
view.applySnapshot(snapshotFromPayload(payload));1173
view.applySnapshot(snapshotFromPayload(payload));1004
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);1174
syncSpawnersOverlay(payload.chunkX, payload.chunkY, draft.spawners);1005
captureDraftBaseline();1175
const restored = isSaveAck ? false : tryRestoreDraftBackupAfterServerLoad(payload);1006
syncSaveButton();1176
if (!restored)1177
{ captureDraftBaseline(); }1178
else1179
{ syncSaveButton(); }1007
if (navigateAfterSave && pendingNavigate)1180
if (navigateAfterSave && pendingNavigate)1008
{1181
{1009
const next = pendingNavigate;1182
const next = pendingNavigate;@@ -1513,15 +1686,46 @@ async function main ()1513
scene.addObject(ticker);1686
scene.addObject(ticker);1514
window.addEventListener("resize", layoutScene);1687
window.addEventListener("resize", layoutScene);1515
1688
1689
accountWhoLabel = accountLabel;1516
$("who").textContent = `${accountLabel} · connecting…`;1690
$("who").textContent = `${accountLabel} · connecting…`;1517
1691
1692
function setWhoConnected (label, isAdmin)1693
{1694
accountWhoLabel = label;1695
$("who").textContent = `${label}${isAdmin ? " · admin" : " · not admin"}`;1696
}1697
1698
function resubscribeEditorSession ({ reloadMap })1699
{1700
socket.send({ type: MessageType.editorLoadSettings });1701
socket.send({ type: MessageType.editorLoadGameAdmins });1702
socket.send({ type: MessageType.editorConsoleSubscribe });1703
requestDimensions();1704
if (reloadMap)1705
{1706
loadNeighborhood(chunkX, chunkY);1707
return;1708
}1709
const coords = neighborhoodCoords(chunkX, chunkY).filter((coord) =>1710
{1711
if (coord.chunkX === chunkX && coord.chunkY === chunkY)1712
{ return !draft || !isSelectedChunkDirty(); }1713
return !dirtyNeighborChunks.has(chunkKey(coord.chunkX, coord.chunkY));1714
});1715
requestChunks(coords);1716
syncSaveButton();1717
}1718
1518
socket = new GameSocket(defaultSocketUrl(), (message) =>1719
socket = new GameSocket(defaultSocketUrl(), (message) =>1519
{1720
{1520
if (message.type === MessageType.session)1721
if (message.type === MessageType.session)1521
{1722
{1723
const wasReady = sessionReady;1522
sessionAuthSubject = message.authSubject ?? null;1724
sessionAuthSubject = message.authSubject ?? null;1725
sessionReady = true;1726
socket.notifySessionEstablished();1523
const label = message.username ?? message.authSubject ?? "Unknown";1727
const label = message.username ?? message.authSubject ?? "Unknown";1524
$("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;1728
setWhoConnected(label, !!message.isAdmin);1525
if (!message.isAdmin)1729
if (!message.isAdmin)1526
{1730
{1527
$("error").textContent = "Admin access required.";1731
$("error").textContent = "Admin access required.";@@ -1534,11 +1738,7 @@ async function main ()1534
restartBtn.hidden = false;1738
restartBtn.hidden = false;1535
restartBtn.disabled = false;1739
restartBtn.disabled = false;1536
}1740
}1537
socket.send({ type: MessageType.editorLoadSettings });1741
resubscribeEditorSession({ reloadMap: !wasReady });1538
socket.send({ type: MessageType.editorLoadGameAdmins });1539
socket.send({ type: MessageType.editorConsoleSubscribe });1540
requestDimensions();1541
loadNeighborhood(0, 0);1542
}1742
}1543
else if (message.type === MessageType.editorSettings1743
else if (message.type === MessageType.editorSettings1544
|| message.type === MessageType.editorGameAdmins)1744
|| message.type === MessageType.editorGameAdmins)@@ -1571,15 +1771,18 @@ async function main ()1571
{ renderGlobalChangelog(message.changelog ?? []); }1771
{ renderGlobalChangelog(message.changelog ?? []); }1572
else if (message.type === MessageType.editorChunk)1772
else if (message.type === MessageType.editorChunk)1573
{1773
{1574
const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);1774
const msgDim = normalizeDimensionId(message.dimensionId ?? selectedDimensionId);1575
if (msgDim !== selectedDimensionId)1775
if (msgDim !== selectedDimensionId)1576
{ return; }1776
{ return; }1777
const isSaveAck = pendingSaveAcks.delete(1778
editorChunkSaveKey(msgDim, message.chunkX, message.chunkY)1779
);1577
if (message.settings)1780
if (message.settings)1578
{ view.setSettings(message.settings); }1781
{ view.setSettings(message.settings); }1579
if (!inEditorView(message.chunkX, message.chunkY))1782
if (!inEditorView(message.chunkX, message.chunkY))1580
{ return; }1783
{ return; }1581
if (message.chunkX === chunkX && message.chunkY === chunkY)1784
if (message.chunkX === chunkX && message.chunkY === chunkY)1582
{ showSelectedChunk(message); }1785
{ showSelectedChunk(message, { isSaveAck }); }1583
else1786
else1584
{1787
{1585
const key = chunkKey(message.chunkX, message.chunkY);1788
const key = chunkKey(message.chunkX, message.chunkY);@@ -1616,6 +1819,7 @@ async function main ()1616
if (giftsModal?.isOpen())1819
if (giftsModal?.isOpen())1617
{ giftsModal.handleError?.(message.message); }1820
{ giftsModal.handleError?.(message.message); }1618
pendingCreatedDimensionId = null;1821
pendingCreatedDimensionId = null;1822
pendingSaveAcks.clear();1619
navigateAfterSave = false;1823
navigateAfterSave = false;1620
dimensionPicker?.setValue(selectedDimensionId);1824
dimensionPicker?.setValue(selectedDimensionId);1621
if (applyInFlight)1825
if (applyInFlight)@@ -1627,22 +1831,59 @@ async function main ()1627
}1831
}1628
}1832
}1629
}, {1833
}, {1834
autoReconnect: true,1835
onOpen ()1836
{1837
if (sessionReady)1838
{ $("who").textContent = `${accountWhoLabel} · reconnected, waiting for session…`; }1839
},1840
onReconnecting ({ attempt, delayMs })1841
{1842
$("who").textContent = `${accountWhoLabel} · reconnecting…`;1843
if (sessionReady)1844
{1845
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept."1846
+ ` (attempt ${attempt}, retry in ${Math.round(delayMs / 100) / 10}s)`;1847
}1848
},1630
onClose (event)1849
onClose (event)1631
{1850
{1632
if (event.code === 1000)1851
if (event.code === 1000)1633
{ return; }1852
{ return; }1634
const reasons = {1853
const authOrRestart = {1635
4401: "Sign in expired or missing. Use Sign out, then sign in again.",1854
4401: "Sign in expired or missing. Use Sign out, then sign in again.",1636
1011: "Server could not verify your account with auth.timfalken.com.",1855
1011: "Server could not verify your account with auth.timfalken.com.",1637
1006: "Connection dropped before the editor session started.",1638
1001: "Server is restarting. Reload this page in a moment."1856
1001: "Server is restarting. Reload this page in a moment."1639
};1857
};1858
if (authOrRestart[event.code])1859
{1860
sessionReady = false;1861
$("who").textContent = "Connection failed";1862
$("error").textContent = authOrRestart[event.code];1863
return;1864
}1865
if (sessionReady)1866
{1867
$("who").textContent = `${accountWhoLabel} · reconnecting…`;1868
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";1869
persistDirtyDraftBackup();1870
return;1871
}1872
const reasons = {1873
1006: "Connection dropped before the editor session started."1874
};1640
const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;1875
const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;1641
$("who").textContent = "Connection failed";1876
$("who").textContent = "Connection failed";1642
$("error").textContent = detail;1877
$("error").textContent = detail;1643
},1878
},1644
onError ()1879
onError ()1645
{1880
{1881
if (sessionReady)1882
{1883
$("who").textContent = `${accountWhoLabel} · reconnecting…`;1884
$("error").textContent = "Connection lost while editing. Reconnecting… Your unsaved draft is kept.";1885
return;1886
}1646
$("who").textContent = "Connection failed";1887
$("who").textContent = "Connection failed";1647
$("error").textContent = "Could not open a live connection to the server.";1888
$("error").textContent = "Could not open a live connection to the server.";1648
}1889
}@@ -1721,7 +1962,17 @@ async function main ()1721
initSidePanelTabs();1962
initSidePanelTabs();1722
game.startGame();1963
game.startGame();1723
useNearestNeighbour(scene, game.images);1964
useNearestNeighbour(scene, game.images);1724
await socket.connect();1965
try1966
{ await socket.connect(); }1967
catch (error)1968
{1969
// autoReconnect keeps retrying; surface the first failure without aborting the editor UI1970
if (!sessionReady)1971
{1972
$("who").textContent = "Connection failed";1973
$("error").textContent = error?.message || "Could not open a live connection to the server.";1974
}1975
}1725
}1976
}1726
1977
1727
$("tool").textContent = selectedToolLabel();1978
$("tool").textContent = selectedToolLabel();@@ -0,0 +1,24 @@
1
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2
3
/**
4
* Editor chunk saves and reloads share the same `EDITOR_CHUNK` reply.
5
* After `EDITOR_SAVE_CHUNK` the local draft is still dirty (baseline is not
6
* updated until the ack is applied). Treating that ack like a reconnect reload
7
* leaves the Save button dirty even though the server already persisted.
8
*/
9
10
export function editorChunkSaveKey (dimensionId, chunkX, chunkY)
11
{
12
return `${normalizeDimensionId(dimensionId ?? OVERWORLD_ID)}:${chunkX | 0},${chunkY | 0}`;
13
}
14
15
/**
16
* Whether an incoming selected-chunk `EDITOR_CHUNK` should replace the local draft.
17
* Save acks must apply even while dirty. Non-ack reloads must not wipe unsaved paint.
18
*
19
* @param {{ isSaveAck?: boolean, isDirty?: boolean }} options
20
*/
21
export function shouldApplySelectedEditorChunk ({ isSaveAck = false, isDirty = false } = {})
22
{
23
return !!isSaveAck || !isDirty;
24
}
@@ -0,0 +1,24 @@1
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";2
3
/**4
* Editor chunk saves and reloads share the same `EDITOR_CHUNK` reply.5
* After `EDITOR_SAVE_CHUNK` the local draft is still dirty (baseline is not6
* updated until the ack is applied). Treating that ack like a reconnect reload7
* leaves the Save button dirty even though the server already persisted.8
*/9
10
export function editorChunkSaveKey (dimensionId, chunkX, chunkY)11
{12
return `${normalizeDimensionId(dimensionId ?? OVERWORLD_ID)}:${chunkX | 0},${chunkY | 0}`;13
}14
15
/**16
* Whether an incoming selected-chunk `EDITOR_CHUNK` should replace the local draft.17
* Save acks must apply even while dirty. Non-ack reloads must not wipe unsaved paint.18
*19
* @param {{ isSaveAck?: boolean, isDirty?: boolean }} options20
*/21
export function shouldApplySelectedEditorChunk ({ isSaveAck = false, isDirty = false } = {})22
{23
return !!isSaveAck || !isDirty;24
}@@ -1,34 +1,119 @@
1
/** Close codes that should not trigger auto-reconnect (auth / intentional server kicks). */
2
export const NO_AUTO_RECONNECT_CODES = new Set([
3
1000, // normal closure (also used by intentional close())
4
1001, // going away / server restart
5
4000, // logged in elsewhere
6
4401, // authentication required
7
1011 // authentication / session setup failed
8
]);
9
10
/**
11
* Exponential backoff delay for reconnect attempts.
12
* @param {number} attempt zero-based attempt index
13
* @param {{ baseMs?: number, maxMs?: number }} [options]
14
*/
15
export function nextReconnectDelayMs (attempt, { baseMs = 750, maxMs = 20_000 } = {})
16
{
17
const n = Math.max(0, attempt | 0);
18
return Math.min(maxMs, baseMs * (2 ** n));
19
}
20
21
/**
22
* @param {number} code WebSocket close code
23
* @param {{ intentional?: boolean, autoReconnect?: boolean }} [options]
24
*/
25
export function shouldAutoReconnect (code, { intentional = false, autoReconnect = false } = {})
26
{
27
if (!autoReconnect || intentional)
28
{ return false; }
29
return !NO_AUTO_RECONNECT_CODES.has(code | 0);
30
}
31
1
32
export class GameSocket
2
33
{
3
constructor(url, onMessage, { onClose, onError } = {})
34
/**
35
* @param {string} url
36
* @param {(message: object) => void} onMessage
37
* @param {{
38
* onClose?: (event: CloseEvent) => void,
39
* onError?: (event: Event) => void,
40
* onOpen?: (event: Event) => void,
41
* onReconnecting?: (info: { attempt: number, delayMs: number, code: number }) => void,
42
* autoReconnect?: boolean,
43
* reconnectBaseMs?: number,
44
* reconnectMaxMs?: number
45
* }} [options]
46
*/
47
constructor (url, onMessage, {
48
onClose,
49
onError,
50
onOpen,
51
onReconnecting,
52
autoReconnect = false,
53
reconnectBaseMs = 750,
54
reconnectMaxMs = 20_000
55
} = {})
4
56
{
5
57
this.url = url;
6
58
this.onMessage = onMessage;
7
59
this.onClose = onClose;
8
60
this.onError = onError;
61
this.onOpen = onOpen;
62
this.onReconnecting = onReconnecting;
63
this.autoReconnect = !!autoReconnect;
64
this.reconnectBaseMs = reconnectBaseMs;
65
this.reconnectMaxMs = reconnectMaxMs;
9
66
this.socket = null;
10
}
11
12
connect ()
13
{
14
this.socket = new WebSocket(this.url);
15
this.socket.addEventListener("message", (event) =>
67
this._intentionalClose = false;
68
this._reconnectAttempt = 0;
69
this._reconnectTimer = null;
70
this._boundMessage = (event) =>
16
71
{
17
72
this.onMessage(JSON.parse(event.data));
18
});
19
this.socket.addEventListener("close", (event) =>
73
};
74
this._boundClose = (event) =>
20
75
{
21
this.onClose?.(event);
22
});
23
this.socket.addEventListener("error", (event) =>
76
this._handleClose(event);
77
};
78
this._boundError = (event) =>
24
79
{
25
80
this.onError?.(event);
26
});
27
return new Promise((resolve, reject) =>
81
};
82
this._boundOpen = (event) =>
28
83
{
29
this.socket.addEventListener("open", resolve, { once: true });
30
this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true });
31
});
84
this.onOpen?.(event);
85
};
86
}
87
88
connect ()
89
{
90
this._intentionalClose = false;
91
return this._openSocket();
92
}
93
94
/** Graceful client-initiated close — does not auto-reconnect. */
95
close (code = 1000, reason = "Client closed")
96
{
97
this._intentionalClose = true;
98
this._clearReconnectTimer();
99
this._reconnectAttempt = 0;
100
const socket = this.socket;
101
this._detach(socket);
102
if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING))
103
{
104
try
105
{ socket.close(code, reason); }
106
catch
107
{ /* ignore */ }
108
}
109
this.socket = null;
110
}
111
112
/** Call when an application SESSION (or equivalent) is established so backoff resets. */
113
notifySessionEstablished ()
114
{
115
this._reconnectAttempt = 0;
116
this._clearReconnectTimer();
32
117
}
33
118
34
119
send (payload)
@@ -37,6 +122,106 @@ export class GameSocket
37
122
{ throw new Error("WebSocket is not connected."); }
38
123
this.socket.send(JSON.stringify(payload));
39
124
}
125
126
get reconnecting ()
127
{
128
return this._reconnectTimer != null;
129
}
130
131
_openSocket ()
132
{
133
this._clearReconnectTimer();
134
this._detach(this.socket);
135
const socket = new WebSocket(this.url);
136
this.socket = socket;
137
socket.addEventListener("message", this._boundMessage);
138
socket.addEventListener("close", this._boundClose);
139
socket.addEventListener("error", this._boundError);
140
socket.addEventListener("open", this._boundOpen);
141
142
return new Promise((resolve, reject) =>
143
{
144
const onOpen = () =>
145
{
146
cleanup();
147
resolve();
148
};
149
const onError = () =>
150
{
151
cleanup();
152
reject(new Error("WebSocket failed"));
153
};
154
const cleanup = () =>
155
{
156
socket.removeEventListener("open", onOpen);
157
socket.removeEventListener("error", onError);
158
};
159
socket.addEventListener("open", onOpen, { once: true });
160
socket.addEventListener("error", onError, { once: true });
161
});
162
}
163
164
_detach (socket)
165
{
166
if (!socket)
167
{ return; }
168
socket.removeEventListener("message", this._boundMessage);
169
socket.removeEventListener("close", this._boundClose);
170
socket.removeEventListener("error", this._boundError);
171
socket.removeEventListener("open", this._boundOpen);
172
}
173
174
_clearReconnectTimer ()
175
{
176
if (this._reconnectTimer != null)
177
{
178
clearTimeout(this._reconnectTimer);
179
this._reconnectTimer = null;
180
}
181
}
182
183
_scheduleReconnect (code)
184
{
185
const attempt = this._reconnectAttempt;
186
const delayMs = nextReconnectDelayMs(attempt, {
187
baseMs: this.reconnectBaseMs,
188
maxMs: this.reconnectMaxMs
189
});
190
this._reconnectAttempt = attempt + 1;
191
this.onReconnecting?.({ attempt: this._reconnectAttempt, delayMs, code: code | 0 });
192
this._reconnectTimer = setTimeout(() =>
193
{
194
this._reconnectTimer = null;
195
void this._openSocket().catch(() =>
196
{
197
// open/error path usually also emits close; if not, retry from here
198
if (this._intentionalClose || !this.autoReconnect || this.socket)
199
{ return; }
200
this._scheduleReconnect(code);
201
});
202
}, delayMs);
203
}
204
205
_handleClose (event)
206
{
207
this._detach(event?.target ?? this.socket);
208
if (this.socket === event?.target)
209
{ this.socket = null; }
210
211
this.onClose?.(event);
212
213
const code = event?.code | 0;
214
if (!shouldAutoReconnect(code, {
215
intentional: this._intentionalClose,
216
autoReconnect: this.autoReconnect
217
}))
218
{
219
this._intentionalClose = false;
220
return;
221
}
222
223
this._scheduleReconnect(code);
224
}
40
225
}
41
226
42
227
export function defaultSocketUrl ()
@@ -1,34 +1,119 @@1
/** Close codes that should not trigger auto-reconnect (auth / intentional server kicks). */2
export const NO_AUTO_RECONNECT_CODES = new Set([3
1000, // normal closure (also used by intentional close())4
1001, // going away / server restart5
4000, // logged in elsewhere6
4401, // authentication required7
1011 // authentication / session setup failed8
]);9
10
/**11
* Exponential backoff delay for reconnect attempts.12
* @param {number} attempt zero-based attempt index13
* @param {{ baseMs?: number, maxMs?: number }} [options]14
*/15
export function nextReconnectDelayMs (attempt, { baseMs = 750, maxMs = 20_000 } = {})16
{17
const n = Math.max(0, attempt | 0);18
return Math.min(maxMs, baseMs * (2 ** n));19
}20
21
/**22
* @param {number} code WebSocket close code23
* @param {{ intentional?: boolean, autoReconnect?: boolean }} [options]24
*/25
export function shouldAutoReconnect (code, { intentional = false, autoReconnect = false } = {})26
{27
if (!autoReconnect || intentional)28
{ return false; }29
return !NO_AUTO_RECONNECT_CODES.has(code | 0);30
}31
1
export class GameSocket32
export class GameSocket2
{33
{3
constructor(url, onMessage, { onClose, onError } = {})34
/**35
* @param {string} url36
* @param {(message: object) => void} onMessage37
* @param {{38
* onClose?: (event: CloseEvent) => void,39
* onError?: (event: Event) => void,40
* onOpen?: (event: Event) => void,41
* onReconnecting?: (info: { attempt: number, delayMs: number, code: number }) => void,42
* autoReconnect?: boolean,43
* reconnectBaseMs?: number,44
* reconnectMaxMs?: number45
* }} [options]46
*/47
constructor (url, onMessage, {48
onClose,49
onError,50
onOpen,51
onReconnecting,52
autoReconnect = false,53
reconnectBaseMs = 750,54
reconnectMaxMs = 20_00055
} = {})4
{56
{5
this.url = url;57
this.url = url;6
this.onMessage = onMessage;58
this.onMessage = onMessage;7
this.onClose = onClose;59
this.onClose = onClose;8
this.onError = onError;60
this.onError = onError;61
this.onOpen = onOpen;62
this.onReconnecting = onReconnecting;63
this.autoReconnect = !!autoReconnect;64
this.reconnectBaseMs = reconnectBaseMs;65
this.reconnectMaxMs = reconnectMaxMs;9
this.socket = null;66
this.socket = null;10
}67
this._intentionalClose = false;11
68
this._reconnectAttempt = 0;12
connect ()69
this._reconnectTimer = null;13
{70
this._boundMessage = (event) =>14
this.socket = new WebSocket(this.url);15
this.socket.addEventListener("message", (event) =>16
{71
{17
this.onMessage(JSON.parse(event.data));72
this.onMessage(JSON.parse(event.data));18
});73
};19
this.socket.addEventListener("close", (event) =>74
this._boundClose = (event) =>20
{75
{21
this.onClose?.(event);76
this._handleClose(event);22
});77
};23
this.socket.addEventListener("error", (event) =>78
this._boundError = (event) =>24
{79
{25
this.onError?.(event);80
this.onError?.(event);26
});81
};27
return new Promise((resolve, reject) =>82
this._boundOpen = (event) =>28
{83
{29
this.socket.addEventListener("open", resolve, { once: true });84
this.onOpen?.(event);30
this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true });85
};31
});86
}87
88
connect ()89
{90
this._intentionalClose = false;91
return this._openSocket();92
}93
94
/** Graceful client-initiated close — does not auto-reconnect. */95
close (code = 1000, reason = "Client closed")96
{97
this._intentionalClose = true;98
this._clearReconnectTimer();99
this._reconnectAttempt = 0;100
const socket = this.socket;101
this._detach(socket);102
if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING))103
{104
try105
{ socket.close(code, reason); }106
catch107
{ /* ignore */ }108
}109
this.socket = null;110
}111
112
/** Call when an application SESSION (or equivalent) is established so backoff resets. */113
notifySessionEstablished ()114
{115
this._reconnectAttempt = 0;116
this._clearReconnectTimer();32
}117
}33
118
34
send (payload)119
send (payload)@@ -37,6 +122,106 @@ export class GameSocket37
{ throw new Error("WebSocket is not connected."); }122
{ throw new Error("WebSocket is not connected."); }38
this.socket.send(JSON.stringify(payload));123
this.socket.send(JSON.stringify(payload));39
}124
}125
126
get reconnecting ()127
{128
return this._reconnectTimer != null;129
}130
131
_openSocket ()132
{133
this._clearReconnectTimer();134
this._detach(this.socket);135
const socket = new WebSocket(this.url);136
this.socket = socket;137
socket.addEventListener("message", this._boundMessage);138
socket.addEventListener("close", this._boundClose);139
socket.addEventListener("error", this._boundError);140
socket.addEventListener("open", this._boundOpen);141
142
return new Promise((resolve, reject) =>143
{144
const onOpen = () =>145
{146
cleanup();147
resolve();148
};149
const onError = () =>150
{151
cleanup();152
reject(new Error("WebSocket failed"));153
};154
const cleanup = () =>155
{156
socket.removeEventListener("open", onOpen);157
socket.removeEventListener("error", onError);158
};159
socket.addEventListener("open", onOpen, { once: true });160
socket.addEventListener("error", onError, { once: true });161
});162
}163
164
_detach (socket)165
{166
if (!socket)167
{ return; }168
socket.removeEventListener("message", this._boundMessage);169
socket.removeEventListener("close", this._boundClose);170
socket.removeEventListener("error", this._boundError);171
socket.removeEventListener("open", this._boundOpen);172
}173
174
_clearReconnectTimer ()175
{176
if (this._reconnectTimer != null)177
{178
clearTimeout(this._reconnectTimer);179
this._reconnectTimer = null;180
}181
}182
183
_scheduleReconnect (code)184
{185
const attempt = this._reconnectAttempt;186
const delayMs = nextReconnectDelayMs(attempt, {187
baseMs: this.reconnectBaseMs,188
maxMs: this.reconnectMaxMs189
});190
this._reconnectAttempt = attempt + 1;191
this.onReconnecting?.({ attempt: this._reconnectAttempt, delayMs, code: code | 0 });192
this._reconnectTimer = setTimeout(() =>193
{194
this._reconnectTimer = null;195
void this._openSocket().catch(() =>196
{197
// open/error path usually also emits close; if not, retry from here198
if (this._intentionalClose || !this.autoReconnect || this.socket)199
{ return; }200
this._scheduleReconnect(code);201
});202
}, delayMs);203
}204
205
_handleClose (event)206
{207
this._detach(event?.target ?? this.socket);208
if (this.socket === event?.target)209
{ this.socket = null; }210
211
this.onClose?.(event);212
213
const code = event?.code | 0;214
if (!shouldAutoReconnect(code, {215
intentional: this._intentionalClose,216
autoReconnect: this.autoReconnect217
}))218
{219
this._intentionalClose = false;220
return;221
}222
223
this._scheduleReconnect(code);224
}40
}225
}41
226
42
export function defaultSocketUrl ()227
export function defaultSocketUrl ()@@ -2,6 +2,7 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO
2
2
import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3
3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4
4
import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";
5
import { enclosedAmbientDarkness } from "/shared/lighting/enclosed.js";
5
6
import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";
6
7
import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7
8
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
@@ -4372,6 +4373,32 @@ export class WorldView
4372
4373
return dark;
4373
4374
}
4374
4375
4376
#tileEnclosedFlag (tileX, tileY)
4377
{
4378
const chunkX = Math.floor(tileX / CHUNK_SIZE);
4379
const chunkY = Math.floor(tileY / CHUNK_SIZE);
4380
const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4381
if (!snapshot)
4382
{ return 0; }
4383
const enclosed = snapshot.enclosed;
4384
if (!Array.isArray(enclosed) || enclosed.length < CHUNK_SIZE * CHUNK_SIZE)
4385
{ return 0; }
4386
const localX = tileX - chunkX * CHUNK_SIZE;
4387
const localY = tileY - chunkY * CHUNK_SIZE;
4388
if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
4389
{ return 0; }
4390
return enclosed[localY * CHUNK_SIZE + localX] ? 1 : 0;
4391
}
4392
4393
/** Base ambient plus enclosed bonus, clamped to nightDarkness peak. */
4394
#ambientDarknessForTile (tileX, tileY, baseAmbient = this.#ambientDarkness())
4395
{
4396
return enclosedAmbientDarkness(baseAmbient, this.#tileEnclosedFlag(tileX, tileY), {
4397
enclosedDarknessBonus: this.settings.enclosedDarknessBonus ?? 0.10,
4398
nightDarkness: this.settings.nightDarkness ?? 0.72
4399
});
4400
}
4401
4375
4402
setLocalBlind (blind)
4376
4403
{
4377
4404
this.localBlind = !!blind;
@@ -6016,8 +6043,11 @@ export class WorldView
6016
6043
/** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */
6017
6044
#tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark)
6018
6045
{
6046
const tileAmbient = objects?.tileX != null && objects?.tileY != null
6047
? this.#ambientDarknessForTile(objects.tileX, objects.tileY, ambientDark)
6048
: ambientDark;
6019
6049
const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion);
6020
return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
6050
return Math.min(1, Math.max(0, tileAmbient) * (1 - lights) + dark);
6021
6051
}
6022
6052
6023
6053
#tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
@@ -6028,6 +6058,7 @@ export class WorldView
6028
6058
/** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
6029
6059
#intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
6030
6060
{
6061
const tileAmbient = this.#ambientDarknessForTile(tileX, tileY, ambientDark);
6031
6062
const tileObjects = this.tiles.get(`${tileX},${tileY}`);
6032
6063
if (tileObjects)
6033
6064
{ return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); }
@@ -6035,7 +6066,7 @@ export class WorldView
6035
6066
const chunkY = Math.floor(tileY / CHUNK_SIZE);
6036
6067
const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
6037
6068
if (!snapshot)
6038
{ return 1 - Math.min(1, Math.max(0, ambientDark)); }
6069
{ return 1 - Math.min(1, Math.max(0, tileAmbient)); }
6039
6070
const localX = tileX - chunkX * CHUNK_SIZE;
6040
6071
const localY = tileY - chunkY * CHUNK_SIZE;
6041
6072
const index = localY * CHUNK_SIZE + localX;
@@ -6044,7 +6075,7 @@ export class WorldView
6044
6075
const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
6045
6076
const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
6046
6077
const lights = Math.max(bakedLit, dynamic);
6047
const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
6078
const shade = Math.min(1, Math.max(0, tileAmbient) * (1 - lights) + dark);
6048
6079
return 1 - shade;
6049
6080
}
6050
6081
@@ -6183,6 +6214,11 @@ export class WorldView
6183
6214
if (!snapshot?.light)
6184
6215
{ return null; }
6185
6216
const bakedHash = this.#hashUint8Array(snapshot.light);
6217
const enclosedHash = Array.isArray(snapshot.enclosed)
6218
? this.#hashUint8Array(snapshot.enclosed)
6219
: 0;
6220
const bonusKey = Math.round(Math.max(0, this.settings.enclosedDarknessBonus ?? 0.10) * 1000);
6221
const peakKey = Math.round(Math.max(0, this.settings.nightDarkness ?? 0.72) * 1000);
6186
6222
// Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring).
6187
6223
const lights = activeLights;
6188
6224
const darks = this._activeSpellDarks ?? [];
@@ -6202,7 +6238,7 @@ export class WorldView
6202
6238
{ continue; }
6203
6239
darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`;
6204
6240
}
6205
return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`;
6241
return `a:${mode}:${ambientKey}:${bonusKey}:${peakKey}:${bakedHash}:${enclosedHash}:${lightsKey}|${darksKey}`;
6206
6242
}
6207
6243
6208
6244
#invalidateNeighborLightmapCaches (chunkX, chunkY)
@@ -2,6 +2,7 @@ import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BO2
import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";2
import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";3
import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";4
import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";4
import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";5
import { enclosedAmbientDarkness } from "/shared/lighting/enclosed.js";5
import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";6
import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";6
import { smoothLitCorner } from "/shared/lighting/lightCorners.js";7
import { smoothLitCorner } from "/shared/lighting/lightCorners.js";7
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";8
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";@@ -4372,6 +4373,32 @@ export class WorldView4372
return dark;4373
return dark;4373
}4374
}4374
4375
4376
#tileEnclosedFlag (tileX, tileY)4377
{4378
const chunkX = Math.floor(tileX / CHUNK_SIZE);4379
const chunkY = Math.floor(tileY / CHUNK_SIZE);4380
const snapshot = this.chunks.get(`${chunkX},${chunkY}`);4381
if (!snapshot)4382
{ return 0; }4383
const enclosed = snapshot.enclosed;4384
if (!Array.isArray(enclosed) || enclosed.length < CHUNK_SIZE * CHUNK_SIZE)4385
{ return 0; }4386
const localX = tileX - chunkX * CHUNK_SIZE;4387
const localY = tileY - chunkY * CHUNK_SIZE;4388
if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)4389
{ return 0; }4390
return enclosed[localY * CHUNK_SIZE + localX] ? 1 : 0;4391
}4392
4393
/** Base ambient plus enclosed bonus, clamped to nightDarkness peak. */4394
#ambientDarknessForTile (tileX, tileY, baseAmbient = this.#ambientDarkness())4395
{4396
return enclosedAmbientDarkness(baseAmbient, this.#tileEnclosedFlag(tileX, tileY), {4397
enclosedDarknessBonus: this.settings.enclosedDarknessBonus ?? 0.10,4398
nightDarkness: this.settings.nightDarkness ?? 0.724399
});4400
}4401
4375
setLocalBlind (blind)4402
setLocalBlind (blind)4376
{4403
{4377
this.localBlind = !!blind;4404
this.localBlind = !!blind;@@ -6016,8 +6043,11 @@ export class WorldView6016
/** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */6043
/** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */6017
#tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark)6044
#tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark)6018
{6045
{6046
const tileAmbient = objects?.tileX != null && objects?.tileY != null6047
? this.#ambientDarknessForTile(objects.tileX, objects.tileY, ambientDark)6048
: ambientDark;6019
const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion);6049
const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion);6020
return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);6050
return Math.min(1, Math.max(0, tileAmbient) * (1 - lights) + dark);6021
}6051
}6022
6052
6023
#tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())6053
#tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())@@ -6028,6 +6058,7 @@ export class WorldView6028
/** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */6058
/** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */6029
#intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())6059
#intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())6030
{6060
{6061
const tileAmbient = this.#ambientDarknessForTile(tileX, tileY, ambientDark);6031
const tileObjects = this.tiles.get(`${tileX},${tileY}`);6062
const tileObjects = this.tiles.get(`${tileX},${tileY}`);6032
if (tileObjects)6063
if (tileObjects)6033
{ return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); }6064
{ return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); }@@ -6035,7 +6066,7 @@ export class WorldView6035
const chunkY = Math.floor(tileY / CHUNK_SIZE);6066
const chunkY = Math.floor(tileY / CHUNK_SIZE);6036
const snapshot = this.chunks.get(`${chunkX},${chunkY}`);6067
const snapshot = this.chunks.get(`${chunkX},${chunkY}`);6037
if (!snapshot)6068
if (!snapshot)6038
{ return 1 - Math.min(1, Math.max(0, ambientDark)); }6069
{ return 1 - Math.min(1, Math.max(0, tileAmbient)); }6039
const localX = tileX - chunkX * CHUNK_SIZE;6070
const localX = tileX - chunkX * CHUNK_SIZE;6040
const localY = tileY - chunkY * CHUNK_SIZE;6071
const localY = tileY - chunkY * CHUNK_SIZE;6041
const index = localY * CHUNK_SIZE + localX;6072
const index = localY * CHUNK_SIZE + localX;@@ -6044,7 +6075,7 @@ export class WorldView6044
const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);6075
const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);6045
const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);6076
const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);6046
const lights = Math.max(bakedLit, dynamic);6077
const lights = Math.max(bakedLit, dynamic);6047
const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);6078
const shade = Math.min(1, Math.max(0, tileAmbient) * (1 - lights) + dark);6048
return 1 - shade;6079
return 1 - shade;6049
}6080
}6050
6081
@@ -6183,6 +6214,11 @@ export class WorldView6183
if (!snapshot?.light)6214
if (!snapshot?.light)6184
{ return null; }6215
{ return null; }6185
const bakedHash = this.#hashUint8Array(snapshot.light);6216
const bakedHash = this.#hashUint8Array(snapshot.light);6217
const enclosedHash = Array.isArray(snapshot.enclosed)6218
? this.#hashUint8Array(snapshot.enclosed)6219
: 0;6220
const bonusKey = Math.round(Math.max(0, this.settings.enclosedDarknessBonus ?? 0.10) * 1000);6221
const peakKey = Math.round(Math.max(0, this.settings.nightDarkness ?? 0.72) * 1000);6186
// Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring).6222
// Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring).6187
const lights = activeLights;6223
const lights = activeLights;6188
const darks = this._activeSpellDarks ?? [];6224
const darks = this._activeSpellDarks ?? [];@@ -6202,7 +6238,7 @@ export class WorldView6202
{ continue; }6238
{ continue; }6203
darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`;6239
darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`;6204
}6240
}6205
return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`;6241
return `a:${mode}:${ambientKey}:${bonusKey}:${peakKey}:${bakedHash}:${enclosedHash}:${lightsKey}|${darksKey}`;6206
}6242
}6207
6243
6208
#invalidateNeighborLightmapCaches (chunkX, chunkY)6244
#invalidateNeighborLightmapCaches (chunkX, chunkY)@@ -0,0 +1,27 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
4
import { editorChunkSaveKey, shouldApplySelectedEditorChunk } from "../src/editor/saveAck.js";
5
6
test("editorChunkSaveKey is dimension-scoped", () =>
7
{
8
assert.equal(editorChunkSaveKey(OVERWORLD_ID, 1, 2), "overworld:1,2");
9
assert.equal(editorChunkSaveKey("Cave A", 1, 2), "cave-a:1,2");
10
assert.notEqual(
11
editorChunkSaveKey(OVERWORLD_ID, 0, 0),
12
editorChunkSaveKey("cave_a", 0, 0)
13
);
14
assert.equal(editorChunkSaveKey(undefined, 0, 0), editorChunkSaveKey(OVERWORLD_ID, 0, 0));
15
});
16
17
test("save ack applies even when the local draft is still dirty", () =>
18
{
19
assert.equal(shouldApplySelectedEditorChunk({ isSaveAck: true, isDirty: true }), true);
20
assert.equal(shouldApplySelectedEditorChunk({ isSaveAck: true, isDirty: false }), true);
21
});
22
23
test("non-ack reload keeps unsaved paint on the selected chunk", () =>
24
{
25
assert.equal(shouldApplySelectedEditorChunk({ isSaveAck: false, isDirty: true }), false);
26
assert.equal(shouldApplySelectedEditorChunk({ isSaveAck: false, isDirty: false }), true);
27
});
@@ -0,0 +1,27 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { OVERWORLD_ID } from "../../shared/world/dimensions.js";4
import { editorChunkSaveKey, shouldApplySelectedEditorChunk } from "../src/editor/saveAck.js";5
6
test("editorChunkSaveKey is dimension-scoped", () =>7
{8
assert.equal(editorChunkSaveKey(OVERWORLD_ID, 1, 2), "overworld:1,2");9
assert.equal(editorChunkSaveKey("Cave A", 1, 2), "cave-a:1,2");10
assert.notEqual(11
editorChunkSaveKey(OVERWORLD_ID, 0, 0),12
editorChunkSaveKey("cave_a", 0, 0)13
);14
assert.equal(editorChunkSaveKey(undefined, 0, 0), editorChunkSaveKey(OVERWORLD_ID, 0, 0));15
});16
17
test("save ack applies even when the local draft is still dirty", () =>18
{19
assert.equal(shouldApplySelectedEditorChunk({ isSaveAck: true, isDirty: true }), true);20
assert.equal(shouldApplySelectedEditorChunk({ isSaveAck: true, isDirty: false }), true);21
});22
23
test("non-ack reload keeps unsaved paint on the selected chunk", () =>24
{25
assert.equal(shouldApplySelectedEditorChunk({ isSaveAck: false, isDirty: true }), false);26
assert.equal(shouldApplySelectedEditorChunk({ isSaveAck: false, isDirty: false }), true);27
});@@ -0,0 +1,25 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import {
4
nextReconnectDelayMs,
5
shouldAutoReconnect,
6
NO_AUTO_RECONNECT_CODES
7
} from "../src/net/socket.js";
8
9
test("nextReconnectDelayMs grows exponentially and caps", () =>
10
{
11
assert.equal(nextReconnectDelayMs(0, { baseMs: 750, maxMs: 20_000 }), 750);
12
assert.equal(nextReconnectDelayMs(1, { baseMs: 750, maxMs: 20_000 }), 1500);
13
assert.equal(nextReconnectDelayMs(2, { baseMs: 750, maxMs: 20_000 }), 3000);
14
assert.equal(nextReconnectDelayMs(10, { baseMs: 750, maxMs: 20_000 }), 20_000);
15
assert.equal(nextReconnectDelayMs(-1, { baseMs: 500, maxMs: 1000 }), 500);
16
});
17
18
test("shouldAutoReconnect skips intentional, auth, and restart closes", () =>
19
{
20
assert.equal(shouldAutoReconnect(1006, { autoReconnect: true }), true);
21
assert.equal(shouldAutoReconnect(1006, { autoReconnect: false }), false);
22
assert.equal(shouldAutoReconnect(1006, { autoReconnect: true, intentional: true }), false);
23
for (const code of NO_AUTO_RECONNECT_CODES)
24
{ assert.equal(shouldAutoReconnect(code, { autoReconnect: true }), false); }
25
});
@@ -0,0 +1,25 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import {4
nextReconnectDelayMs,5
shouldAutoReconnect,6
NO_AUTO_RECONNECT_CODES7
} from "../src/net/socket.js";8
9
test("nextReconnectDelayMs grows exponentially and caps", () =>10
{11
assert.equal(nextReconnectDelayMs(0, { baseMs: 750, maxMs: 20_000 }), 750);12
assert.equal(nextReconnectDelayMs(1, { baseMs: 750, maxMs: 20_000 }), 1500);13
assert.equal(nextReconnectDelayMs(2, { baseMs: 750, maxMs: 20_000 }), 3000);14
assert.equal(nextReconnectDelayMs(10, { baseMs: 750, maxMs: 20_000 }), 20_000);15
assert.equal(nextReconnectDelayMs(-1, { baseMs: 500, maxMs: 1000 }), 500);16
});17
18
test("shouldAutoReconnect skips intentional, auth, and restart closes", () =>19
{20
assert.equal(shouldAutoReconnect(1006, { autoReconnect: true }), true);21
assert.equal(shouldAutoReconnect(1006, { autoReconnect: false }), false);22
assert.equal(shouldAutoReconnect(1006, { autoReconnect: true, intentional: true }), false);23
for (const code of NO_AUTO_RECONNECT_CODES)24
{ assert.equal(shouldAutoReconnect(code, { autoReconnect: true }), false); }25
});@@ -1,8 +1,9 @@
1
1
import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock, BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
2
2
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3
import { localToTile } from "../world/coordinates.js";
3
import { localToTile, chunkKey } from "../world/coordinates.js";
4
4
import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";
5
5
import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
6
import { bakeEnclosedMaps } from "../lighting/enclosedBaker.js";
6
7
import { closedNeighborEdges } from "../world/chunkFlags.js";
7
8
import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";
8
9
import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
@@ -120,18 +121,42 @@ export class EditorService
120
121
121
122
const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
122
123
const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
124
const loadForBake = (x, y) => this.#loadForBake(
125
x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId
126
);
123
127
const baked = bakeLightMaps(
124
128
chunkX,
125
129
chunkY,
126
(x, y) => this.#loadForBake(x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId),
127
maxDefinitionLightRange(BLOCK_DEFINITIONS, GROUND_DEFINITIONS)
130
loadForBake,
131
maxDefinitionLightRange(BLOCK_DEFINITIONS, GROUND_DEFINITIONS),
132
dimId
128
133
);
129
134
const byKey = new Map();
130
135
for (const result of baked)
136
{ byKey.set(chunkKey(result.chunkX, result.chunkY, dimId), result); }
137
138
const enclosedBaked = bakeEnclosedMaps(chunkX, chunkY, (x, y) =>
139
{
140
const key = chunkKey(x, y, dimId);
141
if (byKey.has(key))
142
{ return byKey.get(key).data; }
143
return loadForBake(x, y);
144
}, dimId);
145
for (const result of enclosedBaked)
146
{
147
const key = chunkKey(result.chunkX, result.chunkY, dimId);
148
if (byKey.has(key))
149
{ byKey.get(key).data.enclosed = result.data.enclosed; }
150
else
151
{ byKey.set(key, result); }
152
}
153
154
for (const result of byKey.values())
131
155
{
132
156
const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
133
157
|| this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId)
134
|| result.data.light.some((value) => value > 0);
158
|| result.data.light.some((value) => value > 0)
159
|| (Array.isArray(result.data.enclosed) && result.data.enclosed.some((value) => value > 0));
135
160
136
161
if (!shouldStore)
137
162
{ continue; }
@@ -1,8 +1,9 @@1
import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock, BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";1
import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock, BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";2
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";2
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";3
import { localToTile } from "../world/coordinates.js";3
import { localToTile, chunkKey } from "../world/coordinates.js";4
import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";4
import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";5
import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";5
import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";6
import { bakeEnclosedMaps } from "../lighting/enclosedBaker.js";6
import { closedNeighborEdges } from "../world/chunkFlags.js";7
import { closedNeighborEdges } from "../world/chunkFlags.js";7
import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";8
import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";8
import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";9
import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";@@ -120,18 +121,42 @@ export class EditorService120
121
121
const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);122
const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);122
const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);123
const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);124
const loadForBake = (x, y) => this.#loadForBake(125
x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId126
);123
const baked = bakeLightMaps(127
const baked = bakeLightMaps(124
chunkX,128
chunkX,125
chunkY,129
chunkY,126
(x, y) => this.#loadForBake(x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId),130
loadForBake,127
maxDefinitionLightRange(BLOCK_DEFINITIONS, GROUND_DEFINITIONS)131
maxDefinitionLightRange(BLOCK_DEFINITIONS, GROUND_DEFINITIONS),132
dimId128
);133
);129
134
const byKey = new Map();130
for (const result of baked)135
for (const result of baked)136
{ byKey.set(chunkKey(result.chunkX, result.chunkY, dimId), result); }137
138
const enclosedBaked = bakeEnclosedMaps(chunkX, chunkY, (x, y) =>139
{140
const key = chunkKey(x, y, dimId);141
if (byKey.has(key))142
{ return byKey.get(key).data; }143
return loadForBake(x, y);144
}, dimId);145
for (const result of enclosedBaked)146
{147
const key = chunkKey(result.chunkX, result.chunkY, dimId);148
if (byKey.has(key))149
{ byKey.get(key).data.enclosed = result.data.enclosed; }150
else151
{ byKey.set(key, result); }152
}153
154
for (const result of byKey.values())131
{155
{132
const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY156
const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY133
|| this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId)157
|| this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId)134
|| result.data.light.some((value) => value > 0);158
|| result.data.light.some((value) => value > 0)159
|| (Array.isArray(result.data.enclosed) && result.data.enclosed.some((value) => value > 0));135
160
136
if (!shouldStore)161
if (!shouldStore)137
{ continue; }162
{ continue; }@@ -1,4 +1,5 @@
1
1
import { WebSocketServer } from "ws";
2
import { startWebSocketKeepalive } from "./wsKeepalive.js";
2
3
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3
4
import { chunkKey, parseChunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4
5
import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -19,6 +20,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
19
20
const wss = new WebSocketServer({ server: httpServer, path: "/ws" });
20
21
const sessions = new Map();
21
22
let draining = false;
23
const keepalive = startWebSocketKeepalive(wss);
22
24
23
25
subscribeConsole((entry) =>
24
26
{
@@ -2545,6 +2547,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
2545
2547
async shutdown ()
2546
2548
{
2547
2549
draining = true;
2550
keepalive.stop();
2548
2551
await Promise.all([...sessions.values()].map(async (session) =>
2549
2552
{
2550
2553
await sendAsync(session, {
@@ -1,4 +1,5 @@1
import { WebSocketServer } from "ws";1
import { WebSocketServer } from "ws";2
import { startWebSocketKeepalive } from "./wsKeepalive.js";2
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";3
import { MessageType, GAIT } from "../../../shared/protocol/constants.js";3
import { chunkKey, parseChunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";4
import { chunkKey, parseChunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";4
import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";5
import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";@@ -19,6 +20,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,19
const wss = new WebSocketServer({ server: httpServer, path: "/ws" });20
const wss = new WebSocketServer({ server: httpServer, path: "/ws" });20
const sessions = new Map();21
const sessions = new Map();21
let draining = false;22
let draining = false;23
const keepalive = startWebSocketKeepalive(wss);22
24
23
subscribeConsole((entry) =>25
subscribeConsole((entry) =>24
{26
{@@ -2545,6 +2547,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,2545
async shutdown ()2547
async shutdown ()2546
{2548
{2547
draining = true;2549
draining = true;2550
keepalive.stop();2548
await Promise.all([...sessions.values()].map(async (session) =>2551
await Promise.all([...sessions.values()].map(async (session) =>2549
{2552
{2550
await sendAsync(session, {2553
await sendAsync(session, {@@ -0,0 +1,77 @@
1
/**
2
* Protocol-level WebSocket ping/pong keepalive so idle editor (and play)
3
* sessions are not killed by proxies that drop quiet connections.
4
*
5
* Browsers auto-reply to WebSocket ping frames; the `ws` library surfaces pong.
6
*/
7
8
export const DEFAULT_WS_PING_INTERVAL_MS = 25_000;
9
10
/**
11
* @param {import("ws").WebSocketServer} wss
12
* @param {{ intervalMs?: number, setIntervalFn?: typeof setInterval, clearIntervalFn?: typeof clearInterval }} [options]
13
* @returns {{ stop: () => void, intervalMs: number }}
14
*/
15
export function startWebSocketKeepalive (wss, options = {})
16
{
17
const intervalMs = options.intervalMs ?? DEFAULT_WS_PING_INTERVAL_MS;
18
const setIntervalFn = options.setIntervalFn ?? setInterval;
19
const clearIntervalFn = options.clearIntervalFn ?? clearInterval;
20
21
const onConnection = (socket) =>
22
{
23
socket.isAlive = true;
24
socket.on("pong", () =>
25
{
26
socket.isAlive = true;
27
});
28
};
29
30
wss.on("connection", onConnection);
31
for (const socket of wss.clients)
32
{ onConnection(socket); }
33
34
const interval = setIntervalFn(() =>
35
{
36
for (const socket of wss.clients)
37
{
38
if (socket.isAlive === false)
39
{
40
socket.terminate();
41
continue;
42
}
43
socket.isAlive = false;
44
try
45
{ socket.ping(); }
46
catch
47
{
48
try
49
{ socket.terminate(); }
50
catch
51
{ /* ignore */ }
52
}
53
}
54
}, intervalMs);
55
56
if (typeof interval?.unref === "function")
57
{ interval.unref(); }
58
59
const onClose = () =>
60
{
61
stop();
62
};
63
wss.on("close", onClose);
64
65
let stopped = false;
66
function stop ()
67
{
68
if (stopped)
69
{ return; }
70
stopped = true;
71
clearIntervalFn(interval);
72
wss.off("connection", onConnection);
73
wss.off("close", onClose);
74
}
75
76
return { stop, intervalMs };
77
}
@@ -0,0 +1,77 @@1
/**2
* Protocol-level WebSocket ping/pong keepalive so idle editor (and play)3
* sessions are not killed by proxies that drop quiet connections.4
*5
* Browsers auto-reply to WebSocket ping frames; the `ws` library surfaces pong.6
*/7
8
export const DEFAULT_WS_PING_INTERVAL_MS = 25_000;9
10
/**11
* @param {import("ws").WebSocketServer} wss12
* @param {{ intervalMs?: number, setIntervalFn?: typeof setInterval, clearIntervalFn?: typeof clearInterval }} [options]13
* @returns {{ stop: () => void, intervalMs: number }}14
*/15
export function startWebSocketKeepalive (wss, options = {})16
{17
const intervalMs = options.intervalMs ?? DEFAULT_WS_PING_INTERVAL_MS;18
const setIntervalFn = options.setIntervalFn ?? setInterval;19
const clearIntervalFn = options.clearIntervalFn ?? clearInterval;20
21
const onConnection = (socket) =>22
{23
socket.isAlive = true;24
socket.on("pong", () =>25
{26
socket.isAlive = true;27
});28
};29
30
wss.on("connection", onConnection);31
for (const socket of wss.clients)32
{ onConnection(socket); }33
34
const interval = setIntervalFn(() =>35
{36
for (const socket of wss.clients)37
{38
if (socket.isAlive === false)39
{40
socket.terminate();41
continue;42
}43
socket.isAlive = false;44
try45
{ socket.ping(); }46
catch47
{48
try49
{ socket.terminate(); }50
catch51
{ /* ignore */ }52
}53
}54
}, intervalMs);55
56
if (typeof interval?.unref === "function")57
{ interval.unref(); }58
59
const onClose = () =>60
{61
stop();62
};63
wss.on("close", onClose);64
65
let stopped = false;66
function stop ()67
{68
if (stopped)69
{ return; }70
stopped = true;71
clearIntervalFn(interval);72
wss.off("connection", onConnection);73
wss.off("close", onClose);74
}75
76
return { stop, intervalMs };77
}@@ -0,0 +1,42 @@
1
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2
import { bakeEnclosedWindow, ENCLOSED_BAKE_CHUNK_RADIUS } from "../../../shared/lighting/enclosed.js";
3
import { chunkKey, chebyshevChunks } from "../world/coordinates.js";
4
import { cloneChunkData } from "../world/chunkData.js";
5
6
export { ENCLOSED_BAKE_CHUNK_RADIUS };
7
8
/**
9
* Bake enclosed masks into cloned chunk data for the 3×3 window around the saved chunk.
10
* Same return shape as bakeLightMaps for easy merge in editor save.
11
*/
12
export function bakeEnclosedMaps (centerChunkX, centerChunkY, loadChunk, dimensionId = OVERWORLD_ID)
13
{
14
const dim = normalizeDimensionId(dimensionId);
15
const loaded = new Map();
16
17
function getData (chunkX, chunkY)
18
{
19
const key = chunkKey(chunkX, chunkY, dim);
20
if (!loaded.has(key))
21
{ loaded.set(key, cloneChunkData(loadChunk(chunkX, chunkY))); }
22
return loaded.get(key);
23
}
24
25
// Prefetch window so clone exists before mask write.
26
for (const coord of chebyshevChunks(centerChunkX, centerChunkY, ENCLOSED_BAKE_CHUNK_RADIUS))
27
{ getData(coord.chunkX, coord.chunkY); }
28
29
const baked = bakeEnclosedWindow(centerChunkX, centerChunkY, (chunkX, chunkY) => getData(chunkX, chunkY));
30
for (const entry of baked)
31
{
32
const data = getData(entry.chunkX, entry.chunkY);
33
data.enclosed = entry.enclosed;
34
}
35
36
return baked.map((entry) => ({
37
chunkX: entry.chunkX,
38
chunkY: entry.chunkY,
39
dimensionId: dim,
40
data: loaded.get(chunkKey(entry.chunkX, entry.chunkY, dim))
41
}));
42
}
@@ -0,0 +1,42 @@1
import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";2
import { bakeEnclosedWindow, ENCLOSED_BAKE_CHUNK_RADIUS } from "../../../shared/lighting/enclosed.js";3
import { chunkKey, chebyshevChunks } from "../world/coordinates.js";4
import { cloneChunkData } from "../world/chunkData.js";5
6
export { ENCLOSED_BAKE_CHUNK_RADIUS };7
8
/**9
* Bake enclosed masks into cloned chunk data for the 3×3 window around the saved chunk.10
* Same return shape as bakeLightMaps for easy merge in editor save.11
*/12
export function bakeEnclosedMaps (centerChunkX, centerChunkY, loadChunk, dimensionId = OVERWORLD_ID)13
{14
const dim = normalizeDimensionId(dimensionId);15
const loaded = new Map();16
17
function getData (chunkX, chunkY)18
{19
const key = chunkKey(chunkX, chunkY, dim);20
if (!loaded.has(key))21
{ loaded.set(key, cloneChunkData(loadChunk(chunkX, chunkY))); }22
return loaded.get(key);23
}24
25
// Prefetch window so clone exists before mask write.26
for (const coord of chebyshevChunks(centerChunkX, centerChunkY, ENCLOSED_BAKE_CHUNK_RADIUS))27
{ getData(coord.chunkX, coord.chunkY); }28
29
const baked = bakeEnclosedWindow(centerChunkX, centerChunkY, (chunkX, chunkY) => getData(chunkX, chunkY));30
for (const entry of baked)31
{32
const data = getData(entry.chunkX, entry.chunkY);33
data.enclosed = entry.enclosed;34
}35
36
return baked.map((entry) => ({37
chunkX: entry.chunkX,38
chunkY: entry.chunkY,39
dimensionId: dim,40
data: loaded.get(chunkKey(entry.chunkX, entry.chunkY, dim))41
}));42
}@@ -3305,6 +3305,7 @@ export class Simulation
3305
3305
grounds: data.grounds,
3306
3306
blocks: data.blocks,
3307
3307
light: data.light,
3308
enclosed: data.enclosed,
3308
3309
entities: [],
3309
3310
groundItems: []
3310
3311
};
@@ -3305,6 +3305,7 @@ export class Simulation3305
grounds: data.grounds,3305
grounds: data.grounds,3306
blocks: data.blocks,3306
blocks: data.blocks,3307
light: data.light,3307
light: data.light,3308
enclosed: data.enclosed,3308
entities: [],3309
entities: [],3309
groundItems: []3310
groundItems: []3310
};3311
};@@ -2347,6 +2347,7 @@ export class WorkerWorld
2347
2347
grounds: data.grounds,
2348
2348
blocks: data.blocks,
2349
2349
light: data.light,
2350
enclosed: data.enclosed,
2350
2351
occlusion: data.occlusion,
2351
2352
entities: [],
2352
2353
groundItems: []
@@ -2373,6 +2374,7 @@ export class WorkerWorld
2373
2374
grounds: data.grounds,
2374
2375
blocks: data.blocks,
2375
2376
light: data.light,
2377
enclosed: data.enclosed,
2376
2378
occlusion: data.occlusion,
2377
2379
entities,
2378
2380
groundItems: groundItemsInChunk(this, chunkX, chunkY, dim)
@@ -2347,6 +2347,7 @@ export class WorkerWorld2347
grounds: data.grounds,2347
grounds: data.grounds,2348
blocks: data.blocks,2348
blocks: data.blocks,2349
light: data.light,2349
light: data.light,2350
enclosed: data.enclosed,2350
occlusion: data.occlusion,2351
occlusion: data.occlusion,2351
entities: [],2352
entities: [],2352
groundItems: []2353
groundItems: []@@ -2373,6 +2374,7 @@ export class WorkerWorld2373
grounds: data.grounds,2374
grounds: data.grounds,2374
blocks: data.blocks,2375
blocks: data.blocks,2375
light: data.light,2376
light: data.light,2377
enclosed: data.enclosed,2376
occlusion: data.occlusion,2378
occlusion: data.occlusion,2377
entities,2379
entities,2378
groundItems: groundItemsInChunk(this, chunkX, chunkY, dim)2380
groundItems: groundItemsInChunk(this, chunkX, chunkY, dim)@@ -31,11 +31,13 @@ export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defa
31
31
const grounds = new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId));
32
32
const blocks = new Array(tileCount).fill(null);
33
33
const light = new Array(tileCount).fill(0);
34
const enclosed = new Array(tileCount).fill(0);
34
35
return {
35
36
open: false,
36
37
grounds,
37
38
blocks,
38
39
light,
40
enclosed,
39
41
spawners: []
40
42
};
41
43
}
@@ -47,6 +49,7 @@ export function cloneChunkData (data)
47
49
grounds: data.grounds.map((ground) => normalizeGround(ground)),
48
50
blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),
49
51
light: data.light.slice(),
52
enclosed: ensureChunkEnclosed(data).slice(),
50
53
occlusion: ensureChunkOcclusion(data).slice(),
51
54
spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)
52
55
};
@@ -59,6 +62,7 @@ export function encodeChunkBlob (data)
59
62
grounds: data.grounds.map((ground) => normalizeGround(ground)),
60
63
blocks: data.blocks.map((block) => normalizeBlock(block)),
61
64
light: data.light,
65
enclosed: ensureChunkEnclosed(data),
62
66
spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)
63
67
};
64
68
normalized.occlusion = bakeChunkOcclusion(normalized);
@@ -76,6 +80,9 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
76
80
const grounds = Array.isArray(parsed.grounds) ? parsed.grounds.slice(0, tileCount) : fallback.grounds;
77
81
const blocks = Array.isArray(parsed.blocks) ? parsed.blocks.slice(0, tileCount) : fallback.blocks.slice();
78
82
const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;
83
const enclosed = Array.isArray(parsed.enclosed)
84
? parsed.enclosed.slice(0, tileCount).map((v) => (v ? 1 : 0))
85
: fallback.enclosed.slice();
79
86
80
87
while (grounds.length < tileCount)
81
88
{ grounds.push(normalizeGround(groundTypeId, groundTypeId)); }
@@ -83,6 +90,8 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
83
90
{ blocks.push(null); }
84
91
while (light.length < tileCount)
85
92
{ light.push(0); }
93
while (enclosed.length < tileCount)
94
{ enclosed.push(0); }
86
95
87
96
const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);
88
97
const originX = (chunkX | 0) * CHUNK_SIZE;
@@ -107,6 +116,7 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
107
116
return normalized;
108
117
}),
109
118
light,
119
enclosed,
110
120
spawners
111
121
};
112
122
decoded.occlusion = bakeChunkOcclusion(decoded);
@@ -162,6 +172,7 @@ export function getTile (data, localX, localY)
162
172
groundState: ground.state,
163
173
block: data.blocks[index],
164
174
light: data.light[index],
175
enclosed: ensureChunkEnclosed(data)[index] ? 1 : 0,
165
176
spawner: spawnerAt(data, localX, localY)
166
177
};
167
178
}
@@ -262,4 +273,16 @@ function migrateLegacySpawners (blocks, authored, parsedHint)
262
273
return [...byKey.values()].filter(Boolean);
263
274
}
264
275
276
277
export function ensureChunkEnclosed (data)
278
{
279
const tileCount = CHUNK_SIZE * CHUNK_SIZE;
280
if (Array.isArray(data?.enclosed) && data.enclosed.length >= tileCount)
281
{ return data.enclosed; }
282
const enclosed = new Array(tileCount).fill(0);
283
if (data)
284
{ data.enclosed = enclosed; }
285
return enclosed;
286
}
287
265
288
export { GroundType, normalizeGround, normalizeBlock };
@@ -31,11 +31,13 @@ export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defa31
const grounds = new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId));31
const grounds = new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId));32
const blocks = new Array(tileCount).fill(null);32
const blocks = new Array(tileCount).fill(null);33
const light = new Array(tileCount).fill(0);33
const light = new Array(tileCount).fill(0);34
const enclosed = new Array(tileCount).fill(0);34
return {35
return {35
open: false,36
open: false,36
grounds,37
grounds,37
blocks,38
blocks,38
light,39
light,40
enclosed,39
spawners: []41
spawners: []40
};42
};41
}43
}@@ -47,6 +49,7 @@ export function cloneChunkData (data)47
grounds: data.grounds.map((ground) => normalizeGround(ground)),49
grounds: data.grounds.map((ground) => normalizeGround(ground)),48
blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),50
blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),49
light: data.light.slice(),51
light: data.light.slice(),52
enclosed: ensureChunkEnclosed(data).slice(),50
occlusion: ensureChunkOcclusion(data).slice(),53
occlusion: ensureChunkOcclusion(data).slice(),51
spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)54
spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)52
};55
};@@ -59,6 +62,7 @@ export function encodeChunkBlob (data)59
grounds: data.grounds.map((ground) => normalizeGround(ground)),62
grounds: data.grounds.map((ground) => normalizeGround(ground)),60
blocks: data.blocks.map((block) => normalizeBlock(block)),63
blocks: data.blocks.map((block) => normalizeBlock(block)),61
light: data.light,64
light: data.light,65
enclosed: ensureChunkEnclosed(data),62
spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)66
spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)63
};67
};64
normalized.occlusion = bakeChunkOcclusion(normalized);68
normalized.occlusion = bakeChunkOcclusion(normalized);@@ -76,6 +80,9 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def76
const grounds = Array.isArray(parsed.grounds) ? parsed.grounds.slice(0, tileCount) : fallback.grounds;80
const grounds = Array.isArray(parsed.grounds) ? parsed.grounds.slice(0, tileCount) : fallback.grounds;77
const blocks = Array.isArray(parsed.blocks) ? parsed.blocks.slice(0, tileCount) : fallback.blocks.slice();81
const blocks = Array.isArray(parsed.blocks) ? parsed.blocks.slice(0, tileCount) : fallback.blocks.slice();78
const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;82
const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;83
const enclosed = Array.isArray(parsed.enclosed)84
? parsed.enclosed.slice(0, tileCount).map((v) => (v ? 1 : 0))85
: fallback.enclosed.slice();79
86
80
while (grounds.length < tileCount)87
while (grounds.length < tileCount)81
{ grounds.push(normalizeGround(groundTypeId, groundTypeId)); }88
{ grounds.push(normalizeGround(groundTypeId, groundTypeId)); }@@ -83,6 +90,8 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def83
{ blocks.push(null); }90
{ blocks.push(null); }84
while (light.length < tileCount)91
while (light.length < tileCount)85
{ light.push(0); }92
{ light.push(0); }93
while (enclosed.length < tileCount)94
{ enclosed.push(0); }86
95
87
const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);96
const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);88
const originX = (chunkX | 0) * CHUNK_SIZE;97
const originX = (chunkX | 0) * CHUNK_SIZE;@@ -107,6 +116,7 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def107
return normalized;116
return normalized;108
}),117
}),109
light,118
light,119
enclosed,110
spawners120
spawners111
};121
};112
decoded.occlusion = bakeChunkOcclusion(decoded);122
decoded.occlusion = bakeChunkOcclusion(decoded);@@ -162,6 +172,7 @@ export function getTile (data, localX, localY)162
groundState: ground.state,172
groundState: ground.state,163
block: data.blocks[index],173
block: data.blocks[index],164
light: data.light[index],174
light: data.light[index],175
enclosed: ensureChunkEnclosed(data)[index] ? 1 : 0,165
spawner: spawnerAt(data, localX, localY)176
spawner: spawnerAt(data, localX, localY)166
};177
};167
}178
}@@ -262,4 +273,16 @@ function migrateLegacySpawners (blocks, authored, parsedHint)262
return [...byKey.values()].filter(Boolean);273
return [...byKey.values()].filter(Boolean);263
}274
}264
275
276
277
export function ensureChunkEnclosed (data)278
{279
const tileCount = CHUNK_SIZE * CHUNK_SIZE;280
if (Array.isArray(data?.enclosed) && data.enclosed.length >= tileCount)281
{ return data.enclosed; }282
const enclosed = new Array(tileCount).fill(0);283
if (data)284
{ data.enclosed = enclosed; }285
return enclosed;286
}287
265
export { GroundType, normalizeGround, normalizeBlock };288
export { GroundType, normalizeGround, normalizeBlock };@@ -7,6 +7,7 @@ import { WorldDatabase } from "../src/persistence/worldDb.js";
7
7
import { StateDatabase } from "../src/persistence/stateDb.js";
8
8
import { EditorService, diffQuests, diffDialogues } from "../src/editor/service.js";
9
9
import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
10
import { BlockType } from "../../shared/definitions/tiles.js";
10
11
11
12
function tempDirs ()
12
13
{
@@ -78,3 +79,37 @@ test("quest and dialogue saves append changelogs with usernames", () =>
78
79
stateDb.close();
79
80
}
80
81
});
82
83
test("saveChunk persists Void in a non-overworld dimension and returns it on the ack payload", () =>
84
{
85
const { worldDb, stateDb } = tempDirs();
86
try
87
{
88
stateDb.createAccount("auth:42", true, null, "timfa");
89
const editor = new EditorService(worldDb, stateDb);
90
editor.createDimension("void_hall", "Void Hall", "auth:42");
91
const loaded = editor.loadChunk(1, 2, "void_hall");
92
const blocks = loaded.data.blocks.slice();
93
blocks[0] = { typeId: BlockType.void, state: null, config: null };
94
const saved = editor.saveChunk(1, 2, {
95
open: true,
96
grounds: loaded.data.grounds,
97
blocks,
98
spawners: []
99
}, "auth:42", "void_hall");
100
assert.equal(saved.dimensionId, "void_hall");
101
assert.equal(saved.chunkX, 1);
102
assert.equal(saved.chunkY, 2);
103
assert.equal(saved.data.blocks[0]?.typeId, BlockType.void);
104
assert.ok(saved.changelog.some((entry) =>
105
(entry.diffEntries ?? []).some((line) => line.includes("Block Void placed"))));
106
const reloaded = editor.loadChunk(1, 2, "void_hall");
107
assert.equal(reloaded.data.blocks[0]?.typeId, BlockType.void);
108
assert.equal(reloaded.dimensionId, "void_hall");
109
}
110
finally
111
{
112
worldDb.close();
113
stateDb.close();
114
}
115
});
@@ -7,6 +7,7 @@ import { WorldDatabase } from "../src/persistence/worldDb.js";7
import { StateDatabase } from "../src/persistence/stateDb.js";7
import { StateDatabase } from "../src/persistence/stateDb.js";8
import { EditorService, diffQuests, diffDialogues } from "../src/editor/service.js";8
import { EditorService, diffQuests, diffDialogues } from "../src/editor/service.js";9
import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";9
import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";10
import { BlockType } from "../../shared/definitions/tiles.js";10
11
11
function tempDirs ()12
function tempDirs ()12
{13
{@@ -78,3 +79,37 @@ test("quest and dialogue saves append changelogs with usernames", () =>78
stateDb.close();79
stateDb.close();79
}80
}80
});81
});82
83
test("saveChunk persists Void in a non-overworld dimension and returns it on the ack payload", () =>84
{85
const { worldDb, stateDb } = tempDirs();86
try87
{88
stateDb.createAccount("auth:42", true, null, "timfa");89
const editor = new EditorService(worldDb, stateDb);90
editor.createDimension("void_hall", "Void Hall", "auth:42");91
const loaded = editor.loadChunk(1, 2, "void_hall");92
const blocks = loaded.data.blocks.slice();93
blocks[0] = { typeId: BlockType.void, state: null, config: null };94
const saved = editor.saveChunk(1, 2, {95
open: true,96
grounds: loaded.data.grounds,97
blocks,98
spawners: []99
}, "auth:42", "void_hall");100
assert.equal(saved.dimensionId, "void_hall");101
assert.equal(saved.chunkX, 1);102
assert.equal(saved.chunkY, 2);103
assert.equal(saved.data.blocks[0]?.typeId, BlockType.void);104
assert.ok(saved.changelog.some((entry) =>105
(entry.diffEntries ?? []).some((line) => line.includes("Block Void placed"))));106
const reloaded = editor.loadChunk(1, 2, "void_hall");107
assert.equal(reloaded.data.blocks[0]?.typeId, BlockType.void);108
assert.equal(reloaded.dimensionId, "void_hall");109
}110
finally111
{112
worldDb.close();113
stateDb.close();114
}115
});@@ -29,3 +29,12 @@ test("chunk diffs describe spawner placement", () =>
29
29
const bullets = diffChunks(0, 0, previous, next, true);
30
30
assert.ok(bullets.some((line) => line.includes("Spawner (deer) placed at 2, 3.")));
31
31
});
32
33
test("chunk diffs name the Void block", () =>
34
{
35
const previous = createEmptyChunkData();
36
const next = createEmptyChunkData();
37
next.blocks[0] = { typeId: BlockType.void, state: null, config: null };
38
const bullets = diffChunks(0, 0, previous, next, true);
39
assert.ok(bullets.some((line) => line.includes("Block Void placed at 0, 0.")));
40
});
@@ -29,3 +29,12 @@ test("chunk diffs describe spawner placement", () =>29
const bullets = diffChunks(0, 0, previous, next, true);29
const bullets = diffChunks(0, 0, previous, next, true);30
assert.ok(bullets.some((line) => line.includes("Spawner (deer) placed at 2, 3.")));30
assert.ok(bullets.some((line) => line.includes("Spawner (deer) placed at 2, 3.")));31
});31
});32
33
test("chunk diffs name the Void block", () =>34
{35
const previous = createEmptyChunkData();36
const next = createEmptyChunkData();37
next.blocks[0] = { typeId: BlockType.void, state: null, config: null };38
const bullets = diffChunks(0, 0, previous, next, true);39
assert.ok(bullets.some((line) => line.includes("Block Void placed at 0, 0.")));40
});@@ -0,0 +1,218 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { createEmptyChunkData, encodeChunkBlob, decodeChunkBlob } from "../src/world/chunkData.js";
4
import { bakeEnclosedMaps } from "../src/lighting/enclosedBaker.js";
5
import {
6
isEnclosedBoundaryTile,
7
isEnclosedInteriorCandidate,
8
bakeEnclosedWindow,
9
enclosedAmbientDarkness
10
} from "../../shared/lighting/enclosed.js";
11
import { BlockType, GroundType } from "../../shared/definitions/tiles.js";
12
import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../shared/protocol/constants.js";
13
14
function idx (localX, localY)
15
{
16
return localY * CHUNK_SIZE + localX;
17
}
18
19
function wallRect (data, x0, y0, x1, y1)
20
{
21
for (let y = y0; y <= y1; y++)
22
{
23
for (let x = x0; x <= x1; x++)
24
{
25
if (x === x0 || x === x1 || y === y0 || y === y1)
26
{ data.blocks[idx(x, y)] = { typeId: BlockType.stoneWall, config: null }; }
27
}
28
}
29
}
30
31
function loadMap (chunks)
32
{
33
return (cx, cy) => chunks.get(`${cx},${cy}`) ?? createEmptyChunkData();
34
}
35
36
function enclosedAt (results, chunkX, chunkY, localX, localY)
37
{
38
const entry = results.find((r) => r.chunkX === chunkX && r.chunkY === chunkY);
39
assert.ok(entry, `missing enclosed result for ${chunkX},${chunkY}`);
40
return entry.enclosed[idx(localX, localY)];
41
}
42
43
test("predicates: open floor is interior; wall is boundary; water is interior; door is boundary", () =>
44
{
45
const data = createEmptyChunkData();
46
data.blocks[idx(1, 1)] = { typeId: BlockType.stoneWall, config: null };
47
data.grounds[idx(2, 2)] = { typeId: GroundType.water, state: null };
48
data.blocks[idx(3, 3)] = { typeId: BlockType.door, state: "pine-s-open", config: { restingState: "pine-s-closed" } };
49
data.blocks[idx(4, 4)] = { typeId: BlockType.door, state: "pine-s-closed", config: null };
50
51
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 0, 0), false);
52
assert.equal(isEnclosedInteriorCandidate(data.grounds, data.blocks, 0, 0), true);
53
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 1, 1), true);
54
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 2, 2), false, "water is not boundary");
55
assert.equal(isEnclosedInteriorCandidate(data.grounds, data.blocks, 2, 2), true);
56
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 3, 3), true, "open door is boundary");
57
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 4, 4), true, "closed door is boundary");
58
});
59
60
test("open field → nothing enclosed", () =>
61
{
62
const origin = createEmptyChunkData();
63
origin.open = true;
64
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));
65
const self = results.find((r) => r.chunkX === 0 && r.chunkY === 0);
66
assert.ok(self.enclosed.every((v) => v === 0));
67
});
68
69
test("walled room with door → interior + walls + door marked", () =>
70
{
71
const origin = createEmptyChunkData();
72
origin.open = true;
73
// Room at local 4..8, door on south wall at (6,8)
74
wallRect(origin, 4, 4, 8, 8);
75
origin.blocks[idx(6, 8)] = { typeId: BlockType.door, state: "pine-s-closed", config: null };
76
77
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));
78
assert.equal(enclosedAt(results, 0, 0, 6, 6), 1, "interior marked");
79
assert.equal(enclosedAt(results, 0, 0, 5, 5), 1, "interior near corner marked");
80
assert.equal(enclosedAt(results, 0, 0, 4, 6), 1, "west wall (shared edge) marked");
81
assert.equal(enclosedAt(results, 0, 0, 6, 4), 1, "north wall (shared edge) marked");
82
assert.equal(enclosedAt(results, 0, 0, 6, 8), 1, "door marked");
83
assert.equal(enclosedAt(results, 0, 0, 4, 4), 1, "outer wall corner marked via diagonal");
84
assert.equal(enclosedAt(results, 0, 0, 0, 0), 0, "outside not marked");
85
assert.equal(enclosedAt(results, 0, 0, 6, 9), 0, "just outside door not marked");
86
});
87
88
test("1×1 wall and 3×1 wall strip → nothing enclosed", () =>
89
{
90
const origin = createEmptyChunkData();
91
origin.open = true;
92
origin.blocks[idx(8, 8)] = { typeId: BlockType.stoneWall, config: null };
93
origin.blocks[idx(10, 8)] = { typeId: BlockType.stoneWall, config: null };
94
origin.blocks[idx(11, 8)] = { typeId: BlockType.stoneWall, config: null };
95
origin.blocks[idx(12, 8)] = { typeId: BlockType.stoneWall, config: null };
96
97
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));
98
const self = results.find((r) => r.chunkX === 0 && r.chunkY === 0);
99
assert.ok(self.enclosed.every((v) => v === 0), "lone walls must not mark enclosed");
100
});
101
102
test("water inside courtyard counts as enclosed interior", () =>
103
{
104
const origin = createEmptyChunkData();
105
origin.open = true;
106
wallRect(origin, 4, 4, 10, 10);
107
origin.grounds[idx(7, 7)] = { typeId: GroundType.water, state: null };
108
origin.grounds[idx(7, 8)] = { typeId: GroundType.water, state: null };
109
110
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));
111
assert.equal(enclosedAt(results, 0, 0, 7, 7), 1, "water tile enclosed");
112
assert.equal(enclosedAt(results, 0, 0, 7, 8), 1, "water tile enclosed");
113
assert.equal(enclosedAt(results, 0, 0, 6, 6), 1, "dry interior enclosed");
114
});
115
116
test("cross-chunk room within 3×3 is enclosed", () =>
117
{
118
const a = createEmptyChunkData();
119
const b = createEmptyChunkData();
120
a.open = true;
121
b.open = true;
122
// Room straddling chunk 0,0 and 1,0: walls from localX 12..15 on chunk0 and 0..3 on chunk1, y 4..8
123
for (let y = 4; y <= 8; y++)
124
{
125
for (let x = 12; x < CHUNK_SIZE; x++)
126
{
127
if (x === 12 || y === 4 || y === 8)
128
{ a.blocks[idx(x, y)] = { typeId: BlockType.stoneWall, config: null }; }
129
}
130
for (let x = 0; x <= 3; x++)
131
{
132
if (x === 3 || y === 4 || y === 8)
133
{ b.blocks[idx(x, y)] = { typeId: BlockType.stoneWall, config: null }; }
134
}
135
}
136
// Close east/west already; seal was on vertical edges. Fill north/south across seam.
137
for (let x = 13; x < CHUNK_SIZE; x++)
138
{
139
a.blocks[idx(x, 4)] = { typeId: BlockType.stoneWall, config: null };
140
a.blocks[idx(x, 8)] = { typeId: BlockType.stoneWall, config: null };
141
}
142
for (let x = 0; x <= 2; x++)
143
{
144
b.blocks[idx(x, 4)] = { typeId: BlockType.stoneWall, config: null };
145
b.blocks[idx(x, 8)] = { typeId: BlockType.stoneWall, config: null };
146
}
147
148
const chunks = new Map([["0,0", a], ["1,0", b]]);
149
const results = bakeEnclosedWindow(0, 0, loadMap(chunks));
150
assert.equal(enclosedAt(results, 0, 0, 14, 6), 1, "interior on chunk 0");
151
assert.equal(enclosedAt(results, 1, 0, 1, 6), 1, "interior on chunk 1");
152
assert.equal(enclosedAt(results, 0, 0, 12, 6), 1, "west wall marked");
153
assert.equal(enclosedAt(results, 1, 0, 3, 6), 1, "east wall marked");
154
});
155
156
test("region open to window edge → not enclosed", () =>
157
{
158
const origin = createEmptyChunkData();
159
origin.open = true;
160
// Three-sided "U" open to the south toward chunk interior / edge path — leave south open
161
// so flood from window edge reaches the pocket.
162
for (let y = 1; y <= 4; y++)
163
{
164
origin.blocks[idx(1, y)] = { typeId: BlockType.stoneWall, config: null };
165
origin.blocks[idx(5, y)] = { typeId: BlockType.stoneWall, config: null };
166
}
167
for (let x = 1; x <= 5; x++)
168
{ origin.blocks[idx(x, 1)] = { typeId: BlockType.stoneWall, config: null }; }
169
170
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));
171
assert.equal(enclosedAt(results, 0, 0, 3, 3), 0, "open pocket not enclosed");
172
assert.equal(enclosedAt(results, 0, 0, 1, 1), 0, "walls of open pocket not enclosed");
173
});
174
175
test("bakeEnclosedMaps writes enclosed onto chunk data", () =>
176
{
177
const origin = createEmptyChunkData();
178
origin.open = true;
179
wallRect(origin, 4, 4, 8, 8);
180
const baked = bakeEnclosedMaps(0, 0, (x, y) => (x === 0 && y === 0 ? origin : createEmptyChunkData()));
181
const self = baked.find((c) => c.chunkX === 0 && c.chunkY === 0);
182
assert.equal(self.data.enclosed[idx(6, 6)], 1);
183
assert.equal(self.data.enclosed.length, CHUNK_SIZE * CHUNK_SIZE);
184
});
185
186
test("encode/decode persists enclosed (legacy default 0)", () =>
187
{
188
const data = createEmptyChunkData();
189
data.open = true;
190
data.enclosed[idx(2, 2)] = 1;
191
const decoded = decodeChunkBlob(encodeChunkBlob(data));
192
assert.equal(decoded.enclosed[idx(2, 2)], 1);
193
assert.equal(decoded.enclosed[idx(0, 0)], 0);
194
195
const legacy = decodeChunkBlob(JSON.stringify({
196
open: true,
197
grounds: data.grounds,
198
blocks: data.blocks,
199
light: data.light,
200
spawners: []
201
}));
202
assert.equal(legacy.enclosed.length, CHUNK_SIZE * CHUNK_SIZE);
203
assert.ok(legacy.enclosed.every((v) => v === 0));
204
});
205
206
test("enclosedAmbientDarkness adds bonus and clamps to night peak", () =>
207
{
208
assert.equal(enclosedAmbientDarkness(0, 0, { enclosedDarknessBonus: 0.1, nightDarkness: 0.72 }), 0);
209
assert.equal(enclosedAmbientDarkness(0, 1, { enclosedDarknessBonus: 0.1, nightDarkness: 0.72 }), 0.1);
210
assert.equal(
211
enclosedAmbientDarkness(0.7, 1, { enclosedDarknessBonus: 0.1, nightDarkness: 0.72 }),
212
0.72
213
);
214
assert.equal(
215
DEFAULT_WORLD_SETTINGS.enclosedDarknessBonus,
216
0.10
217
);
218
});
@@ -0,0 +1,218 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { createEmptyChunkData, encodeChunkBlob, decodeChunkBlob } from "../src/world/chunkData.js";4
import { bakeEnclosedMaps } from "../src/lighting/enclosedBaker.js";5
import {6
isEnclosedBoundaryTile,7
isEnclosedInteriorCandidate,8
bakeEnclosedWindow,9
enclosedAmbientDarkness10
} from "../../shared/lighting/enclosed.js";11
import { BlockType, GroundType } from "../../shared/definitions/tiles.js";12
import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../shared/protocol/constants.js";13
14
function idx (localX, localY)15
{16
return localY * CHUNK_SIZE + localX;17
}18
19
function wallRect (data, x0, y0, x1, y1)20
{21
for (let y = y0; y <= y1; y++)22
{23
for (let x = x0; x <= x1; x++)24
{25
if (x === x0 || x === x1 || y === y0 || y === y1)26
{ data.blocks[idx(x, y)] = { typeId: BlockType.stoneWall, config: null }; }27
}28
}29
}30
31
function loadMap (chunks)32
{33
return (cx, cy) => chunks.get(`${cx},${cy}`) ?? createEmptyChunkData();34
}35
36
function enclosedAt (results, chunkX, chunkY, localX, localY)37
{38
const entry = results.find((r) => r.chunkX === chunkX && r.chunkY === chunkY);39
assert.ok(entry, `missing enclosed result for ${chunkX},${chunkY}`);40
return entry.enclosed[idx(localX, localY)];41
}42
43
test("predicates: open floor is interior; wall is boundary; water is interior; door is boundary", () =>44
{45
const data = createEmptyChunkData();46
data.blocks[idx(1, 1)] = { typeId: BlockType.stoneWall, config: null };47
data.grounds[idx(2, 2)] = { typeId: GroundType.water, state: null };48
data.blocks[idx(3, 3)] = { typeId: BlockType.door, state: "pine-s-open", config: { restingState: "pine-s-closed" } };49
data.blocks[idx(4, 4)] = { typeId: BlockType.door, state: "pine-s-closed", config: null };50
51
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 0, 0), false);52
assert.equal(isEnclosedInteriorCandidate(data.grounds, data.blocks, 0, 0), true);53
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 1, 1), true);54
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 2, 2), false, "water is not boundary");55
assert.equal(isEnclosedInteriorCandidate(data.grounds, data.blocks, 2, 2), true);56
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 3, 3), true, "open door is boundary");57
assert.equal(isEnclosedBoundaryTile(data.grounds, data.blocks, 4, 4), true, "closed door is boundary");58
});59
60
test("open field → nothing enclosed", () =>61
{62
const origin = createEmptyChunkData();63
origin.open = true;64
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));65
const self = results.find((r) => r.chunkX === 0 && r.chunkY === 0);66
assert.ok(self.enclosed.every((v) => v === 0));67
});68
69
test("walled room with door → interior + walls + door marked", () =>70
{71
const origin = createEmptyChunkData();72
origin.open = true;73
// Room at local 4..8, door on south wall at (6,8)74
wallRect(origin, 4, 4, 8, 8);75
origin.blocks[idx(6, 8)] = { typeId: BlockType.door, state: "pine-s-closed", config: null };76
77
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));78
assert.equal(enclosedAt(results, 0, 0, 6, 6), 1, "interior marked");79
assert.equal(enclosedAt(results, 0, 0, 5, 5), 1, "interior near corner marked");80
assert.equal(enclosedAt(results, 0, 0, 4, 6), 1, "west wall (shared edge) marked");81
assert.equal(enclosedAt(results, 0, 0, 6, 4), 1, "north wall (shared edge) marked");82
assert.equal(enclosedAt(results, 0, 0, 6, 8), 1, "door marked");83
assert.equal(enclosedAt(results, 0, 0, 4, 4), 1, "outer wall corner marked via diagonal");84
assert.equal(enclosedAt(results, 0, 0, 0, 0), 0, "outside not marked");85
assert.equal(enclosedAt(results, 0, 0, 6, 9), 0, "just outside door not marked");86
});87
88
test("1×1 wall and 3×1 wall strip → nothing enclosed", () =>89
{90
const origin = createEmptyChunkData();91
origin.open = true;92
origin.blocks[idx(8, 8)] = { typeId: BlockType.stoneWall, config: null };93
origin.blocks[idx(10, 8)] = { typeId: BlockType.stoneWall, config: null };94
origin.blocks[idx(11, 8)] = { typeId: BlockType.stoneWall, config: null };95
origin.blocks[idx(12, 8)] = { typeId: BlockType.stoneWall, config: null };96
97
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));98
const self = results.find((r) => r.chunkX === 0 && r.chunkY === 0);99
assert.ok(self.enclosed.every((v) => v === 0), "lone walls must not mark enclosed");100
});101
102
test("water inside courtyard counts as enclosed interior", () =>103
{104
const origin = createEmptyChunkData();105
origin.open = true;106
wallRect(origin, 4, 4, 10, 10);107
origin.grounds[idx(7, 7)] = { typeId: GroundType.water, state: null };108
origin.grounds[idx(7, 8)] = { typeId: GroundType.water, state: null };109
110
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));111
assert.equal(enclosedAt(results, 0, 0, 7, 7), 1, "water tile enclosed");112
assert.equal(enclosedAt(results, 0, 0, 7, 8), 1, "water tile enclosed");113
assert.equal(enclosedAt(results, 0, 0, 6, 6), 1, "dry interior enclosed");114
});115
116
test("cross-chunk room within 3×3 is enclosed", () =>117
{118
const a = createEmptyChunkData();119
const b = createEmptyChunkData();120
a.open = true;121
b.open = true;122
// Room straddling chunk 0,0 and 1,0: walls from localX 12..15 on chunk0 and 0..3 on chunk1, y 4..8123
for (let y = 4; y <= 8; y++)124
{125
for (let x = 12; x < CHUNK_SIZE; x++)126
{127
if (x === 12 || y === 4 || y === 8)128
{ a.blocks[idx(x, y)] = { typeId: BlockType.stoneWall, config: null }; }129
}130
for (let x = 0; x <= 3; x++)131
{132
if (x === 3 || y === 4 || y === 8)133
{ b.blocks[idx(x, y)] = { typeId: BlockType.stoneWall, config: null }; }134
}135
}136
// Close east/west already; seal was on vertical edges. Fill north/south across seam.137
for (let x = 13; x < CHUNK_SIZE; x++)138
{139
a.blocks[idx(x, 4)] = { typeId: BlockType.stoneWall, config: null };140
a.blocks[idx(x, 8)] = { typeId: BlockType.stoneWall, config: null };141
}142
for (let x = 0; x <= 2; x++)143
{144
b.blocks[idx(x, 4)] = { typeId: BlockType.stoneWall, config: null };145
b.blocks[idx(x, 8)] = { typeId: BlockType.stoneWall, config: null };146
}147
148
const chunks = new Map([["0,0", a], ["1,0", b]]);149
const results = bakeEnclosedWindow(0, 0, loadMap(chunks));150
assert.equal(enclosedAt(results, 0, 0, 14, 6), 1, "interior on chunk 0");151
assert.equal(enclosedAt(results, 1, 0, 1, 6), 1, "interior on chunk 1");152
assert.equal(enclosedAt(results, 0, 0, 12, 6), 1, "west wall marked");153
assert.equal(enclosedAt(results, 1, 0, 3, 6), 1, "east wall marked");154
});155
156
test("region open to window edge → not enclosed", () =>157
{158
const origin = createEmptyChunkData();159
origin.open = true;160
// Three-sided "U" open to the south toward chunk interior / edge path — leave south open161
// so flood from window edge reaches the pocket.162
for (let y = 1; y <= 4; y++)163
{164
origin.blocks[idx(1, y)] = { typeId: BlockType.stoneWall, config: null };165
origin.blocks[idx(5, y)] = { typeId: BlockType.stoneWall, config: null };166
}167
for (let x = 1; x <= 5; x++)168
{ origin.blocks[idx(x, 1)] = { typeId: BlockType.stoneWall, config: null }; }169
170
const results = bakeEnclosedWindow(0, 0, loadMap(new Map([["0,0", origin]])));171
assert.equal(enclosedAt(results, 0, 0, 3, 3), 0, "open pocket not enclosed");172
assert.equal(enclosedAt(results, 0, 0, 1, 1), 0, "walls of open pocket not enclosed");173
});174
175
test("bakeEnclosedMaps writes enclosed onto chunk data", () =>176
{177
const origin = createEmptyChunkData();178
origin.open = true;179
wallRect(origin, 4, 4, 8, 8);180
const baked = bakeEnclosedMaps(0, 0, (x, y) => (x === 0 && y === 0 ? origin : createEmptyChunkData()));181
const self = baked.find((c) => c.chunkX === 0 && c.chunkY === 0);182
assert.equal(self.data.enclosed[idx(6, 6)], 1);183
assert.equal(self.data.enclosed.length, CHUNK_SIZE * CHUNK_SIZE);184
});185
186
test("encode/decode persists enclosed (legacy default 0)", () =>187
{188
const data = createEmptyChunkData();189
data.open = true;190
data.enclosed[idx(2, 2)] = 1;191
const decoded = decodeChunkBlob(encodeChunkBlob(data));192
assert.equal(decoded.enclosed[idx(2, 2)], 1);193
assert.equal(decoded.enclosed[idx(0, 0)], 0);194
195
const legacy = decodeChunkBlob(JSON.stringify({196
open: true,197
grounds: data.grounds,198
blocks: data.blocks,199
light: data.light,200
spawners: []201
}));202
assert.equal(legacy.enclosed.length, CHUNK_SIZE * CHUNK_SIZE);203
assert.ok(legacy.enclosed.every((v) => v === 0));204
});205
206
test("enclosedAmbientDarkness adds bonus and clamps to night peak", () =>207
{208
assert.equal(enclosedAmbientDarkness(0, 0, { enclosedDarknessBonus: 0.1, nightDarkness: 0.72 }), 0);209
assert.equal(enclosedAmbientDarkness(0, 1, { enclosedDarknessBonus: 0.1, nightDarkness: 0.72 }), 0.1);210
assert.equal(211
enclosedAmbientDarkness(0.7, 1, { enclosedDarknessBonus: 0.1, nightDarkness: 0.72 }),212
0.72213
);214
assert.equal(215
DEFAULT_WORLD_SETTINGS.enclosedDarknessBonus,216
0.10217
);218
});@@ -0,0 +1,87 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { EventEmitter } from "node:events";
4
import {
5
startWebSocketKeepalive,
6
DEFAULT_WS_PING_INTERVAL_MS
7
} from "../src/gateway/wsKeepalive.js";
8
9
class FakeSocket extends EventEmitter
10
{
11
constructor ()
12
{
13
super();
14
this.isAlive = undefined;
15
this.pingCount = 0;
16
this.terminated = false;
17
}
18
19
ping ()
20
{
21
this.pingCount += 1;
22
}
23
24
terminate ()
25
{
26
this.terminated = true;
27
}
28
}
29
30
class FakeWss extends EventEmitter
31
{
32
constructor ()
33
{
34
super();
35
this.clients = new Set();
36
}
37
}
38
39
test("startWebSocketKeepalive pings open sockets and terminates stale ones", () =>
40
{
41
const wss = new FakeWss();
42
const timers = [];
43
const keepalive = startWebSocketKeepalive(wss, {
44
intervalMs: 1000,
45
setIntervalFn (fn, ms)
46
{
47
timers.push({ fn, ms });
48
return 1;
49
},
50
clearIntervalFn () {}
51
});
52
assert.equal(keepalive.intervalMs, 1000);
53
assert.equal(DEFAULT_WS_PING_INTERVAL_MS, 25_000);
54
assert.equal(timers.length, 1);
55
56
const live = new FakeSocket();
57
const stale = new FakeSocket();
58
wss.clients.add(live);
59
wss.clients.add(stale);
60
wss.emit("connection", live);
61
wss.emit("connection", stale);
62
assert.equal(live.isAlive, true);
63
assert.equal(stale.isAlive, true);
64
65
live.emit("pong");
66
assert.equal(live.isAlive, true);
67
68
// First tick: mark not alive and ping
69
timers[0].fn();
70
assert.equal(live.isAlive, false);
71
assert.equal(stale.isAlive, false);
72
assert.equal(live.pingCount, 1);
73
assert.equal(stale.pingCount, 1);
74
assert.equal(stale.terminated, false);
75
76
live.emit("pong");
77
assert.equal(live.isAlive, true);
78
79
// Second tick: live gets pinged again; stale (no pong) is terminated
80
timers[0].fn();
81
assert.equal(live.terminated, false);
82
assert.equal(stale.terminated, true);
83
assert.equal(live.pingCount, 2);
84
85
keepalive.stop();
86
keepalive.stop(); // idempotent
87
});
@@ -0,0 +1,87 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { EventEmitter } from "node:events";4
import {5
startWebSocketKeepalive,6
DEFAULT_WS_PING_INTERVAL_MS7
} from "../src/gateway/wsKeepalive.js";8
9
class FakeSocket extends EventEmitter10
{11
constructor ()12
{13
super();14
this.isAlive = undefined;15
this.pingCount = 0;16
this.terminated = false;17
}18
19
ping ()20
{21
this.pingCount += 1;22
}23
24
terminate ()25
{26
this.terminated = true;27
}28
}29
30
class FakeWss extends EventEmitter31
{32
constructor ()33
{34
super();35
this.clients = new Set();36
}37
}38
39
test("startWebSocketKeepalive pings open sockets and terminates stale ones", () =>40
{41
const wss = new FakeWss();42
const timers = [];43
const keepalive = startWebSocketKeepalive(wss, {44
intervalMs: 1000,45
setIntervalFn (fn, ms)46
{47
timers.push({ fn, ms });48
return 1;49
},50
clearIntervalFn () {}51
});52
assert.equal(keepalive.intervalMs, 1000);53
assert.equal(DEFAULT_WS_PING_INTERVAL_MS, 25_000);54
assert.equal(timers.length, 1);55
56
const live = new FakeSocket();57
const stale = new FakeSocket();58
wss.clients.add(live);59
wss.clients.add(stale);60
wss.emit("connection", live);61
wss.emit("connection", stale);62
assert.equal(live.isAlive, true);63
assert.equal(stale.isAlive, true);64
65
live.emit("pong");66
assert.equal(live.isAlive, true);67
68
// First tick: mark not alive and ping69
timers[0].fn();70
assert.equal(live.isAlive, false);71
assert.equal(stale.isAlive, false);72
assert.equal(live.pingCount, 1);73
assert.equal(stale.pingCount, 1);74
assert.equal(stale.terminated, false);75
76
live.emit("pong");77
assert.equal(live.isAlive, true);78
79
// Second tick: live gets pinged again; stale (no pong) is terminated80
timers[0].fn();81
assert.equal(live.terminated, false);82
assert.equal(stale.terminated, true);83
assert.equal(live.pingCount, 2);84
85
keepalive.stop();86
keepalive.stop(); // idempotent87
});