BlueGit

timfa questward

Files

questward / server / src / world / chunkData.js

chunkData.js

chunkData.js 9.1 KiB Download Raw
1import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2import
3 {
4 BlockType,
5 GroundType,
6 isBlockPassable,
7 blockLightOcclusionForBlock,
8 LightOcclusion,
9 isGroundPassable,
10 isWaterGround,
11 isLavaGround,
12 blockBlocksRangedAttacks,
13 normalizeGround,
14 normalizeBlock
15 } from "../../../shared/definitions/tiles.js";
16import { isDoorTraversable } from "../../../shared/world/doors.js";
17import { tileLightOcclusionAt, bakeChunkOcclusion, ensureChunkOcclusion } from "../../../shared/lighting/chunkOcclusion.js";
18import { collectBlockLightSources, collectGroundLightSources } from "../../../shared/lighting/blockLights.js";
19import
20 {
21 flowerBlockState,
22 flowerColorIdFromBlockState,
23 flowerColorIdForTile
24 } from "../../../shared/definitions/dyes.js";
25import { normalizeSpawnerConfig } from "../../../shared/definitions/mobs.js";
26import { tileIndex } from "./coordinates.js";
27
28export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
29{
30 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
31 const grounds = new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId));
32 const blocks = new Array(tileCount).fill(null);
33 const light = new Array(tileCount).fill(0);
34 const enclosed = new Array(tileCount).fill(0);
35 return {
36 open: false,
37 grounds,
38 blocks,
39 light,
40 enclosed,
41 spawners: []
42 };
43}
44
45export function cloneChunkData (data)
46{
47 return {
48 open: data.open,
49 grounds: data.grounds.map((ground) => normalizeGround(ground)),
50 blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),
51 light: data.light.slice(),
52 enclosed: ensureChunkEnclosed(data).slice(),
53 occlusion: ensureChunkOcclusion(data).slice(),
54 spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)
55 };
56}
57
58export function encodeChunkBlob (data)
59{
60 const normalized = {
61 open: !!data.open,
62 grounds: data.grounds.map((ground) => normalizeGround(ground)),
63 blocks: data.blocks.map((block) => normalizeBlock(block)),
64 light: data.light,
65 enclosed: ensureChunkEnclosed(data),
66 spawners: (data.spawners ?? []).map((entry) => normalizeSpawner(entry)).filter(Boolean)
67 };
68 normalized.occlusion = bakeChunkOcclusion(normalized);
69 return JSON.stringify(normalized);
70}
71
72export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId, chunkX = 0, chunkY = 0)
73{
74 if (!blob)
75 { return createEmptyChunkData(groundTypeId); }
76
77 const parsed = typeof blob === "string" ? JSON.parse(blob) : blob;
78 const fallback = createEmptyChunkData(groundTypeId);
79 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
80 const grounds = Array.isArray(parsed.grounds) ? parsed.grounds.slice(0, tileCount) : fallback.grounds;
81 const blocks = Array.isArray(parsed.blocks) ? parsed.blocks.slice(0, tileCount) : fallback.blocks.slice();
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();
86
87 while (grounds.length < tileCount)
88 { grounds.push(normalizeGround(groundTypeId, groundTypeId)); }
89 while (blocks.length < tileCount)
90 { blocks.push(null); }
91 while (light.length < tileCount)
92 { light.push(0); }
93 while (enclosed.length < tileCount)
94 { enclosed.push(0); }
95
96 const spawners = migrateLegacySpawners(blocks, Array.isArray(parsed.spawners) ? parsed.spawners : [], parsed);
97 const originX = (chunkX | 0) * CHUNK_SIZE;
98 const originY = (chunkY | 0) * CHUNK_SIZE;
99
100 const decoded = {
101 open: !!parsed.open,
102 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
103 blocks: blocks.map((block, index) =>
104 {
105 const normalized = normalizeBlock(block);
106 if (normalized?.typeId === BlockType.spawner)
107 { return null; }
108 if (normalized?.typeId === BlockType.flower && !flowerColorIdFromBlockState(normalized.state))
109 {
110 const localX = index % CHUNK_SIZE;
111 const localY = (index / CHUNK_SIZE) | 0;
112 normalized.state = flowerBlockState(
113 flowerColorIdForTile(originX + localX, originY + localY)
114 );
115 }
116 return normalized;
117 }),
118 light,
119 enclosed,
120 spawners
121 };
122 decoded.occlusion = bakeChunkOcclusion(decoded);
123 return decoded;
124}
125
126export function normalizeSpawner (value)
127{
128 if (!value || !Number.isInteger(value.localX) || !Number.isInteger(value.localY))
129 { return null; }
130 if (value.localX < 0 || value.localY < 0 || value.localX >= CHUNK_SIZE || value.localY >= CHUNK_SIZE)
131 { return null; }
132 const config = value.config && typeof value.config === "object" ? value.config : {};
133 const spawnerId = typeof config.spawnerId === "string" && config.spawnerId
134 ? config.spawnerId
135 : `${value.localX},${value.localY}`;
136 return {
137 localX: value.localX,
138 localY: value.localY,
139 config: normalizeSpawnerConfig(config, spawnerId)
140 };
141}
142
143export function spawnerAt (data, localX, localY)
144{
145 return (data.spawners ?? []).find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
146}
147
148export function setSpawner (data, localX, localY, config)
149{
150 if (!Array.isArray(data.spawners))
151 { data.spawners = []; }
152 const next = normalizeSpawner({ localX, localY, config });
153 data.spawners = data.spawners.filter((entry) => entry.localX !== localX || entry.localY !== localY);
154 if (next)
155 { data.spawners.push(next); }
156 return next;
157}
158
159export function clearSpawner (data, localX, localY)
160{
161 if (!Array.isArray(data.spawners))
162 { return; }
163 data.spawners = data.spawners.filter((entry) => entry.localX !== localX || entry.localY !== localY);
164}
165
166export function getTile (data, localX, localY)
167{
168 const index = tileIndex(localX, localY);
169 const ground = normalizeGround(data.grounds[index]);
170 return {
171 groundTypeId: ground.typeId,
172 groundState: ground.state,
173 block: data.blocks[index],
174 light: data.light[index],
175 enclosed: ensureChunkEnclosed(data)[index] ? 1 : 0,
176 spawner: spawnerAt(data, localX, localY)
177 };
178}
179
180export function setGround (data, localX, localY, groundTypeId, state = null)
181{
182 data.grounds[tileIndex(localX, localY)] = normalizeGround({ typeId: groundTypeId, state });
183}
184
185export function setBlock (data, localX, localY, block)
186{
187 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
188}
189
190export function isChunkTilePassable (data, localX, localY, { canOpenDoors = false, requirementsAllow = true } = {})
191{
192 const index = tileIndex(localX, localY);
193 const ground = normalizeGround(data.grounds[index]);
194 if (!isGroundPassable(ground.typeId))
195 { return false; }
196 const block = data.blocks[index];
197 if (!block)
198 { return true; }
199 if ((block.typeId | 0) === BlockType.door)
200 { return isDoorTraversable(block, { canOpenDoors, requirementsAllow }); }
201 return isBlockPassable(block.typeId, block.state);
202}
203
204/** Light occlusion level for a chunk tile (water stays clear even when impassable). */
205export function chunkTileLightOcclusion (data, localX, localY)
206{
207 return tileLightOcclusionAt(data.grounds, data.blocks, localX, localY);
208}
209
210/** True when light rays are not solid-stopped (partial canopy still clears). */
211export function isChunkTileClearForLight (data, localX, localY)
212{
213 return chunkTileLightOcclusion(data, localX, localY) !== LightOcclusion.solid;
214}
215
216/** True when ranged attacks and spell casts may trace a ray through this tile. */
217export function isChunkTileClearForRangedAttacks (data, localX, localY)
218{
219 const index = tileIndex(localX, localY);
220 const ground = normalizeGround(data.grounds[index]);
221 // Water and lava block walking but not projectiles / spell rays.
222 if (
223 !isGroundPassable(ground.typeId)
224 && !isWaterGround(ground.typeId)
225 && !isLavaGround(ground.typeId)
226 )
227 { return false; }
228 const block = data.blocks[index];
229 return !blockBlocksRangedAttacks(block?.typeId ?? null, block?.state ?? null, block);
230}
231
232export function collectLightSources (chunkX, chunkY, data)
233{
234 return [
235 ...collectBlockLightSources(chunkX, chunkY, data?.blocks),
236 ...collectGroundLightSources(chunkX, chunkY, data?.grounds)
237 ];
238}
239
240function migrateLegacySpawners (blocks, authored, parsedHint)
241{
242 const byKey = new Map();
243 for (const entry of authored)
244 {
245 const normalized = normalizeSpawner(entry);
246 if (normalized)
247 { byKey.set(`${normalized.localX},${normalized.localY}`, normalized); }
248 }
249
250 for (let index = 0; index < blocks.length; index++)
251 {
252 const block = normalizeBlock(blocks[index]);
253 if (block?.typeId !== BlockType.spawner)
254 { continue; }
255 const localX = index % CHUNK_SIZE;
256 const localY = Math.floor(index / CHUNK_SIZE);
257 const key = `${localX},${localY}`;
258 if (!byKey.has(key))
259 {
260 const spawnerId = block.config?.spawnerId
261 ?? (parsedHint?.chunkX != null
262 ? `${parsedHint.chunkX}:${parsedHint.chunkY}:${index}`
263 : key);
264 byKey.set(key, normalizeSpawner({
265 localX,
266 localY,
267 config: { spawnerId, ...(block.config ?? {}) }
268 }));
269 }
270 blocks[index] = null;
271 }
272
273 return [...byKey.values()].filter(Boolean);
274}
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
288export { GroundType, normalizeGround, normalizeBlock };