BlueGit

timfa questward

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.

timfa Tim Falken · pushed by timfa

Authored 2026-09-10 · 2 months ago

Hash
b5ff29813bf7d51432fdb1f0d981fedbf7e2ba50
Parent
1f56b7c3
11 files changed +608 −9
client/src/editor/main.js +8 −0
@@ -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,
client/src/render/worldView.js +40 −4
@@ -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_BO
2import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
2import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";
4import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";
5import { enclosedAmbientDarkness } from "/shared/lighting/enclosed.js";
5import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";
6import { collectBlockLightSources, collectGroundLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";
6import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
8import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
@@ -4372,6 +4373,32 @@ export class WorldView
4372 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.72
4399 });
4400 }
4401
4375 setLocalBlind (blind)
4402 setLocalBlind (blind)
4376 {
4403 {
4377 this.localBlind = !!blind;
4404 this.localBlind = !!blind;
@@ -6016,8 +6043,11 @@ export class WorldView
6016 /** 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 != null
6047 ? 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 WorldView
6028 /** 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 WorldView
6035 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 WorldView
6044 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 WorldView
6183 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 WorldView
6202 { 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)
server/src/editor/service.js +30 −5
@@ -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 @@
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock, BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock, BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3import { localToTile } from "../world/coordinates.js";
3import { localToTile, chunkKey } from "../world/coordinates.js";
4import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";
4import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob, normalizeSpawner } from "../world/chunkData.js";
5import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
5import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
6import { bakeEnclosedMaps } from "../lighting/enclosedBaker.js";
6import { closedNeighborEdges } from "../world/chunkFlags.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
7import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";
8import { coerceSettingValue, diffSettings, diffItemSeedValues, allSettingFields, itemSeedMapsEqual } from "../../../shared/definitions/worldSettings.js";
8import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
9import { normalizeItemSeedValues } from "../../../shared/shop/pricing.js";
@@ -120,18 +121,42 @@ export class EditorService
120
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, dimId
126 );
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 dimId
128 );
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 else
151 { byKey.set(key, result); }
152 }
153
154 for (const result of byKey.values())
131 {
155 {
132 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
156 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
133 || 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; }
server/src/lighting/enclosedBaker.js added +42 −0
@@ -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 @@
1import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2import { bakeEnclosedWindow, ENCLOSED_BAKE_CHUNK_RADIUS } from "../../../shared/lighting/enclosed.js";
3import { chunkKey, chebyshevChunks } from "../world/coordinates.js";
4import { cloneChunkData } from "../world/chunkData.js";
5
6export { 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 */
12export 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}
server/src/simulation/simulation.js +1 −0
@@ -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 Simulation
3305 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 };
server/src/simulation/workerWorld.js +2 −0
@@ -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 WorkerWorld
2347 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 WorkerWorld
2373 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)
server/src/world/chunkData.js +23 −0
@@ -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.defa
31 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.def
76 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.def
83 { 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.def
107 return normalized;
116 return normalized;
108 }),
117 }),
109 light,
118 light,
119 enclosed,
110 spawners
120 spawners
111 };
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
277export 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
265export { GroundType, normalizeGround, normalizeBlock };
288export { GroundType, normalizeGround, normalizeBlock };
server/tests/enclosed.test.js added +218 −0
@@ -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 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { createEmptyChunkData, encodeChunkBlob, decodeChunkBlob } from "../src/world/chunkData.js";
4import { bakeEnclosedMaps } from "../src/lighting/enclosedBaker.js";
5import {
6 isEnclosedBoundaryTile,
7 isEnclosedInteriorCandidate,
8 bakeEnclosedWindow,
9 enclosedAmbientDarkness
10} from "../../shared/lighting/enclosed.js";
11import { BlockType, GroundType } from "../../shared/definitions/tiles.js";
12import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../shared/protocol/constants.js";
13
14function idx (localX, localY)
15{
16 return localY * CHUNK_SIZE + localX;
17}
18
19function 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
31function loadMap (chunks)
32{
33 return (cx, cy) => chunks.get(`${cx},${cy}`) ?? createEmptyChunkData();
34}
35
36function 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
43test("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
60test("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
69test("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
88test("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
102test("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
116test("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
156test("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
175test("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
186test("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
206test("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});
shared/definitions/worldSettings.js +10 −0
@@ -45,6 +45,16 @@ export const WORLD_SETTING_CATEGORIES = [
45 45 step: 0.01,
46 46 previewNightHour: 23
47 47 },
48 {
49 key: "enclosedDarknessBonus",
50 label: "Enclosed darkness bonus",
51 hint: "Extra ambient darkness inside baked enclosed rooms (interior + enclosing walls/doors). Clamped so ambient never exceeds Night darkness. Build a small walled room, save the chunk, then use Night preview to check.",
52 type: "range",
53 min: 0,
54 max: 1,
55 step: 0.01,
56 previewNightHour: 23
57 },
48 58 {
49 59 key: "wetSandBand",
50 60 label: "Wet sand band",
@@ -45,6 +45,16 @@ export const WORLD_SETTING_CATEGORIES = [
45 step: 0.01,
45 step: 0.01,
46 previewNightHour: 23
46 previewNightHour: 23
47 },
47 },
48 {
49 key: "enclosedDarknessBonus",
50 label: "Enclosed darkness bonus",
51 hint: "Extra ambient darkness inside baked enclosed rooms (interior + enclosing walls/doors). Clamped so ambient never exceeds Night darkness. Build a small walled room, save the chunk, then use Night preview to check.",
52 type: "range",
53 min: 0,
54 max: 1,
55 step: 0.01,
56 previewNightHour: 23
57 },
48 {
58 {
49 key: "wetSandBand",
59 key: "wetSandBand",
50 label: "Wet sand band",
60 label: "Wet sand band",
shared/lighting/enclosed.js added +232 −0
@@ -0,0 +1,232 @@
1 import { CHUNK_SIZE } from "../protocol/constants.js";
2 import {
3 BlockType,
4 LightOcclusion,
5 blockDefinition,
6 isBlockPassable,
7 isGroundPassable,
8 normalizeGround
9 } from "../definitions/tiles.js";
10 import { tileLightOcclusionAt } from "./chunkOcclusion.js";
11
12 /** Chebyshev chunk radius for enclosed bake window (3×3 chunks). */
13 export const ENCLOSED_BAKE_CHUNK_RADIUS = 1;
14
15 /**
16 * Door tiles are always enclosure boundaries (open or closed).
17 * Uses BlockType.door / def.door — not light-occlusion-of-open-passage.
18 */
19 export function isEnclosedDoorBlock (block)
20 {
21 if (!block)
22 { return false; }
23 if ((block.typeId | 0) === BlockType.door)
24 { return true; }
25 return !!blockDefinition(block.typeId)?.door;
26 }
27
28 /**
29 * Boundary = (solid LoS ∧ impassable) ∨ door.
30 * Water (impassable walk, clear LoS) is NOT boundary → interior candidate.
31 * Doors ignore open/closed passability; they are always boundary.
32 */
33 export function isEnclosedBoundaryTile (grounds, blocks, localX, localY)
34 {
35 const index = localY * CHUNK_SIZE + localX;
36 const block = blocks?.[index] ?? null;
37 if (isEnclosedDoorBlock(block))
38 { return true; }
39
40 const solidLos = tileLightOcclusionAt(grounds, blocks, localX, localY) === LightOcclusion.solid;
41 if (!solidLos)
42 { return false; }
43
44 const ground = normalizeGround(grounds?.[index]);
45 if (!isGroundPassable(ground.typeId))
46 { return true; }
47 if (!block)
48 { return false; }
49 return !isBlockPassable(block.typeId, block.state);
50 }
51
52 /** Interior candidate = not a boundary tile. */
53 export function isEnclosedInteriorCandidate (grounds, blocks, localX, localY)
54 {
55 return !isEnclosedBoundaryTile(grounds, blocks, localX, localY);
56 }
57
58 /**
59 * Bake enclosed masks for the 3×3 chunk window around `centerChunkX/Y`.
60 * Floods "outside" from the window edge through interior tiles; remaining
61 * interior components (plus their shared-edge boundary tiles) are enclosed.
62 * Regions that touch the window edge as interior are treated as outdoors.
63 *
64 * @param {number} centerChunkX
65 * @param {number} centerChunkY
66 * @param {(chunkX: number, chunkY: number) => { grounds: any[], blocks: any[] } | null | undefined} loadChunk
67 * @returns {{ chunkX: number, chunkY: number, enclosed: number[] }[]}
68 */
69 export function bakeEnclosedWindow (centerChunkX, centerChunkY, loadChunk)
70 {
71 const radius = ENCLOSED_BAKE_CHUNK_RADIUS;
72 const minChunkX = centerChunkX - radius;
73 const minChunkY = centerChunkY - radius;
74 const maxChunkX = centerChunkX + radius;
75 const maxChunkY = centerChunkY + radius;
76 const winChunks = 2 * radius + 1;
77 const size = winChunks * CHUNK_SIZE;
78 const minTileX = minChunkX * CHUNK_SIZE;
79 const minTileY = minChunkY * CHUNK_SIZE;
80
81 const chunkCache = new Map();
82 function chunkAt (chunkX, chunkY)
83 {
84 const key = `${chunkX},${chunkY}`;
85 if (!chunkCache.has(key))
86 { chunkCache.set(key, loadChunk(chunkX, chunkY) ?? null); }
87 return chunkCache.get(key);
88 }
89
90 function tileGroundsBlocks (tileX, tileY)
91 {
92 const chunkX = Math.floor(tileX / CHUNK_SIZE);
93 const chunkY = Math.floor(tileY / CHUNK_SIZE);
94 const data = chunkAt(chunkX, chunkY);
95 if (!data)
96 { return null; }
97 const localX = tileX - chunkX * CHUNK_SIZE;
98 const localY = tileY - chunkY * CHUNK_SIZE;
99 return { grounds: data.grounds, blocks: data.blocks, localX, localY };
100 }
101
102 const boundary = new Uint8Array(size * size);
103 const interior = new Uint8Array(size * size);
104 for (let wy = 0; wy < size; wy++)
105 {
106 for (let wx = 0; wx < size; wx++)
107 {
108 const tileX = minTileX + wx;
109 const tileY = minTileY + wy;
110 const loc = tileGroundsBlocks(tileX, tileY);
111 const idx = wy * size + wx;
112 if (!loc)
113 {
114 // Missing chunk → treat as open outdoors (interior) so edge flood escapes.
115 interior[idx] = 1;
116 continue;
117 }
118 if (isEnclosedBoundaryTile(loc.grounds, loc.blocks, loc.localX, loc.localY))
119 { boundary[idx] = 1; }
120 else
121 { interior[idx] = 1; }
122 }
123 }
124
125 const outside = new Uint8Array(size * size);
126 const queue = [];
127 function trySeed (wx, wy)
128 {
129 const idx = wy * size + wx;
130 if (!interior[idx] || outside[idx])
131 { return; }
132 outside[idx] = 1;
133 queue.push(idx);
134 }
135 for (let wx = 0; wx < size; wx++)
136 {
137 trySeed(wx, 0);
138 trySeed(wx, size - 1);
139 }
140 for (let wy = 1; wy < size - 1; wy++)
141 {
142 trySeed(0, wy);
143 trySeed(size - 1, wy);
144 }
145
146 const neighbors = [[1, 0], [-1, 0], [0, 1], [0, -1]];
147 while (queue.length > 0)
148 {
149 const idx = queue.pop();
150 const wx = idx % size;
151 const wy = (idx / size) | 0;
152 for (const [dx, dy] of neighbors)
153 {
154 const nx = wx + dx;
155 const ny = wy + dy;
156 if (nx < 0 || ny < 0 || nx >= size || ny >= size)
157 { continue; }
158 const nIdx = ny * size + nx;
159 if (!interior[nIdx] || outside[nIdx])
160 { continue; }
161 outside[nIdx] = 1;
162 queue.push(nIdx);
163 }
164 }
165
166 const enclosedWin = new Uint8Array(size * size);
167 for (let idx = 0; idx < size * size; idx++)
168 {
169 if (interior[idx] && !outside[idx])
170 { enclosedWin[idx] = 1; }
171 }
172 // Expand onto boundary tiles that enclose interiors (8-neighborhood so
173 // rectangular room corners are included; one step only — no wall-strip flood).
174 const encloseNeighbors = [
175 [1, 0], [-1, 0], [0, 1], [0, -1],
176 [1, 1], [1, -1], [-1, 1], [-1, -1]
177 ];
178 for (let wy = 0; wy < size; wy++)
179 {
180 for (let wx = 0; wx < size; wx++)
181 {
182 const idx = wy * size + wx;
183 if (!enclosedWin[idx] || !interior[idx])
184 { continue; }
185 for (const [dx, dy] of encloseNeighbors)
186 {
187 const nx = wx + dx;
188 const ny = wy + dy;
189 if (nx < 0 || ny < 0 || nx >= size || ny >= size)
190 { continue; }
191 const nIdx = ny * size + nx;
192 if (boundary[nIdx])
193 { enclosedWin[nIdx] = 1; }
194 }
195 }
196 }
197
198 const results = [];
199 for (let cy = minChunkY; cy <= maxChunkY; cy++)
200 {
201 for (let cx = minChunkX; cx <= maxChunkX; cx++)
202 {
203 const enclosed = new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
204 const baseWX = (cx - minChunkX) * CHUNK_SIZE;
205 const baseWY = (cy - minChunkY) * CHUNK_SIZE;
206 for (let localY = 0; localY < CHUNK_SIZE; localY++)
207 {
208 for (let localX = 0; localX < CHUNK_SIZE; localX++)
209 {
210 const wIdx = (baseWY + localY) * size + (baseWX + localX);
211 enclosed[localY * CHUNK_SIZE + localX] = enclosedWin[wIdx] ? 1 : 0;
212 }
213 }
214 results.push({ chunkX: cx, chunkY: cy, enclosed });
215 }
216 }
217 return results;
218 }
219
220 /** Ambient darkness for a tile: base ambient + enclosed bonus, capped at night peak. */
221 export function enclosedAmbientDarkness (baseAmbient, enclosedFlag, {
222 enclosedDarknessBonus = 0.10,
223 nightDarkness = 0.72
224 } = {})
225 {
226 const base = Math.min(1, Math.max(0, baseAmbient ?? 0));
227 if (!enclosedFlag)
228 { return base; }
229 const bonus = Math.min(1, Math.max(0, enclosedDarknessBonus ?? 0));
230 const peak = Math.min(1, Math.max(0, nightDarkness ?? 0.72));
231 return Math.min(peak, base + bonus);
232 }
@@ -0,0 +1,232 @@
1import { CHUNK_SIZE } from "../protocol/constants.js";
2import {
3 BlockType,
4 LightOcclusion,
5 blockDefinition,
6 isBlockPassable,
7 isGroundPassable,
8 normalizeGround
9} from "../definitions/tiles.js";
10import { tileLightOcclusionAt } from "./chunkOcclusion.js";
11
12/** Chebyshev chunk radius for enclosed bake window (3×3 chunks). */
13export const ENCLOSED_BAKE_CHUNK_RADIUS = 1;
14
15/**
16 * Door tiles are always enclosure boundaries (open or closed).
17 * Uses BlockType.door / def.door — not light-occlusion-of-open-passage.
18 */
19export function isEnclosedDoorBlock (block)
20{
21 if (!block)
22 { return false; }
23 if ((block.typeId | 0) === BlockType.door)
24 { return true; }
25 return !!blockDefinition(block.typeId)?.door;
26}
27
28/**
29 * Boundary = (solid LoS ∧ impassable) ∨ door.
30 * Water (impassable walk, clear LoS) is NOT boundary → interior candidate.
31 * Doors ignore open/closed passability; they are always boundary.
32 */
33export function isEnclosedBoundaryTile (grounds, blocks, localX, localY)
34{
35 const index = localY * CHUNK_SIZE + localX;
36 const block = blocks?.[index] ?? null;
37 if (isEnclosedDoorBlock(block))
38 { return true; }
39
40 const solidLos = tileLightOcclusionAt(grounds, blocks, localX, localY) === LightOcclusion.solid;
41 if (!solidLos)
42 { return false; }
43
44 const ground = normalizeGround(grounds?.[index]);
45 if (!isGroundPassable(ground.typeId))
46 { return true; }
47 if (!block)
48 { return false; }
49 return !isBlockPassable(block.typeId, block.state);
50}
51
52/** Interior candidate = not a boundary tile. */
53export function isEnclosedInteriorCandidate (grounds, blocks, localX, localY)
54{
55 return !isEnclosedBoundaryTile(grounds, blocks, localX, localY);
56}
57
58/**
59 * Bake enclosed masks for the 3×3 chunk window around `centerChunkX/Y`.
60 * Floods "outside" from the window edge through interior tiles; remaining
61 * interior components (plus their shared-edge boundary tiles) are enclosed.
62 * Regions that touch the window edge as interior are treated as outdoors.
63 *
64 * @param {number} centerChunkX
65 * @param {number} centerChunkY
66 * @param {(chunkX: number, chunkY: number) => { grounds: any[], blocks: any[] } | null | undefined} loadChunk
67 * @returns {{ chunkX: number, chunkY: number, enclosed: number[] }[]}
68 */
69export function bakeEnclosedWindow (centerChunkX, centerChunkY, loadChunk)
70{
71 const radius = ENCLOSED_BAKE_CHUNK_RADIUS;
72 const minChunkX = centerChunkX - radius;
73 const minChunkY = centerChunkY - radius;
74 const maxChunkX = centerChunkX + radius;
75 const maxChunkY = centerChunkY + radius;
76 const winChunks = 2 * radius + 1;
77 const size = winChunks * CHUNK_SIZE;
78 const minTileX = minChunkX * CHUNK_SIZE;
79 const minTileY = minChunkY * CHUNK_SIZE;
80
81 const chunkCache = new Map();
82 function chunkAt (chunkX, chunkY)
83 {
84 const key = `${chunkX},${chunkY}`;
85 if (!chunkCache.has(key))
86 { chunkCache.set(key, loadChunk(chunkX, chunkY) ?? null); }
87 return chunkCache.get(key);
88 }
89
90 function tileGroundsBlocks (tileX, tileY)
91 {
92 const chunkX = Math.floor(tileX / CHUNK_SIZE);
93 const chunkY = Math.floor(tileY / CHUNK_SIZE);
94 const data = chunkAt(chunkX, chunkY);
95 if (!data)
96 { return null; }
97 const localX = tileX - chunkX * CHUNK_SIZE;
98 const localY = tileY - chunkY * CHUNK_SIZE;
99 return { grounds: data.grounds, blocks: data.blocks, localX, localY };
100 }
101
102 const boundary = new Uint8Array(size * size);
103 const interior = new Uint8Array(size * size);
104 for (let wy = 0; wy < size; wy++)
105 {
106 for (let wx = 0; wx < size; wx++)
107 {
108 const tileX = minTileX + wx;
109 const tileY = minTileY + wy;
110 const loc = tileGroundsBlocks(tileX, tileY);
111 const idx = wy * size + wx;
112 if (!loc)
113 {
114 // Missing chunk → treat as open outdoors (interior) so edge flood escapes.
115 interior[idx] = 1;
116 continue;
117 }
118 if (isEnclosedBoundaryTile(loc.grounds, loc.blocks, loc.localX, loc.localY))
119 { boundary[idx] = 1; }
120 else
121 { interior[idx] = 1; }
122 }
123 }
124
125 const outside = new Uint8Array(size * size);
126 const queue = [];
127 function trySeed (wx, wy)
128 {
129 const idx = wy * size + wx;
130 if (!interior[idx] || outside[idx])
131 { return; }
132 outside[idx] = 1;
133 queue.push(idx);
134 }
135 for (let wx = 0; wx < size; wx++)
136 {
137 trySeed(wx, 0);
138 trySeed(wx, size - 1);
139 }
140 for (let wy = 1; wy < size - 1; wy++)
141 {
142 trySeed(0, wy);
143 trySeed(size - 1, wy);
144 }
145
146 const neighbors = [[1, 0], [-1, 0], [0, 1], [0, -1]];
147 while (queue.length > 0)
148 {
149 const idx = queue.pop();
150 const wx = idx % size;
151 const wy = (idx / size) | 0;
152 for (const [dx, dy] of neighbors)
153 {
154 const nx = wx + dx;
155 const ny = wy + dy;
156 if (nx < 0 || ny < 0 || nx >= size || ny >= size)
157 { continue; }
158 const nIdx = ny * size + nx;
159 if (!interior[nIdx] || outside[nIdx])
160 { continue; }
161 outside[nIdx] = 1;
162 queue.push(nIdx);
163 }
164 }
165
166 const enclosedWin = new Uint8Array(size * size);
167 for (let idx = 0; idx < size * size; idx++)
168 {
169 if (interior[idx] && !outside[idx])
170 { enclosedWin[idx] = 1; }
171 }
172 // Expand onto boundary tiles that enclose interiors (8-neighborhood so
173 // rectangular room corners are included; one step only — no wall-strip flood).
174 const encloseNeighbors = [
175 [1, 0], [-1, 0], [0, 1], [0, -1],
176 [1, 1], [1, -1], [-1, 1], [-1, -1]
177 ];
178 for (let wy = 0; wy < size; wy++)
179 {
180 for (let wx = 0; wx < size; wx++)
181 {
182 const idx = wy * size + wx;
183 if (!enclosedWin[idx] || !interior[idx])
184 { continue; }
185 for (const [dx, dy] of encloseNeighbors)
186 {
187 const nx = wx + dx;
188 const ny = wy + dy;
189 if (nx < 0 || ny < 0 || nx >= size || ny >= size)
190 { continue; }
191 const nIdx = ny * size + nx;
192 if (boundary[nIdx])
193 { enclosedWin[nIdx] = 1; }
194 }
195 }
196 }
197
198 const results = [];
199 for (let cy = minChunkY; cy <= maxChunkY; cy++)
200 {
201 for (let cx = minChunkX; cx <= maxChunkX; cx++)
202 {
203 const enclosed = new Array(CHUNK_SIZE * CHUNK_SIZE).fill(0);
204 const baseWX = (cx - minChunkX) * CHUNK_SIZE;
205 const baseWY = (cy - minChunkY) * CHUNK_SIZE;
206 for (let localY = 0; localY < CHUNK_SIZE; localY++)
207 {
208 for (let localX = 0; localX < CHUNK_SIZE; localX++)
209 {
210 const wIdx = (baseWY + localY) * size + (baseWX + localX);
211 enclosed[localY * CHUNK_SIZE + localX] = enclosedWin[wIdx] ? 1 : 0;
212 }
213 }
214 results.push({ chunkX: cx, chunkY: cy, enclosed });
215 }
216 }
217 return results;
218}
219
220/** Ambient darkness for a tile: base ambient + enclosed bonus, capped at night peak. */
221export function enclosedAmbientDarkness (baseAmbient, enclosedFlag, {
222 enclosedDarknessBonus = 0.10,
223 nightDarkness = 0.72
224} = {})
225{
226 const base = Math.min(1, Math.max(0, baseAmbient ?? 0));
227 if (!enclosedFlag)
228 { return base; }
229 const bonus = Math.min(1, Math.max(0, enclosedDarknessBonus ?? 0));
230 const peak = Math.min(1, Math.max(0, nightDarkness ?? 0.72));
231 return Math.min(peak, base + bonus);
232}
shared/protocol/constants.js +2 −0
@@ -50,6 +50,8 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
50 50 defaultGroundTypeId: 1,
51 51 characterDeletionDelayMs: 24 * 60 * 60 * 1000,
52 52 nightDarkness: 0.72,
53 /** Extra ambient darkness inside baked enclosed areas; clamped to nightDarkness peak. */
54 enclosedDarknessBonus: 0.10,
53 55 /** Fraction of a sand tile facing liquid water that blends toward sand-wet (0–1). */
54 56 wetSandBand: 0.6,
55 57 chatMaxCharacters: 100,
@@ -50,6 +50,8 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
50 defaultGroundTypeId: 1,
50 defaultGroundTypeId: 1,
51 characterDeletionDelayMs: 24 * 60 * 60 * 1000,
51 characterDeletionDelayMs: 24 * 60 * 60 * 1000,
52 nightDarkness: 0.72,
52 nightDarkness: 0.72,
53 /** Extra ambient darkness inside baked enclosed areas; clamped to nightDarkness peak. */
54 enclosedDarknessBonus: 0.10,
53 /** Fraction of a sand tile facing liquid water that blends toward sand-wet (0–1). */
55 /** Fraction of a sand tile facing liquid water that blends toward sand-wet (0–1). */
54 wetSandBand: 0.6,
56 wetSandBand: 0.6,
55 chatMaxCharacters: 100,
57 chatMaxCharacters: 100,