BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 38.9 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } 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 SORT_HP_BAR = 5;
18const SORT_FX = 6;
19const RENDER_LAYER_BLOOM = "bloom";
20
21const HP_BAR_W = 14;
22const HP_BAR_H = 4;
23const WALK_TILT_DEG = 6;
24const RUN_TILT_DEG = 8;
25const SHOVE_TILE_FRACTION = 0.25;
26const SHOVE_MS = 280;
27const DAMAGE_FLASH_MS = 180;
28const DAMAGE_FLOAT_MS = 900;
29
30const SPRITE_SHADE_FRAG = [
31 "precision mediump float;",
32 "varying vec2 v_texCoord;",
33 "uniform sampler2D u_texture;",
34 "uniform float u_alpha;",
35 "void main() {",
36 " vec4 color = texture2D(u_texture, v_texCoord);",
37 " if (color.a <= 0.0) { discard; }",
38 " gl_FragColor = vec4(0.0, 0.0, 0.0, color.a * u_alpha);",
39 "}"
40].join("\n");
41
42const DAMAGE_FLASH_FRAG = [
43 "precision mediump float;",
44 "varying vec2 v_texCoord;",
45 "uniform sampler2D u_texture;",
46 "uniform float u_strength;",
47 "void main() {",
48 " vec4 color = texture2D(u_texture, v_texCoord);",
49 " if (color.a <= 0.0) { discard; }",
50 " vec3 flash = mix(color.rgb, vec3(1.0, 0.12, 0.12), u_strength);",
51 " gl_FragColor = vec4(flash, color.a);",
52 "}"
53].join("\n");
54
55let spriteShadeShader = null;
56let damageFlashShader = null;
57
58function getSpriteShadeShader ()
59{
60 if (!spriteShadeShader)
61 { spriteShadeShader = Shader.fragment(SPRITE_SHADE_FRAG); }
62 return spriteShadeShader;
63}
64
65function getDamageFlashShader ()
66{
67 if (!damageFlashShader)
68 { damageFlashShader = Shader.fragment(DAMAGE_FLASH_FRAG); }
69 return damageFlashShader;
70}
71
72export class WorldView
73{
74 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
75 {
76 this.game = game;
77 this.scene = scene;
78 this.catalog = catalog;
79 this.preview = null;
80 this.zoom = 2;
81 this.chunks = new Map();
82 this.bakedChunks = new Map();
83 this.tiles = new Map();
84 this.entities = new Map();
85 this.groundItems = new Map();
86 this.edges = new Map();
87 this.localEntityId = null;
88 this.settings = { ...DEFAULT_WORLD_SETTINGS };
89 this.worldHour = 12;
90 this.nightPreview = null;
91 this.followPlayer = true;
92 this.dynamicLights = [];
93 this.swipes = [];
94 this.damageFloats = [];
95 this.damageNumbersEl = document.getElementById("damage-numbers");
96 this.#syncBloomLayer();
97 }
98
99 setSettings (settings)
100 {
101 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
102 this.#syncBloomLayer();
103 }
104
105 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
106 {
107 this.localEntityId = entityId;
108 this.#upsertEntity({
109 entityId,
110 characterId,
111 tileX,
112 tileY,
113 gait,
114 sex,
115 firstName,
116 lastName,
117 layers: layers ?? undefined
118 });
119 }
120
121 applySnapshot (snapshot)
122 {
123 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
124 this.chunks.set(key, snapshot);
125 this.#rebuildChunk(snapshot);
126 this.#redrawPreview();
127 for (const entity of snapshot.entities ?? [])
128 { this.#upsertEntity(entity); }
129 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
130 for (const [id, item] of [...this.groundItems.entries()])
131 {
132 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
133 { this.despawnGroundItem(id); }
134 }
135 for (const item of snapshot.groundItems ?? [])
136 { this.upsertGroundItem(item); }
137 this.#rebuildAllEdges();
138 }
139
140 removeChunk (chunkX, chunkY)
141 {
142 const key = `${chunkX},${chunkY}`;
143 this.chunks.delete(key);
144 this.#destroyBakedChunk(key);
145 this.#destroyEdges(key);
146 for (const [tileKey, objects] of [...this.tiles.entries()])
147 {
148 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
149 {
150 objects.block?.destroy();
151 objects.blockBloom?.destroy();
152 objects.spriteShade?.destroy();
153 objects.shade?.destroy();
154 this.tiles.delete(tileKey);
155 }
156 }
157 for (const [id, item] of [...this.groundItems.entries()])
158 {
159 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
160 { this.despawnGroundItem(id); }
161 }
162 this.#rebuildAllEdges();
163 }
164
165 setChunkOpen (chunkX, chunkY, open)
166 {
167 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
168 if (!snapshot)
169 { return; }
170 snapshot.open = !!open;
171 this.#rebuildAllEdges();
172 }
173
174 spawnEntity (payload)
175 {
176 this.#upsertEntity(payload);
177 }
178
179 moveEntity (payload)
180 {
181 const existing = this.entities.get(payload.entityId);
182 if (!existing)
183 {
184 this.#upsertEntity(payload);
185 return;
186 }
187 const size = this.tileSize();
188 existing.fromX = existing.visualX;
189 existing.fromY = existing.visualY;
190 existing.tileX = payload.tileX;
191 existing.tileY = payload.tileY;
192 existing.gait = payload.gait;
193 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
194 if (payload.worldX != null && payload.worldY != null)
195 {
196 existing.worldX = payload.worldX;
197 existing.worldY = payload.worldY;
198 existing.targetX = payload.worldX * size;
199 existing.targetY = payload.worldY * size;
200 }
201 else
202 {
203 const pivot = tilePivot(payload.tileX, payload.tileY, size);
204 existing.targetX = pivot.x;
205 existing.targetY = pivot.y;
206 }
207 existing.lerpStarted = performance.now();
208 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
209 }
210
211 despawnEntity (entityId)
212 {
213 const existing = this.entities.get(entityId);
214 if (!existing)
215 { return; }
216 existing.object?.destroy();
217 existing.spriteShade?.destroy();
218 existing.hpBar?.destroy();
219 for (const shade of existing.overlayShades ?? [])
220 { shade.destroy(); }
221 for (const overlay of existing.overlays ?? [])
222 { overlay.destroy(); }
223 for (const overlay of existing.bloomOverlays ?? [])
224 { overlay.destroy(); }
225 this.entities.delete(entityId);
226 }
227
228 updateEntityHealth (entityId, health, maxHealth)
229 {
230 const entity = this.entities.get(entityId);
231 if (!entity)
232 { return; }
233 entity.health = health;
234 entity.maxHealth = maxHealth;
235 this.#syncHpBar(entity);
236 }
237
238 flashDamage (entityId)
239 {
240 const entity = this.entities.get(entityId);
241 if (!entity)
242 { return; }
243 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
244 }
245
246 spawnDamageNumber (entityId, damage)
247 {
248 const amount = damage | 0;
249 if (amount <= 0)
250 { return; }
251 this.damageFloats.push({
252 entityId,
253 damage: amount,
254 started: performance.now()
255 });
256 }
257
258 setAppearance (payload)
259 {
260 const existing = this.entities.get(payload.entityId);
261 if (!existing)
262 { return; }
263 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
264 this.#placeEntity(existing);
265 }
266
267 upsertGroundItem (payload)
268 {
269 const size = this.tileSize();
270 const pivot = tilePivot(payload.tileX, payload.tileY, size);
271 let item = this.groundItems.get(payload.groundItemId);
272 if (!item)
273 {
274 const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
275 this.scene.addObject(object);
276 item = { object };
277 this.groundItems.set(payload.groundItemId, item);
278 }
279 item.groundItemId = payload.groundItemId;
280 item.tileX = payload.tileX;
281 item.tileY = payload.tileY;
282 item.itemId = payload.itemId;
283 item.quantity = payload.quantity;
284 item.displayName = payload.displayName;
285 item.sprite = payload.sprite;
286 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
287 }
288
289 despawnGroundItem (groundItemId)
290 {
291 const item = this.groundItems.get(groundItemId);
292 if (!item)
293 { return; }
294 item.object?.destroy();
295 this.groundItems.delete(groundItemId);
296 }
297
298 groundItemAtTile (tileX, tileY)
299 {
300 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
301 }
302
303 groundItemsAtTile (tileX, tileY)
304 {
305 const items = [];
306 for (const item of this.groundItems.values())
307 {
308 if (item.tileX === tileX && item.tileY === tileY)
309 { items.push(item); }
310 }
311 return items;
312 }
313
314 entitiesAtTile (tileX, tileY)
315 {
316 const matches = [];
317 for (const entity of this.entities.values())
318 {
319 if (entity.tileX === tileX && entity.tileY === tileY)
320 { matches.push(entity); }
321 }
322 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
323 return matches;
324 }
325
326 setZoom (zoom, limits = { min: 1, max: 4 })
327 {
328 const min = limits.min ?? 1;
329 const max = limits.max ?? 4;
330 this.zoom = Math.min(max, Math.max(min, zoom));
331 for (const snapshot of this.chunks.values())
332 {
333 this.#layoutBakedChunk(snapshot);
334 for (let localY = 0; localY < CHUNK_SIZE; localY++)
335 {
336 for (let localX = 0; localX < CHUNK_SIZE; localX++)
337 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
338 }
339 }
340 const size = this.tileSize();
341 for (const entity of this.entities.values())
342 {
343 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
344 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
345 entity.fromX = entity.visualX;
346 entity.fromY = entity.visualY;
347 entity.targetX = entity.visualX;
348 entity.targetY = entity.visualY;
349 entity.lerpStarted = null;
350 this.#placeEntity(entity);
351 }
352 for (const item of this.groundItems.values())
353 {
354 const pivot = tilePivot(item.tileX, item.tileY, size);
355 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
356 }
357 this.#rebuildAllEdges();
358 this.#redrawPreview();
359 }
360
361 tileSize ()
362 {
363 return SPRITE_SIZE_PX * this.zoom;
364 }
365
366 screenToTile (mouseX, mouseY)
367 {
368 const size = this.tileSize();
369 const worldX = mouseX - this.scene.cameraPosition.x;
370 const worldY = mouseY - this.scene.cameraPosition.y;
371 return {
372 tileX: Math.floor(worldX / size),
373 tileY: Math.floor(worldY / size)
374 };
375 }
376
377 entityAtScreen (mouseX, mouseY)
378 {
379 let best = null;
380 let bestLayer = -Infinity;
381 for (const entity of this.entities.values())
382 {
383 const box = this.#entityScreenBox(entity);
384 if (!box)
385 { continue; }
386 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
387 {
388 const layer = entity.object?.layer ?? 0;
389 if (layer >= bestLayer)
390 {
391 best = entity;
392 bestLayer = layer;
393 }
394 }
395 }
396 return best;
397 }
398
399 nametagAnchor (entity)
400 {
401 const box = this.#entityScreenBox(entity);
402 if (!box)
403 { return null; }
404 return { x: (box.left + box.right) / 2, y: box.top };
405 }
406
407 #entityScreenBox (entity)
408 {
409 const object = entity?.object;
410 if (!object)
411 { return null; }
412 const size = object.transform.size;
413 const x = object.transform.position.x + this.scene.cameraPosition.x;
414 const y = object.transform.position.y + this.scene.cameraPosition.y;
415 return {
416 left: x - size.x / 2,
417 right: x + size.x / 2,
418 top: y - size.y / 2,
419 bottom: y + size.y / 2
420 };
421 }
422
423 update (deltaTime)
424 {
425 const now = performance.now();
426 const size = this.tileSize();
427 for (const entity of this.entities.values())
428 {
429 const target = entity.targetX != null && entity.targetY != null
430 ? { x: entity.targetX, y: entity.targetY }
431 : tilePivot(entity.tileX, entity.tileY, size);
432 if (entity.lerpStarted != null)
433 {
434 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
435 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
436 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
437 if (t >= 1)
438 { entity.lerpStarted = null; }
439 }
440 else
441 {
442 entity.visualX = target.x;
443 entity.visualY = target.y;
444 }
445 this.#updateShove(entity, now, size);
446 this.#placeEntity(entity, now);
447 }
448
449 this.#updateSwipes(now);
450 this.#updateDamageNumbers(now);
451 this.#centerCamera();
452 this.#updateShade(deltaTime);
453 }
454
455 #updateShove (entity, now, tileSize)
456 {
457 if (!entity.shove)
458 {
459 entity.shoveOffsetX = 0;
460 entity.shoveOffsetY = 0;
461 return;
462 }
463 const elapsed = now - entity.shove.started;
464 const t = Math.min(1, elapsed / entity.shove.durationMs);
465 const maxDist = tileSize * SHOVE_TILE_FRACTION;
466 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
467 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
468 const dist = Math.hypot(dx, dy) || 1;
469 const ux = dx / dist;
470 const uy = dy / dist;
471 let phase;
472 if (t < 0.45)
473 { phase = t / 0.45; }
474 else
475 { phase = 1 - (t - 0.45) / 0.55; }
476 entity.shoveOffsetX = ux * maxDist * phase;
477 entity.shoveOffsetY = uy * maxDist * phase;
478 if (t >= 1)
479 { entity.shove = null; }
480 }
481
482 spawnCombatSwing (payload)
483 {
484 const attacker = this.entities.get(payload.attackerId);
485 const target = this.entities.get(payload.targetId);
486 if (!attacker || !target)
487 { return; }
488 attacker.shove = {
489 startVisualX: attacker.visualX,
490 startVisualY: attacker.visualY,
491 targetVisualX: target.visualX,
492 targetVisualY: target.visualY,
493 started: performance.now(),
494 durationMs: SHOVE_MS
495 };
496 const midX = (attacker.visualX + target.visualX) / 2;
497 const midY = (attacker.visualY + target.visualY) / 2;
498 const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;
499 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
500 const spriteName = "fx:melee-swipe:melee-swipe";
501 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
502 if (object.transform)
503 { object.transform.rotation = angle; }
504 this.scene.addObject(object);
505 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
506 this.swipes.push({ object, until: performance.now() + 500 });
507 }
508
509 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 0.5, durationMs = 250 })
510 {
511 this.dynamicLights.push({
512 worldX,
513 worldY,
514 radiusTiles,
515 intensity,
516 until: performance.now() + durationMs
517 });
518 }
519
520 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
521 {
522 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
523 if (!snapshot)
524 { return; }
525 const index = localY * CHUNK_SIZE + localX;
526 if (ground !== undefined)
527 { snapshot.grounds[index] = ground; }
528 if (block !== undefined)
529 { snapshot.blocks[index] = block; }
530 if (light !== undefined)
531 { snapshot.light[index] = light; }
532 this.#rebuildChunk(snapshot);
533 }
534
535 setTilePreview (tileX, tileY, override)
536 {
537 const previous = this.preview;
538 this.preview = { tileX, tileY, ...override };
539 const chunkX = Math.floor(tileX / CHUNK_SIZE);
540 const chunkY = Math.floor(tileY / CHUNK_SIZE);
541 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
542 if (snapshot)
543 { this.#rebuildChunk(snapshot); }
544 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
545 {
546 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
547 if (prevSnapshot && prevSnapshot !== snapshot)
548 { this.#rebuildChunk(prevSnapshot); }
549 }
550 }
551
552 clearTilePreview ()
553 {
554 const previous = this.preview;
555 this.preview = null;
556 if (previous)
557 {
558 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
559 if (snapshot)
560 { this.#rebuildChunk(snapshot); }
561 }
562 }
563
564 #lerpMs (gait)
565 {
566 const walk = this.settings.walkTilesPerSecond || 2;
567 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
568 return seconds * 1000;
569 }
570
571 #centerCamera ()
572 {
573 if (!this.followPlayer)
574 { return; }
575 const local = this.entities.get(this.localEntityId);
576 if (!local)
577 { return; }
578 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
579 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
580 }
581
582 #upsertEntity (payload)
583 {
584 const size = this.tileSize();
585 const pivot = tilePivot(payload.tileX, payload.tileY, size);
586 let entity = this.entities.get(payload.entityId);
587 if (!entity)
588 {
589 const spriteName = payload.layers?.[0]?.sprite
590 ?? payload.sprite
591 ?? bodySpriteName(payload.sex);
592 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
593 this.scene.addObject(object);
594 this.#startIdleAnimation(object);
595 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
596 this.entities.set(payload.entityId, entity);
597 }
598 entity.entityId = payload.entityId;
599 entity.tileX = payload.tileX;
600 entity.tileY = payload.tileY;
601 entity.gait = payload.gait;
602 entity.sex = payload.sex ?? entity.sex;
603 entity.characterId = payload.characterId ?? entity.characterId ?? null;
604 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
605 entity.hostile = !!payload.hostile;
606 entity.canFight = !!payload.canFight;
607 entity.talkable = !!payload.talkable;
608 entity.untargetable = !!payload.untargetable;
609 entity.freeFlight = !!payload.freeFlight;
610 if (payload.health != null)
611 { entity.health = payload.health; }
612 if (payload.maxHealth != null)
613 { entity.maxHealth = payload.maxHealth; }
614 if (payload.firstName)
615 { entity.firstName = payload.firstName; }
616 if (payload.lastName)
617 { entity.lastName = payload.lastName; }
618 entity.firstName = entity.firstName ?? "";
619 entity.lastName = entity.lastName ?? "";
620 if (payload.worldX != null && payload.worldY != null)
621 {
622 entity.worldX = payload.worldX;
623 entity.worldY = payload.worldY;
624 entity.visualX = payload.worldX * size;
625 entity.visualY = payload.worldY * size;
626 entity.targetX = entity.visualX;
627 entity.targetY = entity.visualY;
628 }
629 else
630 {
631 entity.visualX = pivot.x;
632 entity.visualY = pivot.y;
633 entity.targetX = pivot.x;
634 entity.targetY = pivot.y;
635 }
636 entity.fromX = entity.visualX;
637 entity.fromY = entity.visualY;
638 if (payload.layers)
639 { this.#applyLayers(entity, payload.layers); }
640 this.#syncHpBar(entity);
641 this.#placeEntity(entity, performance.now());
642 }
643
644 #applyLayers (entity, layers)
645 {
646 const base = layers[0]?.sprite
647 ?? bodySpriteName(entity.sex);
648 if (this.game.images[base])
649 {
650 entity.object.renderer.sprite = this.game.images[base];
651 this.#startIdleAnimation(entity.object);
652 }
653 for (const overlay of entity.overlays ?? [])
654 { overlay.destroy(); }
655 for (const overlay of entity.bloomOverlays ?? [])
656 { overlay.destroy(); }
657 entity.overlays = [];
658 entity.bloomOverlays = [];
659 for (const layer of layers.slice(1))
660 {
661 const image = this.game.images[layer.sprite];
662 if (!image)
663 { continue; }
664 const object = new GameObject(0, 0, image, SORT_ENTITY);
665 this.scene.addObject(object);
666 entity.overlays.push(object);
667 const bloomName = bloomCompanionName(layer.sprite);
668 const bloomImage = this.game.images[bloomName];
669 if (!bloomImage)
670 { continue; }
671 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
672 bloom.renderer.layer = RENDER_LAYER_BLOOM;
673 this.scene.addObject(bloom);
674 entity.bloomOverlays.push(bloom);
675 }
676 }
677
678 #placeEntity (entity, now = performance.now())
679 {
680 const zoom = this.zoom;
681 const offsetX = entity.shoveOffsetX ?? 0;
682 const offsetY = entity.shoveOffsetY ?? 0;
683 const pivotX = entity.visualX + offsetX;
684 const pivotY = entity.visualY + offsetY;
685 let walkTilt = 0;
686 if (entity.lerpStarted != null)
687 {
688 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
689 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
690 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
691 walkTilt = Math.sin(cycles) * tilt;
692 }
693 const flashStrength = (entity.damageFlashUntil ?? 0) > now
694 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
695 : 0;
696 const tileShade = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
697
698 entity.object.transform.rotation = walkTilt;
699 this.#applyDamageFlash(entity.object, flashStrength);
700 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
701 for (let index = 0; index < (entity.overlays ?? []).length; index++)
702 {
703 const overlay = entity.overlays[index];
704 overlay.transform.rotation = walkTilt;
705 this.#applyDamageFlash(overlay, flashStrength);
706 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.001, SORT_ENTITY);
707 }
708 for (const overlay of entity.bloomOverlays ?? [])
709 {
710 overlay.transform.rotation = walkTilt;
711 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
712 }
713 if (flashStrength > 0)
714 {
715 entity.spriteShade?.destroy();
716 entity.spriteShade = null;
717 for (const shade of entity.overlayShades ?? [])
718 { shade?.destroy(); }
719 entity.overlayShades = [];
720 }
721 else
722 {
723 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, pivotX, pivotY);
724 const nextOverlayShades = [];
725 for (let index = 0; index < (entity.overlays ?? []).length; index++)
726 {
727 nextOverlayShades.push(this.#placeSpriteShade(
728 entity.overlayShades?.[index] ?? null,
729 entity.overlays[index],
730 pivotX,
731 pivotY + 0.001
732 ));
733 }
734 for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
735 { entity.overlayShades[index]?.destroy(); }
736 entity.overlayShades = nextOverlayShades;
737 if (entity.spriteShade)
738 { entity.spriteShade.renderer.alpha = tileShade; }
739 for (const shade of entity.overlayShades ?? [])
740 {
741 if (shade)
742 { shade.renderer.alpha = tileShade; }
743 }
744 }
745 this.#placeHpBar(entity, pivotX, pivotY);
746 }
747
748 #applyDamageFlash (object, strength)
749 {
750 if (!object?.renderer)
751 { return; }
752 if (strength > 0)
753 {
754 object.renderer.shader = getDamageFlashShader();
755 object.renderer.shaderUniforms = { u_strength: strength };
756 return;
757 }
758 if (object.renderer.shader === getDamageFlashShader())
759 {
760 object.renderer.shader = null;
761 object.renderer.shaderUniforms = null;
762 }
763 }
764
765 #syncHpBar (entity)
766 {
767 const current = entity.health;
768 const max = entity.maxHealth;
769 const show = entity.mobTypeId != null
770 && current != null
771 && max != null
772 && max > 0
773 && current < max;
774 if (!show)
775 {
776 entity.hpBar?.destroy();
777 entity.hpBar = null;
778 entity.hpBarCanvas = null;
779 return;
780 }
781 if (!entity.hpBarCanvas)
782 {
783 entity.hpBarCanvas = document.createElement("canvas");
784 entity.hpBarCanvas.width = HP_BAR_W;
785 entity.hpBarCanvas.height = HP_BAR_H;
786 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
787 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
788 this.scene.addObject(entity.hpBar);
789 }
790 drawHpBar(entity.hpBarCanvas, current, max);
791 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
792 }
793
794 #placeHpBar (entity, pivotX, pivotY)
795 {
796 if (!entity.hpBar)
797 { return; }
798 const sprite = entity.object?.renderer?.sprite;
799 if (!sprite)
800 { return; }
801 const zoom = this.zoom;
802 const drawH = sprite.height * zoom;
803 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
804 const spriteTop = centerY - drawH / 2;
805 const barW = HP_BAR_W * zoom;
806 const barH = HP_BAR_H * zoom;
807 entity.hpBar.transform.position.x = pivotX;
808 entity.hpBar.transform.position.y = spriteTop - barH / 2;
809 entity.hpBar.transform.size = new vector(barW, barH);
810 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
811 this.#markSortDirty();
812 }
813
814 #rebuildChunk (snapshot)
815 {
816 this.#bakeAndPlaceChunk(snapshot);
817 const tall = new Set(
818 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
819 .map((entry) => `${entry.tileX},${entry.tileY}`)
820 );
821 for (let localY = 0; localY < CHUNK_SIZE; localY++)
822 {
823 for (let localX = 0; localX < CHUNK_SIZE; localX++)
824 {
825 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
826 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
827 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
828 }
829 }
830 }
831
832 #redrawPreview ()
833 {
834 if (!this.preview)
835 { return; }
836 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
837 if (snapshot)
838 { this.#rebuildChunk(snapshot); }
839 }
840
841 #bakeAndPlaceChunk (snapshot)
842 {
843 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
844 const atlases = bakeChunkAtlases({
845 snapshot,
846 catalog: this.catalog,
847 images: this.game.images,
848 preview: this.preview
849 });
850 let baked = this.bakedChunks.get(key);
851 if (!baked)
852 {
853 baked = {
854 groundCanvas: atlases.ground,
855 blockCanvases: atlases.blockRows,
856 bloomCanvas: atlases.bloom,
857 groundImage: frameworkImageFromCanvas(atlases.ground),
858 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
859 bloomImage: frameworkImageFromCanvas(atlases.bloom),
860 groundObject: null,
861 blockObjects: [],
862 bloomObject: null,
863 tallBlocks: atlases.tallBlocks
864 };
865 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
866 this.scene.addObject(baked.groundObject);
867 for (let row = 0; row < CHUNK_SIZE; row++)
868 {
869 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
870 this.scene.addObject(object);
871 baked.blockObjects.push(object);
872 }
873 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
874 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
875 this.scene.addObject(baked.bloomObject);
876 this.bakedChunks.set(key, baked);
877 }
878 else
879 {
880 copyCanvas(atlases.ground, baked.groundCanvas);
881 for (let row = 0; row < CHUNK_SIZE; row++)
882 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
883 copyCanvas(atlases.bloom, baked.bloomCanvas);
884 invalidateCanvasTexture(this.scene, baked.groundCanvas);
885 for (const canvas of baked.blockCanvases)
886 { invalidateCanvasTexture(this.scene, canvas); }
887 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
888 baked.tallBlocks = atlases.tallBlocks;
889 }
890 this.#layoutBakedChunk(snapshot);
891 }
892
893 #layoutBakedChunk (snapshot)
894 {
895 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
896 const baked = this.bakedChunks.get(key);
897 if (!baked)
898 { return; }
899 const size = this.tileSize();
900 const left = snapshot.chunkX * CHUNK_SIZE * size;
901 const top = snapshot.chunkY * CHUNK_SIZE * size;
902 const chunkPx = CHUNK_SIZE * size;
903 baked.groundObject.transform.position.x = left + chunkPx / 2;
904 baked.groundObject.transform.position.y = top + chunkPx / 2;
905 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
906 baked.groundObject.layer = LAYER_GROUND;
907
908 for (let row = 0; row < CHUNK_SIZE; row++)
909 {
910 const object = baked.blockObjects[row];
911 const rowY = top + row * size + size / 2;
912 object.transform.position.x = left + chunkPx / 2;
913 object.transform.position.y = rowY;
914 object.transform.size = new vector(chunkPx, size);
915 object.layer = ySortLayer(rowY, SORT_BLOCK);
916 }
917
918 baked.bloomObject.transform.position.x = left + chunkPx / 2;
919 baked.bloomObject.transform.position.y = top + chunkPx / 2;
920 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
921 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
922 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
923 this.#markSortDirty();
924 setNearestFilter(this.scene, baked.groundCanvas);
925 for (const canvas of baked.blockCanvases)
926 { setNearestFilter(this.scene, canvas); }
927 setNearestFilter(this.scene, baked.bloomCanvas);
928 }
929
930 #destroyBakedChunk (key)
931 {
932 const baked = this.bakedChunks.get(key);
933 if (!baked)
934 { return; }
935 baked.groundObject?.destroy();
936 for (const object of baked.blockObjects ?? [])
937 { object.destroy(); }
938 baked.bloomObject?.destroy();
939 invalidateCanvasTexture(this.scene, baked.groundCanvas);
940 for (const canvas of baked.blockCanvases ?? [])
941 { invalidateCanvasTexture(this.scene, canvas); }
942 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
943 this.bakedChunks.delete(key);
944 }
945
946 #drawTile (tileX, tileY, forceTall = null)
947 {
948 const chunkX = Math.floor(tileX / CHUNK_SIZE);
949 const chunkY = Math.floor(tileY / CHUNK_SIZE);
950 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
951 if (!snapshot)
952 { return; }
953 const localX = tileX - chunkX * CHUNK_SIZE;
954 const localY = tileY - chunkY * CHUNK_SIZE;
955 const index = localY * CHUNK_SIZE + localX;
956 const key = `${tileX},${tileY}`;
957 let objects = this.tiles.get(key);
958 if (!objects)
959 {
960 objects = { chunkX, chunkY, tileX, tileY };
961 this.tiles.set(key, objects);
962 }
963 objects.tileX = tileX;
964 objects.tileY = tileY;
965 objects.chunkX = chunkX;
966 objects.chunkY = chunkY;
967
968 const size = this.tileSize();
969 const pivot = tilePivot(tileX, tileY, size);
970 objects.light = snapshot.light[index] ?? 0;
971 const previousShade = objects.shade;
972 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, ySortLayer(pivot.y, SORT_SHADE));
973 if (objects.shade && objects.shade !== previousShade)
974 { objects.shade.renderer.alpha = 0; }
975
976 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
977 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
978 const isTall = forceTall === true || !!tallEntry;
979 if (isTall && tallEntry)
980 {
981 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
982 if (objects.block)
983 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY); }
984 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
985 objects.spriteShade = this.#placeSpriteShade(objects.spriteShade, objects.block, pivot.x, pivot.y);
986 }
987 else
988 {
989 if (objects.block)
990 {
991 objects.block.destroy();
992 objects.block = null;
993 }
994 if (objects.blockBloom)
995 {
996 objects.blockBloom.destroy();
997 objects.blockBloom = null;
998 }
999 if (objects.spriteShade)
1000 {
1001 objects.spriteShade.destroy();
1002 objects.spriteShade = null;
1003 }
1004 }
1005 }
1006
1007 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
1008 {
1009 if (!name)
1010 {
1011 existing?.destroy();
1012 return null;
1013 }
1014 const object = this.#ensureSprite(existing, name, sortOrder);
1015 if (!object)
1016 { return null; }
1017 object.renderer.layer = RENDER_LAYER_BLOOM;
1018 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
1019 return object;
1020 }
1021
1022 #placeSpriteShade (existing, targetObject, pivotX, pivotY)
1023 {
1024 if (!targetObject?.renderer?.sprite)
1025 {
1026 existing?.destroy();
1027 return null;
1028 }
1029 const sprite = targetObject.renderer.sprite;
1030 if (!existing || existing.renderer.sprite !== sprite)
1031 {
1032 existing?.destroy();
1033 existing = new GameObject(0, 0, sprite, SORT_SPRITE_SHADE);
1034 this.scene.addObject(existing);
1035 }
1036 existing.renderer.sprite = sprite;
1037 existing.renderer.shader = getSpriteShadeShader();
1038 existing.renderer.subImage = targetObject.renderer.subImage || 0;
1039 existing.renderer.mirrorX = !!targetObject.renderer.mirrorX;
1040 existing.renderer.mirrorY = !!targetObject.renderer.mirrorY;
1041 const zoom = this.zoom;
1042 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1043 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
1044 existing.transform.position.x = center.x;
1045 existing.transform.position.y = center.y;
1046 existing.transform.size = new vector(draw.w, draw.h);
1047 existing.layer = ySortLayer(pivotY, SORT_SPRITE_SHADE);
1048 this.#markSortDirty();
1049 return existing;
1050 }
1051
1052 #tileFill (existing, name, x, y, layer)
1053 {
1054 existing = this.#ensureSprite(existing, name, layer);
1055 if (!existing)
1056 { return null; }
1057 const size = this.tileSize();
1058 existing.transform.position.x = x;
1059 existing.transform.position.y = y;
1060 existing.transform.size = new vector(size, size);
1061 existing.layer = layer;
1062 this.#markSortDirty();
1063 return existing;
1064 }
1065
1066 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
1067 {
1068 const sprite = object?.renderer?.sprite;
1069 if (!sprite)
1070 { return; }
1071 const zoom = this.zoom;
1072 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1073 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
1074 object.transform.position.x = center.x;
1075 object.transform.position.y = center.y;
1076 object.transform.size = new vector(draw.w, draw.h);
1077 object.layer = ySortLayer(sortY, subOrder);
1078 this.#markSortDirty();
1079 }
1080
1081 #ensureSprite (existing, name, layer)
1082 {
1083 const sprite = this.game.images[name];
1084 if (!sprite)
1085 {
1086 existing?.destroy();
1087 return null;
1088 }
1089 if (!existing || existing.renderer.sprite !== sprite)
1090 {
1091 existing?.destroy();
1092 existing = new GameObject(0, 0, sprite, layer);
1093 this.scene.addObject(existing);
1094 this.#startIdleAnimation(existing);
1095 }
1096 return existing;
1097 }
1098
1099 #startIdleAnimation (object)
1100 {
1101 const sprite = object?.renderer?.sprite;
1102 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
1103 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
1104 }
1105
1106 #neighborClosed (snapshot, dir, dx, dy)
1107 {
1108 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
1109 if (other)
1110 { return !other.open; }
1111 return !!snapshot.closedEdges?.[dir];
1112 }
1113
1114 #rebuildAllEdges ()
1115 {
1116 const seen = new Set();
1117 for (const snapshot of this.chunks.values())
1118 {
1119 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1120 seen.add(key);
1121 this.#rebuildChunkEdges(snapshot);
1122 }
1123 for (const key of [...this.edges.keys()])
1124 {
1125 if (!seen.has(key))
1126 { this.#destroyEdges(key); }
1127 }
1128 }
1129
1130 #rebuildChunkEdges (snapshot)
1131 {
1132 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1133 let bars = this.edges.get(key);
1134 if (!bars)
1135 {
1136 bars = {};
1137 this.edges.set(key, bars);
1138 }
1139
1140 const size = this.tileSize();
1141 const chunkPx = CHUNK_SIZE * size;
1142 const left = snapshot.chunkX * CHUNK_SIZE * size;
1143 const top = snapshot.chunkY * CHUNK_SIZE * size;
1144 const centerX = left + chunkPx / 2;
1145 const centerY = top + chunkPx / 2;
1146 const thickness = Math.max(2, Math.round(2 * this.zoom));
1147 const draw = snapshot.open === true;
1148
1149 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
1150 centerX, top, chunkPx, thickness, true);
1151 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
1152 centerX, top + chunkPx, chunkPx, thickness, true);
1153 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
1154 left, centerY, chunkPx, thickness, false);
1155 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
1156 left + chunkPx, centerY, chunkPx, thickness, false);
1157 }
1158
1159 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
1160 {
1161 if (!visible)
1162 {
1163 if (existing)
1164 { existing.renderer.visible = false; }
1165 return existing;
1166 }
1167
1168 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
1169 existing.renderer.visible = true;
1170 existing.transform.position.x = x;
1171 existing.transform.position.y = y;
1172 existing.transform.size = horizontal
1173 ? new vector(length, thickness)
1174 : new vector(thickness, length);
1175 existing.layer = LAYER_EDGE;
1176 this.#markSortDirty();
1177 return existing;
1178 }
1179
1180 #destroyEdges (key)
1181 {
1182 const bars = this.edges.get(key);
1183 if (!bars)
1184 { return; }
1185 bars.north?.destroy();
1186 bars.east?.destroy();
1187 bars.south?.destroy();
1188 bars.west?.destroy();
1189 this.edges.delete(key);
1190 }
1191
1192 #markSortDirty ()
1193 {
1194 this.scene._sortDirty = true;
1195 }
1196
1197 #updateShade ()
1198 {
1199 const hour = this.nightPreview ?? this.worldHour;
1200 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
1201 const now = performance.now();
1202 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1203 for (const objects of this.tiles.values())
1204 {
1205 const baked = Math.min(1, Math.max(0, (objects.light ?? 0) / 255));
1206 let dynamic = 0;
1207 for (const light of this.dynamicLights)
1208 {
1209 const dx = (objects.tileX + 0.5) - light.worldX;
1210 const dy = (objects.tileY + 0.5) - light.worldY;
1211 const dist = Math.hypot(dx, dy);
1212 if (dist >= light.radiusTiles)
1213 { continue; }
1214 const falloff = 1 - dist / light.radiusTiles;
1215 dynamic = Math.max(dynamic, falloff * light.intensity);
1216 }
1217 const intensity = Math.max(baked, dynamic);
1218 const alpha = ambientDark * (1 - intensity);
1219 objects.shadeAlpha = alpha;
1220 if (objects.shade)
1221 { objects.shade.renderer.alpha = alpha; }
1222 if (objects.spriteShade)
1223 { objects.spriteShade.renderer.alpha = alpha; }
1224 }
1225 for (const entity of this.entities.values())
1226 {
1227 const alpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
1228 if (entity.spriteShade)
1229 { entity.spriteShade.renderer.alpha = alpha; }
1230 for (const shade of entity.overlayShades ?? [])
1231 {
1232 if (shade)
1233 { shade.renderer.alpha = alpha; }
1234 }
1235 }
1236 }
1237
1238 #updateSwipes (now)
1239 {
1240 this.swipes = this.swipes.filter((swipe) =>
1241 {
1242 if (swipe.until > now)
1243 { return true; }
1244 swipe.object?.destroy();
1245 return false;
1246 });
1247 }
1248
1249 #updateDamageNumbers (now)
1250 {
1251 const layer = this.damageNumbersEl;
1252 if (!layer)
1253 { return; }
1254 this.damageFloats = this.damageFloats.filter((entry) =>
1255 {
1256 const elapsed = now - entry.started;
1257 if (elapsed >= DAMAGE_FLOAT_MS)
1258 {
1259 entry.element?.remove();
1260 return false;
1261 }
1262 const entity = this.entities.get(entry.entityId);
1263 if (!entity)
1264 {
1265 entry.element?.remove();
1266 return false;
1267 }
1268 if (!entry.element)
1269 {
1270 entry.element = document.createElement("span");
1271 entry.element.className = "damage-number";
1272 entry.element.textContent = String(entry.damage);
1273 layer.append(entry.element);
1274 }
1275 const anchor = this.nametagAnchor(entity);
1276 if (!anchor)
1277 { return true; }
1278 const t = elapsed / DAMAGE_FLOAT_MS;
1279 entry.element.style.left = `${anchor.x}px`;
1280 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
1281 entry.element.style.opacity = String(1 - t);
1282 return true;
1283 });
1284 }
1285
1286 #syncBloomLayer ()
1287 {
1288 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
1289 this.scene.setLayers([
1290 { name: "default" },
1291 {
1292 name: RENDER_LAYER_BLOOM,
1293 composite: "add",
1294 postShaders: Shader.getBloomPostChain({
1295 threshold: settings.bloomThreshold,
1296 softKnee: settings.bloomSoftKnee,
1297 intensity: settings.bloomIntensity,
1298 blurSize: settings.bloomBlurSize,
1299 saturation: settings.bloomSaturation,
1300 colorPreserve: settings.bloomColorPreserve,
1301 dilate: settings.bloomDilate,
1302 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
1303 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
1304 })
1305 }
1306 ]);
1307 }
1308}
1309
1310export function nightFactor (hour, nightDarkness = 0.72)
1311{
1312 const peak = Math.min(1, Math.max(0, nightDarkness));
1313 if (hour >= 8 && hour <= 16)
1314 { return 0; }
1315 if (hour >= 22 || hour <= 5)
1316 { return peak; }
1317 if (hour < 8)
1318 { return lerp(peak, 0, (hour - 5) / 3); }
1319 return lerp(0, peak, (hour - 16) / 6);
1320}
1321
1322function bodySpriteName (sex)
1323{
1324 const key = sex === "female" ? "player-body-female" : "player-body-male";
1325 return spriteImageName("character", key, key);
1326}
1327
1328function lerp (a, b, t)
1329{
1330 return a + (b - a) * Math.min(1, Math.max(0, t));
1331}
1332
1333function drawHpBar (canvas, current, max)
1334{
1335 const ctx = canvas.getContext("2d");
1336 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
1337 ctx.fillStyle = "#000000";
1338 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
1339 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
1340 const fillW = Math.round(12 * ratio);
1341 if (fillW > 0)
1342 {
1343 ctx.fillStyle = "#ff0000";
1344 ctx.fillRect(1, 1, fillW, 2);
1345 }
1346}
1347
1348function copyCanvas (source, dest)
1349{
1350 const ctx = dest.getContext("2d");
1351 ctx.imageSmoothingEnabled = false;
1352 ctx.clearRect(0, 0, dest.width, dest.height);
1353 ctx.drawImage(source, 0, 0);
1354}
1355
1356function setNearestFilter (scene, canvas)
1357{
1358 const glContext = scene?.glContext;
1359 if (!glContext || !canvas)
1360 { return; }
1361 const texture = glContext.getTexture(canvas);
1362 if (!texture)
1363 { return; }
1364 const gl = glContext.gl;
1365 gl.bindTexture(gl.TEXTURE_2D, texture);
1366 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1367 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1368}