BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 31.3 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { itemSpriteName } from "/shared/definitions/items.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5import {
6 bakeChunkAtlases,
7 frameworkImageFromCanvas,
8 invalidateCanvasTexture
9} from "./chunkBake.js";
10
11const LAYER_GROUND = 0;
12const LAYER_EDGE = 900000;
13const SORT_BLOCK = 1;
14const SORT_SHADE = 2;
15const SORT_ENTITY = 3;
16const SORT_SPRITE_SHADE = 4;
17const RENDER_LAYER_BLOOM = "bloom";
18
19const SPRITE_SHADE_FRAG = [
20 "precision mediump float;",
21 "varying vec2 v_texCoord;",
22 "uniform sampler2D u_texture;",
23 "uniform float u_alpha;",
24 "void main() {",
25 " vec4 color = texture2D(u_texture, v_texCoord);",
26 " if (color.a <= 0.0) { discard; }",
27 " gl_FragColor = vec4(0.0, 0.0, 0.0, color.a * u_alpha);",
28 "}"
29].join("\n");
30
31let spriteShadeShader = null;
32
33function getSpriteShadeShader ()
34{
35 if (!spriteShadeShader)
36 { spriteShadeShader = Shader.fragment(SPRITE_SHADE_FRAG); }
37 return spriteShadeShader;
38}
39
40export class WorldView
41{
42 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
43 {
44 this.game = game;
45 this.scene = scene;
46 this.catalog = catalog;
47 this.preview = null;
48 this.zoom = 2;
49 this.chunks = new Map();
50 this.bakedChunks = new Map();
51 this.tiles = new Map();
52 this.entities = new Map();
53 this.groundItems = new Map();
54 this.edges = new Map();
55 this.localEntityId = null;
56 this.settings = { ...DEFAULT_WORLD_SETTINGS };
57 this.worldHour = 12;
58 this.nightPreview = null;
59 this.followPlayer = true;
60 this.dynamicLights = [];
61 this.swipes = [];
62 this.#syncBloomLayer();
63 }
64
65 setSettings (settings)
66 {
67 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
68 this.#syncBloomLayer();
69 }
70
71 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
72 {
73 this.localEntityId = entityId;
74 this.#upsertEntity({
75 entityId,
76 characterId,
77 tileX,
78 tileY,
79 gait,
80 sex,
81 firstName,
82 lastName,
83 layers: layers ?? undefined
84 });
85 }
86
87 applySnapshot (snapshot)
88 {
89 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
90 this.chunks.set(key, snapshot);
91 this.#rebuildChunk(snapshot);
92 this.#redrawPreview();
93 for (const entity of snapshot.entities ?? [])
94 { this.#upsertEntity(entity); }
95 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
96 for (const [id, item] of [...this.groundItems.entries()])
97 {
98 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
99 { this.despawnGroundItem(id); }
100 }
101 for (const item of snapshot.groundItems ?? [])
102 { this.upsertGroundItem(item); }
103 this.#rebuildAllEdges();
104 }
105
106 removeChunk (chunkX, chunkY)
107 {
108 const key = `${chunkX},${chunkY}`;
109 this.chunks.delete(key);
110 this.#destroyBakedChunk(key);
111 this.#destroyEdges(key);
112 for (const [tileKey, objects] of [...this.tiles.entries()])
113 {
114 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
115 {
116 objects.block?.destroy();
117 objects.blockBloom?.destroy();
118 objects.spriteShade?.destroy();
119 objects.shade?.destroy();
120 this.tiles.delete(tileKey);
121 }
122 }
123 for (const [id, item] of [...this.groundItems.entries()])
124 {
125 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
126 { this.despawnGroundItem(id); }
127 }
128 this.#rebuildAllEdges();
129 }
130
131 setChunkOpen (chunkX, chunkY, open)
132 {
133 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
134 if (!snapshot)
135 { return; }
136 snapshot.open = !!open;
137 this.#rebuildAllEdges();
138 }
139
140 spawnEntity (payload)
141 {
142 this.#upsertEntity(payload);
143 }
144
145 moveEntity (payload)
146 {
147 const existing = this.entities.get(payload.entityId);
148 if (!existing)
149 {
150 this.#upsertEntity(payload);
151 return;
152 }
153 const size = this.tileSize();
154 existing.fromX = existing.visualX;
155 existing.fromY = existing.visualY;
156 existing.tileX = payload.tileX;
157 existing.tileY = payload.tileY;
158 existing.gait = payload.gait;
159 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
160 if (payload.worldX != null && payload.worldY != null)
161 {
162 existing.worldX = payload.worldX;
163 existing.worldY = payload.worldY;
164 existing.targetX = payload.worldX * size;
165 existing.targetY = payload.worldY * size;
166 }
167 else
168 {
169 const pivot = tilePivot(payload.tileX, payload.tileY, size);
170 existing.targetX = pivot.x;
171 existing.targetY = pivot.y;
172 }
173 existing.lerpStarted = performance.now();
174 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
175 }
176
177 despawnEntity (entityId)
178 {
179 const existing = this.entities.get(entityId);
180 if (!existing)
181 { return; }
182 existing.object?.destroy();
183 existing.spriteShade?.destroy();
184 for (const shade of existing.overlayShades ?? [])
185 { shade.destroy(); }
186 for (const overlay of existing.overlays ?? [])
187 { overlay.destroy(); }
188 for (const overlay of existing.bloomOverlays ?? [])
189 { overlay.destroy(); }
190 this.entities.delete(entityId);
191 }
192
193 setAppearance (payload)
194 {
195 const existing = this.entities.get(payload.entityId);
196 if (!existing)
197 { return; }
198 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
199 this.#placeEntity(existing);
200 }
201
202 upsertGroundItem (payload)
203 {
204 const size = this.tileSize();
205 const pivot = tilePivot(payload.tileX, payload.tileY, size);
206 let item = this.groundItems.get(payload.groundItemId);
207 if (!item)
208 {
209 const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
210 this.scene.addObject(object);
211 item = { object };
212 this.groundItems.set(payload.groundItemId, item);
213 }
214 item.groundItemId = payload.groundItemId;
215 item.tileX = payload.tileX;
216 item.tileY = payload.tileY;
217 item.itemId = payload.itemId;
218 item.quantity = payload.quantity;
219 item.displayName = payload.displayName;
220 item.sprite = payload.sprite;
221 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
222 }
223
224 despawnGroundItem (groundItemId)
225 {
226 const item = this.groundItems.get(groundItemId);
227 if (!item)
228 { return; }
229 item.object?.destroy();
230 this.groundItems.delete(groundItemId);
231 }
232
233 groundItemAtTile (tileX, tileY)
234 {
235 for (const item of this.groundItems.values())
236 {
237 if (item.tileX === tileX && item.tileY === tileY)
238 { return item; }
239 }
240 return null;
241 }
242
243 setZoom (zoom, limits = { min: 1, max: 4 })
244 {
245 const min = limits.min ?? 1;
246 const max = limits.max ?? 4;
247 this.zoom = Math.min(max, Math.max(min, zoom));
248 for (const snapshot of this.chunks.values())
249 {
250 this.#layoutBakedChunk(snapshot);
251 for (let localY = 0; localY < CHUNK_SIZE; localY++)
252 {
253 for (let localX = 0; localX < CHUNK_SIZE; localX++)
254 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
255 }
256 }
257 const size = this.tileSize();
258 for (const entity of this.entities.values())
259 {
260 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
261 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
262 entity.fromX = entity.visualX;
263 entity.fromY = entity.visualY;
264 entity.targetX = entity.visualX;
265 entity.targetY = entity.visualY;
266 entity.lerpStarted = null;
267 this.#placeEntity(entity);
268 }
269 for (const item of this.groundItems.values())
270 {
271 const pivot = tilePivot(item.tileX, item.tileY, size);
272 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
273 }
274 this.#rebuildAllEdges();
275 this.#redrawPreview();
276 }
277
278 tileSize ()
279 {
280 return SPRITE_SIZE_PX * this.zoom;
281 }
282
283 screenToTile (mouseX, mouseY)
284 {
285 const size = this.tileSize();
286 const worldX = mouseX - this.scene.cameraPosition.x;
287 const worldY = mouseY - this.scene.cameraPosition.y;
288 return {
289 tileX: Math.floor(worldX / size),
290 tileY: Math.floor(worldY / size)
291 };
292 }
293
294 entityAtScreen (mouseX, mouseY)
295 {
296 let best = null;
297 let bestLayer = -Infinity;
298 for (const entity of this.entities.values())
299 {
300 const box = this.#entityScreenBox(entity);
301 if (!box)
302 { continue; }
303 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
304 {
305 const layer = entity.object?.layer ?? 0;
306 if (layer >= bestLayer)
307 {
308 best = entity;
309 bestLayer = layer;
310 }
311 }
312 }
313 return best;
314 }
315
316 nametagAnchor (entity)
317 {
318 const box = this.#entityScreenBox(entity);
319 if (!box)
320 { return null; }
321 return { x: (box.left + box.right) / 2, y: box.top };
322 }
323
324 #entityScreenBox (entity)
325 {
326 const object = entity?.object;
327 if (!object)
328 { return null; }
329 const size = object.transform.size;
330 const x = object.transform.position.x + this.scene.cameraPosition.x;
331 const y = object.transform.position.y + this.scene.cameraPosition.y;
332 return {
333 left: x - size.x / 2,
334 right: x + size.x / 2,
335 top: y - size.y / 2,
336 bottom: y + size.y / 2
337 };
338 }
339
340 update (deltaTime)
341 {
342 const now = performance.now();
343 const size = this.tileSize();
344 for (const entity of this.entities.values())
345 {
346 const target = entity.targetX != null && entity.targetY != null
347 ? { x: entity.targetX, y: entity.targetY }
348 : tilePivot(entity.tileX, entity.tileY, size);
349 if (entity.lerpStarted != null)
350 {
351 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
352 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
353 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
354 if (t >= 1)
355 { entity.lerpStarted = null; }
356 }
357 else
358 {
359 entity.visualX = target.x;
360 entity.visualY = target.y;
361 }
362 this.#placeEntity(entity);
363 }
364
365 this.#updateSwipes(now);
366 this.#centerCamera();
367 this.#updateShade(deltaTime);
368 }
369
370 spawnCombatSwing (payload)
371 {
372 const attacker = this.entities.get(payload.attackerId);
373 const target = this.entities.get(payload.targetId);
374 if (!attacker || !target)
375 { return; }
376 const midX = (attacker.visualX + target.visualX) / 2;
377 const midY = (attacker.visualY + target.visualY) / 2;
378 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
379 const spriteName = "fx:melee-swipe:melee-swipe";
380 const object = new GameObject(midX, midY, this.game.images[spriteName], SORT_ENTITY + 1);
381 if (object.transform)
382 { object.transform.rotation = angle; }
383 this.scene.addObject(object);
384 this.swipes.push({ object, until: performance.now() + 500 });
385 this.addDynamicLight({
386 worldX: (attacker.tileX + target.tileX) / 2 + 0.5,
387 worldY: (attacker.tileY + target.tileY) / 2 + 0.5,
388 radiusTiles: 2.5,
389 intensity: 0.55,
390 durationMs: 220
391 });
392 }
393
394 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
395 {
396 this.dynamicLights.push({
397 worldX,
398 worldY,
399 radiusTiles,
400 intensity,
401 until: performance.now() + durationMs
402 });
403 }
404
405 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
406 {
407 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
408 if (!snapshot)
409 { return; }
410 const index = localY * CHUNK_SIZE + localX;
411 if (ground !== undefined)
412 { snapshot.grounds[index] = ground; }
413 if (block !== undefined)
414 { snapshot.blocks[index] = block; }
415 if (light !== undefined)
416 { snapshot.light[index] = light; }
417 this.#rebuildChunk(snapshot);
418 }
419
420 setTilePreview (tileX, tileY, override)
421 {
422 const previous = this.preview;
423 this.preview = { tileX, tileY, ...override };
424 const chunkX = Math.floor(tileX / CHUNK_SIZE);
425 const chunkY = Math.floor(tileY / CHUNK_SIZE);
426 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
427 if (snapshot)
428 { this.#rebuildChunk(snapshot); }
429 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
430 {
431 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
432 if (prevSnapshot && prevSnapshot !== snapshot)
433 { this.#rebuildChunk(prevSnapshot); }
434 }
435 }
436
437 clearTilePreview ()
438 {
439 const previous = this.preview;
440 this.preview = null;
441 if (previous)
442 {
443 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
444 if (snapshot)
445 { this.#rebuildChunk(snapshot); }
446 }
447 }
448
449 #lerpMs (gait)
450 {
451 const walk = this.settings.walkTilesPerSecond || 2;
452 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
453 return seconds * 1000;
454 }
455
456 #centerCamera ()
457 {
458 if (!this.followPlayer)
459 { return; }
460 const local = this.entities.get(this.localEntityId);
461 if (!local)
462 { return; }
463 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
464 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
465 }
466
467 #upsertEntity (payload)
468 {
469 const size = this.tileSize();
470 const pivot = tilePivot(payload.tileX, payload.tileY, size);
471 let entity = this.entities.get(payload.entityId);
472 if (!entity)
473 {
474 const spriteName = payload.layers?.[0]?.sprite
475 ?? payload.sprite
476 ?? bodySpriteName(payload.sex);
477 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
478 this.scene.addObject(object);
479 this.#startIdleAnimation(object);
480 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
481 this.entities.set(payload.entityId, entity);
482 }
483 entity.entityId = payload.entityId;
484 entity.tileX = payload.tileX;
485 entity.tileY = payload.tileY;
486 entity.gait = payload.gait;
487 entity.sex = payload.sex ?? entity.sex;
488 entity.characterId = payload.characterId ?? entity.characterId ?? null;
489 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
490 entity.hostile = !!payload.hostile;
491 entity.talkable = !!payload.talkable;
492 entity.untargetable = !!payload.untargetable;
493 entity.freeFlight = !!payload.freeFlight;
494 if (payload.firstName)
495 { entity.firstName = payload.firstName; }
496 if (payload.lastName)
497 { entity.lastName = payload.lastName; }
498 entity.firstName = entity.firstName ?? "";
499 entity.lastName = entity.lastName ?? "";
500 if (payload.worldX != null && payload.worldY != null)
501 {
502 entity.worldX = payload.worldX;
503 entity.worldY = payload.worldY;
504 entity.visualX = payload.worldX * size;
505 entity.visualY = payload.worldY * size;
506 entity.targetX = entity.visualX;
507 entity.targetY = entity.visualY;
508 }
509 else
510 {
511 entity.visualX = pivot.x;
512 entity.visualY = pivot.y;
513 entity.targetX = pivot.x;
514 entity.targetY = pivot.y;
515 }
516 entity.fromX = entity.visualX;
517 entity.fromY = entity.visualY;
518 if (payload.layers)
519 { this.#applyLayers(entity, payload.layers); }
520 this.#placeEntity(entity);
521 }
522
523 #applyLayers (entity, layers)
524 {
525 const base = layers[0]?.sprite
526 ?? bodySpriteName(entity.sex);
527 if (this.game.images[base])
528 {
529 entity.object.renderer.sprite = this.game.images[base];
530 this.#startIdleAnimation(entity.object);
531 }
532 for (const overlay of entity.overlays ?? [])
533 { overlay.destroy(); }
534 for (const overlay of entity.bloomOverlays ?? [])
535 { overlay.destroy(); }
536 entity.overlays = [];
537 entity.bloomOverlays = [];
538 for (const layer of layers.slice(1))
539 {
540 const image = this.game.images[layer.sprite];
541 if (!image)
542 { continue; }
543 const object = new GameObject(0, 0, image, SORT_ENTITY);
544 this.scene.addObject(object);
545 entity.overlays.push(object);
546 const bloomName = bloomCompanionName(layer.sprite);
547 const bloomImage = this.game.images[bloomName];
548 if (!bloomImage)
549 { continue; }
550 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
551 bloom.renderer.layer = RENDER_LAYER_BLOOM;
552 this.scene.addObject(bloom);
553 entity.bloomOverlays.push(bloom);
554 }
555 }
556
557 #placeEntity (entity)
558 {
559 this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
560 for (const overlay of entity.overlays ?? [])
561 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
562 for (const overlay of entity.bloomOverlays ?? [])
563 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
564 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);
565 const nextOverlayShades = [];
566 for (let index = 0; index < (entity.overlays ?? []).length; index++)
567 {
568 nextOverlayShades.push(this.#placeSpriteShade(
569 entity.overlayShades?.[index] ?? null,
570 entity.overlays[index],
571 entity.visualX,
572 entity.visualY + 0.001
573 ));
574 }
575 for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
576 { entity.overlayShades[index]?.destroy(); }
577 entity.overlayShades = nextOverlayShades;
578 }
579
580 #rebuildChunk (snapshot)
581 {
582 this.#bakeAndPlaceChunk(snapshot);
583 const tall = new Set(
584 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
585 .map((entry) => `${entry.tileX},${entry.tileY}`)
586 );
587 for (let localY = 0; localY < CHUNK_SIZE; localY++)
588 {
589 for (let localX = 0; localX < CHUNK_SIZE; localX++)
590 {
591 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
592 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
593 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
594 }
595 }
596 }
597
598 #redrawPreview ()
599 {
600 if (!this.preview)
601 { return; }
602 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
603 if (snapshot)
604 { this.#rebuildChunk(snapshot); }
605 }
606
607 #bakeAndPlaceChunk (snapshot)
608 {
609 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
610 const atlases = bakeChunkAtlases({
611 snapshot,
612 catalog: this.catalog,
613 images: this.game.images,
614 preview: this.preview
615 });
616 let baked = this.bakedChunks.get(key);
617 if (!baked)
618 {
619 baked = {
620 groundCanvas: atlases.ground,
621 blockCanvases: atlases.blockRows,
622 bloomCanvas: atlases.bloom,
623 groundImage: frameworkImageFromCanvas(atlases.ground),
624 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
625 bloomImage: frameworkImageFromCanvas(atlases.bloom),
626 groundObject: null,
627 blockObjects: [],
628 bloomObject: null,
629 tallBlocks: atlases.tallBlocks
630 };
631 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
632 this.scene.addObject(baked.groundObject);
633 for (let row = 0; row < CHUNK_SIZE; row++)
634 {
635 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
636 this.scene.addObject(object);
637 baked.blockObjects.push(object);
638 }
639 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
640 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
641 this.scene.addObject(baked.bloomObject);
642 this.bakedChunks.set(key, baked);
643 }
644 else
645 {
646 copyCanvas(atlases.ground, baked.groundCanvas);
647 for (let row = 0; row < CHUNK_SIZE; row++)
648 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
649 copyCanvas(atlases.bloom, baked.bloomCanvas);
650 invalidateCanvasTexture(this.scene, baked.groundCanvas);
651 for (const canvas of baked.blockCanvases)
652 { invalidateCanvasTexture(this.scene, canvas); }
653 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
654 baked.tallBlocks = atlases.tallBlocks;
655 }
656 this.#layoutBakedChunk(snapshot);
657 }
658
659 #layoutBakedChunk (snapshot)
660 {
661 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
662 const baked = this.bakedChunks.get(key);
663 if (!baked)
664 { return; }
665 const size = this.tileSize();
666 const left = snapshot.chunkX * CHUNK_SIZE * size;
667 const top = snapshot.chunkY * CHUNK_SIZE * size;
668 const chunkPx = CHUNK_SIZE * size;
669 baked.groundObject.transform.position.x = left + chunkPx / 2;
670 baked.groundObject.transform.position.y = top + chunkPx / 2;
671 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
672 baked.groundObject.layer = LAYER_GROUND;
673
674 for (let row = 0; row < CHUNK_SIZE; row++)
675 {
676 const object = baked.blockObjects[row];
677 const rowY = top + row * size + size / 2;
678 object.transform.position.x = left + chunkPx / 2;
679 object.transform.position.y = rowY;
680 object.transform.size = new vector(chunkPx, size);
681 object.layer = ySortLayer(rowY, SORT_BLOCK);
682 }
683
684 baked.bloomObject.transform.position.x = left + chunkPx / 2;
685 baked.bloomObject.transform.position.y = top + chunkPx / 2;
686 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
687 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
688 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
689 this.#markSortDirty();
690 setNearestFilter(this.scene, baked.groundCanvas);
691 for (const canvas of baked.blockCanvases)
692 { setNearestFilter(this.scene, canvas); }
693 setNearestFilter(this.scene, baked.bloomCanvas);
694 }
695
696 #destroyBakedChunk (key)
697 {
698 const baked = this.bakedChunks.get(key);
699 if (!baked)
700 { return; }
701 baked.groundObject?.destroy();
702 for (const object of baked.blockObjects ?? [])
703 { object.destroy(); }
704 baked.bloomObject?.destroy();
705 invalidateCanvasTexture(this.scene, baked.groundCanvas);
706 for (const canvas of baked.blockCanvases ?? [])
707 { invalidateCanvasTexture(this.scene, canvas); }
708 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
709 this.bakedChunks.delete(key);
710 }
711
712 #drawTile (tileX, tileY, forceTall = null)
713 {
714 const chunkX = Math.floor(tileX / CHUNK_SIZE);
715 const chunkY = Math.floor(tileY / CHUNK_SIZE);
716 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
717 if (!snapshot)
718 { return; }
719 const localX = tileX - chunkX * CHUNK_SIZE;
720 const localY = tileY - chunkY * CHUNK_SIZE;
721 const index = localY * CHUNK_SIZE + localX;
722 const key = `${tileX},${tileY}`;
723 let objects = this.tiles.get(key);
724 if (!objects)
725 {
726 objects = { chunkX, chunkY, tileX, tileY };
727 this.tiles.set(key, objects);
728 }
729 objects.tileX = tileX;
730 objects.tileY = tileY;
731 objects.chunkX = chunkX;
732 objects.chunkY = chunkY;
733
734 const size = this.tileSize();
735 const pivot = tilePivot(tileX, tileY, size);
736 objects.light = snapshot.light[index] ?? 0;
737 const previousShade = objects.shade;
738 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE));
739 if (objects.shade && objects.shade !== previousShade)
740 { objects.shade.renderer.alpha = 0; }
741
742 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
743 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
744 const isTall = forceTall === true || !!tallEntry;
745 if (isTall && tallEntry)
746 {
747 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
748 if (objects.block)
749 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); }
750 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
751 objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y);
752 }
753 else
754 {
755 if (objects.block)
756 {
757 objects.block.destroy();
758 objects.block = null;
759 }
760 if (objects.blockBloom)
761 {
762 objects.blockBloom.destroy();
763 objects.blockBloom = null;
764 }
765 if (objects.spriteShade)
766 {
767 objects.spriteShade.destroy();
768 objects.spriteShade = null;
769 }
770 }
771 }
772
773 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
774 {
775 if (!name)
776 {
777 existing?.destroy();
778 return null;
779 }
780 const object = this.#ensureSprite(existing, name, sortOrder);
781 if (!object)
782 { return null; }
783 object.renderer.layer = RENDER_LAYER_BLOOM;
784 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
785 return object;
786 }
787
788 #placeSpriteShade (existing, targetObject, pivotX, pivotY)
789 {
790 if (!targetObject?.renderer?.sprite)
791 {
792 existing?.destroy();
793 return null;
794 }
795 const sprite = targetObject.renderer.sprite;
796 if (!existing || existing.renderer.sprite !== sprite)
797 {
798 existing?.destroy();
799 existing = new GameObject(0, 0, sprite, SORT_SPRITE_SHADE);
800 this.scene.addObject(existing);
801 }
802 existing.renderer.sprite = sprite;
803 existing.renderer.shader = getSpriteShadeShader();
804 existing.renderer.subImage = targetObject.renderer.subImage || 0;
805 existing.renderer.mirrorX = !!targetObject.renderer.mirrorX;
806 existing.renderer.mirrorY = !!targetObject.renderer.mirrorY;
807 const zoom = this.zoom;
808 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
809 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
810 existing.transform.position.x = center.x;
811 existing.transform.position.y = center.y;
812 existing.transform.size = new vector(draw.w, draw.h);
813 existing.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);
814 this.#markSortDirty();
815 return existing;
816 }
817
818 #tileFill (existing, name, x, y, layer)
819 {
820 existing = this.#ensureSprite(existing, name, layer);
821 if (!existing)
822 { return null; }
823 const size = this.tileSize();
824 existing.transform.position.x = x;
825 existing.transform.position.y = y;
826 existing.transform.size = new vector(size, size);
827 existing.layer = layer;
828 this.#markSortDirty();
829 return existing;
830 }
831
832 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
833 {
834 const sprite = object?.renderer?.sprite;
835 if (!sprite)
836 { return; }
837 const zoom = this.zoom;
838 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
839 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
840 object.transform.position.x = center.x;
841 object.transform.position.y = center.y;
842 object.transform.size = new vector(draw.w, draw.h);
843 object.layer = ySortLayer(sortY, subOrder);
844 this.#markSortDirty();
845 }
846
847 #ensureSprite (existing, name, layer)
848 {
849 const sprite = this.game.images[name];
850 if (!sprite)
851 {
852 existing?.destroy();
853 return null;
854 }
855 if (!existing || existing.renderer.sprite !== sprite)
856 {
857 existing?.destroy();
858 existing = new GameObject(0, 0, sprite, layer);
859 this.scene.addObject(existing);
860 this.#startIdleAnimation(existing);
861 }
862 return existing;
863 }
864
865 #startIdleAnimation (object)
866 {
867 const sprite = object?.renderer?.sprite;
868 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
869 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
870 }
871
872 #neighborClosed (snapshot, dir, dx, dy)
873 {
874 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
875 if (other)
876 { return !other.open; }
877 return !!snapshot.closedEdges?.[dir];
878 }
879
880 #rebuildAllEdges ()
881 {
882 const seen = new Set();
883 for (const snapshot of this.chunks.values())
884 {
885 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
886 seen.add(key);
887 this.#rebuildChunkEdges(snapshot);
888 }
889 for (const key of [...this.edges.keys()])
890 {
891 if (!seen.has(key))
892 { this.#destroyEdges(key); }
893 }
894 }
895
896 #rebuildChunkEdges (snapshot)
897 {
898 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
899 let bars = this.edges.get(key);
900 if (!bars)
901 {
902 bars = {};
903 this.edges.set(key, bars);
904 }
905
906 const size = this.tileSize();
907 const chunkPx = CHUNK_SIZE * size;
908 const left = snapshot.chunkX * CHUNK_SIZE * size;
909 const top = snapshot.chunkY * CHUNK_SIZE * size;
910 const centerX = left + chunkPx / 2;
911 const centerY = top + chunkPx / 2;
912 const thickness = Math.max(2, Math.round(2 * this.zoom));
913 const draw = snapshot.open === true;
914
915 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
916 centerX, top, chunkPx, thickness, true);
917 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
918 centerX, top + chunkPx, chunkPx, thickness, true);
919 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
920 left, centerY, chunkPx, thickness, false);
921 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
922 left + chunkPx, centerY, chunkPx, thickness, false);
923 }
924
925 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
926 {
927 if (!visible)
928 {
929 if (existing)
930 { existing.renderer.visible = false; }
931 return existing;
932 }
933
934 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
935 existing.renderer.visible = true;
936 existing.transform.position.x = x;
937 existing.transform.position.y = y;
938 existing.transform.size = horizontal
939 ? new vector(length, thickness)
940 : new vector(thickness, length);
941 existing.layer = LAYER_EDGE;
942 this.#markSortDirty();
943 return existing;
944 }
945
946 #destroyEdges (key)
947 {
948 const bars = this.edges.get(key);
949 if (!bars)
950 { return; }
951 bars.north?.destroy();
952 bars.east?.destroy();
953 bars.south?.destroy();
954 bars.west?.destroy();
955 this.edges.delete(key);
956 }
957
958 #markSortDirty ()
959 {
960 this.scene._sortDirty = true;
961 }
962
963 #updateShade ()
964 {
965 const hour = this.nightPreview ?? this.worldHour;
966 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
967 const now = performance.now();
968 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
969 for (const objects of this.tiles.values())
970 {
971 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
972 let dynamic = 0;
973 for (const light of this.dynamicLights)
974 {
975 const dx = (objects.tileX + 0.5) - light.worldX;
976 const dy = (objects.tileY + 0.5) - light.worldY;
977 const dist = Math.hypot(dx, dy);
978 if (dist >= light.radiusTiles)
979 { continue; }
980 const falloff = 1 - dist / light.radiusTiles;
981 dynamic = Math.max(dynamic, falloff * light.intensity);
982 }
983 const intensity = Math.max(baked, dynamic);
984 const alpha = ambientDark * (1 - intensity);
985 objects.shadeAlpha = alpha;
986 if (objects.shade)
987 { objects.shade.renderer.alpha = alpha; }
988 if (objects.spriteShade)
989 { objects.spriteShade.renderer.alpha = alpha; }
990 }
991 for (const entity of this.entities.values())
992 {
993 const alpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
994 if (entity.spriteShade)
995 { entity.spriteShade.renderer.alpha = alpha; }
996 for (const shade of entity.overlayShades ?? [])
997 {
998 if (shade)
999 { shade.renderer.alpha = alpha; }
1000 }
1001 }
1002 }
1003
1004 #updateSwipes (now)
1005 {
1006 this.swipes = this.swipes.filter((swipe) =>
1007 {
1008 if (swipe.until > now)
1009 { return true; }
1010 swipe.object?.destroy();
1011 return false;
1012 });
1013 }
1014
1015 #syncBloomLayer ()
1016 {
1017 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
1018 this.scene.setLayers([
1019 { name: "default" },
1020 {
1021 name: RENDER_LAYER_BLOOM,
1022 composite: "add",
1023 postShaders: Shader.getBloomPostChain({
1024 threshold: settings.bloomThreshold,
1025 softKnee: settings.bloomSoftKnee,
1026 intensity: settings.bloomIntensity,
1027 blurSize: settings.bloomBlurSize,
1028 saturation: settings.bloomSaturation,
1029 colorPreserve: settings.bloomColorPreserve,
1030 dilate: settings.bloomDilate,
1031 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
1032 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
1033 })
1034 }
1035 ]);
1036 }
1037}
1038
1039export function nightFactor (hour, nightDarkness = 0.72)
1040{
1041 const peak = Math.min(1, Math.max(0, nightDarkness));
1042 if (hour >= 8 && hour <= 16)
1043 { return 0; }
1044 if (hour >= 22 || hour <= 5)
1045 { return peak; }
1046 if (hour < 8)
1047 { return lerp(peak, 0, (hour - 5) / 3); }
1048 return lerp(0, peak, (hour - 16) / 6);
1049}
1050
1051function bodySpriteName (sex)
1052{
1053 const key = sex === "female" ? "player-body-female" : "player-body-male";
1054 return spriteImageName("character", key, key);
1055}
1056
1057function lerp (a, b, t)
1058{
1059 return a + (b - a) * Math.min(1, Math.max(0, t));
1060}
1061
1062function copyCanvas (source, dest)
1063{
1064 const ctx = dest.getContext("2d");
1065 ctx.imageSmoothingEnabled = false;
1066 ctx.clearRect(0, 0, dest.width, dest.height);
1067 ctx.drawImage(source, 0, 0);
1068}
1069
1070function setNearestFilter (scene, canvas)
1071{
1072 const glContext = scene?.glContext;
1073 if (!glContext || !canvas)
1074 { return; }
1075 const texture = glContext.getTexture(canvas);
1076 if (!texture)
1077 { return; }
1078 const gl = glContext.gl;
1079 gl.bindTexture(gl.TEXTURE_2D, texture);
1080 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1081 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1082}