BlueGit

timfa questward

Files

questward / client / src / render / chunkBake.js

chunkBake.js

chunkBake.js 14.8 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js";
5import {
6 SOFT_TERRAIN_NEIGHBOR_DIRS,
7 softTerrainBlendWeight,
8 softTerrainNeighborSample,
9 mixSoftTerrainPixel
10} from "/shared/render/softTerrain.js";
11import { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js";
12
13/**
14 * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases.
15 * Oversized or animated blocks/grounds are returned for individual sprites.
16 * When `cache` is set, identical ground/row/bloom layouts reuse canvases already in GPU memory.
17 * @param {{
18 * snapshot: object,
19 * catalog: object,
20 * images: object,
21 * preview?: object | null,
22 * season?: string,
23 * softTerrain?: boolean,
24 * resolveGround?: (tileX: number, tileY: number) => object | number | null,
25 * cache?: ReturnType<typeof import("./chunkAtlasCache.js").createChunkAtlasCache>
26 * }} options
27 */
28export function bakeChunkAtlases ({
29 snapshot,
30 catalog,
31 images,
32 preview = null,
33 season = SeasonId.summer,
34 softTerrain = false,
35 resolveGround = null,
36 cache = null
37})
38{
39 const extras = collectChunkSpriteExtras({
40 snapshot,
41 catalog,
42 images,
43 preview,
44 season
45 });
46 const keys = computeChunkAtlasKeys({
47 snapshot,
48 catalog,
49 preview,
50 season,
51 softTerrain,
52 resolveGround
53 });
54 const bakeCtx = {
55 snapshot,
56 catalog,
57 images,
58 preview,
59 season,
60 softTerrain,
61 resolveGround
62 };
63
64 let groundEntry;
65 let blockRowEntries;
66 let bloomEntry;
67
68 if (cache)
69 {
70 groundEntry = cache.acquireGround(keys.groundKey, () => bakeGroundCanvas(bakeCtx));
71 blockRowEntries = keys.blockRowKeys.map((key, row) =>
72 cache.acquireBlockRow(key, () => bakeBlockRowCanvas(bakeCtx, row)));
73 bloomEntry = cache.acquireBloom(keys.bloomKey, () => bakeBloomCanvas(bakeCtx));
74 }
75 else
76 {
77 groundEntry = { canvas: bakeGroundCanvas(bakeCtx) };
78 blockRowEntries = keys.blockRowKeys.map((_key, row) => ({
79 canvas: bakeBlockRowCanvas(bakeCtx, row)
80 }));
81 bloomEntry = { canvas: bakeBloomCanvas(bakeCtx) };
82 }
83
84 return {
85 ground: groundEntry.canvas,
86 blockRows: blockRowEntries.map((entry) => entry.canvas),
87 bloom: bloomEntry.canvas,
88 tallBlocks: extras.tallBlocks,
89 animatedGrounds: extras.animatedGrounds,
90 cacheRefs: cache
91 ? {
92 ground: groundEntry,
93 blockRows: blockRowEntries,
94 bloom: bloomEntry
95 }
96 : null
97 };
98}
99
100export { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js";
101
102export function collectChunkSpriteExtras ({
103 snapshot,
104 catalog,
105 images,
106 preview = null,
107 season = SeasonId.summer
108})
109{
110 const tallBlocks = [];
111 const animatedGrounds = [];
112 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
113 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
114
115 for (let localY = 0; localY < CHUNK_SIZE; localY++)
116 {
117 for (let localX = 0; localX < CHUNK_SIZE; localX++)
118 {
119 const index = localY * CHUNK_SIZE + localX;
120 const tileX = baseTileX + localX;
121 const tileY = baseTileY + localY;
122 const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
123 const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
124
125 const groundName = groundSpriteName(catalog, groundEntry, season);
126 const groundMeta = groundCatalogMeta(catalog, groundEntry);
127 if (groundName && !isBakeable(images[groundName], groundMeta))
128 {
129 animatedGrounds.push({
130 tileX,
131 tileY,
132 sprite: groundName,
133 typeId: normalizeGround(groundEntry).typeId,
134 bloom: groundBloomName(catalog, groundEntry, season)
135 });
136 }
137
138 const blockName = blockSpriteName(catalog, blockEntry, season);
139 if (!blockName)
140 { continue; }
141 const blockMeta = blockCatalogMeta(catalog, blockEntry);
142 if (!isBakeable(images[blockName], blockMeta))
143 {
144 tallBlocks.push({
145 tileX,
146 tileY,
147 sprite: blockName,
148 bloom: blockBloomName(catalog, blockEntry, season)
149 });
150 }
151 }
152 }
153
154 return { tallBlocks, animatedGrounds };
155}
156
157function bakeGroundCanvas ({
158 snapshot,
159 catalog,
160 images,
161 preview,
162 season,
163 softTerrain,
164 resolveGround
165})
166{
167 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
168 const height = CHUNK_SIZE * SPRITE_SIZE_PX;
169 const ground = makeCanvas(width, height);
170 const groundCtx = ground.getContext("2d", { willReadFrequently: softTerrain });
171 groundCtx.imageSmoothingEnabled = false;
172 groundCtx.clearRect(0, 0, width, height);
173 const pixelCache = softTerrain ? new Map() : null;
174 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
175 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
176
177 for (let localY = 0; localY < CHUNK_SIZE; localY++)
178 {
179 for (let localX = 0; localX < CHUNK_SIZE; localX++)
180 {
181 const tileX = baseTileX + localX;
182 const tileY = baseTileY + localY;
183 const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
184 const dx = localX * SPRITE_SIZE_PX;
185 const dy = localY * SPRITE_SIZE_PX;
186 const groundName = groundSpriteName(catalog, groundEntry, season);
187 const groundMeta = groundCatalogMeta(catalog, groundEntry);
188 if (!isBakeable(images[groundName], groundMeta))
189 { continue; }
190 const blendable = softTerrain && isGroundBlendable(groundEntry);
191 if (blendable)
192 {
193 blitSoftGround(
194 groundCtx,
195 images,
196 catalog,
197 groundEntry,
198 groundName,
199 dx,
200 dy,
201 tileX,
202 tileY,
203 season,
204 resolveGround,
205 pixelCache
206 );
207 }
208 else
209 { blit(groundCtx, images[groundName], dx, dy); }
210 }
211 }
212 return ground;
213}
214
215function bakeBlockRowCanvas ({
216 snapshot,
217 catalog,
218 images,
219 preview,
220 season
221}, row)
222{
223 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
224 const canvas = makeCanvas(width, SPRITE_SIZE_PX);
225 const ctx = canvas.getContext("2d");
226 ctx.imageSmoothingEnabled = false;
227 ctx.clearRect(0, 0, width, SPRITE_SIZE_PX);
228 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
229 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
230
231 for (let localX = 0; localX < CHUNK_SIZE; localX++)
232 {
233 const index = row * CHUNK_SIZE + localX;
234 const tileX = baseTileX + localX;
235 const tileY = baseTileY + row;
236 const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
237 const blockName = blockSpriteName(catalog, blockEntry, season);
238 if (!blockName)
239 { continue; }
240 const blockMeta = blockCatalogMeta(catalog, blockEntry);
241 if (!isBakeable(images[blockName], blockMeta))
242 { continue; }
243 blit(ctx, images[blockName], localX * SPRITE_SIZE_PX, 0);
244 }
245 return canvas;
246}
247
248function bakeBloomCanvas ({
249 snapshot,
250 catalog,
251 images,
252 preview,
253 season
254})
255{
256 const width = CHUNK_SIZE * SPRITE_SIZE_PX;
257 const bloom = makeCanvas(width, width);
258 const bloomCtx = bloom.getContext("2d");
259 bloomCtx.imageSmoothingEnabled = false;
260 bloomCtx.clearRect(0, 0, width, width);
261 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
262 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
263
264 for (let localY = 0; localY < CHUNK_SIZE; localY++)
265 {
266 for (let localX = 0; localX < CHUNK_SIZE; localX++)
267 {
268 const index = localY * CHUNK_SIZE + localX;
269 const tileX = baseTileX + localX;
270 const tileY = baseTileY + localY;
271 const dx = localX * SPRITE_SIZE_PX;
272 const dy = localY * SPRITE_SIZE_PX;
273 const groundEntry = tileGroundEntry(snapshot, preview, localX, localY);
274 const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index);
275
276 const groundBloom = groundBloomName(catalog, groundEntry, season);
277 if (groundBloom)
278 { blit(bloomCtx, images[groundBloom], dx, dy); }
279
280 const blockName = blockSpriteName(catalog, blockEntry, season);
281 if (!blockName)
282 { continue; }
283 const blockMeta = blockCatalogMeta(catalog, blockEntry);
284 if (!isBakeable(images[blockName], blockMeta))
285 { continue; }
286 const blockBloom = blockBloomName(catalog, blockEntry, season);
287 if (blockBloom)
288 { blit(bloomCtx, images[blockBloom], dx, dy); }
289 }
290 }
291 return bloom;
292}
293
294export function isBakeable (sprite, meta = null)
295{
296 if (!sprite?.g_image)
297 { return false; }
298 if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX)
299 { return false; }
300 const frames = Number(sprite.subImages) || Number(sprite.subImgTotal) || (meta?.frames ?? 1);
301 const speed = sprite._animationSpeed ?? meta?.animationSpeed ?? 0;
302 if (frames > 1)
303 { return false; }
304 if (speed > 0)
305 { return false; }
306 return true;
307}
308
309function tileGroundEntry (snapshot, preview, localX, localY)
310{
311 const index = localY * CHUNK_SIZE + localX;
312 const baseTileX = snapshot.chunkX * CHUNK_SIZE;
313 const baseTileY = snapshot.chunkY * CHUNK_SIZE;
314 const tileX = baseTileX + localX;
315 const tileY = baseTileY + localY;
316 let groundEntry = snapshot.grounds[index];
317 if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.ground !== undefined)
318 { groundEntry = preview.ground; }
319 return groundEntry;
320}
321
322function tileBlockEntry (snapshot, preview, tileX, tileY, index)
323{
324 let blockEntry = snapshot.blocks[index];
325 if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.block !== undefined)
326 { blockEntry = preview.block; }
327 return blockEntry;
328}
329
330function makeCanvas (width, height)
331{
332 const canvas = document.createElement("canvas");
333 canvas.width = width;
334 canvas.height = height;
335 return canvas;
336}
337
338function blit (ctx, sprite, dx, dy)
339{
340 if (!sprite?.g_image)
341 { return; }
342 const sub = sprite.getSubImage(0);
343 ctx.drawImage(
344 sprite.g_image,
345 sub.sx,
346 sub.sy,
347 sub.sw,
348 sub.sh,
349 dx,
350 dy,
351 SPRITE_SIZE_PX,
352 SPRITE_SIZE_PX
353 );
354}
355
356function isGroundBlendable (ground)
357{
358 const entry = normalizeGround(ground);
359 return !!GROUND_DEFINITIONS[entry.typeId]?.blendable;
360}
361
362function groundVisualKey (catalog, ground, season)
363{
364 const entry = normalizeGround(ground);
365 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
366 const states = catalog.grounds?.[def.key]?.states ?? [];
367 const state = resolveSeasonalVisualState(states, entry.state, season);
368 return `${entry.typeId}:${state ?? ""}`;
369}
370
371function blitSoftGround (
372 ctx,
373 images,
374 catalog,
375 groundEntry,
376 groundName,
377 dx,
378 dy,
379 tileX,
380 tileY,
381 season,
382 resolveGround,
383 pixelCache
384)
385{
386 const selfPixels = spritePixels(images[groundName], pixelCache);
387 if (!selfPixels)
388 {
389 blit(ctx, images[groundName], dx, dy);
390 return;
391 }
392
393 const selfKey = groundVisualKey(catalog, groundEntry, season);
394 const neighborSprites = [];
395 for (const { ndx, ndy } of SOFT_TERRAIN_NEIGHBOR_DIRS)
396 {
397 const neighborGround = resolveNeighborGround(
398 tileX + ndx,
399 tileY + ndy,
400 resolveGround
401 );
402 if (neighborGround == null)
403 { continue; }
404 if (groundVisualKey(catalog, neighborGround, season) === selfKey)
405 { continue; }
406 const neighborName = groundSpriteName(catalog, neighborGround, season);
407 const pixels = spritePixels(images[neighborName], pixelCache);
408 if (!pixels)
409 { continue; }
410 neighborSprites.push({
411 ndx,
412 ndy,
413 pixels,
414 neighborBlendable: isGroundBlendable(neighborGround)
415 });
416 }
417
418 if (!neighborSprites.length)
419 {
420 blit(ctx, images[groundName], dx, dy);
421 return;
422 }
423
424 const out = ctx.createImageData(SPRITE_SIZE_PX, SPRITE_SIZE_PX);
425 const dst = out.data;
426 for (let py = 0; py < SPRITE_SIZE_PX; py++)
427 {
428 for (let px = 0; px < SPRITE_SIZE_PX; px++)
429 {
430 const self = readPixel(selfPixels, px, py);
431 const contribs = [];
432 for (const neighbor of neighborSprites)
433 {
434 const weight = softTerrainBlendWeight(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX, {
435 neighborBlendable: neighbor.neighborBlendable
436 });
437 if (weight <= 0)
438 { continue; }
439 const sample = softTerrainNeighborSample(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX);
440 contribs.push({
441 weight,
442 color: readPixel(neighbor.pixels, sample.sx, sample.sy)
443 });
444 }
445 const mixed = mixSoftTerrainPixel(self, contribs);
446 const i = (py * SPRITE_SIZE_PX + px) * 4;
447 dst[i] = mixed.r;
448 dst[i + 1] = mixed.g;
449 dst[i + 2] = mixed.b;
450 dst[i + 3] = mixed.a;
451 }
452 }
453 ctx.putImageData(out, dx, dy);
454}
455
456function resolveNeighborGround (tileX, tileY, resolveGround)
457{
458 if (typeof resolveGround === "function")
459 { return resolveGround(tileX, tileY); }
460 return null;
461}
462
463function spritePixels (sprite, cache)
464{
465 if (!sprite?.g_image)
466 { return null; }
467 const key = sprite.g_image?.src ?? sprite;
468 if (cache?.has(key))
469 { return cache.get(key); }
470 const sub = sprite.getSubImage(0);
471 const canvas = makeCanvas(SPRITE_SIZE_PX, SPRITE_SIZE_PX);
472 const ctx = canvas.getContext("2d", { willReadFrequently: true });
473 ctx.imageSmoothingEnabled = false;
474 ctx.drawImage(
475 sprite.g_image,
476 sub.sx,
477 sub.sy,
478 sub.sw,
479 sub.sh,
480 0,
481 0,
482 SPRITE_SIZE_PX,
483 SPRITE_SIZE_PX
484 );
485 const data = ctx.getImageData(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX);
486 cache?.set(key, data);
487 return data;
488}
489
490function readPixel (imageData, x, y)
491{
492 const i = (y * imageData.width + x) * 4;
493 const d = imageData.data;
494 return { r: d[i], g: d[i + 1], b: d[i + 2], a: d[i + 3] };
495}
496
497function groundSpriteName (catalog, ground, season = SeasonId.summer)
498{
499 const entry = normalizeGround(ground);
500 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
501 const states = catalog.grounds?.[def.key]?.states ?? [];
502 const state = resolveSeasonalVisualState(states, entry.state, season);
503 return spriteImageName("ground", def.key, state);
504}
505
506function blockSpriteName (catalog, block, season = SeasonId.summer)
507{
508 const entry = normalizeBlock(block);
509 if (!entry)
510 { return null; }
511 const def = BLOCK_DEFINITIONS[entry.typeId];
512 if (!def || def.editorHidden)
513 { return null; }
514 const states = catalog.blocks?.[def.key]?.states ?? [];
515 const state = resolveSeasonalVisualState(states, entry.state, season);
516 return spriteImageName("block", def.key, state);
517}
518
519function groundBloomName (catalog, ground, season = SeasonId.summer)
520{
521 const entry = normalizeGround(ground);
522 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
523 const type = catalog.grounds?.[def.key];
524 const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);
525 if (!state || !type?.blooms?.[state])
526 { return null; }
527 return bloomImageName("ground", def.key, state);
528}
529
530function blockBloomName (catalog, block, season = SeasonId.summer)
531{
532 const entry = normalizeBlock(block);
533 if (!entry)
534 { return null; }
535 const def = BLOCK_DEFINITIONS[entry.typeId];
536 if (!def)
537 { return null; }
538 const type = catalog.blocks?.[def.key];
539 const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season);
540 if (!state || !type?.blooms?.[state])
541 { return null; }
542 return bloomImageName("block", def.key, state);
543}
544
545function blockCatalogMeta (catalog, block)
546{
547 const entry = normalizeBlock(block);
548 if (!entry)
549 { return null; }
550 const def = BLOCK_DEFINITIONS[entry.typeId];
551 if (!def)
552 { return null; }
553 return catalog.blocks?.[def.key] ?? null;
554}
555
556function groundCatalogMeta (catalog, ground)
557{
558 const entry = normalizeGround(ground);
559 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
560 return catalog.grounds?.[def.key] ?? {
561 frames: def.frames,
562 animationSpeed: def.animationSpeed
563 };
564}