BlueGit

timfa questward

Files

questward / server / src / lighting / baker.js

baker.js

baker.js 2.5 KiB Download Raw
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { encodeLight, evaluateLightRay, lightIntensity } from "../../../shared/lighting/raycast.js";
3import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
4import { cloneChunkData, collectLightSources, createEmptyChunkData, chunkTileLightOcclusion } from "../world/chunkData.js";
5
6export { bresenhamTiles, encodeLight, falloffAtDistance, lightIntensity, rayReaches } from "../../../shared/lighting/raycast.js";
7
8export function maxDefinitionLightRange (blockDefs)
9{
10 let max = 0;
11 for (const def of Object.values(blockDefs))
12 { max = Math.max(max, def.lightRangeTiles ?? 0); }
13 return max;
14}
15
16export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
17{
18 const halo = maxLightChunkRadius(maxRange);
19 const affected = chebyshevChunks(centerChunkX, centerChunkY, halo);
20 const loaded = new Map();
21
22 function getData (chunkX, chunkY)
23 {
24 const key = chunkKey(chunkX, chunkY);
25 if (!loaded.has(key))
26 { loaded.set(key, cloneChunkData(loadChunk(chunkX, chunkY))); }
27 return loaded.get(key);
28 }
29
30 const sources = [];
31 for (const coord of chebyshevChunks(centerChunkX, centerChunkY, halo + 1))
32 {
33 const data = getData(coord.chunkX, coord.chunkY);
34 sources.push(...collectLightSources(coord.chunkX, coord.chunkY, data));
35 }
36
37 function occlusionAt (tileX, tileY)
38 {
39 const data = getData(tileToChunk(tileX), tileToChunk(tileY));
40 return chunkTileLightOcclusion(data, tileToLocal(tileX), tileToLocal(tileY));
41 }
42
43 for (const coord of affected)
44 {
45 const data = getData(coord.chunkX, coord.chunkY);
46 for (let localY = 0; localY < CHUNK_SIZE; localY++)
47 {
48 for (let localX = 0; localX < CHUNK_SIZE; localX++)
49 {
50 const tileX = coord.chunkX * CHUNK_SIZE + localX;
51 const tileY = coord.chunkY * CHUNK_SIZE + localY;
52 const index = localY * CHUNK_SIZE + localX;
53 let best = 0;
54 for (const source of sources)
55 {
56 const geo = Math.hypot(tileX - source.tileX, tileY - source.tileY);
57 if (geo > source.range)
58 { continue; }
59 const ray = evaluateLightRay(source.tileX, source.tileY, tileX, tileY, occlusionAt);
60 if (!ray.reaches)
61 { continue; }
62 best = Math.max(best, encodeLight(geo + ray.extraDistance, source.range));
63 }
64 data.light[index] = best;
65 }
66 }
67 }
68
69 return affected.map((coord) => ({
70 chunkX: coord.chunkX,
71 chunkY: coord.chunkY,
72 data: loaded.get(chunkKey(coord.chunkX, coord.chunkY))
73 }));
74}
75
76export function defaultLightChunk (groundTypeId)
77{
78 return createEmptyChunkData(groundTypeId);
79}