BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

Pickup ui options
timfa Tim Falken · pushed by timfa · 2 months ago
47f357e3 History
worldView.js 31.7 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 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
236 }
237
238 groundItemsAtTile (tileX, tileY)
239 {
240 const items = [];
241 for (const item of this.groundItems.values())
242 {
243 if (item.tileX === tileX && item.tileY === tileY)
244 { items.push(item); }
245 }
246 return items;
247 }
248
249 entitiesAtTile (tileX, tileY)
250 {
251 const matches = [];
252 for (const entity of this.entities.values())
253 {
254 if (entity.tileX === tileX && entity.tileY === tileY)
255 { matches.push(entity); }
256 }
257 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
258 return matches;
259 }
260
261 setZoom (zoom, limits = { min: 1, max: 4 })
262 {
263 const min = limits.min ?? 1;
264 const max = limits.max ?? 4;
265 this.zoom = Math.min(max, Math.max(min, zoom));
266 for (const snapshot of this.chunks.values())
267 {
268 this.#layoutBakedChunk(snapshot);
269 for (let localY = 0; localY < CHUNK_SIZE; localY++)
270 {
271 for (let localX = 0; localX < CHUNK_SIZE; localX++)
272 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
273 }
274 }
275 const size = this.tileSize();
276 for (const entity of this.entities.values())
277 {
278 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
279 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
280 entity.fromX = entity.visualX;
281 entity.fromY = entity.visualY;
282 entity.targetX = entity.visualX;
283 entity.targetY = entity.visualY;
284 entity.lerpStarted = null;
285 this.#placeEntity(entity);
286 }
287 for (const item of this.groundItems.values())
288 {
289 const pivot = tilePivot(item.tileX, item.tileY, size);
290 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
291 }
292 this.#rebuildAllEdges();
293 this.#redrawPreview();
294 }
295
296 tileSize ()
297 {
298 return SPRITE_SIZE_PX * this.zoom;
299 }
300
301 screenToTile (mouseX, mouseY)
302 {
303 const size = this.tileSize();
304 const worldX = mouseX - this.scene.cameraPosition.x;
305 const worldY = mouseY - this.scene.cameraPosition.y;
306 return {
307 tileX: Math.floor(worldX / size),
308 tileY: Math.floor(worldY / size)
309 };
310 }
311
312 entityAtScreen (mouseX, mouseY)
313 {
314 let best = null;
315 let bestLayer = -Infinity;
316 for (const entity of this.entities.values())
317 {
318 const box = this.#entityScreenBox(entity);
319 if (!box)
320 { continue; }
321 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
322 {
323 const layer = entity.object?.layer ?? 0;
324 if (layer >= bestLayer)
325 {
326 best = entity;
327 bestLayer = layer;
328 }
329 }
330 }
331 return best;
332 }
333
334 nametagAnchor (entity)
335 {
336 const box = this.#entityScreenBox(entity);
337 if (!box)
338 { return null; }
339 return { x: (box.left + box.right) / 2, y: box.top };
340 }
341
342 #entityScreenBox (entity)
343 {
344 const object = entity?.object;
345 if (!object)
346 { return null; }
347 const size = object.transform.size;
348 const x = object.transform.position.x + this.scene.cameraPosition.x;
349 const y = object.transform.position.y + this.scene.cameraPosition.y;
350 return {
351 left: x - size.x / 2,
352 right: x + size.x / 2,
353 top: y - size.y / 2,
354 bottom: y + size.y / 2
355 };
356 }
357
358 update (deltaTime)
359 {
360 const now = performance.now();
361 const size = this.tileSize();
362 for (const entity of this.entities.values())
363 {
364 const target = entity.targetX != null && entity.targetY != null
365 ? { x: entity.targetX, y: entity.targetY }
366 : tilePivot(entity.tileX, entity.tileY, size);
367 if (entity.lerpStarted != null)
368 {
369 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
370 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
371 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
372 if (t >= 1)
373 { entity.lerpStarted = null; }
374 }
375 else
376 {
377 entity.visualX = target.x;
378 entity.visualY = target.y;
379 }
380 this.#placeEntity(entity);
381 }
382
383 this.#updateSwipes(now);
384 this.#centerCamera();
385 this.#updateShade(deltaTime);
386 }
387
388 spawnCombatSwing (payload)
389 {
390 const attacker = this.entities.get(payload.attackerId);
391 const target = this.entities.get(payload.targetId);
392 if (!attacker || !target)
393 { return; }
394 const midX = (attacker.visualX + target.visualX) / 2;
395 const midY = (attacker.visualY + target.visualY) / 2;
396 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
397 const spriteName = "fx:melee-swipe:melee-swipe";
398 const object = new GameObject(midX, midY, this.game.images[spriteName], SORT_ENTITY + 1);
399 if (object.transform)
400 { object.transform.rotation = angle; }
401 this.scene.addObject(object);
402 this.swipes.push({ object, until: performance.now() + 500 });
403 this.addDynamicLight({
404 worldX: (attacker.tileX + target.tileX) / 2 + 0.5,
405 worldY: (attacker.tileY + target.tileY) / 2 + 0.5,
406 radiusTiles: 2.5,
407 intensity: 0.55,
408 durationMs: 220
409 });
410 }
411
412 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
413 {
414 this.dynamicLights.push({
415 worldX,
416 worldY,
417 radiusTiles,
418 intensity,
419 until: performance.now() + durationMs
420 });
421 }
422
423 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
424 {
425 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
426 if (!snapshot)
427 { return; }
428 const index = localY * CHUNK_SIZE + localX;
429 if (ground !== undefined)
430 { snapshot.grounds[index] = ground; }
431 if (block !== undefined)
432 { snapshot.blocks[index] = block; }
433 if (light !== undefined)
434 { snapshot.light[index] = light; }
435 this.#rebuildChunk(snapshot);
436 }
437
438 setTilePreview (tileX, tileY, override)
439 {
440 const previous = this.preview;
441 this.preview = { tileX, tileY, ...override };
442 const chunkX = Math.floor(tileX / CHUNK_SIZE);
443 const chunkY = Math.floor(tileY / CHUNK_SIZE);
444 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
445 if (snapshot)
446 { this.#rebuildChunk(snapshot); }
447 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
448 {
449 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
450 if (prevSnapshot && prevSnapshot !== snapshot)
451 { this.#rebuildChunk(prevSnapshot); }
452 }
453 }
454
455 clearTilePreview ()
456 {
457 const previous = this.preview;
458 this.preview = null;
459 if (previous)
460 {
461 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
462 if (snapshot)
463 { this.#rebuildChunk(snapshot); }
464 }
465 }
466
467 #lerpMs (gait)
468 {
469 const walk = this.settings.walkTilesPerSecond || 2;
470 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
471 return seconds * 1000;
472 }
473
474 #centerCamera ()
475 {
476 if (!this.followPlayer)
477 { return; }
478 const local = this.entities.get(this.localEntityId);
479 if (!local)
480 { return; }
481 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
482 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
483 }
484
485 #upsertEntity (payload)
486 {
487 const size = this.tileSize();
488 const pivot = tilePivot(payload.tileX, payload.tileY, size);
489 let entity = this.entities.get(payload.entityId);
490 if (!entity)
491 {
492 const spriteName = payload.layers?.[0]?.sprite
493 ?? payload.sprite
494 ?? bodySpriteName(payload.sex);
495 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
496 this.scene.addObject(object);
497 this.#startIdleAnimation(object);
498 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
499 this.entities.set(payload.entityId, entity);
500 }
501 entity.entityId = payload.entityId;
502 entity.tileX = payload.tileX;
503 entity.tileY = payload.tileY;
504 entity.gait = payload.gait;
505 entity.sex = payload.sex ?? entity.sex;
506 entity.characterId = payload.characterId ?? entity.characterId ?? null;
507 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
508 entity.hostile = !!payload.hostile;
509 entity.talkable = !!payload.talkable;
510 entity.untargetable = !!payload.untargetable;
511 entity.freeFlight = !!payload.freeFlight;
512 if (payload.firstName)
513 { entity.firstName = payload.firstName; }
514 if (payload.lastName)
515 { entity.lastName = payload.lastName; }
516 entity.firstName = entity.firstName ?? "";
517 entity.lastName = entity.lastName ?? "";
518 if (payload.worldX != null && payload.worldY != null)
519 {
520 entity.worldX = payload.worldX;
521 entity.worldY = payload.worldY;
522 entity.visualX = payload.worldX * size;
523 entity.visualY = payload.worldY * size;
524 entity.targetX = entity.visualX;
525 entity.targetY = entity.visualY;
526 }
527 else
528 {
529 entity.visualX = pivot.x;
530 entity.visualY = pivot.y;
531 entity.targetX = pivot.x;
532 entity.targetY = pivot.y;
533 }
534 entity.fromX = entity.visualX;
535 entity.fromY = entity.visualY;
536 if (payload.layers)
537 { this.#applyLayers(entity, payload.layers); }
538 this.#placeEntity(entity);
539 }
540
541 #applyLayers (entity, layers)
542 {
543 const base = layers[0]?.sprite
544 ?? bodySpriteName(entity.sex);
545 if (this.game.images[base])
546 {
547 entity.object.renderer.sprite = this.game.images[base];
548 this.#startIdleAnimation(entity.object);
549 }
550 for (const overlay of entity.overlays ?? [])
551 { overlay.destroy(); }
552 for (const overlay of entity.bloomOverlays ?? [])
553 { overlay.destroy(); }
554 entity.overlays = [];
555 entity.bloomOverlays = [];
556 for (const layer of layers.slice(1))
557 {
558 const image = this.game.images[layer.sprite];
559 if (!image)
560 { continue; }
561 const object = new GameObject(0, 0, image, SORT_ENTITY);
562 this.scene.addObject(object);
563 entity.overlays.push(object);
564 const bloomName = bloomCompanionName(layer.sprite);
565 const bloomImage = this.game.images[bloomName];
566 if (!bloomImage)
567 { continue; }
568 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
569 bloom.renderer.layer = RENDER_LAYER_BLOOM;
570 this.scene.addObject(bloom);
571 entity.bloomOverlays.push(bloom);
572 }
573 }
574
575 #placeEntity (entity)
576 {
577 this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
578 for (const overlay of entity.overlays ?? [])
579 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
580 for (const overlay of entity.bloomOverlays ?? [])
581 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
582 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);
583 const nextOverlayShades = [];
584 for (let index = 0; index < (entity.overlays ?? []).length; index++)
585 {
586 nextOverlayShades.push(this.#placeSpriteShade(
587 entity.overlayShades?.[index] ?? null,
588 entity.overlays[index],
589 entity.visualX,
590 entity.visualY + 0.001
591 ));
592 }
593 for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
594 { entity.overlayShades[index]?.destroy(); }
595 entity.overlayShades = nextOverlayShades;
596 }
597
598 #rebuildChunk (snapshot)
599 {
600 this.#bakeAndPlaceChunk(snapshot);
601 const tall = new Set(
602 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
603 .map((entry) => `${entry.tileX},${entry.tileY}`)
604 );
605 for (let localY = 0; localY < CHUNK_SIZE; localY++)
606 {
607 for (let localX = 0; localX < CHUNK_SIZE; localX++)
608 {
609 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
610 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
611 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
612 }
613 }
614 }
615
616 #redrawPreview ()
617 {
618 if (!this.preview)
619 { return; }
620 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
621 if (snapshot)
622 { this.#rebuildChunk(snapshot); }
623 }
624
625 #bakeAndPlaceChunk (snapshot)
626 {
627 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
628 const atlases = bakeChunkAtlases({
629 snapshot,
630 catalog: this.catalog,
631 images: this.game.images,
632 preview: this.preview
633 });
634 let baked = this.bakedChunks.get(key);
635 if (!baked)
636 {
637 baked = {
638 groundCanvas: atlases.ground,
639 blockCanvases: atlases.blockRows,
640 bloomCanvas: atlases.bloom,
641 groundImage: frameworkImageFromCanvas(atlases.ground),
642 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
643 bloomImage: frameworkImageFromCanvas(atlases.bloom),
644 groundObject: null,
645 blockObjects: [],
646 bloomObject: null,
647 tallBlocks: atlases.tallBlocks
648 };
649 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
650 this.scene.addObject(baked.groundObject);
651 for (let row = 0; row < CHUNK_SIZE; row++)
652 {
653 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
654 this.scene.addObject(object);
655 baked.blockObjects.push(object);
656 }
657 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
658 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
659 this.scene.addObject(baked.bloomObject);
660 this.bakedChunks.set(key, baked);
661 }
662 else
663 {
664 copyCanvas(atlases.ground, baked.groundCanvas);
665 for (let row = 0; row < CHUNK_SIZE; row++)
666 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
667 copyCanvas(atlases.bloom, baked.bloomCanvas);
668 invalidateCanvasTexture(this.scene, baked.groundCanvas);
669 for (const canvas of baked.blockCanvases)
670 { invalidateCanvasTexture(this.scene, canvas); }
671 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
672 baked.tallBlocks = atlases.tallBlocks;
673 }
674 this.#layoutBakedChunk(snapshot);
675 }
676
677 #layoutBakedChunk (snapshot)
678 {
679 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
680 const baked = this.bakedChunks.get(key);
681 if (!baked)
682 { return; }
683 const size = this.tileSize();
684 const left = snapshot.chunkX * CHUNK_SIZE * size;
685 const top = snapshot.chunkY * CHUNK_SIZE * size;
686 const chunkPx = CHUNK_SIZE * size;
687 baked.groundObject.transform.position.x = left + chunkPx / 2;
688 baked.groundObject.transform.position.y = top + chunkPx / 2;
689 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
690 baked.groundObject.layer = LAYER_GROUND;
691
692 for (let row = 0; row < CHUNK_SIZE; row++)
693 {
694 const object = baked.blockObjects[row];
695 const rowY = top + row * size + size / 2;
696 object.transform.position.x = left + chunkPx / 2;
697 object.transform.position.y = rowY;
698 object.transform.size = new vector(chunkPx, size);
699 object.layer = ySortLayer(rowY, SORT_BLOCK);
700 }
701
702 baked.bloomObject.transform.position.x = left + chunkPx / 2;
703 baked.bloomObject.transform.position.y = top + chunkPx / 2;
704 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
705 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
706 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
707 this.#markSortDirty();
708 setNearestFilter(this.scene, baked.groundCanvas);
709 for (const canvas of baked.blockCanvases)
710 { setNearestFilter(this.scene, canvas); }
711 setNearestFilter(this.scene, baked.bloomCanvas);
712 }
713
714 #destroyBakedChunk (key)
715 {
716 const baked = this.bakedChunks.get(key);
717 if (!baked)
718 { return; }
719 baked.groundObject?.destroy();
720 for (const object of baked.blockObjects ?? [])
721 { object.destroy(); }
722 baked.bloomObject?.destroy();
723 invalidateCanvasTexture(this.scene, baked.groundCanvas);
724 for (const canvas of baked.blockCanvases ?? [])
725 { invalidateCanvasTexture(this.scene, canvas); }
726 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
727 this.bakedChunks.delete(key);
728 }
729
730 #drawTile (tileX, tileY, forceTall = null)
731 {
732 const chunkX = Math.floor(tileX / CHUNK_SIZE);
733 const chunkY = Math.floor(tileY / CHUNK_SIZE);
734 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
735 if (!snapshot)
736 { return; }
737 const localX = tileX - chunkX * CHUNK_SIZE;
738 const localY = tileY - chunkY * CHUNK_SIZE;
739 const index = localY * CHUNK_SIZE + localX;
740 const key = `${tileX},${tileY}`;
741 let objects = this.tiles.get(key);
742 if (!objects)
743 {
744 objects = { chunkX, chunkY, tileX, tileY };
745 this.tiles.set(key, objects);
746 }
747 objects.tileX = tileX;
748 objects.tileY = tileY;
749 objects.chunkX = chunkX;
750 objects.chunkY = chunkY;
751
752 const size = this.tileSize();
753 const pivot = tilePivot(tileX, tileY, size);
754 objects.light = snapshot.light[index] ?? 0;
755 const previousShade = objects.shade;
756 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE));
757 if (objects.shade && objects.shade !== previousShade)
758 { objects.shade.renderer.alpha = 0; }
759
760 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
761 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
762 const isTall = forceTall === true || !!tallEntry;
763 if (isTall && tallEntry)
764 {
765 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
766 if (objects.block)
767 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); }
768 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
769 objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y);
770 }
771 else
772 {
773 if (objects.block)
774 {
775 objects.block.destroy();
776 objects.block = null;
777 }
778 if (objects.blockBloom)
779 {
780 objects.blockBloom.destroy();
781 objects.blockBloom = null;
782 }
783 if (objects.spriteShade)
784 {
785 objects.spriteShade.destroy();
786 objects.spriteShade = null;
787 }
788 }
789 }
790
791 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
792 {
793 if (!name)
794 {
795 existing?.destroy();
796 return null;
797 }
798 const object = this.#ensureSprite(existing, name, sortOrder);
799 if (!object)
800 { return null; }
801 object.renderer.layer = RENDER_LAYER_BLOOM;
802 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
803 return object;
804 }
805
806 #placeSpriteShade (existing, targetObject, pivotX, pivotY)
807 {
808 if (!targetObject?.renderer?.sprite)
809 {
810 existing?.destroy();
811 return null;
812 }
813 const sprite = targetObject.renderer.sprite;
814 if (!existing || existing.renderer.sprite !== sprite)
815 {
816 existing?.destroy();
817 existing = new GameObject(0, 0, sprite, SORT_SPRITE_SHADE);
818 this.scene.addObject(existing);
819 }
820 existing.renderer.sprite = sprite;
821 existing.renderer.shader = getSpriteShadeShader();
822 existing.renderer.subImage = targetObject.renderer.subImage || 0;
823 existing.renderer.mirrorX = !!targetObject.renderer.mirrorX;
824 existing.renderer.mirrorY = !!targetObject.renderer.mirrorY;
825 const zoom = this.zoom;
826 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
827 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
828 existing.transform.position.x = center.x;
829 existing.transform.position.y = center.y;
830 existing.transform.size = new vector(draw.w, draw.h);
831 existing.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);
832 this.#markSortDirty();
833 return existing;
834 }
835
836 #tileFill (existing, name, x, y, layer)
837 {
838 existing = this.#ensureSprite(existing, name, layer);
839 if (!existing)
840 { return null; }
841 const size = this.tileSize();
842 existing.transform.position.x = x;
843 existing.transform.position.y = y;
844 existing.transform.size = new vector(size, size);
845 existing.layer = layer;
846 this.#markSortDirty();
847 return existing;
848 }
849
850 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
851 {
852 const sprite = object?.renderer?.sprite;
853 if (!sprite)
854 { return; }
855 const zoom = this.zoom;
856 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
857 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
858 object.transform.position.x = center.x;
859 object.transform.position.y = center.y;
860 object.transform.size = new vector(draw.w, draw.h);
861 object.layer = ySortLayer(sortY, subOrder);
862 this.#markSortDirty();
863 }
864
865 #ensureSprite (existing, name, layer)
866 {
867 const sprite = this.game.images[name];
868 if (!sprite)
869 {
870 existing?.destroy();
871 return null;
872 }
873 if (!existing || existing.renderer.sprite !== sprite)
874 {
875 existing?.destroy();
876 existing = new GameObject(0, 0, sprite, layer);
877 this.scene.addObject(existing);
878 this.#startIdleAnimation(existing);
879 }
880 return existing;
881 }
882
883 #startIdleAnimation (object)
884 {
885 const sprite = object?.renderer?.sprite;
886 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
887 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
888 }
889
890 #neighborClosed (snapshot, dir, dx, dy)
891 {
892 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
893 if (other)
894 { return !other.open; }
895 return !!snapshot.closedEdges?.[dir];
896 }
897
898 #rebuildAllEdges ()
899 {
900 const seen = new Set();
901 for (const snapshot of this.chunks.values())
902 {
903 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
904 seen.add(key);
905 this.#rebuildChunkEdges(snapshot);
906 }
907 for (const key of [...this.edges.keys()])
908 {
909 if (!seen.has(key))
910 { this.#destroyEdges(key); }
911 }
912 }
913
914 #rebuildChunkEdges (snapshot)
915 {
916 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
917 let bars = this.edges.get(key);
918 if (!bars)
919 {
920 bars = {};
921 this.edges.set(key, bars);
922 }
923
924 const size = this.tileSize();
925 const chunkPx = CHUNK_SIZE * size;
926 const left = snapshot.chunkX * CHUNK_SIZE * size;
927 const top = snapshot.chunkY * CHUNK_SIZE * size;
928 const centerX = left + chunkPx / 2;
929 const centerY = top + chunkPx / 2;
930 const thickness = Math.max(2, Math.round(2 * this.zoom));
931 const draw = snapshot.open === true;
932
933 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
934 centerX, top, chunkPx, thickness, true);
935 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
936 centerX, top + chunkPx, chunkPx, thickness, true);
937 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
938 left, centerY, chunkPx, thickness, false);
939 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
940 left + chunkPx, centerY, chunkPx, thickness, false);
941 }
942
943 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
944 {
945 if (!visible)
946 {
947 if (existing)
948 { existing.renderer.visible = false; }
949 return existing;
950 }
951
952 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
953 existing.renderer.visible = true;
954 existing.transform.position.x = x;
955 existing.transform.position.y = y;
956 existing.transform.size = horizontal
957 ? new vector(length, thickness)
958 : new vector(thickness, length);
959 existing.layer = LAYER_EDGE;
960 this.#markSortDirty();
961 return existing;
962 }
963
964 #destroyEdges (key)
965 {
966 const bars = this.edges.get(key);
967 if (!bars)
968 { return; }
969 bars.north?.destroy();
970 bars.east?.destroy();
971 bars.south?.destroy();
972 bars.west?.destroy();
973 this.edges.delete(key);
974 }
975
976 #markSortDirty ()
977 {
978 this.scene._sortDirty = true;
979 }
980
981 #updateShade ()
982 {
983 const hour = this.nightPreview ?? this.worldHour;
984 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
985 const now = performance.now();
986 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
987 for (const objects of this.tiles.values())
988 {
989 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
990 let dynamic = 0;
991 for (const light of this.dynamicLights)
992 {
993 const dx = (objects.tileX + 0.5) - light.worldX;
994 const dy = (objects.tileY + 0.5) - light.worldY;
995 const dist = Math.hypot(dx, dy);
996 if (dist >= light.radiusTiles)
997 { continue; }
998 const falloff = 1 - dist / light.radiusTiles;
999 dynamic = Math.max(dynamic, falloff * light.intensity);
1000 }
1001 const intensity = Math.max(baked, dynamic);
1002 const alpha = ambientDark * (1 - intensity);
1003 objects.shadeAlpha = alpha;
1004 if (objects.shade)
1005 { objects.shade.renderer.alpha = alpha; }
1006 if (objects.spriteShade)
1007 { objects.spriteShade.renderer.alpha = alpha; }
1008 }
1009 for (const entity of this.entities.values())
1010 {
1011 const alpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
1012 if (entity.spriteShade)
1013 { entity.spriteShade.renderer.alpha = alpha; }
1014 for (const shade of entity.overlayShades ?? [])
1015 {
1016 if (shade)
1017 { shade.renderer.alpha = alpha; }
1018 }
1019 }
1020 }
1021
1022 #updateSwipes (now)
1023 {
1024 this.swipes = this.swipes.filter((swipe) =>
1025 {
1026 if (swipe.until > now)
1027 { return true; }
1028 swipe.object?.destroy();
1029 return false;
1030 });
1031 }
1032
1033 #syncBloomLayer ()
1034 {
1035 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
1036 this.scene.setLayers([
1037 { name: "default" },
1038 {
1039 name: RENDER_LAYER_BLOOM,
1040 composite: "add",
1041 postShaders: Shader.getBloomPostChain({
1042 threshold: settings.bloomThreshold,
1043 softKnee: settings.bloomSoftKnee,
1044 intensity: settings.bloomIntensity,
1045 blurSize: settings.bloomBlurSize,
1046 saturation: settings.bloomSaturation,
1047 colorPreserve: settings.bloomColorPreserve,
1048 dilate: settings.bloomDilate,
1049 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
1050 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
1051 })
1052 }
1053 ]);
1054 }
1055}
1056
1057export function nightFactor (hour, nightDarkness = 0.72)
1058{
1059 const peak = Math.min(1, Math.max(0, nightDarkness));
1060 if (hour >= 8 && hour <= 16)
1061 { return 0; }
1062 if (hour >= 22 || hour <= 5)
1063 { return peak; }
1064 if (hour < 8)
1065 { return lerp(peak, 0, (hour - 5) / 3); }
1066 return lerp(0, peak, (hour - 16) / 6);
1067}
1068
1069function bodySpriteName (sex)
1070{
1071 const key = sex === "female" ? "player-body-female" : "player-body-male";
1072 return spriteImageName("character", key, key);
1073}
1074
1075function lerp (a, b, t)
1076{
1077 return a + (b - a) * Math.min(1, Math.max(0, t));
1078}
1079
1080function copyCanvas (source, dest)
1081{
1082 const ctx = dest.getContext("2d");
1083 ctx.imageSmoothingEnabled = false;
1084 ctx.clearRect(0, 0, dest.width, dest.height);
1085 ctx.drawImage(source, 0, 0);
1086}
1087
1088function setNearestFilter (scene, canvas)
1089{
1090 const glContext = scene?.glContext;
1091 if (!glContext || !canvas)
1092 { return; }
1093 const texture = glContext.getTexture(canvas);
1094 if (!texture)
1095 { return; }
1096 const gl = glContext.gl;
1097 gl.bindTexture(gl.TEXTURE_2D, texture);
1098 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1099 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1100}