BlueGit

timfa questward

Merge hybrid 3×3 dynamic block lighting into master.

timfa Tim Falken · pushed by timfa

Authored 2026-09-02 · 2 months ago

Hash
988ba1da2dc7061450e79360f972500740653e74
5 files changed +267 −47
client/src/render/worldView.js +110 −21
@@ -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 { collectBlockLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";
5 6 import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
6 7 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
7 8 import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
@@ -16,7 +17,7 @@ import
16 17 import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
17 18 import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
18 19 import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, LightOcclusion, blockDefinition, blockLightOcclusionForBlock } from "/shared/definitions/tiles.js";
19 import { doorSortSubOrder } from "/shared/world/doors.js";
20 import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js";
20 21 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
21 22 import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
22 23 import { createChunkAtlasCache } from "./chunkAtlasCache.js";
@@ -3126,20 +3127,61 @@ export class WorldView
3126 3127 {
3127 3128 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3128 3129 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3129 if (this.#playerChunkX != null
3130 && (chunkX !== this.#playerChunkX || chunkY !== this.#playerChunkY))
3130 const prevX = this.#playerChunkX;
3131 const prevY = this.#playerChunkY;
3132 if (prevX != null
3133 && (chunkX !== prevX || chunkY !== prevY))
3131 3134 {
3132 const dx = chunkX - this.#playerChunkX;
3133 const dy = chunkY - this.#playerChunkY;
3135 const dx = chunkX - prevX;
3136 const dy = chunkY - prevY;
3134 3137 if (dx !== 0)
3135 3138 { this.#playerMoveChunkDx = Math.sign(dx); }
3136 3139 if (dy !== 0)
3137 3140 { this.#playerMoveChunkDy = Math.sign(dy); }
3141 this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY);
3138 3142 }
3139 3143 this.#playerChunkX = chunkX;
3140 3144 this.#playerChunkY = chunkY;
3141 3145 }
3142 3146
3147 /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */
3148 #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY)
3149 {
3150 this.#invalidateNeighborLightmapCaches(prevChunkX, prevChunkY);
3151 this.#invalidateNeighborLightmapCaches(chunkX, chunkY);
3152 const doorChunks = new Set();
3153 for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]])
3154 {
3155 for (let dy = -1; dy <= 1; dy++)
3156 {
3157 for (let dx = -1; dx <= 1; dx++)
3158 { doorChunks.add(`${cx + dx},${cy + dy}`); }
3159 }
3160 }
3161 for (const key of doorChunks)
3162 {
3163 const [cx, cy] = key.split(",").map(Number);
3164 this.#redrawDoorTilesInChunk(cx, cy);
3165 }
3166 }
3167
3168 #redrawDoorTilesInChunk (chunkX, chunkY)
3169 {
3170 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3171 if (!snapshot?.blocks)
3172 { return; }
3173 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3174 {
3175 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3176 {
3177 const block = snapshot.blocks[localY * CHUNK_SIZE + localX];
3178 if (!blockDefinition(block?.typeId)?.door)
3179 { continue; }
3180 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
3181 }
3182 }
3183 }
3184
3143 3185 #playerChunkCoords ()
3144 3186 {
3145 3187 const local = this.entities.get(this.localEntityId);
@@ -3668,6 +3710,17 @@ export class WorldView
3668 3710 let blockSource = snapshot.blocks[index];
3669 3711 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined)
3670 3712 { blockSource = this.preview.block; }
3713 // Outer map ring: always show doors at resting (matches baked light; no entities there).
3714 if (
3715 blockSource
3716 && blockDefinition(blockSource.typeId)?.door
3717 && !this.#isActiveLightingChunk(chunkX, chunkY)
3718 )
3719 {
3720 const resting = doorRestingState(blockSource);
3721 if (resting && resting !== blockSource.state)
3722 { blockSource = { ...blockSource, state: resting }; }
3723 }
3671 3724 const tileBlock = tileBlockSpriteEntry(
3672 3725 this.catalog,
3673 3726 this.game.images,
@@ -3911,41 +3964,73 @@ export class WorldView
3911 3964 }
3912 3965
3913 3966 /**
3914 * Lights to simulate for one chunk: inner chunks get all inner sources; outer ring
3915 * chunks only receive inner sources close enough to reach the chunk bounds.
3967 * Lights to simulate for one chunk.
3968 * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk.
3969 * Outer ring: only mobile lights originating inside the 3×3 that reach the chunk (baked fills the rest).
3916 3970 */
3917 #dynamicLightsForChunk (chunkX, chunkY, activeLights)
3971 #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = [])
3918 3972 {
3919 3973 const center = this.#activeLightingCenterChunk();
3920 3974 if (!center)
3921 { return activeLights; }
3922 const inner = this.#innerDynamicLights(activeLights);
3975 { return [...mobileLights, ...blockLights]; }
3923 3976 if (this.#isActiveLightingChunk(chunkX, chunkY))
3924 { return inner; }
3977 {
3978 const inner = this.#innerDynamicLights(mobileLights);
3979 const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3980 return [...inner, ...blocks];
3981 }
3982 const inner = this.#innerDynamicLights(mobileLights);
3925 3983 return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3926 3984 }
3927 3985
3928 #dynamicLightsForTile (tileX, tileY, activeLights)
3986 #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = [])
3929 3987 {
3930 3988 return this.#dynamicLightsForChunk(
3931 3989 Math.floor(tileX / CHUNK_SIZE),
3932 3990 Math.floor(tileY / CHUNK_SIZE),
3933 activeLights
3991 mobileLights,
3992 blockLights
3934 3993 );
3935 3994 }
3936 3995
3996 /** Authored torches/furnaces in chunks that can light the active 3×3 (or all chunks in editor). */
3997 #collectBlockLightsForShading ()
3998 {
3999 const center = this.#activeLightingCenterChunk();
4000 const maxRange = maxBlockLightRangeTiles();
4001 const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1;
4002 const sources = [];
4003 if (!center)
4004 {
4005 for (const snapshot of this.chunks.values())
4006 { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); }
4007 return sources;
4008 }
4009 for (let dy = -1 - halo; dy <= 1 + halo; dy++)
4010 {
4011 for (let dx = -1 - halo; dx <= 1 + halo; dx++)
4012 {
4013 const snapshot = this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`);
4014 if (!snapshot?.blocks)
4015 { continue; }
4016 sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks));
4017 }
4018 }
4019 return sources;
4020 }
4021
3937 4022 #updateShade ()
3938 4023 {
3939 4024 const ambientDark = this.#ambientDarkness();
3940 4025 const now = performance.now();
3941 4026 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3942 4027
3943 const activeLights = [...this.dynamicLights];
4028 const mobileLights = [...this.dynamicLights];
3944 4029 for (const light of this.spellLights.values())
3945 4030 {
3946 4031 if (light.until <= now)
3947 4032 { continue; }
3948 activeLights.push({
4033 mobileLights.push({
3949 4034 tileX: light.tileX,
3950 4035 tileY: light.tileY,
3951 4036 range: light.range,
@@ -3992,19 +4077,20 @@ export class WorldView
3992 4077 const tileSize = this.tileSize();
3993 4078 const blindLight = this.#blindVisionLight();
3994 4079 if (blindLight)
3995 { activeLights.push(blindLight); }
4080 { mobileLights.push(blindLight); }
3996 4081 for (const entity of this.entities.values())
3997 4082 {
3998 4083 const range = entity.lightRadiusTiles ?? 0;
3999 4084 if (range <= 0)
4000 4085 { continue; }
4001 activeLights.push({
4086 mobileLights.push({
4002 4087 tileX: Math.floor(entity.visualX / tileSize),
4003 4088 tileY: Math.floor(entity.visualY / tileSize),
4004 4089 range,
4005 4090 intensity: entity.lightIntensity ?? 1
4006 4091 });
4007 4092 }
4093 const blockLights = this.#collectBlockLightsForShading();
4008 4094
4009 4095 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
4010 4096
@@ -4012,7 +4098,7 @@ export class WorldView
4012 4098 {
4013 4099 if (objects._inViewport === false)
4014 4100 { continue; }
4015 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights);
4101 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights);
4016 4102 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
4017 4103 }
4018 4104
@@ -4020,7 +4106,7 @@ export class WorldView
4020 4106 {
4021 4107 if (baked._inViewport === false)
4022 4108 { continue; }
4023 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
4109 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights);
4024 4110 this.#writeChunkLightmap(baked, lights, lightOcclusion, ambientDark);
4025 4111 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
4026 4112 if (baked.groundObject?.renderer?.shaderUniforms)
@@ -4074,7 +4160,9 @@ export class WorldView
4074 4160
4075 4161 #tileLightSources (objects, activeLights, lightOcclusion)
4076 4162 {
4077 const baked = lightIntensity(objects.light ?? 0);
4163 // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps.
4164 const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY);
4165 const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0;
4078 4166 const dynamic = dynamicLightAtTile(
4079 4167 objects.tileX,
4080 4168 objects.tileY,
@@ -4116,7 +4204,8 @@ export class WorldView
4116 4204 const localX = tileX - chunkX * CHUNK_SIZE;
4117 4205 const localY = tileY - chunkY * CHUNK_SIZE;
4118 4206 const index = localY * CHUNK_SIZE + localX;
4119 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
4207 const useBaked = !this.#isActiveLightingTile(tileX, tileY);
4208 const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0;
4120 4209 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
4121 4210 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
4122 4211 const lights = Math.max(bakedLit, dynamic);
@@ -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 { collectBlockLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";
5import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
6import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
6import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
7import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
7import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
8import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
@@ -16,7 +17,7 @@ import
16import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
17import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
17import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
18import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
18import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, LightOcclusion, blockDefinition, blockLightOcclusionForBlock } from "/shared/definitions/tiles.js";
19import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, LightOcclusion, blockDefinition, blockLightOcclusionForBlock } from "/shared/definitions/tiles.js";
19import { doorSortSubOrder } from "/shared/world/doors.js";
20import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js";
20import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
21import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
21import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
22import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
22import { createChunkAtlasCache } from "./chunkAtlasCache.js";
23import { createChunkAtlasCache } from "./chunkAtlasCache.js";
@@ -3126,20 +3127,61 @@ export class WorldView
3126 {
3127 {
3127 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3128 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3128 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3129 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3129 if (this.#playerChunkX != null
3130 const prevX = this.#playerChunkX;
3130 && (chunkX !== this.#playerChunkX || chunkY !== this.#playerChunkY))
3131 const prevY = this.#playerChunkY;
3132 if (prevX != null
3133 && (chunkX !== prevX || chunkY !== prevY))
3131 {
3134 {
3132 const dx = chunkX - this.#playerChunkX;
3135 const dx = chunkX - prevX;
3133 const dy = chunkY - this.#playerChunkY;
3136 const dy = chunkY - prevY;
3134 if (dx !== 0)
3137 if (dx !== 0)
3135 { this.#playerMoveChunkDx = Math.sign(dx); }
3138 { this.#playerMoveChunkDx = Math.sign(dx); }
3136 if (dy !== 0)
3139 if (dy !== 0)
3137 { this.#playerMoveChunkDy = Math.sign(dy); }
3140 { this.#playerMoveChunkDy = Math.sign(dy); }
3141 this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY);
3138 }
3142 }
3139 this.#playerChunkX = chunkX;
3143 this.#playerChunkX = chunkX;
3140 this.#playerChunkY = chunkY;
3144 this.#playerChunkY = chunkY;
3141 }
3145 }
3142
3146
3147 /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */
3148 #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY)
3149 {
3150 this.#invalidateNeighborLightmapCaches(prevChunkX, prevChunkY);
3151 this.#invalidateNeighborLightmapCaches(chunkX, chunkY);
3152 const doorChunks = new Set();
3153 for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]])
3154 {
3155 for (let dy = -1; dy <= 1; dy++)
3156 {
3157 for (let dx = -1; dx <= 1; dx++)
3158 { doorChunks.add(`${cx + dx},${cy + dy}`); }
3159 }
3160 }
3161 for (const key of doorChunks)
3162 {
3163 const [cx, cy] = key.split(",").map(Number);
3164 this.#redrawDoorTilesInChunk(cx, cy);
3165 }
3166 }
3167
3168 #redrawDoorTilesInChunk (chunkX, chunkY)
3169 {
3170 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3171 if (!snapshot?.blocks)
3172 { return; }
3173 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3174 {
3175 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3176 {
3177 const block = snapshot.blocks[localY * CHUNK_SIZE + localX];
3178 if (!blockDefinition(block?.typeId)?.door)
3179 { continue; }
3180 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
3181 }
3182 }
3183 }
3184
3143 #playerChunkCoords ()
3185 #playerChunkCoords ()
3144 {
3186 {
3145 const local = this.entities.get(this.localEntityId);
3187 const local = this.entities.get(this.localEntityId);
@@ -3668,6 +3710,17 @@ export class WorldView
3668 let blockSource = snapshot.blocks[index];
3710 let blockSource = snapshot.blocks[index];
3669 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined)
3711 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined)
3670 { blockSource = this.preview.block; }
3712 { blockSource = this.preview.block; }
3713 // Outer map ring: always show doors at resting (matches baked light; no entities there).
3714 if (
3715 blockSource
3716 && blockDefinition(blockSource.typeId)?.door
3717 && !this.#isActiveLightingChunk(chunkX, chunkY)
3718 )
3719 {
3720 const resting = doorRestingState(blockSource);
3721 if (resting && resting !== blockSource.state)
3722 { blockSource = { ...blockSource, state: resting }; }
3723 }
3671 const tileBlock = tileBlockSpriteEntry(
3724 const tileBlock = tileBlockSpriteEntry(
3672 this.catalog,
3725 this.catalog,
3673 this.game.images,
3726 this.game.images,
@@ -3911,41 +3964,73 @@ export class WorldView
3911 }
3964 }
3912
3965
3913 /**
3966 /**
3914 * Lights to simulate for one chunk: inner chunks get all inner sources; outer ring
3967 * Lights to simulate for one chunk.
3915 * chunks only receive inner sources close enough to reach the chunk bounds.
3968 * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk.
3969 * Outer ring: only mobile lights originating inside the 3×3 that reach the chunk (baked fills the rest).
3916 */
3970 */
3917 #dynamicLightsForChunk (chunkX, chunkY, activeLights)
3971 #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = [])
3918 {
3972 {
3919 const center = this.#activeLightingCenterChunk();
3973 const center = this.#activeLightingCenterChunk();
3920 if (!center)
3974 if (!center)
3921 { return activeLights; }
3975 { return [...mobileLights, ...blockLights]; }
3922 const inner = this.#innerDynamicLights(activeLights);
3923 if (this.#isActiveLightingChunk(chunkX, chunkY))
3976 if (this.#isActiveLightingChunk(chunkX, chunkY))
3924 { return inner; }
3977 {
3978 const inner = this.#innerDynamicLights(mobileLights);
3979 const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3980 return [...inner, ...blocks];
3981 }
3982 const inner = this.#innerDynamicLights(mobileLights);
3925 return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3983 return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3926 }
3984 }
3927
3985
3928 #dynamicLightsForTile (tileX, tileY, activeLights)
3986 #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = [])
3929 {
3987 {
3930 return this.#dynamicLightsForChunk(
3988 return this.#dynamicLightsForChunk(
3931 Math.floor(tileX / CHUNK_SIZE),
3989 Math.floor(tileX / CHUNK_SIZE),
3932 Math.floor(tileY / CHUNK_SIZE),
3990 Math.floor(tileY / CHUNK_SIZE),
3933 activeLights
3991 mobileLights,
3992 blockLights
3934 );
3993 );
3935 }
3994 }
3936
3995
3996 /** Authored torches/furnaces in chunks that can light the active 3×3 (or all chunks in editor). */
3997 #collectBlockLightsForShading ()
3998 {
3999 const center = this.#activeLightingCenterChunk();
4000 const maxRange = maxBlockLightRangeTiles();
4001 const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1;
4002 const sources = [];
4003 if (!center)
4004 {
4005 for (const snapshot of this.chunks.values())
4006 { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); }
4007 return sources;
4008 }
4009 for (let dy = -1 - halo; dy <= 1 + halo; dy++)
4010 {
4011 for (let dx = -1 - halo; dx <= 1 + halo; dx++)
4012 {
4013 const snapshot = this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`);
4014 if (!snapshot?.blocks)
4015 { continue; }
4016 sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks));
4017 }
4018 }
4019 return sources;
4020 }
4021
3937 #updateShade ()
4022 #updateShade ()
3938 {
4023 {
3939 const ambientDark = this.#ambientDarkness();
4024 const ambientDark = this.#ambientDarkness();
3940 const now = performance.now();
4025 const now = performance.now();
3941 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
4026 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3942
4027
3943 const activeLights = [...this.dynamicLights];
4028 const mobileLights = [...this.dynamicLights];
3944 for (const light of this.spellLights.values())
4029 for (const light of this.spellLights.values())
3945 {
4030 {
3946 if (light.until <= now)
4031 if (light.until <= now)
3947 { continue; }
4032 { continue; }
3948 activeLights.push({
4033 mobileLights.push({
3949 tileX: light.tileX,
4034 tileX: light.tileX,
3950 tileY: light.tileY,
4035 tileY: light.tileY,
3951 range: light.range,
4036 range: light.range,
@@ -3992,19 +4077,20 @@ export class WorldView
3992 const tileSize = this.tileSize();
4077 const tileSize = this.tileSize();
3993 const blindLight = this.#blindVisionLight();
4078 const blindLight = this.#blindVisionLight();
3994 if (blindLight)
4079 if (blindLight)
3995 { activeLights.push(blindLight); }
4080 { mobileLights.push(blindLight); }
3996 for (const entity of this.entities.values())
4081 for (const entity of this.entities.values())
3997 {
4082 {
3998 const range = entity.lightRadiusTiles ?? 0;
4083 const range = entity.lightRadiusTiles ?? 0;
3999 if (range <= 0)
4084 if (range <= 0)
4000 { continue; }
4085 { continue; }
4001 activeLights.push({
4086 mobileLights.push({
4002 tileX: Math.floor(entity.visualX / tileSize),
4087 tileX: Math.floor(entity.visualX / tileSize),
4003 tileY: Math.floor(entity.visualY / tileSize),
4088 tileY: Math.floor(entity.visualY / tileSize),
4004 range,
4089 range,
4005 intensity: entity.lightIntensity ?? 1
4090 intensity: entity.lightIntensity ?? 1
4006 });
4091 });
4007 }
4092 }
4093 const blockLights = this.#collectBlockLightsForShading();
4008
4094
4009 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
4095 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
4010
4096
@@ -4012,7 +4098,7 @@ export class WorldView
4012 {
4098 {
4013 if (objects._inViewport === false)
4099 if (objects._inViewport === false)
4014 { continue; }
4100 { continue; }
4015 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights);
4101 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights);
4016 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
4102 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
4017 }
4103 }
4018
4104
@@ -4020,7 +4106,7 @@ export class WorldView
4020 {
4106 {
4021 if (baked._inViewport === false)
4107 if (baked._inViewport === false)
4022 { continue; }
4108 { continue; }
4023 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
4109 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights);
4024 this.#writeChunkLightmap(baked, lights, lightOcclusion, ambientDark);
4110 this.#writeChunkLightmap(baked, lights, lightOcclusion, ambientDark);
4025 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
4111 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
4026 if (baked.groundObject?.renderer?.shaderUniforms)
4112 if (baked.groundObject?.renderer?.shaderUniforms)
@@ -4074,7 +4160,9 @@ export class WorldView
4074
4160
4075 #tileLightSources (objects, activeLights, lightOcclusion)
4161 #tileLightSources (objects, activeLights, lightOcclusion)
4076 {
4162 {
4077 const baked = lightIntensity(objects.light ?? 0);
4163 // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps.
4164 const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY);
4165 const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0;
4078 const dynamic = dynamicLightAtTile(
4166 const dynamic = dynamicLightAtTile(
4079 objects.tileX,
4167 objects.tileX,
4080 objects.tileY,
4168 objects.tileY,
@@ -4116,7 +4204,8 @@ export class WorldView
4116 const localX = tileX - chunkX * CHUNK_SIZE;
4204 const localX = tileX - chunkX * CHUNK_SIZE;
4117 const localY = tileY - chunkY * CHUNK_SIZE;
4205 const localY = tileY - chunkY * CHUNK_SIZE;
4118 const index = localY * CHUNK_SIZE + localX;
4206 const index = localY * CHUNK_SIZE + localX;
4119 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
4207 const useBaked = !this.#isActiveLightingTile(tileX, tileY);
4208 const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0;
4120 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
4209 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
4121 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
4210 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
4122 const lights = Math.max(bakedLit, dynamic);
4211 const lights = Math.max(bakedLit, dynamic);
server/src/combat/service.js +14 −7
@@ -36,11 +36,11 @@ import
36 36 } from "../../../shared/combat/darkness.js";
37 37 import
38 38 {
39 bakedTileLight01,
40 39 entityLightAtTile,
41 40 tileCombatLight01,
42 41 tileIndexLocal
43 42 } from "../../../shared/lighting/combatLight.js";
43 import { blockLightSourcesNearTile } from "../../../shared/lighting/blockLights.js";
44 44 import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js";
45 45 import { LightOcclusion } from "../../../shared/definitions/tiles.js";
46 46 import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js";
@@ -450,20 +450,27 @@ function lightOcclusionAtWorld (world, x, y)
450 450 return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY);
451 451 }
452 452
453 /** Target-tile lighting 0–1 (baked + entity/spell lights − spell dark + time of day). */
453 /**
454 * Target-tile lighting 0–1 for combat.
455 * Block lights (torches, …) use live occlusion so passage-open doors let light through;
456 * entity/spell lights layer on top (same compositing as client inner 3×3).
457 */
454 458 export function tileLightAt (world, tileX, tileY, now = Date.now())
455 459 {
456 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY));
457 const index = tileIndexLocal(tileX, tileY);
458 const baked = bakedTileLight01(data?.light, index);
460 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y);
461 const blockSources = blockLightSourcesNearTile(
462 (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY),
463 tileX,
464 tileY
465 );
466 const blockLit = dynamicLightAtTile(tileX, tileY, blockSources, occlusionAt);
459 467 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
460 468 const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now);
461 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y);
462 469 const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt);
463 470 const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt);
464 471 const worldTime = world.worldTime?.(now);
465 472 return tileCombatLight01({
466 bakedLight01: baked,
473 bakedLight01: blockLit,
467 474 entityLight01: entity,
468 475 spellLight01: spellLight,
469 476 spellDark01: spellDark,
@@ -36,11 +36,11 @@ import
36 } from "../../../shared/combat/darkness.js";
36 } from "../../../shared/combat/darkness.js";
37import
37import
38 {
38 {
39 bakedTileLight01,
40 entityLightAtTile,
39 entityLightAtTile,
41 tileCombatLight01,
40 tileCombatLight01,
42 tileIndexLocal
41 tileIndexLocal
43 } from "../../../shared/lighting/combatLight.js";
42 } from "../../../shared/lighting/combatLight.js";
43import { blockLightSourcesNearTile } from "../../../shared/lighting/blockLights.js";
44import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js";
44import { dynamicDarknessAtTile, dynamicLightAtTile, rayReaches } from "../../../shared/lighting/raycast.js";
45import { LightOcclusion } from "../../../shared/definitions/tiles.js";
45import { LightOcclusion } from "../../../shared/definitions/tiles.js";
46import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js";
46import { tileLightOcclusionAt } from "../../../shared/lighting/chunkOcclusion.js";
@@ -450,20 +450,27 @@ function lightOcclusionAtWorld (world, x, y)
450 return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY);
450 return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY);
451}
451}
452
452
453/** Target-tile lighting 0–1 (baked + entity/spell lights − spell dark + time of day). */
453/**
454 * Target-tile lighting 0–1 for combat.
455 * Block lights (torches, …) use live occlusion so passage-open doors let light through;
456 * entity/spell lights layer on top (same compositing as client inner 3×3).
457 */
454export function tileLightAt (world, tileX, tileY, now = Date.now())
458export function tileLightAt (world, tileX, tileY, now = Date.now())
455{
459{
456 const data = world.chunkData?.(tileToChunk(tileX), tileToChunk(tileY));
460 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y);
457 const index = tileIndexLocal(tileX, tileY);
461 const blockSources = blockLightSourcesNearTile(
458 const baked = bakedTileLight01(data?.light, index);
462 (chunkX, chunkY) => world.chunkData?.(chunkX, chunkY),
463 tileX,
464 tileY
465 );
466 const blockLit = dynamicLightAtTile(tileX, tileY, blockSources, occlusionAt);
459 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
467 const entity = entityLightAtTile(world.ecs, Component, tileX, tileY, now);
460 const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now);
468 const { lights, darks } = spellLightsForDynamicLighting(world.spellLights, now);
461 const occlusionAt = (x, y) => lightOcclusionAtWorld(world, x, y);
462 const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt);
469 const spellLight = dynamicLightAtTile(tileX, tileY, lights, occlusionAt);
463 const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt);
470 const spellDark = dynamicDarknessAtTile(tileX, tileY, darks, occlusionAt);
464 const worldTime = world.worldTime?.(now);
471 const worldTime = world.worldTime?.(now);
465 return tileCombatLight01({
472 return tileCombatLight01({
466 bakedLight01: baked,
473 bakedLight01: blockLit,
467 entityLight01: entity,
474 entityLight01: entity,
468 spellLight01: spellLight,
475 spellLight01: spellLight,
469 spellDark01: spellDark,
476 spellDark01: spellDark,
server/src/world/chunkData.js +2 −19
@@ -7,12 +7,12 @@ import {
7 7 LightOcclusion,
8 8 isGroundPassable,
9 9 blockBlocksRangedAttacks,
10 blockLightRange,
11 10 normalizeGround,
12 11 normalizeBlock
13 12 } from "../../../shared/definitions/tiles.js";
14 13 import { isDoorTraversable } from "../../../shared/world/doors.js";
15 14 import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";
15 import { collectBlockLightSources } from "../../../shared/lighting/blockLights.js";
16 16 import {
17 17 flowerBlockState,
18 18 flowerColorIdFromBlockState,
@@ -211,24 +211,7 @@ export function isChunkTileClearForRangedAttacks (data, localX, localY)
211 211
212 212 export function collectLightSources (chunkX, chunkY, data)
213 213 {
214 const sources = [];
215 for (let localY = 0; localY < CHUNK_SIZE; localY++)
216 {
217 for (let localX = 0; localX < CHUNK_SIZE; localX++)
218 {
219 const block = data.blocks[tileIndex(localX, localY)];
220 const range = blockLightRange(block?.typeId ?? null);
221 if (range > 0)
222 {
223 sources.push({
224 tileX: chunkX * CHUNK_SIZE + localX,
225 tileY: chunkY * CHUNK_SIZE + localY,
226 range
227 });
228 }
229 }
230 }
231 return sources;
214 return collectBlockLightSources(chunkX, chunkY, data?.blocks);
232 215 }
233 216
234 217 function migrateLegacySpawners (blocks, authored, parsedHint)
@@ -7,12 +7,12 @@ import {
7 LightOcclusion,
7 LightOcclusion,
8 isGroundPassable,
8 isGroundPassable,
9 blockBlocksRangedAttacks,
9 blockBlocksRangedAttacks,
10 blockLightRange,
11 normalizeGround,
10 normalizeGround,
12 normalizeBlock
11 normalizeBlock
13} from "../../../shared/definitions/tiles.js";
12} from "../../../shared/definitions/tiles.js";
14import { isDoorTraversable } from "../../../shared/world/doors.js";
13import { isDoorTraversable } from "../../../shared/world/doors.js";
15import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";
14import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";
15import { collectBlockLightSources } from "../../../shared/lighting/blockLights.js";
16import {
16import {
17 flowerBlockState,
17 flowerBlockState,
18 flowerColorIdFromBlockState,
18 flowerColorIdFromBlockState,
@@ -211,24 +211,7 @@ export function isChunkTileClearForRangedAttacks (data, localX, localY)
211
211
212export function collectLightSources (chunkX, chunkY, data)
212export function collectLightSources (chunkX, chunkY, data)
213{
213{
214 const sources = [];
214 return collectBlockLightSources(chunkX, chunkY, data?.blocks);
215 for (let localY = 0; localY < CHUNK_SIZE; localY++)
216 {
217 for (let localX = 0; localX < CHUNK_SIZE; localX++)
218 {
219 const block = data.blocks[tileIndex(localX, localY)];
220 const range = blockLightRange(block?.typeId ?? null);
221 if (range > 0)
222 {
223 sources.push({
224 tileX: chunkX * CHUNK_SIZE + localX,
225 tileY: chunkY * CHUNK_SIZE + localY,
226 range
227 });
228 }
229 }
230 }
231 return sources;
232}
215}
233
216
234function migrateLegacySpawners (blocks, authored, parsedHint)
217function migrateLegacySpawners (blocks, authored, parsedHint)
server/tests/lighting.test.js +69 −0
@@ -4,8 +4,13 @@ import { createEmptyChunkData } from "../src/world/chunkData.js";
4 4 import { bakeLightMaps } from "../src/lighting/baker.js";
5 5 import { bresenhamTiles, dynamicLightAtTile, evaluateLightRay, rayReaches } from "../../shared/lighting/raycast.js";
6 6 import { makeSnapshotLightOcclusion } from "../../shared/lighting/tilePassable.js";
7 import { collectBlockLightSources } from "../../shared/lighting/blockLights.js";
8 import { tileLightOcclusionAt, bakeChunkOcclusion } from "../../shared/lighting/chunkOcclusion.js";
7 9 import { BlockType, blockLightOcclusionForBlock, LightOcclusion } from "../../shared/definitions/tiles.js";
8 10 import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
11 import { tileLightAt } from "../src/combat/service.js";
12 import { maybeOpenDoorOnApproach } from "../src/doors/service.js";
13 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9 14
10 15 test("Bresenham visits start and end tiles", () =>
11 16 {
@@ -218,3 +223,67 @@ test("lit corner blend does not darken daylight beside occluding walls", async (
218 223 });
219 224 assert.equal(openBlend, (1 + 0.5 + 0.5 + 0.25) / 4);
220 225 });
226
227 test("collectBlockLightSources finds torches", () =>
228 {
229 const data = createEmptyChunkData();
230 data.blocks[0] = { typeId: BlockType.torch, config: null };
231 const sources = collectBlockLightSources(0, 0, data.blocks);
232 assert.equal(sources.length, 1);
233 assert.equal(sources[0].tileX, 0);
234 assert.equal(sources[0].tileY, 0);
235 assert.ok(sources[0].range > 0);
236 });
237
238 test("dynamic block light is blocked by a resting door and passes when passage-open", () =>
239 {
240 const chunks = new Map();
241 const data = createEmptyChunkData();
242 data.open = true;
243 data.blocks[0] = { typeId: BlockType.torch, config: null };
244 data.blocks[1] = { typeId: BlockType.door, state: "pine-s-closed", config: null };
245 data.occlusion = bakeChunkOcclusion(data);
246 chunks.set("0,0", { chunkX: 0, chunkY: 0, grounds: data.grounds, blocks: data.blocks, occlusion: data.occlusion });
247
248 const occlusion = makeSnapshotLightOcclusion(chunks);
249 const sources = collectBlockLightSources(0, 0, data.blocks);
250 assert.equal(dynamicLightAtTile(2, 0, sources, occlusion), 0, "closed door blocks torch");
251
252 data.blocks[1] = {
253 typeId: BlockType.door,
254 state: "pine-s-open",
255 config: { restingState: "pine-s-closed" }
256 };
257 data.occlusion[1] = tileLightOcclusionAt(data.grounds, data.blocks, 1, 0);
258 assert.ok(dynamicLightAtTile(2, 0, sources, occlusion) > 0, "passage-open door lets torch through");
259 });
260
261 test("tileLightAt at night rises when a door opens between torch and target", () =>
262 {
263 const harness = makeSimulation({ workerCount: 1 });
264 try
265 {
266 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
267 harness.simulation.spawnCharacter(1, character);
268 harness.simulation.step();
269 const record = harness.simulation.entityRecord(character.character_id);
270 const worker = harness.simulation.workers[record.workerId];
271 worker.world.worldTime = () => ({ hour: 0 });
272
273 const data = worker.world.chunkData(0, 0);
274 const torchIndex = 8 * CHUNK_SIZE + 8;
275 const doorIndex = 8 * CHUNK_SIZE + 9;
276 data.blocks[torchIndex] = { typeId: BlockType.torch, config: null };
277 data.blocks[doorIndex] = { typeId: BlockType.door, state: "pine-s-closed", config: null };
278 data.occlusion[torchIndex] = tileLightOcclusionAt(data.grounds, data.blocks, 8, 8);
279 data.occlusion[doorIndex] = tileLightOcclusionAt(data.grounds, data.blocks, 9, 8);
280
281 const closed = tileLightAt(worker.world, 10, 8);
282 const opened = maybeOpenDoorOnApproach(worker.world, character.character_id, 9, 8);
283 assert.ok(opened);
284 const open = tileLightAt(worker.world, 10, 8);
285 assert.ok(open > closed + 0.05, `expected open (${open}) brighter than closed (${closed})`);
286 }
287 finally
288 { harness.close(); }
289 });
@@ -4,8 +4,13 @@ import { createEmptyChunkData } from "../src/world/chunkData.js";
4import { bakeLightMaps } from "../src/lighting/baker.js";
4import { bakeLightMaps } from "../src/lighting/baker.js";
5import { bresenhamTiles, dynamicLightAtTile, evaluateLightRay, rayReaches } from "../../shared/lighting/raycast.js";
5import { bresenhamTiles, dynamicLightAtTile, evaluateLightRay, rayReaches } from "../../shared/lighting/raycast.js";
6import { makeSnapshotLightOcclusion } from "../../shared/lighting/tilePassable.js";
6import { makeSnapshotLightOcclusion } from "../../shared/lighting/tilePassable.js";
7import { collectBlockLightSources } from "../../shared/lighting/blockLights.js";
8import { tileLightOcclusionAt, bakeChunkOcclusion } from "../../shared/lighting/chunkOcclusion.js";
7import { BlockType, blockLightOcclusionForBlock, LightOcclusion } from "../../shared/definitions/tiles.js";
9import { BlockType, blockLightOcclusionForBlock, LightOcclusion } from "../../shared/definitions/tiles.js";
8import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
10import { CHUNK_SIZE } from "../../shared/protocol/constants.js";
11import { tileLightAt } from "../src/combat/service.js";
12import { maybeOpenDoorOnApproach } from "../src/doors/service.js";
13import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
9
14
10test("Bresenham visits start and end tiles", () =>
15test("Bresenham visits start and end tiles", () =>
11{
16{
@@ -218,3 +223,67 @@ test("lit corner blend does not darken daylight beside occluding walls", async (
218 });
223 });
219 assert.equal(openBlend, (1 + 0.5 + 0.5 + 0.25) / 4);
224 assert.equal(openBlend, (1 + 0.5 + 0.5 + 0.25) / 4);
220});
225});
226
227test("collectBlockLightSources finds torches", () =>
228{
229 const data = createEmptyChunkData();
230 data.blocks[0] = { typeId: BlockType.torch, config: null };
231 const sources = collectBlockLightSources(0, 0, data.blocks);
232 assert.equal(sources.length, 1);
233 assert.equal(sources[0].tileX, 0);
234 assert.equal(sources[0].tileY, 0);
235 assert.ok(sources[0].range > 0);
236});
237
238test("dynamic block light is blocked by a resting door and passes when passage-open", () =>
239{
240 const chunks = new Map();
241 const data = createEmptyChunkData();
242 data.open = true;
243 data.blocks[0] = { typeId: BlockType.torch, config: null };
244 data.blocks[1] = { typeId: BlockType.door, state: "pine-s-closed", config: null };
245 data.occlusion = bakeChunkOcclusion(data);
246 chunks.set("0,0", { chunkX: 0, chunkY: 0, grounds: data.grounds, blocks: data.blocks, occlusion: data.occlusion });
247
248 const occlusion = makeSnapshotLightOcclusion(chunks);
249 const sources = collectBlockLightSources(0, 0, data.blocks);
250 assert.equal(dynamicLightAtTile(2, 0, sources, occlusion), 0, "closed door blocks torch");
251
252 data.blocks[1] = {
253 typeId: BlockType.door,
254 state: "pine-s-open",
255 config: { restingState: "pine-s-closed" }
256 };
257 data.occlusion[1] = tileLightOcclusionAt(data.grounds, data.blocks, 1, 0);
258 assert.ok(dynamicLightAtTile(2, 0, sources, occlusion) > 0, "passage-open door lets torch through");
259});
260
261test("tileLightAt at night rises when a door opens between torch and target", () =>
262{
263 const harness = makeSimulation({ workerCount: 1 });
264 try
265 {
266 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
267 harness.simulation.spawnCharacter(1, character);
268 harness.simulation.step();
269 const record = harness.simulation.entityRecord(character.character_id);
270 const worker = harness.simulation.workers[record.workerId];
271 worker.world.worldTime = () => ({ hour: 0 });
272
273 const data = worker.world.chunkData(0, 0);
274 const torchIndex = 8 * CHUNK_SIZE + 8;
275 const doorIndex = 8 * CHUNK_SIZE + 9;
276 data.blocks[torchIndex] = { typeId: BlockType.torch, config: null };
277 data.blocks[doorIndex] = { typeId: BlockType.door, state: "pine-s-closed", config: null };
278 data.occlusion[torchIndex] = tileLightOcclusionAt(data.grounds, data.blocks, 8, 8);
279 data.occlusion[doorIndex] = tileLightOcclusionAt(data.grounds, data.blocks, 9, 8);
280
281 const closed = tileLightAt(worker.world, 10, 8);
282 const opened = maybeOpenDoorOnApproach(worker.world, character.character_id, 9, 8);
283 assert.ok(opened);
284 const open = tileLightAt(worker.world, 10, 8);
285 assert.ok(open > closed + 0.05, `expected open (${open}) brighter than closed (${closed})`);
286 }
287 finally
288 { harness.close(); }
289});
shared/lighting/blockLights.js added +72 −0
@@ -0,0 +1,72 @@
1 /** Authored block lights (torches, furnaces, …) for dynamic lighting / combat. */
2
3 import { CHUNK_SIZE } from "../protocol/constants.js";
4 import { BLOCK_DEFINITIONS, blockLightRange } from "../definitions/tiles.js";
5
6 let cachedMaxRange = null;
7
8 /** Max `lightRangeTiles` across block defs (cached). */
9 export function maxBlockLightRangeTiles ()
10 {
11 if (cachedMaxRange != null)
12 { return cachedMaxRange; }
13 let max = 0;
14 for (const def of Object.values(BLOCK_DEFINITIONS))
15 { max = Math.max(max, def.lightRangeTiles ?? 0); }
16 cachedMaxRange = max;
17 return max;
18 }
19
20 /**
21 * Collect block light sources from one chunk's blocks array (row-major, CHUNK_SIZE²).
22 * @returns {Array<{ tileX: number, tileY: number, range: number }>}
23 */
24 export function collectBlockLightSources (chunkX, chunkY, blocks)
25 {
26 const sources = [];
27 if (!Array.isArray(blocks) || blocks.length < CHUNK_SIZE * CHUNK_SIZE)
28 { return sources; }
29 for (let localY = 0; localY < CHUNK_SIZE; localY++)
30 {
31 for (let localX = 0; localX < CHUNK_SIZE; localX++)
32 {
33 const block = blocks[localY * CHUNK_SIZE + localX];
34 const range = blockLightRange(block?.typeId ?? null);
35 if (range > 0)
36 {
37 sources.push({
38 tileX: chunkX * CHUNK_SIZE + localX,
39 tileY: chunkY * CHUNK_SIZE + localY,
40 range
41 });
42 }
43 }
44 }
45 return sources;
46 }
47
48 /**
49 * Block lights in chunks that can reach (tileX, tileY).
50 * @param {(chunkX: number, chunkY: number) => { blocks?: any[] }|null|undefined} loadChunk
51 */
52 export function blockLightSourcesNearTile (loadChunk, tileX, tileY, maxRange = maxBlockLightRangeTiles())
53 {
54 const range = Math.max(0, maxRange | 0);
55 const halo = Math.ceil(range / CHUNK_SIZE) + 1;
56 const centerX = Math.floor(tileX / CHUNK_SIZE);
57 const centerY = Math.floor(tileY / CHUNK_SIZE);
58 const sources = [];
59 for (let dy = -halo; dy <= halo; dy++)
60 {
61 for (let dx = -halo; dx <= halo; dx++)
62 {
63 const chunkX = centerX + dx;
64 const chunkY = centerY + dy;
65 const data = loadChunk(chunkX, chunkY);
66 if (!data?.blocks)
67 { continue; }
68 sources.push(...collectBlockLightSources(chunkX, chunkY, data.blocks));
69 }
70 }
71 return sources;
72 }
@@ -0,0 +1,72 @@
1/** Authored block lights (torches, furnaces, …) for dynamic lighting / combat. */
2
3import { CHUNK_SIZE } from "../protocol/constants.js";
4import { BLOCK_DEFINITIONS, blockLightRange } from "../definitions/tiles.js";
5
6let cachedMaxRange = null;
7
8/** Max `lightRangeTiles` across block defs (cached). */
9export function maxBlockLightRangeTiles ()
10{
11 if (cachedMaxRange != null)
12 { return cachedMaxRange; }
13 let max = 0;
14 for (const def of Object.values(BLOCK_DEFINITIONS))
15 { max = Math.max(max, def.lightRangeTiles ?? 0); }
16 cachedMaxRange = max;
17 return max;
18}
19
20/**
21 * Collect block light sources from one chunk's blocks array (row-major, CHUNK_SIZE²).
22 * @returns {Array<{ tileX: number, tileY: number, range: number }>}
23 */
24export function collectBlockLightSources (chunkX, chunkY, blocks)
25{
26 const sources = [];
27 if (!Array.isArray(blocks) || blocks.length < CHUNK_SIZE * CHUNK_SIZE)
28 { return sources; }
29 for (let localY = 0; localY < CHUNK_SIZE; localY++)
30 {
31 for (let localX = 0; localX < CHUNK_SIZE; localX++)
32 {
33 const block = blocks[localY * CHUNK_SIZE + localX];
34 const range = blockLightRange(block?.typeId ?? null);
35 if (range > 0)
36 {
37 sources.push({
38 tileX: chunkX * CHUNK_SIZE + localX,
39 tileY: chunkY * CHUNK_SIZE + localY,
40 range
41 });
42 }
43 }
44 }
45 return sources;
46}
47
48/**
49 * Block lights in chunks that can reach (tileX, tileY).
50 * @param {(chunkX: number, chunkY: number) => { blocks?: any[] }|null|undefined} loadChunk
51 */
52export function blockLightSourcesNearTile (loadChunk, tileX, tileY, maxRange = maxBlockLightRangeTiles())
53{
54 const range = Math.max(0, maxRange | 0);
55 const halo = Math.ceil(range / CHUNK_SIZE) + 1;
56 const centerX = Math.floor(tileX / CHUNK_SIZE);
57 const centerY = Math.floor(tileY / CHUNK_SIZE);
58 const sources = [];
59 for (let dy = -halo; dy <= halo; dy++)
60 {
61 for (let dx = -halo; dx <= halo; dx++)
62 {
63 const chunkX = centerX + dx;
64 const chunkY = centerY + dy;
65 const data = loadChunk(chunkX, chunkY);
66 if (!data?.blocks)
67 { continue; }
68 sources.push(...collectBlockLightSources(chunkX, chunkY, data.blocks));
69 }
70 }
71 return sources;
72}