Bake enclosed-area masks for indoor darkness bonus.
On editor chunk save, flood-fill a 3×3 chunk window to mark truly enclosed rooms (interior + enclosing walls/doors), persist per-tile enclosed flags, and apply enclosedDarknessBonus (default 0.10) to ambient shade, clamped to nightDarkness. Water counts as interior; doors are always boundaries.
@@ -272,6 +272,7 @@ function snapshotFromPayload (payload)
272
272
grounds: payload.data.grounds,
273
273
blocks: payload.data.blocks,
274
274
light: payload.data.light,
275
enclosed: payload.data.enclosed,
275
276
entities: []
276
277
};
277
278
}
@@ -348,6 +349,9 @@ function applyDraftContents (next)
348
349
? { ...block, config: block.config ?? null }
349
350
: null));
350
351
draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
352
draft.enclosed = Array.isArray(next.enclosed)
353
? next.enclosed.slice().map((v) => (v ? 1 : 0))
354
: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
351
355
draft.spawners = (next.spawners ?? []).map((entry) => ({
352
356
localX: entry.localX | 0,
353
357
localY: entry.localY | 0,
@@ -363,6 +367,7 @@ function applyDraftContents (next)
363
367
grounds: draft.grounds,
364
368
blocks: draft.blocks,
365
369
light: draft.light,
370
enclosed: draft.enclosed,
366
371
entities: []
367
372
});
368
373
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -971,6 +976,9 @@ function showSelectedChunk (payload)
971
976
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
972
977
blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),
973
978
light: payload.data.light.slice(),
979
enclosed: Array.isArray(payload.data.enclosed)
980
? payload.data.enclosed.slice().map((v) => (v ? 1 : 0))
981
: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0),
974
982
spawners: (payload.data.spawners ?? []).map((entry) => ({
975
983
localX: entry.localX,
976
984
localY: entry.localY,
@@ -272,6 +272,7 @@ function snapshotFromPayload (payload)272
grounds: payload.data.grounds,272
grounds: payload.data.grounds,273
blocks: payload.data.blocks,273
blocks: payload.data.blocks,274
light: payload.data.light,274
light: payload.data.light,275
enclosed: payload.data.enclosed,275
entities: []276
entities: []276
};277
};277
}278
}@@ -348,6 +349,9 @@ function applyDraftContents (next)348
? { ...block, config: block.config ?? null }349
? { ...block, config: block.config ?? null }349
: null));350
: null));350
draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);351
draft.light = Array.isArray(next.light) ? next.light.slice() : new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);352
draft.enclosed = Array.isArray(next.enclosed)353
? next.enclosed.slice().map((v) => (v ? 1 : 0))354
: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);351
draft.spawners = (next.spawners ?? []).map((entry) => ({355
draft.spawners = (next.spawners ?? []).map((entry) => ({352
localX: entry.localX | 0,356
localX: entry.localX | 0,353
localY: entry.localY | 0,357
localY: entry.localY | 0,@@ -363,6 +367,7 @@ function applyDraftContents (next)363
grounds: draft.grounds,367
grounds: draft.grounds,364
blocks: draft.blocks,368
blocks: draft.blocks,365
light: draft.light,369
light: draft.light,370
enclosed: draft.enclosed,366
entities: []371
entities: []367
});372
});368
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);373
syncSpawnersOverlay(chunkX, chunkY, draft.spawners);@@ -971,6 +976,9 @@ function showSelectedChunk (payload)971
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),976
grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),972
blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),977
blocks: payload.data.blocks.map((block) => (block ? { ...block, config: block.config ?? null } : null)),973
light: payload.data.light.slice(),978
light: payload.data.light.slice(),979
enclosed: Array.isArray(payload.data.enclosed)980
? payload.data.enclosed.slice().map((v) => (v ? 1 : 0))981
: new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0),974
spawners: (payload.data.spawners ?? []).map((entry) => ({982
spawners: (payload.data.spawners ?? []).map((entry) => ({975
localX: entry.localX,983
localX: entry.localX,976
localY: entry.localY,984
localY: entry.localY,@@ -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)@@ -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; }@@ -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 };@@ -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
});