BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 73.8 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
7import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight } from "/shared/definitions/tiles.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
9import { bakeChunkAtlases } from "./chunkBake.js";
10import {
11 frameworkImageFromCanvas,
12 invalidateCanvasTexture
13} from "./canvasSprite.js";
14import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
15import { SeasonId, seasonIdAt } from "/shared/world/season.js";
16
17const LAYER_GROUND = 0;
18const LAYER_EDGE = 900000;
19const SORT_BLOCK = 2;
20const SORT_ENTITY = 3;
21const SORT_HP_BAR = 4;
22const SORT_FX = 5;
23const RENDER_LAYER_BLOOM = "bloom";
24
25const HP_BAR_W = 14;
26const HP_BAR_H = 4;
27const WALK_TILT_DEG = 6;
28const RUN_TILT_DEG = 8;
29const SHOVE_TILE_FRACTION = 0.25;
30const SHOVE_MS = 280;
31/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
32const GATHER_TOOL_HOLD_MS = 1100;
33const DAMAGE_FLASH_MS = 180;
34const DAMAGE_FLOAT_MS = 900;
35const SKILL_LEVEL_FLOAT_MS = 2800;
36
37const SPRITE_LIGHTING_FRAG = [
38 "precision mediump float;",
39 "varying vec2 v_texCoord;",
40 "uniform sampler2D u_texture;",
41 "uniform float u_darkness;",
42 "uniform float u_strength;",
43 "uniform float u_wade;",
44 "uniform float u_spriteHeight;",
45 "void main() {",
46 " vec4 color = texture2D(u_texture, v_texCoord);",
47 " if (color.a <= 0.0) { discard; }",
48 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
49 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
50 " vec3 rgb = color.rgb;",
51 " if (u_wade > 0.5 && fromBottom < 5.0) {",
52 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
53 " }",
54 " rgb = mix(rgb, vec3(0.0), u_darkness);",
55 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
56 " gl_FragColor = vec4(rgb, color.a);",
57 "}"
58].join("\n");
59
60const WATER_GROUND_FRAG = [
61 "precision mediump float;",
62 "varying vec2 v_texCoord;",
63 "uniform sampler2D u_texture;",
64 "uniform float u_ambientDark;",
65 "uniform float u_litNW;",
66 "uniform float u_litNE;",
67 "uniform float u_litSW;",
68 "uniform float u_litSE;",
69 "uniform float u_time;",
70 "uniform float u_edgeN;",
71 "uniform float u_edgeE;",
72 "uniform float u_edgeS;",
73 "uniform float u_edgeW;",
74 "void main() {",
75 " vec4 color = texture2D(u_texture, v_texCoord);",
76 " if (color.a <= 0.0) { discard; }",
77 " vec3 rgb = color.rgb;",
78 " float foam = 0.0;",
79 " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
80 " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
81 " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
82 " }",
83 " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
84 " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
85 " }",
86 " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
87 " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
88 " }",
89 " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
90 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
91 " }",
92 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
93 " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);",
94 " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);",
95 " float lit = mix(litTop, litBottom, v_texCoord.y);",
96 " float darkness = u_ambientDark * (1.0 - lit);",
97 " rgb = mix(rgb, vec3(0.0), darkness);",
98 " gl_FragColor = vec4(rgb, color.a);",
99 "}"
100].join("\n");
101
102/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
103const TINT_LIT_SPRITE_FRAG = [
104 "precision mediump float;",
105 "varying vec2 v_texCoord;",
106 "uniform sampler2D u_texture;",
107 "uniform float u_darkness;",
108 "uniform float u_strength;",
109 "uniform float u_wade;",
110 "uniform float u_spriteHeight;",
111 "uniform float u_useTint;",
112 "uniform vec3 u_tintColor;",
113 "void main() {",
114 " vec4 color = texture2D(u_texture, v_texCoord);",
115 " if (color.a <= 0.0) { discard; }",
116 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
117 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
118 " vec3 rgb = color.rgb;",
119 " if (u_useTint > 0.5) {",
120 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
121 " float L = color.r;",
122 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
123 " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",
124 " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",
125 " }",
126 " }",
127 " if (u_wade > 0.5 && fromBottom < 5.0) {",
128 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
129 " }",
130 " rgb = mix(rgb, vec3(0.0), u_darkness);",
131 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
132 " gl_FragColor = vec4(rgb, color.a);",
133 "}"
134].join("\n");
135
136const ATLAS_LIGHTING_FRAG = [
137 "precision mediump float;",
138 "varying vec2 v_texCoord;",
139 "uniform sampler2D u_texture;",
140 "uniform sampler2D u_secondary;",
141 "uniform float u_ambientDark;",
142 "uniform float u_lightRow;",
143 "void main() {",
144 " vec4 color = texture2D(u_texture, v_texCoord);",
145 " if (color.a <= 0.0) { discard; }",
146 " vec2 lightUV = v_texCoord;",
147 " if (u_lightRow >= 0.0) {",
148 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
149 " }",
150 " float lit = texture2D(u_secondary, lightUV).r;",
151 " float darkness = u_ambientDark * (1.0 - lit);",
152 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
153 " gl_FragColor = vec4(rgb, color.a);",
154 "}"
155].join("\n");
156
157let spriteLightingShader = null;
158let atlasLightingShader = null;
159let waterGroundShader = null;
160let tintLitSpriteShader = null;
161
162function getSpriteLightingShader ()
163{
164 if (!spriteLightingShader)
165 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
166 return spriteLightingShader;
167}
168
169function getAtlasLightingShader ()
170{
171 if (!atlasLightingShader)
172 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
173 return atlasLightingShader;
174}
175
176function getWaterGroundShader ()
177{
178 if (!waterGroundShader)
179 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
180 return waterGroundShader;
181}
182
183function getTintLitSpriteShader ()
184{
185 if (!tintLitSpriteShader)
186 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
187 return tintLitSpriteShader;
188}
189
190export class WorldView
191{
192 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
193 {
194 this.game = game;
195 this.scene = scene;
196 this.catalog = catalog;
197 this.preview = null;
198 this.zoom = 2;
199 this.chunks = new Map();
200 this.bakedChunks = new Map();
201 this.tiles = new Map();
202 this.entities = new Map();
203 this.groundItems = new Map();
204 this.edges = new Map();
205 this.localEntityId = null;
206 this.localBlind = false;
207 /** @type {"soft"|"simple"} */
208 this.lightingMode = "soft";
209 /** @type {boolean} */
210 this.bloomEnabled = true;
211 this.settings = { ...DEFAULT_WORLD_SETTINGS };
212 this.worldHour = 12;
213 /** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */
214 this.worldSeason = seasonIdAt();
215 this.nightPreview = null;
216 this.followPlayer = true;
217 this.dynamicLights = [];
218 this.swipes = [];
219 this.damageFloats = [];
220 this.damageNumbersEl = document.getElementById("damage-numbers");
221 this.skillLevelFloats = [];
222 this.skillLevelFloatsEl = document.getElementById("skill-level-floats");
223 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
224 this.editorSpawners = new Map();
225 this.spawnRangeHighlight = null;
226 this.wanderRangeHighlight = null;
227 this.#syncBloomLayer();
228 }
229
230 setSettings (settings)
231 {
232 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
233 this.#syncBloomLayer();
234 }
235
236 /**
237 * Client graphics prefs (lighting Soft/Simple, bloom On/Off).
238 * @param {{ lighting?: string, bloom?: string }} prefs
239 */
240 setGraphicsPrefs (prefs)
241 {
242 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
243 { this.lightingMode = prefs.lighting; }
244 if (prefs?.bloom === "off" || prefs?.bloom === "on")
245 {
246 const enabled = prefs.bloom !== "off";
247 if (enabled !== this.bloomEnabled)
248 {
249 this.bloomEnabled = enabled;
250 this.#syncBloomLayer();
251 }
252 else
253 { this.bloomEnabled = enabled; }
254 }
255 }
256
257 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
258 setWorldSeason (season)
259 {
260 const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
261 ? season
262 : seasonIdAt();
263 if (next === this.worldSeason)
264 { return; }
265 this.worldSeason = next;
266 this.#rebakeAllChunks();
267 }
268
269 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
270 {
271 this.localEntityId = entityId;
272 this.#upsertEntity({
273 entityId,
274 characterId,
275 tileX,
276 tileY,
277 gait,
278 sex,
279 firstName,
280 lastName,
281 layers: layers ?? undefined,
282 ...(health != null ? { health } : {}),
283 ...(maxHealth != null ? { maxHealth } : {})
284 });
285 }
286
287 applySnapshot (snapshot)
288 {
289 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
290 this.chunks.set(key, snapshot);
291 this.#rebuildChunk(snapshot);
292 this.#redrawPreview();
293 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
294 if (snapshot.staticOnly)
295 {
296 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
297 this.#rebuildAllEdges();
298 return;
299 }
300 for (const entity of snapshot.entities ?? [])
301 { this.#upsertEntity(entity); }
302 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
303 for (const [id, item] of [...this.groundItems.entries()])
304 {
305 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
306 { this.despawnGroundItem(id); }
307 }
308 for (const item of snapshot.groundItems ?? [])
309 { this.upsertGroundItem(item); }
310 this.#rebuildAllEdges();
311 }
312
313 #stripChunkDynamic (chunkX, chunkY)
314 {
315 for (const [id, item] of [...this.groundItems.entries()])
316 {
317 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
318 { this.despawnGroundItem(id); }
319 }
320 for (const [id, entity] of [...this.entities.entries()])
321 {
322 if (id === this.localEntityId)
323 { continue; }
324 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
325 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
326 { this.despawnEntity(id); }
327 }
328 }
329
330 removeChunk (chunkX, chunkY)
331 {
332 const key = `${chunkX},${chunkY}`;
333 this.chunks.delete(key);
334 this.#destroyBakedChunk(key);
335 this.#destroyEdges(key);
336 const prefix = `${chunkX},${chunkY}:`;
337 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
338 {
339 if (!spawnerKey.startsWith(prefix))
340 { continue; }
341 entry.object?.destroy();
342 this.editorSpawners.delete(spawnerKey);
343 }
344 for (const [tileKey, objects] of [...this.tiles.entries()])
345 {
346 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
347 {
348 objects.ground?.destroy();
349 objects.groundBloom?.destroy();
350 objects.block?.destroy();
351 objects.blockBloom?.destroy();
352 this.tiles.delete(tileKey);
353 }
354 }
355 for (const [id, item] of [...this.groundItems.entries()])
356 {
357 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
358 { this.despawnGroundItem(id); }
359 }
360 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
361 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
362 for (const [id, entity] of [...this.entities.entries()])
363 {
364 if (id === this.localEntityId)
365 { continue; }
366 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
367 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
368 { this.despawnEntity(id); }
369 }
370 this.#rebuildAllEdges();
371 }
372
373 setChunkOpen (chunkX, chunkY, open)
374 {
375 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
376 if (!snapshot)
377 { return; }
378 snapshot.open = !!open;
379 this.#rebuildAllEdges();
380 }
381
382 spawnEntity (payload)
383 {
384 this.#upsertEntity(payload);
385 }
386
387 moveEntity (payload)
388 {
389 const existing = this.entities.get(payload.entityId);
390 if (!existing)
391 {
392 this.#upsertEntity(payload);
393 return;
394 }
395 const size = this.tileSize();
396 existing.fromX = existing.visualX;
397 existing.fromY = existing.visualY;
398 existing.shadeFromTileX = existing.tileX;
399 existing.shadeFromTileY = existing.tileY;
400 existing.tileX = payload.tileX;
401 existing.tileY = payload.tileY;
402 existing.gait = payload.gait;
403 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
404 if (payload.worldX != null && payload.worldY != null)
405 {
406 existing.worldX = payload.worldX;
407 existing.worldY = payload.worldY;
408 existing.targetX = payload.worldX * size;
409 existing.targetY = payload.worldY * size;
410 }
411 else
412 {
413 const pivot = tilePivot(payload.tileX, payload.tileY, size);
414 existing.targetX = pivot.x;
415 existing.targetY = pivot.y;
416 }
417 existing.lerpStarted = performance.now();
418 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
419 }
420
421 despawnEntity (entityId)
422 {
423 const existing = this.entities.get(entityId);
424 if (!existing)
425 { return; }
426 existing.object?.destroy();
427 existing.hpBar?.destroy();
428 for (const overlay of existing.overlays ?? [])
429 { overlay.destroy(); }
430 for (const overlay of existing.bloomOverlays ?? [])
431 { overlay.destroy(); }
432 this.entities.delete(entityId);
433 }
434
435 updateEntityHealth (entityId, health, maxHealth)
436 {
437 const entity = this.entities.get(entityId);
438 if (!entity)
439 { return; }
440 entity.health = health;
441 entity.maxHealth = maxHealth;
442 this.#syncHpBar(entity);
443 }
444
445 flashDamage (entityId)
446 {
447 const entity = this.entities.get(entityId);
448 if (!entity)
449 { return; }
450 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
451 }
452
453 spawnDamageNumber (entityId, damage)
454 {
455 const amount = damage | 0;
456 if (amount <= 0)
457 { return; }
458 this.damageFloats.push({
459 entityId,
460 damage: amount,
461 started: performance.now()
462 });
463 }
464
465 spawnSkillLevelUp (entityId, payload)
466 {
467 const level = payload?.level | 0;
468 if (level <= 0 || !payload?.icon)
469 { return; }
470 this.skillLevelFloats.push({
471 entityId,
472 level,
473 icon: payload.icon,
474 displayName: payload.displayName ?? payload.skillId ?? "",
475 started: performance.now()
476 });
477 }
478
479 setAppearance (payload)
480 {
481 const existing = this.entities.get(payload.entityId);
482 if (!existing)
483 { return; }
484 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
485 if (payload.visualScale != null)
486 { existing.visualScale = Number(payload.visualScale) || 1; }
487 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
488 this.#placeEntity(existing);
489 }
490
491 upsertGroundItem (payload)
492 {
493 const size = this.tileSize();
494 const pivot = tilePivot(payload.tileX, payload.tileY, size);
495 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
496 const spriteName = potion
497 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
498 : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance));
499 let item = this.groundItems.get(payload.groundItemId);
500 if (!item)
501 {
502 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
503 this.scene.addObject(object);
504 item = { object };
505 this.groundItems.set(payload.groundItemId, item);
506 }
507 else if (item.object && this.game.images[spriteName])
508 { item.object.image = this.game.images[spriteName]; }
509 item.groundItemId = payload.groundItemId;
510 item.tileX = payload.tileX;
511 item.tileY = payload.tileY;
512 item.itemId = payload.itemId;
513 item.quantity = payload.quantity;
514 item.displayName = payload.displayName;
515 item.sprite = spriteName;
516 item.instance = payload.instance ?? null;
517 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
518 item.tintColor = resolveItemTint(stack, itemDefinition(payload.itemId));
519 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
520 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
521 }
522
523 despawnGroundItem (groundItemId)
524 {
525 const item = this.groundItems.get(groundItemId);
526 if (!item)
527 { return; }
528 item.object?.destroy();
529 this.groundItems.delete(groundItemId);
530 }
531
532 groundItemAtTile (tileX, tileY)
533 {
534 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
535 }
536
537 groundItemsAtTile (tileX, tileY)
538 {
539 const items = [];
540 for (const item of this.groundItems.values())
541 {
542 if (item.tileX === tileX && item.tileY === tileY)
543 { items.push(item); }
544 }
545 return items;
546 }
547
548 entitiesAtTile (tileX, tileY)
549 {
550 const matches = [];
551 for (const entity of this.entities.values())
552 {
553 if (entity.tileX === tileX && entity.tileY === tileY)
554 { matches.push(entity); }
555 }
556 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
557 return matches;
558 }
559
560 setZoom (zoom, limits = { min: 2, max: 4 })
561 {
562 const min = limits.min ?? 1;
563 const max = limits.max ?? 4;
564 this.zoom = Math.min(max, Math.max(min, zoom));
565 for (const snapshot of this.chunks.values())
566 {
567 this.#layoutBakedChunk(snapshot);
568 this.#rebuildChunk(snapshot);
569 }
570 const size = this.tileSize();
571 for (const entity of this.entities.values())
572 {
573 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
574 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
575 entity.fromX = entity.visualX;
576 entity.fromY = entity.visualY;
577 entity.targetX = entity.visualX;
578 entity.targetY = entity.visualY;
579 entity.lerpStarted = null;
580 this.#placeEntity(entity);
581 }
582 for (const item of this.groundItems.values())
583 {
584 const pivot = tilePivot(item.tileX, item.tileY, size);
585 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
586 }
587 this.#rebuildAllEdges();
588 this.#redrawPreview();
589 this.#relayoutEditorSpawners();
590 this.#relayoutSpawnRangeHighlight();
591 applyNearestToAllTextures(this.scene, this.game.images);
592 }
593
594 tileSize ()
595 {
596 return SPRITE_SIZE_PX * this.zoom;
597 }
598
599 screenToTile (mouseX, mouseY)
600 {
601 const size = this.tileSize();
602 const worldX = mouseX - this.scene.cameraPosition.x;
603 const worldY = mouseY - this.scene.cameraPosition.y;
604 return {
605 tileX: Math.floor(worldX / size),
606 tileY: Math.floor(worldY / size)
607 };
608 }
609
610 entityAtScreen (mouseX, mouseY)
611 {
612 let best = null;
613 let bestLayer = -Infinity;
614 for (const entity of this.entities.values())
615 {
616 const box = this.#entityScreenBox(entity);
617 if (!box)
618 { continue; }
619 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
620 {
621 const layer = entity.object?.layer ?? 0;
622 if (layer >= bestLayer)
623 {
624 best = entity;
625 bestLayer = layer;
626 }
627 }
628 }
629 return best;
630 }
631
632 nametagAnchor (entity)
633 {
634 const box = this.#entityScreenBox(entity);
635 if (!box)
636 { return null; }
637 return { x: (box.left + box.right) / 2, y: box.top };
638 }
639
640 #entityScreenBox (entity)
641 {
642 const object = entity?.object;
643 if (!object)
644 { return null; }
645 const size = object.transform.size;
646 const x = object.transform.position.x + this.scene.cameraPosition.x;
647 const y = object.transform.position.y + this.scene.cameraPosition.y;
648 return {
649 left: x - size.x / 2,
650 right: x + size.x / 2,
651 top: y - size.y / 2,
652 bottom: y + size.y / 2
653 };
654 }
655
656 update (deltaTime)
657 {
658 const now = performance.now();
659 const size = this.tileSize();
660 this.#refreshStackOffsets();
661 for (const entity of this.entities.values())
662 {
663 const target = entity.targetX != null && entity.targetY != null
664 ? { x: entity.targetX, y: entity.targetY }
665 : tilePivot(entity.tileX, entity.tileY, size);
666 if (entity.lerpStarted != null)
667 {
668 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
669 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
670 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
671 if (t >= 1)
672 { entity.lerpStarted = null; }
673 }
674 else
675 {
676 entity.visualX = target.x;
677 entity.visualY = target.y;
678 }
679 this.#updateShove(entity, now, size);
680 this.#expireGatherToolOverlay(entity, now);
681 this.#placeEntity(entity, now);
682 }
683
684 this.#updateSwipes(now);
685 this.#updateDamageNumbers(now);
686 this.#updateSkillLevelFloats(now);
687 this.#centerCamera();
688 this.#cullOffscreenDrawables();
689 this.#updateShade(deltaTime);
690 }
691
692 /**
693 * Evenly space stacked entities on a circle around the tile centre.
694 * Stable assignment by entityId; free-flight entities stay unshifted.
695 */
696 #refreshStackOffsets ()
697 {
698 const byTile = new Map();
699 for (const entity of this.entities.values())
700 {
701 if (entity.freeFlight)
702 {
703 entity.stackOffsetX = 0;
704 entity.stackOffsetY = 0;
705 continue;
706 }
707 const key = `${entity.tileX},${entity.tileY}`;
708 let list = byTile.get(key);
709 if (!list)
710 {
711 list = [];
712 byTile.set(key, list);
713 }
714 list.push(entity);
715 }
716 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
717 for (const list of byTile.values())
718 {
719 if (list.length <= 1)
720 {
721 for (const entity of list)
722 {
723 entity.stackOffsetX = 0;
724 entity.stackOffsetY = 0;
725 }
726 continue;
727 }
728 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
729 const n = list.length;
730 for (let i = 0; i < n; i++)
731 {
732 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
733 list[i].stackOffsetX = Math.cos(angle) * radius;
734 list[i].stackOffsetY = Math.sin(angle) * radius;
735 }
736 }
737 }
738
739 #updateShove (entity, now, tileSize)
740 {
741 if (!entity.shove)
742 {
743 entity.shoveOffsetX = 0;
744 entity.shoveOffsetY = 0;
745 return;
746 }
747 const elapsed = now - entity.shove.started;
748 const t = Math.min(1, elapsed / entity.shove.durationMs);
749 const maxDist = tileSize * SHOVE_TILE_FRACTION;
750 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
751 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
752 const dist = Math.hypot(dx, dy) || 1;
753 const ux = dx / dist;
754 const uy = dy / dist;
755 let phase;
756 if (t < 0.45)
757 { phase = t / 0.45; }
758 else
759 { phase = 1 - (t - 0.45) / 0.55; }
760 entity.shoveOffsetX = ux * maxDist * phase;
761 entity.shoveOffsetY = uy * maxDist * phase;
762 if (t >= 1)
763 { entity.shove = null; }
764 }
765
766 spawnCombatSwing (payload)
767 {
768 const attacker = this.entities.get(payload.attackerId);
769 const target = this.entities.get(payload.targetId);
770 if (!attacker || !target)
771 { return; }
772 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
773 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
774 const tx = target.visualX + (target.stackOffsetX ?? 0);
775 const ty = target.visualY + (target.stackOffsetY ?? 0);
776 this.#applyShove(attacker, tx, ty);
777 const midX = (ax + tx) / 2;
778 const midY = (ay + ty) / 2;
779 const sortY = Math.max(ay, ty) + 0.02;
780 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
781 const spriteName = "fx:melee-swipe:melee-swipe";
782 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
783 if (object.transform)
784 { object.transform.rotation = angle; }
785 this.scene.addObject(object);
786 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
787 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
788 this.swipes.push({
789 object,
790 until: performance.now() + 500,
791 fromTileX: payload.fromTileX,
792 fromTileY: payload.fromTileY,
793 tileX: payload.tileX,
794 tileY: payload.tileY
795 });
796 }
797
798 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
799 spawnGatherSwing (payload)
800 {
801 const attacker = this.entities.get(payload.attackerId);
802 if (!attacker)
803 { return; }
804 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
805 this.#applyShove(attacker, pivot.x, pivot.y);
806 if (payload.toolItemId != null)
807 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
808 }
809
810 #applyShove (entity, targetVisualX, targetVisualY)
811 {
812 entity.shove = {
813 startVisualX: entity.visualX,
814 startVisualY: entity.visualY,
815 targetVisualX,
816 targetVisualY,
817 started: performance.now(),
818 durationMs: SHOVE_MS
819 };
820 }
821
822 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
823 spawnPhysicalProjectileFx (payload)
824 {
825 const spriteName = payload.sprite ?? "fx:projectile:projectile";
826 const image = this.game.images[spriteName];
827 if (!image)
828 { return; }
829 const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
830 const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
831 const midX = (fromPivot.x + toPivot.x) / 2;
832 const midY = (fromPivot.y + toPivot.y) / 2;
833 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
834 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
835 const object = new GameObject(0, 0, image, SORT_FX);
836 if (object.transform)
837 { object.transform.rotation = angle; }
838 this.scene.addObject(object);
839 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
840 this.#applyPhysicalCombatFxDarkness(
841 object,
842 payload.fromTileX,
843 payload.fromTileY,
844 payload.tileX,
845 payload.tileY
846 );
847 this.swipes.push({
848 object,
849 until: performance.now() + (payload.durationMs ?? 500),
850 fromTileX: payload.fromTileX,
851 fromTileY: payload.fromTileY,
852 tileX: payload.tileX,
853 tileY: payload.tileY
854 });
855 }
856
857 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
858 {
859 this.dynamicLights.push({
860 tileX: Math.floor(worldX),
861 tileY: Math.floor(worldY),
862 range: radiusTiles,
863 intensity,
864 until: performance.now() + durationMs
865 });
866 }
867
868 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
869 {
870 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
871 if (!snapshot)
872 { return; }
873 const index = localY * CHUNK_SIZE + localX;
874 if (ground !== undefined)
875 { snapshot.grounds[index] = ground; }
876 if (block !== undefined)
877 { snapshot.blocks[index] = block; }
878 if (light !== undefined)
879 { snapshot.light[index] = light; }
880 this.#rebuildChunk(snapshot);
881 }
882
883 /**
884 * Editor-only mob markers for authored spawners (invisible during play).
885 * @param {number} chunkX
886 * @param {number} chunkY
887 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
888 * @param {(mobTypeId: string) => string} resolveSprite
889 */
890 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
891 {
892 const prefix = `${chunkX},${chunkY}:`;
893 for (const [key, entry] of [...this.editorSpawners.entries()])
894 {
895 if (!key.startsWith(prefix))
896 { continue; }
897 entry.object?.destroy();
898 this.editorSpawners.delete(key);
899 }
900 for (const spawner of spawners ?? [])
901 {
902 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
903 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
904 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
905 if (!spriteName)
906 { continue; }
907 const key = `${prefix}${spawner.localX},${spawner.localY}`;
908 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
909 if (!object)
910 { continue; }
911 object.renderer.alpha = 0.85;
912 const pivot = tilePivot(tileX, tileY, this.tileSize());
913 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
914 this.#markUnlit(object);
915 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
916 }
917 }
918
919 clearEditorSpawners ()
920 {
921 for (const entry of this.editorSpawners.values())
922 { entry.object?.destroy(); }
923 this.editorSpawners.clear();
924 }
925
926 #relayoutEditorSpawners ()
927 {
928 const size = this.tileSize();
929 for (const entry of this.editorSpawners.values())
930 {
931 if (!entry.object)
932 { continue; }
933 const pivot = tilePivot(entry.tileX, entry.tileY, size);
934 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
935 }
936 }
937
938 /**
939 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
940 */
941 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
942 {
943 const spawnRadius = Math.max(0, spawnRange | 0);
944 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
945 if (this.spawnRangeHighlight
946 && this.wanderRangeHighlight
947 && this.spawnRangeHighlight.tileX === tileX
948 && this.spawnRangeHighlight.tileY === tileY
949 && this.spawnRangeHighlight.range === spawnRadius
950 && this.wanderRangeHighlight.range === wanderRadius)
951 {
952 this.#relayoutSpawnRangeHighlight();
953 return;
954 }
955 this.clearSpawnRangeHighlight();
956 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
957 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
958 if (wanderObject)
959 {
960 this.#markUnlit(wanderObject);
961 wanderObject.renderer.alpha = 1;
962 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
963 }
964 if (spawnObject)
965 {
966 this.#markUnlit(spawnObject);
967 spawnObject.renderer.alpha = 1;
968 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
969 }
970 this.#relayoutSpawnRangeHighlight();
971 }
972
973 clearSpawnRangeHighlight ()
974 {
975 this.spawnRangeHighlight?.object?.destroy();
976 this.wanderRangeHighlight?.object?.destroy();
977 this.spawnRangeHighlight = null;
978 this.wanderRangeHighlight = null;
979 }
980
981 #relayoutSpawnRangeHighlight ()
982 {
983 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
984 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
985 }
986
987 #layoutRangeOverlay (highlight, layer)
988 {
989 if (!highlight?.object)
990 { return; }
991 const size = this.tileSize();
992 const side = (2 * highlight.range + 1) * size;
993 const left = (highlight.tileX - highlight.range) * size;
994 const top = (highlight.tileY - highlight.range) * size;
995 highlight.object.transform.position.x = left + side / 2;
996 highlight.object.transform.position.y = top + side / 2;
997 highlight.object.transform.size = new vector(side, side);
998 highlight.object.layer = layer;
999 this.#markSortDirty();
1000 }
1001
1002 setTilePreview (tileX, tileY, override)
1003 {
1004 const previous = this.preview;
1005 this.preview = { tileX, tileY, ...override };
1006 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1007 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1008 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1009 if (snapshot)
1010 { this.#rebuildChunk(snapshot); }
1011 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1012 {
1013 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1014 if (prevSnapshot && prevSnapshot !== snapshot)
1015 { this.#rebuildChunk(prevSnapshot); }
1016 }
1017 }
1018
1019 clearTilePreview ()
1020 {
1021 const previous = this.preview;
1022 this.preview = null;
1023 if (previous)
1024 {
1025 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1026 if (snapshot)
1027 { this.#rebuildChunk(snapshot); }
1028 }
1029 }
1030
1031 #lerpMs (gait)
1032 {
1033 const walk = this.settings.walkTilesPerSecond || 2;
1034 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
1035 return seconds * 1000;
1036 }
1037
1038 #centerCamera ()
1039 {
1040 if (!this.followPlayer)
1041 { return; }
1042 const local = this.entities.get(this.localEntityId);
1043 if (!local)
1044 { return; }
1045 const x = local.visualX + (local.stackOffsetX ?? 0);
1046 const y = local.visualY + (local.stackOffsetY ?? 0);
1047 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
1048 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
1049 }
1050
1051 /**
1052 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
1053 * Tiles fully outside this rect are not drawn.
1054 */
1055 #drawBounds ()
1056 {
1057 const pad = this.tileSize() * 0.5;
1058 const camX = this.scene.cameraPosition.x;
1059 const camY = this.scene.cameraPosition.y;
1060 const w = this.scene.real_size.x;
1061 const h = this.scene.real_size.y;
1062 return {
1063 left: -camX - pad,
1064 right: -camX + w + pad,
1065 top: -camY - pad,
1066 bottom: -camY + h + pad
1067 };
1068 }
1069
1070 #rectIntersects (left, top, right, bottom, bounds)
1071 {
1072 return right >= bounds.left
1073 && left <= bounds.right
1074 && bottom >= bounds.top
1075 && top <= bounds.bottom;
1076 }
1077
1078 #setRendererVisible (object, visible)
1079 {
1080 if (object?.renderer)
1081 { object.renderer.visible = !!visible; }
1082 }
1083
1084 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
1085 #cullOffscreenDrawables ()
1086 {
1087 const bounds = this.#drawBounds();
1088 const size = this.tileSize();
1089
1090 for (const baked of this.bakedChunks.values())
1091 {
1092 const left = baked.chunkX * CHUNK_SIZE * size;
1093 const top = baked.chunkY * CHUNK_SIZE * size;
1094 const chunkPx = CHUNK_SIZE * size;
1095 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
1096 this.#setRendererVisible(baked.groundObject, chunkVisible);
1097 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
1098 baked._inViewport = chunkVisible;
1099 for (let row = 0; row < CHUNK_SIZE; row++)
1100 {
1101 const rowTop = top + row * size;
1102 const rowVisible = chunkVisible && this.#rectIntersects(
1103 left, rowTop, left + chunkPx, rowTop + size, bounds
1104 );
1105 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
1106 }
1107 }
1108
1109 for (const objects of this.tiles.values())
1110 {
1111 const left = objects.tileX * size;
1112 const top = objects.tileY * size;
1113 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
1114 objects._inViewport = visible;
1115 this.#setRendererVisible(objects.ground, visible);
1116 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
1117 this.#setRendererVisible(objects.block, visible);
1118 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
1119 if (objects.waterEdges)
1120 {
1121 for (const edge of Object.values(objects.waterEdges))
1122 { this.#setRendererVisible(edge, visible); }
1123 }
1124 }
1125 }
1126
1127 #upsertEntity (payload)
1128 {
1129 const size = this.tileSize();
1130 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1131 let entity = this.entities.get(payload.entityId);
1132 if (!entity)
1133 {
1134 const spriteName = payload.layers?.[0]?.sprite
1135 ?? payload.sprite
1136 ?? bodySpriteName(payload.sex);
1137 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
1138 this.scene.addObject(object);
1139 this.#startIdleAnimation(object);
1140 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
1141 this.entities.set(payload.entityId, entity);
1142 }
1143 entity.entityId = payload.entityId;
1144 entity.tileX = payload.tileX;
1145 entity.tileY = payload.tileY;
1146 entity.gait = payload.gait;
1147 entity.sex = payload.sex ?? entity.sex;
1148 entity.characterId = payload.characterId ?? entity.characterId ?? null;
1149 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1150 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
1151 entity.canFight = payload.canFight != null
1152 ? !!payload.canFight
1153 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1154 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1155 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1156 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1157 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
1158 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1159 if (payload.visualScale != null)
1160 { entity.visualScale = Number(payload.visualScale) || 1; }
1161 else if (entity.visualScale == null)
1162 { entity.visualScale = 1; }
1163 if (payload.health != null)
1164 { entity.health = payload.health; }
1165 if (payload.maxHealth != null)
1166 { entity.maxHealth = payload.maxHealth; }
1167 if (payload.firstName)
1168 { entity.firstName = payload.firstName; }
1169 if (payload.lastName)
1170 { entity.lastName = payload.lastName; }
1171 entity.firstName = entity.firstName ?? "";
1172 entity.lastName = entity.lastName ?? "";
1173 if (payload.worldX != null && payload.worldY != null)
1174 {
1175 entity.worldX = payload.worldX;
1176 entity.worldY = payload.worldY;
1177 entity.visualX = payload.worldX * size;
1178 entity.visualY = payload.worldY * size;
1179 entity.targetX = entity.visualX;
1180 entity.targetY = entity.visualY;
1181 }
1182 else
1183 {
1184 entity.visualX = pivot.x;
1185 entity.visualY = pivot.y;
1186 entity.targetX = pivot.x;
1187 entity.targetY = pivot.y;
1188 }
1189 entity.fromX = entity.visualX;
1190 entity.fromY = entity.visualY;
1191 if (payload.layers)
1192 { this.#applyLayers(entity, payload.layers); }
1193 this.#syncHpBar(entity);
1194 this.#placeEntity(entity, performance.now());
1195 }
1196
1197 #applyLayers (entity, layers)
1198 {
1199 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
1200 this.#rebuildOverlays(entity);
1201 }
1202
1203 #setGatherToolOverlay (entity, toolItemId)
1204 {
1205 entity.gatherToolItemId = toolItemId;
1206 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
1207 this.#rebuildOverlays(entity);
1208 this.#placeEntity(entity, performance.now());
1209 }
1210
1211 #expireGatherToolOverlay (entity, now)
1212 {
1213 if (entity.gatherToolItemId == null)
1214 { return; }
1215 if ((entity.gatherToolUntil ?? 0) > now)
1216 { return; }
1217 entity.gatherToolItemId = null;
1218 entity.gatherToolUntil = 0;
1219 this.#rebuildOverlays(entity);
1220 }
1221
1222 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
1223 #layersForDisplay (entity)
1224 {
1225 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
1226 const toolId = entity.gatherToolItemId;
1227 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
1228 { return layers; }
1229 const equip = itemEquipSprite(toolId);
1230 if (!equip || !this.game.images[equip])
1231 { return layers; }
1232 const replacement = {
1233 sprite: equip,
1234 itemId: toolId,
1235 tint: resolveEquipTint(toolId)
1236 };
1237 for (let index = layers.length - 1; index >= 1; index--)
1238 {
1239 const def = itemDefinition(layers[index].itemId);
1240 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
1241 {
1242 layers[index] = replacement;
1243 return layers;
1244 }
1245 }
1246 layers.push(replacement);
1247 return layers;
1248 }
1249
1250 #rebuildOverlays (entity)
1251 {
1252 const layers = this.#layersForDisplay(entity);
1253 const base = layers[0]?.sprite
1254 ?? bodySpriteName(entity.sex);
1255 if (this.game.images[base])
1256 {
1257 entity.object.renderer.sprite = this.game.images[base];
1258 this.#startIdleAnimation(entity.object);
1259 }
1260 for (const overlay of entity.overlays ?? [])
1261 { overlay.destroy(); }
1262 for (const overlay of entity.bloomOverlays ?? [])
1263 { overlay.destroy(); }
1264 entity.overlays = [];
1265 entity.overlayTints = [];
1266 entity.bloomOverlays = [];
1267 for (const layer of layers.slice(1))
1268 {
1269 const image = this.game.images[layer.sprite];
1270 if (!image)
1271 { continue; }
1272 const object = new GameObject(0, 0, image, SORT_ENTITY);
1273 this.scene.addObject(object);
1274 entity.overlays.push(object);
1275 entity.overlayTints.push(
1276 layer.tint
1277 ? normalizeRgb(layer.tint)
1278 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
1279 );
1280 const bloomName = bloomCompanionName(layer.sprite);
1281 const bloomImage = this.game.images[bloomName];
1282 if (!bloomImage)
1283 { continue; }
1284 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
1285 bloom.renderer.layer = RENDER_LAYER_BLOOM;
1286 this.#markUnlit(bloom);
1287 this.scene.addObject(bloom);
1288 entity.bloomOverlays.push(bloom);
1289 }
1290 }
1291
1292 #placeEntity (entity, now = performance.now())
1293 {
1294 const zoom = this.zoom;
1295 const offsetX = entity.shoveOffsetX ?? 0;
1296 const offsetY = entity.shoveOffsetY ?? 0;
1297 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
1298 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
1299 let walkTilt = 0;
1300 if (entity.lerpStarted != null)
1301 {
1302 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
1303 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
1304 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
1305 walkTilt = Math.sin(cycles) * tilt;
1306 }
1307 const flashStrength = (entity.damageFlashUntil ?? 0) > now
1308 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
1309 : 0;
1310 const tileShade = this.#entityShadeAlpha(entity, now);
1311 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
1312
1313 entity.object.transform.rotation = walkTilt;
1314 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
1315 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY, entity.visualScale ?? 1);
1316 for (let index = 0; index < (entity.overlays ?? []).length; index++)
1317 {
1318 const overlay = entity.overlays[index];
1319 const overlaySortY = entity.visualY + 0.5 * (index + 1);
1320 overlay.transform.rotation = walkTilt;
1321 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
1322 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
1323 }
1324 for (const overlay of entity.bloomOverlays ?? [])
1325 {
1326 this.#setRendererVisible(overlay, this.bloomEnabled);
1327 if (!this.bloomEnabled)
1328 { continue; }
1329 overlay.transform.rotation = walkTilt;
1330 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1331 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
1332 }
1333 this.#placeHpBar(entity, pivotX, pivotY);
1334 }
1335
1336 #markUnlit (object)
1337 {
1338 if (!object?.renderer)
1339 { return; }
1340 object._lit = false;
1341 object.renderer.shader = null;
1342 object.renderer.shaderUniforms = null;
1343 object.renderer.secondaryMap = null;
1344 }
1345
1346 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
1347 {
1348 if (!object?.renderer || object._lit === false)
1349 { return; }
1350 object._lit = true;
1351 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1352 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1353 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1354 const tint = tintColor ? normalizeRgb(tintColor) : null;
1355 if (tint)
1356 {
1357 object.renderer.shader = getTintLitSpriteShader();
1358 object.renderer.shaderUniforms = {
1359 u_darkness: dark,
1360 u_strength: flash,
1361 u_wade: wade ? 1 : 0,
1362 u_spriteHeight: height,
1363 u_useTint: 1,
1364 u_tintColor: [tint.r, tint.g, tint.b]
1365 };
1366 }
1367 else
1368 {
1369 object.renderer.shader = getSpriteLightingShader();
1370 object.renderer.shaderUniforms = {
1371 u_darkness: dark,
1372 u_strength: flash,
1373 u_wade: wade ? 1 : 0,
1374 u_spriteHeight: height
1375 };
1376 }
1377 object.renderer.secondaryMap = null;
1378 }
1379
1380 #syncGroundItemSprite (item, darkness)
1381 {
1382 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
1383 }
1384
1385 #groundTypeAt (tileX, tileY)
1386 {
1387 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1388 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1389 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1390 if (!snapshot)
1391 { return null; }
1392 const localX = tileX - chunkX * CHUNK_SIZE;
1393 const localY = tileY - chunkY * CHUNK_SIZE;
1394 const index = localY * CHUNK_SIZE + localX;
1395 return normalizeGround(snapshot.grounds?.[index]).typeId;
1396 }
1397
1398 #waterCoastEdges (tileX, tileY)
1399 {
1400 const season = this.worldSeason;
1401 return {
1402 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
1403 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
1404 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
1405 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
1406 };
1407 }
1408
1409 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
1410 {
1411 if (!object?.renderer)
1412 { return; }
1413 const lit = corners ?? {
1414 nw: fallbackLit,
1415 ne: fallbackLit,
1416 sw: fallbackLit,
1417 se: fallbackLit
1418 };
1419 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
1420 object._lit = true;
1421 object.renderer.shader = getWaterGroundShader();
1422 object.renderer.secondaryMap = null;
1423 object.renderer.shaderUniforms = {
1424 u_ambientDark: dark,
1425 u_litNW: lit.nw,
1426 u_litNE: lit.ne,
1427 u_litSW: lit.sw,
1428 u_litSE: lit.se,
1429 u_time: timeSec,
1430 u_edgeN: edges?.n ?? 0,
1431 u_edgeE: edges?.e ?? 0,
1432 u_edgeS: edges?.s ?? 0,
1433 u_edgeW: edges?.w ?? 0
1434 };
1435 }
1436
1437 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
1438 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
1439 {
1440 if (!objects?.ground)
1441 { return; }
1442 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
1443 {
1444 objects.waterEdges = null;
1445 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
1446 return;
1447 }
1448 const fallbackLit = ambientDark > 0
1449 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
1450 : 1;
1451 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
1452 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
1453 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
1454 const localX = objects.tileX - chunkX * CHUNK_SIZE;
1455 const localY = objects.tileY - chunkY * CHUNK_SIZE;
1456 let litCorners = null;
1457 if (chunkBaked)
1458 {
1459 if (this.lightingMode === "simple")
1460 {
1461 const gridW = CHUNK_SIZE + 2;
1462 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
1463 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
1464 }
1465 else
1466 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
1467 }
1468 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1469 this.#syncWaterGroundSprite(
1470 objects.ground,
1471 litCorners,
1472 ambientDark,
1473 objects.waterEdges,
1474 timeSec,
1475 fallbackLit
1476 );
1477 }
1478
1479 #ambientDarkness ()
1480 {
1481 const hour = this.nightPreview ?? this.worldHour;
1482 let dark = nightFactor(hour, this.settings.nightDarkness);
1483 if (this.localBlind)
1484 { dark = Math.min(1, dark + 0.85); }
1485 return dark;
1486 }
1487
1488 setLocalBlind (blind)
1489 {
1490 this.localBlind = !!blind;
1491 }
1492
1493 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
1494 #blindVisionLight ()
1495 {
1496 if (!this.localBlind)
1497 { return null; }
1498 const local = this.entities.get(this.localEntityId);
1499 if (!local)
1500 { return null; }
1501 const tileSize = this.tileSize();
1502 return {
1503 tileX: Math.floor(local.visualX / tileSize),
1504 tileY: Math.floor(local.visualY / tileSize),
1505 range: 2.25,
1506 intensity: 1
1507 };
1508 }
1509
1510 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
1511 {
1512 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
1513 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
1514 this.#syncLitSprite(object, (fromAlpha + toAlpha) / 2);
1515 }
1516
1517 #syncHpBar (entity)
1518 {
1519 const current = entity.health;
1520 const max = entity.maxHealth;
1521 const show = current != null
1522 && max != null
1523 && max > 0
1524 && current < max;
1525 if (!show)
1526 {
1527 entity.hpBar?.destroy();
1528 entity.hpBar = null;
1529 entity.hpBarCanvas = null;
1530 return;
1531 }
1532 if (!entity.hpBarCanvas)
1533 {
1534 entity.hpBarCanvas = document.createElement("canvas");
1535 entity.hpBarCanvas.width = HP_BAR_W;
1536 entity.hpBarCanvas.height = HP_BAR_H;
1537 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
1538 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
1539 this.#markUnlit(entity.hpBar);
1540 this.scene.addObject(entity.hpBar);
1541 }
1542 drawHpBar(entity.hpBarCanvas, current, max);
1543 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
1544 }
1545
1546 #placeHpBar (entity, pivotX, pivotY)
1547 {
1548 if (!entity.hpBar)
1549 { return; }
1550 const sprite = entity.object?.renderer?.sprite;
1551 if (!sprite)
1552 { return; }
1553 const zoom = this.zoom;
1554 const drawH = sprite.height * zoom;
1555 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
1556 const spriteTop = centerY - drawH / 2;
1557 const barW = HP_BAR_W * zoom;
1558 const barH = HP_BAR_H * zoom;
1559 entity.hpBar.transform.position.x = pivotX;
1560 entity.hpBar.transform.position.y = spriteTop - barH / 2;
1561 entity.hpBar.transform.size = new vector(barW, barH);
1562 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
1563 this.#markSortDirty();
1564 }
1565
1566 #rebuildChunk (snapshot)
1567 {
1568 this.#bakeAndPlaceChunk(snapshot);
1569 const tall = new Set(
1570 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
1571 .map((entry) => `${entry.tileX},${entry.tileY}`)
1572 );
1573 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1574 {
1575 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1576 {
1577 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
1578 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
1579 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
1580 }
1581 }
1582 }
1583
1584 #rebakeAllChunks ()
1585 {
1586 for (const snapshot of this.chunks.values())
1587 { this.#rebuildChunk(snapshot); }
1588 }
1589
1590 #bakeAndPlaceChunk (snapshot)
1591 {
1592 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1593 const atlases = bakeChunkAtlases({
1594 snapshot,
1595 catalog: this.catalog,
1596 images: this.game.images,
1597 preview: this.preview,
1598 season: this.worldSeason
1599 });
1600 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
1601 let baked = this.bakedChunks.get(key);
1602 if (!baked)
1603 {
1604 const lightmapCanvas = makeLightmapCanvas(atlasPx);
1605 baked = {
1606 groundCanvas: atlases.ground,
1607 blockCanvases: atlases.blockRows,
1608 bloomCanvas: atlases.bloom,
1609 lightmapCanvas,
1610 groundImage: frameworkImageFromCanvas(atlases.ground),
1611 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
1612 bloomImage: frameworkImageFromCanvas(atlases.bloom),
1613 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
1614 groundObject: null,
1615 blockObjects: [],
1616 bloomObject: null,
1617 tallBlocks: atlases.tallBlocks,
1618 animatedGrounds: atlases.animatedGrounds,
1619 lightmapPixels: null
1620 };
1621 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
1622 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
1623 this.scene.addObject(baked.groundObject);
1624 for (let row = 0; row < CHUNK_SIZE; row++)
1625 {
1626 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
1627 this.#applyAtlasLighting(object, baked.lightmapImage, row);
1628 this.scene.addObject(object);
1629 baked.blockObjects.push(object);
1630 }
1631 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
1632 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
1633 this.#markUnlit(baked.bloomObject);
1634 this.scene.addObject(baked.bloomObject);
1635 this.bakedChunks.set(key, baked);
1636 }
1637 else
1638 {
1639 copyCanvas(atlases.ground, baked.groundCanvas);
1640 for (let row = 0; row < CHUNK_SIZE; row++)
1641 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
1642 copyCanvas(atlases.bloom, baked.bloomCanvas);
1643 invalidateCanvasTexture(this.scene, baked.groundCanvas);
1644 for (const canvas of baked.blockCanvases)
1645 { invalidateCanvasTexture(this.scene, canvas); }
1646 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1647 baked.tallBlocks = atlases.tallBlocks;
1648 baked.animatedGrounds = atlases.animatedGrounds;
1649 }
1650 baked.chunkX = snapshot.chunkX;
1651 baked.chunkY = snapshot.chunkY;
1652 this.#layoutBakedChunk(snapshot);
1653 }
1654
1655 #applyAtlasLighting (object, lightmapImage, lightRow)
1656 {
1657 if (!object?.renderer)
1658 { return; }
1659 object._lit = true;
1660 object.renderer.shader = getAtlasLightingShader();
1661 object.renderer.secondaryMap = lightmapImage;
1662 object.renderer.shaderUniforms = {
1663 u_ambientDark: 0,
1664 u_lightRow: lightRow
1665 };
1666 }
1667
1668 #layoutBakedChunk (snapshot)
1669 {
1670 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1671 const baked = this.bakedChunks.get(key);
1672 if (!baked)
1673 { return; }
1674 const size = this.tileSize();
1675 const left = snapshot.chunkX * CHUNK_SIZE * size;
1676 const top = snapshot.chunkY * CHUNK_SIZE * size;
1677 const chunkPx = CHUNK_SIZE * size;
1678 baked.groundObject.transform.position.x = left + chunkPx / 2;
1679 baked.groundObject.transform.position.y = top + chunkPx / 2;
1680 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
1681 baked.groundObject.layer = LAYER_GROUND;
1682
1683 for (let row = 0; row < CHUNK_SIZE; row++)
1684 {
1685 const object = baked.blockObjects[row];
1686 const rowY = top + row * size + size / 2;
1687 object.transform.position.x = left + chunkPx / 2;
1688 object.transform.position.y = rowY;
1689 object.transform.size = new vector(chunkPx, size);
1690 object.layer = ySortLayer(rowY, SORT_BLOCK);
1691 }
1692
1693 baked.bloomObject.transform.position.x = left + chunkPx / 2;
1694 baked.bloomObject.transform.position.y = top + chunkPx / 2;
1695 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
1696 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
1697 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
1698 this.#markSortDirty();
1699 setNearestFilter(this.scene, baked.groundCanvas);
1700 for (const canvas of baked.blockCanvases)
1701 { setNearestFilter(this.scene, canvas); }
1702 setNearestFilter(this.scene, baked.bloomCanvas);
1703 setNearestFilter(this.scene, baked.lightmapCanvas);
1704 }
1705
1706 #destroyBakedChunk (key)
1707 {
1708 const baked = this.bakedChunks.get(key);
1709 if (!baked)
1710 { return; }
1711 baked.groundObject?.destroy();
1712 for (const object of baked.blockObjects ?? [])
1713 { object.destroy(); }
1714 baked.bloomObject?.destroy();
1715 invalidateCanvasTexture(this.scene, baked.groundCanvas);
1716 for (const canvas of baked.blockCanvases ?? [])
1717 { invalidateCanvasTexture(this.scene, canvas); }
1718 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1719 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
1720 this.bakedChunks.delete(key);
1721 }
1722
1723 #redrawPreview ()
1724 {
1725 if (!this.preview)
1726 { return; }
1727 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
1728 if (snapshot)
1729 { this.#rebuildChunk(snapshot); }
1730 }
1731
1732 #refreshWaterCoastsNear (chunkX, chunkY)
1733 {
1734 const timeSec = performance.now() / 1000;
1735 for (const objects of this.tiles.values())
1736 {
1737 if (!objects.ground || !isWaterGround(objects.groundTypeId))
1738 { continue; }
1739 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1740 { continue; }
1741 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
1742 }
1743 }
1744
1745 #drawTile (tileX, tileY, forceTall = null)
1746 {
1747 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1748 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1749 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1750 if (!snapshot)
1751 { return; }
1752 const localX = tileX - chunkX * CHUNK_SIZE;
1753 const localY = tileY - chunkY * CHUNK_SIZE;
1754 const index = localY * CHUNK_SIZE + localX;
1755 const key = `${tileX},${tileY}`;
1756 let objects = this.tiles.get(key);
1757 if (!objects)
1758 {
1759 objects = { chunkX, chunkY, tileX, tileY };
1760 this.tiles.set(key, objects);
1761 }
1762 objects.tileX = tileX;
1763 objects.tileY = tileY;
1764 objects.chunkX = chunkX;
1765 objects.chunkY = chunkY;
1766 objects.light = snapshot.light[index] ?? 0;
1767
1768 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1769 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1770 if (animatedGround)
1771 {
1772 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
1773 if (objects.ground)
1774 {
1775 const size = this.tileSize();
1776 objects.ground.transform.position.x = tileX * size + size / 2;
1777 objects.ground.transform.position.y = tileY * size + size / 2;
1778 objects.ground.transform.size = new vector(size, size);
1779 objects.ground.layer = LAYER_GROUND;
1780 objects.groundTypeId = animatedGround.typeId;
1781 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
1782 this.#markSortDirty();
1783 }
1784 if (animatedGround.bloom)
1785 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
1786 else
1787 {
1788 objects.groundBloom?.destroy();
1789 objects.groundBloom = null;
1790 }
1791 }
1792 else
1793 {
1794 objects.ground?.destroy();
1795 objects.ground = null;
1796 objects.groundBloom?.destroy();
1797 objects.groundBloom = null;
1798 objects.groundTypeId = null;
1799 objects.waterEdges = null;
1800 }
1801
1802 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1803 const isTall = forceTall === true || !!tallEntry;
1804 if (isTall && tallEntry)
1805 {
1806 const pivot = tilePivot(tileX, tileY, this.tileSize());
1807 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
1808 if (objects.block)
1809 {
1810 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
1811 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
1812 }
1813 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
1814 }
1815 else
1816 {
1817 objects.block?.destroy();
1818 objects.block = null;
1819 objects.blockBloom?.destroy();
1820 objects.blockBloom = null;
1821 }
1822 }
1823
1824 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
1825 {
1826 if (!name)
1827 {
1828 existing?.destroy();
1829 return null;
1830 }
1831 const object = this.#ensureSprite(existing, name, sortOrder);
1832 if (!object)
1833 { return null; }
1834 object.renderer.layer = RENDER_LAYER_BLOOM;
1835 this.#markUnlit(object);
1836 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
1837 return object;
1838 }
1839
1840 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
1841 {
1842 const sprite = object?.renderer?.sprite;
1843 if (!sprite)
1844 { return; }
1845 const zoom = this.zoom;
1846 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1847 const factor = Math.max(0.1, Number(scale) || 1);
1848 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
1849 object.transform.position.x = center.x;
1850 object.transform.position.y = center.y;
1851 object.transform.size = new vector(draw.w * factor, draw.h * factor);
1852 object.layer = ySortLayer(sortY, subOrder);
1853 this.#markSortDirty();
1854 }
1855
1856 #ensureSprite (existing, name, layer)
1857 {
1858 const sprite = this.game.images[name];
1859 if (!sprite)
1860 {
1861 existing?.destroy();
1862 return null;
1863 }
1864 if (!existing || existing.renderer.sprite !== sprite)
1865 {
1866 existing?.destroy();
1867 existing = new GameObject(0, 0, sprite, layer);
1868 this.#syncLitSprite(existing, 0);
1869 this.scene.addObject(existing);
1870 this.#startIdleAnimation(existing);
1871 }
1872 return existing;
1873 }
1874
1875 #startIdleAnimation (object)
1876 {
1877 const sprite = object?.renderer?.sprite;
1878 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
1879 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
1880 }
1881
1882 #neighborClosed (snapshot, dir, dx, dy)
1883 {
1884 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
1885 if (other)
1886 { return !other.open; }
1887 return !!snapshot.closedEdges?.[dir];
1888 }
1889
1890 #rebuildAllEdges ()
1891 {
1892 const seen = new Set();
1893 for (const snapshot of this.chunks.values())
1894 {
1895 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1896 seen.add(key);
1897 this.#rebuildChunkEdges(snapshot);
1898 }
1899 for (const key of [...this.edges.keys()])
1900 {
1901 if (!seen.has(key))
1902 { this.#destroyEdges(key); }
1903 }
1904 }
1905
1906 #rebuildChunkEdges (snapshot)
1907 {
1908 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1909 let bars = this.edges.get(key);
1910 if (!bars)
1911 {
1912 bars = {};
1913 this.edges.set(key, bars);
1914 }
1915
1916 const size = this.tileSize();
1917 const chunkPx = CHUNK_SIZE * size;
1918 const left = snapshot.chunkX * CHUNK_SIZE * size;
1919 const top = snapshot.chunkY * CHUNK_SIZE * size;
1920 const centerX = left + chunkPx / 2;
1921 const centerY = top + chunkPx / 2;
1922 const thickness = Math.max(2, Math.round(2 * this.zoom));
1923 const draw = snapshot.open === true;
1924
1925 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
1926 centerX, top, chunkPx, thickness, true);
1927 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
1928 centerX, top + chunkPx, chunkPx, thickness, true);
1929 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
1930 left, centerY, chunkPx, thickness, false);
1931 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
1932 left + chunkPx, centerY, chunkPx, thickness, false);
1933 }
1934
1935 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
1936 {
1937 if (!visible)
1938 {
1939 if (existing)
1940 { existing.renderer.visible = false; }
1941 return existing;
1942 }
1943
1944 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
1945 this.#markUnlit(existing);
1946 existing.renderer.visible = true;
1947 existing.transform.position.x = x;
1948 existing.transform.position.y = y;
1949 existing.transform.size = horizontal
1950 ? new vector(length, thickness)
1951 : new vector(thickness, length);
1952 existing.layer = LAYER_EDGE;
1953 this.#markSortDirty();
1954 return existing;
1955 }
1956
1957 #destroyEdges (key)
1958 {
1959 const bars = this.edges.get(key);
1960 if (!bars)
1961 { return; }
1962 bars.north?.destroy();
1963 bars.east?.destroy();
1964 bars.south?.destroy();
1965 bars.west?.destroy();
1966 this.edges.delete(key);
1967 }
1968
1969 #entityShadeAlpha (entity, now)
1970 {
1971 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
1972 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
1973 { return toAlpha; }
1974 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
1975 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
1976 return fromAlpha + (toAlpha - fromAlpha) * t;
1977 }
1978
1979 #markSortDirty ()
1980 {
1981 this.scene._sortDirty = true;
1982 }
1983
1984 #updateShade ()
1985 {
1986 const ambientDark = this.#ambientDarkness();
1987 const now = performance.now();
1988 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1989
1990 const activeLights = [...this.dynamicLights];
1991 const tileSize = this.tileSize();
1992 const blindLight = this.#blindVisionLight();
1993 if (blindLight)
1994 { activeLights.push(blindLight); }
1995 for (const entity of this.entities.values())
1996 {
1997 const range = entity.lightRadiusTiles ?? 0;
1998 if (range <= 0)
1999 { continue; }
2000 activeLights.push({
2001 tileX: Math.floor(entity.visualX / tileSize),
2002 tileY: Math.floor(entity.visualY / tileSize),
2003 range,
2004 intensity: 1
2005 });
2006 }
2007
2008 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
2009
2010 for (const objects of this.tiles.values())
2011 {
2012 if (objects._inViewport === false)
2013 { continue; }
2014 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
2015 objects.shadeAlpha = ambientDark * (1 - intensity);
2016 }
2017
2018 for (const baked of this.bakedChunks.values())
2019 {
2020 if (baked._inViewport === false)
2021 { continue; }
2022 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
2023 if (baked.groundObject?.renderer?.shaderUniforms)
2024 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
2025 for (const object of baked.blockObjects ?? [])
2026 {
2027 if (object?.renderer?.shaderUniforms)
2028 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
2029 }
2030 }
2031
2032 const timeSec = now / 1000;
2033 for (const objects of this.tiles.values())
2034 {
2035 if (objects._inViewport === false)
2036 { continue; }
2037 if (objects.block)
2038 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
2039 if (objects.ground && isWaterGround(objects.groundTypeId))
2040 {
2041 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
2042 this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked);
2043 }
2044 else if (objects.ground)
2045 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
2046 }
2047
2048 for (const item of this.groundItems.values())
2049 {
2050 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
2051 this.#syncGroundItemSprite(item, alpha);
2052 }
2053 }
2054
2055 #tileLightIntensity (objects, activeLights, lightOcclusion)
2056 {
2057 const baked = lightIntensity(objects.light ?? 0);
2058 const dynamic = dynamicLightAtTile(
2059 objects.tileX,
2060 objects.tileY,
2061 activeLights,
2062 lightOcclusion
2063 );
2064 return Math.max(baked, dynamic);
2065 }
2066
2067 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
2068 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
2069 {
2070 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
2071 if (tileObjects)
2072 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
2073 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2074 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2075 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2076 if (!snapshot)
2077 { return 0; }
2078 const localX = tileX - chunkX * CHUNK_SIZE;
2079 const localY = tileY - chunkY * CHUNK_SIZE;
2080 const index = localY * CHUNK_SIZE + localX;
2081 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
2082 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
2083 return Math.max(bakedLit, dynamic);
2084 }
2085
2086 /** True when ground or block on this tile occludes light rays (same rules as bake). */
2087 #tileOccludesLight (tileX, tileY)
2088 {
2089 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2090 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2091 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2092 if (!snapshot)
2093 { return false; }
2094 const localX = tileX - chunkX * CHUNK_SIZE;
2095 const localY = tileY - chunkY * CHUNK_SIZE;
2096 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
2097 { return false; }
2098 const index = localY * CHUNK_SIZE + localX;
2099 const ground = normalizeGround(snapshot.grounds?.[index]);
2100 if (!isGroundPassable(ground.typeId))
2101 { return true; }
2102 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
2103 }
2104
2105 #fillChunkLightGrids (baked, activeLights, lightOcclusion)
2106 {
2107 const gridW = CHUNK_SIZE + 2;
2108 const gridSize = gridW * gridW;
2109 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
2110 { baked.lightIntensityGrid = new Float32Array(gridSize); }
2111 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
2112 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
2113 const grid = baked.lightIntensityGrid;
2114 const occlude = baked.lightOccludeGrid;
2115 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
2116 {
2117 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
2118 {
2119 const tileX = baked.chunkX * CHUNK_SIZE + lx;
2120 const tileY = baked.chunkY * CHUNK_SIZE + ly;
2121 const gi = (ly + 1) * gridW + (lx + 1);
2122 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
2123 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
2124 }
2125 }
2126 return { grid, occlude, gridW };
2127 }
2128
2129 #makeLightCornerSampler (grid, occlude, gridW)
2130 {
2131 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
2132 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
2133 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
2134 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
2135 {
2136 const home = sample(homeLx, homeLy);
2137 if (blocks(homeLx, homeLy))
2138 { return home; }
2139 let sum = home;
2140 let count = 1;
2141 sum += openSample(aLx, aLy);
2142 count += 1;
2143 sum += openSample(bLx, bLy);
2144 count += 1;
2145 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
2146 {
2147 sum += openSample(dLx, dLy);
2148 count += 1;
2149 }
2150 return sum / count;
2151 };
2152 return { smoothCorner };
2153 }
2154
2155 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
2156 #tileLitCorners (baked, localX, localY)
2157 {
2158 const grid = baked?.lightIntensityGrid;
2159 const occlude = baked?.lightOccludeGrid;
2160 if (!grid?.length || !occlude?.length)
2161 { return null; }
2162 const gridW = CHUNK_SIZE + 2;
2163 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
2164 return {
2165 nw: smoothCorner(
2166 localX, localY,
2167 localX - 1, localY,
2168 localX, localY - 1,
2169 localX - 1, localY - 1
2170 ),
2171 ne: smoothCorner(
2172 localX, localY,
2173 localX + 1, localY,
2174 localX, localY - 1,
2175 localX + 1, localY - 1
2176 ),
2177 sw: smoothCorner(
2178 localX, localY,
2179 localX - 1, localY,
2180 localX, localY + 1,
2181 localX - 1, localY + 1
2182 ),
2183 se: smoothCorner(
2184 localX, localY,
2185 localX + 1, localY,
2186 localX, localY + 1,
2187 localX + 1, localY + 1
2188 )
2189 };
2190 }
2191
2192 /**
2193 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
2194 * occluding tiles stay flat and contribute 0 into others so light does not bleed
2195 * through a wall to the far side. Diagonals only when both cardinals are clear.
2196 */
2197 #writeChunkLightmap (baked, activeLights, lightOcclusion)
2198 {
2199 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
2200 if (!snapshot)
2201 { return; }
2202 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2203 const pixelCount = atlasPx * atlasPx * 4;
2204 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
2205 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
2206 const pixels = baked.lightmapPixels;
2207
2208 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
2209 const simple = this.lightingMode === "simple";
2210
2211 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2212 {
2213 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2214 {
2215 const baseX = localX * SPRITE_SIZE_PX;
2216 const baseY = localY * SPRITE_SIZE_PX;
2217 if (simple)
2218 {
2219 const gridW = CHUNK_SIZE + 2;
2220 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
2221 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
2222 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2223 {
2224 for (let px = 0; px < SPRITE_SIZE_PX; px++)
2225 {
2226 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
2227 pixels[offset] = value;
2228 pixels[offset + 1] = value;
2229 pixels[offset + 2] = value;
2230 pixels[offset + 3] = 255;
2231 }
2232 }
2233 continue;
2234 }
2235 const corners = this.#tileLitCorners(baked, localX, localY);
2236 const nw = corners.nw;
2237 const ne = corners.ne;
2238 const sw = corners.sw;
2239 const se = corners.se;
2240 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2241 {
2242 const v = (py + 0.5) / SPRITE_SIZE_PX;
2243 const left = nw + (sw - nw) * v;
2244 const right = ne + (se - ne) * v;
2245 for (let px = 0; px < SPRITE_SIZE_PX; px++)
2246 {
2247 const u = (px + 0.5) / SPRITE_SIZE_PX;
2248 const intensity = left + (right - left) * u;
2249 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
2250 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
2251 pixels[offset] = value;
2252 pixels[offset + 1] = value;
2253 pixels[offset + 2] = value;
2254 pixels[offset + 3] = 255;
2255 }
2256 }
2257 }
2258 }
2259 const ctx = baked.lightmapCanvas.getContext("2d");
2260 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
2261 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
2262 }
2263
2264 #updateSwipes (now)
2265 {
2266 this.swipes = this.swipes.filter((swipe) =>
2267 {
2268 if (swipe.until > now)
2269 {
2270 if (swipe.fromTileX != null)
2271 {
2272 this.#applyPhysicalCombatFxDarkness(
2273 swipe.object,
2274 swipe.fromTileX,
2275 swipe.fromTileY,
2276 swipe.tileX,
2277 swipe.tileY
2278 );
2279 }
2280 return true;
2281 }
2282 swipe.object?.destroy();
2283 return false;
2284 });
2285 }
2286
2287 #updateDamageNumbers (now)
2288 {
2289 const layer = this.damageNumbersEl;
2290 if (!layer)
2291 { return; }
2292 this.damageFloats = this.damageFloats.filter((entry) =>
2293 {
2294 const elapsed = now - entry.started;
2295 if (elapsed >= DAMAGE_FLOAT_MS)
2296 {
2297 entry.element?.remove();
2298 return false;
2299 }
2300 const entity = this.entities.get(entry.entityId);
2301 if (!entity)
2302 {
2303 entry.element?.remove();
2304 return false;
2305 }
2306 if (!entry.element)
2307 {
2308 entry.element = document.createElement("span");
2309 entry.element.className = "damage-number";
2310 entry.element.textContent = String(entry.damage);
2311 layer.append(entry.element);
2312 }
2313 const anchor = this.nametagAnchor(entity);
2314 if (!anchor)
2315 { return true; }
2316 const t = elapsed / DAMAGE_FLOAT_MS;
2317 entry.element.style.left = `${anchor.x}px`;
2318 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
2319 entry.element.style.opacity = String(1 - t);
2320 return true;
2321 });
2322 }
2323
2324 #updateSkillLevelFloats (now)
2325 {
2326 const layer = this.skillLevelFloatsEl;
2327 if (!layer)
2328 { return; }
2329 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
2330 {
2331 const elapsed = now - entry.started;
2332 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
2333 {
2334 entry.element?.remove();
2335 return false;
2336 }
2337 const entity = this.entities.get(entry.entityId);
2338 if (!entity)
2339 {
2340 entry.element?.remove();
2341 return false;
2342 }
2343 if (!entry.element)
2344 {
2345 const root = document.createElement("div");
2346 root.className = "skill-level-float";
2347
2348 const levelEl = document.createElement("div");
2349 levelEl.className = "skill-level-float-level";
2350 levelEl.textContent = `↑${entry.level}↑`;
2351
2352 const icon = document.createElement("img");
2353 icon.className = "skill-level-float-icon";
2354 icon.src = entry.icon;
2355 icon.alt = entry.displayName || "";
2356
2357 root.append(levelEl, icon);
2358 entry.element = root;
2359 layer.append(entry.element);
2360 }
2361 const anchor = this.nametagAnchor(entity);
2362 if (!anchor)
2363 { return true; }
2364 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
2365 entry.element.style.left = `${anchor.x}px`;
2366 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
2367 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
2368 return true;
2369 });
2370 }
2371
2372 #syncBloomLayer ()
2373 {
2374 if (!this.bloomEnabled)
2375 {
2376 this.scene.setLayers([{ name: "default" }]);
2377 return;
2378 }
2379 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
2380 this.scene.setLayers([
2381 { name: "default" },
2382 {
2383 name: RENDER_LAYER_BLOOM,
2384 composite: "add",
2385 postShaders: Shader.getBloomPostChain({
2386 threshold: settings.bloomThreshold,
2387 softKnee: settings.bloomSoftKnee,
2388 intensity: settings.bloomIntensity,
2389 blurSize: settings.bloomBlurSize,
2390 saturation: settings.bloomSaturation,
2391 colorPreserve: settings.bloomColorPreserve,
2392 dilate: settings.bloomDilate,
2393 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
2394 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
2395 })
2396 }
2397 ]);
2398 }
2399}
2400
2401export function nightFactor (hour, nightDarkness = 0.72)
2402{
2403 const peak = Math.min(1, Math.max(0, nightDarkness));
2404 if (hour >= 8 && hour <= 16)
2405 { return 0; }
2406 if (hour >= 22 || hour <= 5)
2407 { return peak; }
2408 if (hour < 8)
2409 { return lerp(peak, 0, (hour - 5) / 3); }
2410 return lerp(0, peak, (hour - 16) / 6);
2411}
2412
2413function bodySpriteName (sex)
2414{
2415 const key = sex === "female" ? "player-body-female" : "player-body-male";
2416 return spriteImageName("character", key, key);
2417}
2418
2419function lerp (a, b, t)
2420{
2421 return a + (b - a) * Math.min(1, Math.max(0, t));
2422}
2423
2424function makeLightmapCanvas (size)
2425{
2426 const canvas = document.createElement("canvas");
2427 canvas.width = size;
2428 canvas.height = size;
2429 return canvas;
2430}
2431
2432function copyCanvas (source, dest)
2433{
2434 const ctx = dest.getContext("2d");
2435 ctx.imageSmoothingEnabled = false;
2436 ctx.clearRect(0, 0, dest.width, dest.height);
2437 ctx.drawImage(source, 0, 0);
2438}
2439
2440function drawHpBar (canvas, current, max)
2441{
2442 const ctx = canvas.getContext("2d");
2443 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
2444 ctx.fillStyle = "#000000";
2445 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
2446 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
2447 const fillW = Math.round(12 * ratio);
2448 if (fillW > 0)
2449 {
2450 ctx.fillStyle = "#ff0000";
2451 ctx.fillRect(1, 1, fillW, 2);
2452 }
2453}