| 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 | } |