BlueGit

timfa questward

Files

questward / client / src / render / chunkBake.js

chunkBake.js

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