BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 55.4 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5import { itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6import { resolveItemTint, resolveEquipTint, normalizeRgb } from "/shared/render/tint.js";
7import { normalizeGround, isWadeGround, isWaterGround } 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";
15
16const LAYER_GROUND = 0;
17const LAYER_EDGE = 900000;
18const SORT_BLOCK = 2;
19const SORT_ENTITY = 3;
20const SORT_HP_BAR = 4;
21const SORT_FX = 5;
22const RENDER_LAYER_BLOOM = "bloom";
23
24const HP_BAR_W = 14;
25const HP_BAR_H = 4;
26const WALK_TILT_DEG = 6;
27const RUN_TILT_DEG = 8;
28const SHOVE_TILE_FRACTION = 0.25;
29const SHOVE_MS = 280;
30const DAMAGE_FLASH_MS = 180;
31const DAMAGE_FLOAT_MS = 900;
32
33const SPRITE_LIGHTING_FRAG = [
34 "precision mediump float;",
35 "varying vec2 v_texCoord;",
36 "uniform sampler2D u_texture;",
37 "uniform float u_darkness;",
38 "uniform float u_strength;",
39 "uniform float u_wade;",
40 "uniform float u_spriteHeight;",
41 "void main() {",
42 " vec4 color = texture2D(u_texture, v_texCoord);",
43 " if (color.a <= 0.0) { discard; }",
44 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
45 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
46 " vec3 rgb = color.rgb;",
47 " if (u_wade > 0.5 && fromBottom < 5.0) {",
48 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
49 " }",
50 " rgb = mix(rgb, vec3(0.0), u_darkness);",
51 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
52 " gl_FragColor = vec4(rgb, color.a);",
53 "}"
54].join("\n");
55
56const WATER_GROUND_FRAG = [
57 "precision mediump float;",
58 "varying vec2 v_texCoord;",
59 "uniform sampler2D u_texture;",
60 "uniform float u_darkness;",
61 "uniform float u_time;",
62 "uniform float u_edgeN;",
63 "uniform float u_edgeE;",
64 "uniform float u_edgeS;",
65 "uniform float u_edgeW;",
66 "void main() {",
67 " vec4 color = texture2D(u_texture, v_texCoord);",
68 " if (color.a <= 0.0) { discard; }",
69 " vec3 rgb = color.rgb;",
70 " float foam = 0.0;",
71 " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
72 " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
73 " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
74 " }",
75 " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
76 " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
77 " }",
78 " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
79 " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
80 " }",
81 " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
82 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
83 " }",
84 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
85 " rgb = mix(rgb, vec3(0.0), u_darkness);",
86 " gl_FragColor = vec4(rgb, color.a);",
87 "}"
88].join("\n");
89
90/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
91const TINT_LIT_SPRITE_FRAG = [
92 "precision mediump float;",
93 "varying vec2 v_texCoord;",
94 "uniform sampler2D u_texture;",
95 "uniform float u_darkness;",
96 "uniform float u_strength;",
97 "uniform float u_wade;",
98 "uniform float u_spriteHeight;",
99 "uniform float u_useTint;",
100 "uniform vec3 u_tintColor;",
101 "void main() {",
102 " vec4 color = texture2D(u_texture, v_texCoord);",
103 " if (color.a <= 0.0) { discard; }",
104 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
105 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
106 " vec3 rgb = color.rgb;",
107 " if (u_useTint > 0.5) {",
108 " float eps = 1.0 / 255.0;",
109 " if (abs(color.r - color.b) <= eps && color.g < color.r - eps) {",
110 " float L = color.r;",
111 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
112 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
113 " }",
114 " }",
115 " if (u_wade > 0.5 && fromBottom < 5.0) {",
116 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
117 " }",
118 " rgb = mix(rgb, vec3(0.0), u_darkness);",
119 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
120 " gl_FragColor = vec4(rgb, color.a);",
121 "}"
122].join("\n");
123
124const ATLAS_LIGHTING_FRAG = [
125 "precision mediump float;",
126 "varying vec2 v_texCoord;",
127 "uniform sampler2D u_texture;",
128 "uniform sampler2D u_secondary;",
129 "uniform float u_ambientDark;",
130 "uniform float u_lightRow;",
131 "void main() {",
132 " vec4 color = texture2D(u_texture, v_texCoord);",
133 " if (color.a <= 0.0) { discard; }",
134 " vec2 lightUV = v_texCoord;",
135 " if (u_lightRow >= 0.0) {",
136 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
137 " }",
138 " float lit = texture2D(u_secondary, lightUV).r;",
139 " float darkness = u_ambientDark * (1.0 - lit);",
140 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
141 " gl_FragColor = vec4(rgb, color.a);",
142 "}"
143].join("\n");
144
145let spriteLightingShader = null;
146let atlasLightingShader = null;
147let waterGroundShader = null;
148let tintLitSpriteShader = null;
149
150function getSpriteLightingShader ()
151{
152 if (!spriteLightingShader)
153 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
154 return spriteLightingShader;
155}
156
157function getAtlasLightingShader ()
158{
159 if (!atlasLightingShader)
160 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
161 return atlasLightingShader;
162}
163
164function getWaterGroundShader ()
165{
166 if (!waterGroundShader)
167 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
168 return waterGroundShader;
169}
170
171function getTintLitSpriteShader ()
172{
173 if (!tintLitSpriteShader)
174 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
175 return tintLitSpriteShader;
176}
177
178export class WorldView
179{
180 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
181 {
182 this.game = game;
183 this.scene = scene;
184 this.catalog = catalog;
185 this.preview = null;
186 this.zoom = 2;
187 this.chunks = new Map();
188 this.bakedChunks = new Map();
189 this.tiles = new Map();
190 this.entities = new Map();
191 this.groundItems = new Map();
192 this.edges = new Map();
193 this.localEntityId = null;
194 this.settings = { ...DEFAULT_WORLD_SETTINGS };
195 this.worldHour = 12;
196 this.nightPreview = null;
197 this.followPlayer = true;
198 this.dynamicLights = [];
199 this.swipes = [];
200 this.damageFloats = [];
201 this.damageNumbersEl = document.getElementById("damage-numbers");
202 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
203 this.editorSpawners = new Map();
204 this.spawnRangeHighlight = null;
205 this.wanderRangeHighlight = null;
206 this.#syncBloomLayer();
207 }
208
209 setSettings (settings)
210 {
211 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
212 this.#syncBloomLayer();
213 }
214
215 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
216 {
217 this.localEntityId = entityId;
218 this.#upsertEntity({
219 entityId,
220 characterId,
221 tileX,
222 tileY,
223 gait,
224 sex,
225 firstName,
226 lastName,
227 layers: layers ?? undefined
228 });
229 }
230
231 applySnapshot (snapshot)
232 {
233 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
234 this.chunks.set(key, snapshot);
235 this.#rebuildChunk(snapshot);
236 this.#redrawPreview();
237 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
238 for (const entity of snapshot.entities ?? [])
239 { this.#upsertEntity(entity); }
240 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
241 for (const [id, item] of [...this.groundItems.entries()])
242 {
243 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
244 { this.despawnGroundItem(id); }
245 }
246 for (const item of snapshot.groundItems ?? [])
247 { this.upsertGroundItem(item); }
248 this.#rebuildAllEdges();
249 }
250
251 removeChunk (chunkX, chunkY)
252 {
253 const key = `${chunkX},${chunkY}`;
254 this.chunks.delete(key);
255 this.#destroyBakedChunk(key);
256 this.#destroyEdges(key);
257 const prefix = `${chunkX},${chunkY}:`;
258 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
259 {
260 if (!spawnerKey.startsWith(prefix))
261 { continue; }
262 entry.object?.destroy();
263 this.editorSpawners.delete(spawnerKey);
264 }
265 for (const [tileKey, objects] of [...this.tiles.entries()])
266 {
267 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
268 {
269 objects.ground?.destroy();
270 objects.groundBloom?.destroy();
271 objects.block?.destroy();
272 objects.blockBloom?.destroy();
273 this.tiles.delete(tileKey);
274 }
275 }
276 for (const [id, item] of [...this.groundItems.entries()])
277 {
278 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
279 { this.despawnGroundItem(id); }
280 }
281 this.#rebuildAllEdges();
282 }
283
284 setChunkOpen (chunkX, chunkY, open)
285 {
286 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
287 if (!snapshot)
288 { return; }
289 snapshot.open = !!open;
290 this.#rebuildAllEdges();
291 }
292
293 spawnEntity (payload)
294 {
295 this.#upsertEntity(payload);
296 }
297
298 moveEntity (payload)
299 {
300 const existing = this.entities.get(payload.entityId);
301 if (!existing)
302 {
303 this.#upsertEntity(payload);
304 return;
305 }
306 const size = this.tileSize();
307 existing.fromX = existing.visualX;
308 existing.fromY = existing.visualY;
309 existing.shadeFromTileX = existing.tileX;
310 existing.shadeFromTileY = existing.tileY;
311 existing.tileX = payload.tileX;
312 existing.tileY = payload.tileY;
313 existing.gait = payload.gait;
314 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
315 if (payload.worldX != null && payload.worldY != null)
316 {
317 existing.worldX = payload.worldX;
318 existing.worldY = payload.worldY;
319 existing.targetX = payload.worldX * size;
320 existing.targetY = payload.worldY * size;
321 }
322 else
323 {
324 const pivot = tilePivot(payload.tileX, payload.tileY, size);
325 existing.targetX = pivot.x;
326 existing.targetY = pivot.y;
327 }
328 existing.lerpStarted = performance.now();
329 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
330 }
331
332 despawnEntity (entityId)
333 {
334 const existing = this.entities.get(entityId);
335 if (!existing)
336 { return; }
337 existing.object?.destroy();
338 existing.hpBar?.destroy();
339 for (const overlay of existing.overlays ?? [])
340 { overlay.destroy(); }
341 for (const overlay of existing.bloomOverlays ?? [])
342 { overlay.destroy(); }
343 this.entities.delete(entityId);
344 }
345
346 updateEntityHealth (entityId, health, maxHealth)
347 {
348 const entity = this.entities.get(entityId);
349 if (!entity)
350 { return; }
351 entity.health = health;
352 entity.maxHealth = maxHealth;
353 this.#syncHpBar(entity);
354 }
355
356 flashDamage (entityId)
357 {
358 const entity = this.entities.get(entityId);
359 if (!entity)
360 { return; }
361 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
362 }
363
364 spawnDamageNumber (entityId, damage)
365 {
366 const amount = damage | 0;
367 if (amount <= 0)
368 { return; }
369 this.damageFloats.push({
370 entityId,
371 damage: amount,
372 started: performance.now()
373 });
374 }
375
376 setAppearance (payload)
377 {
378 const existing = this.entities.get(payload.entityId);
379 if (!existing)
380 { return; }
381 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
382 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
383 this.#placeEntity(existing);
384 }
385
386 upsertGroundItem (payload)
387 {
388 const size = this.tileSize();
389 const pivot = tilePivot(payload.tileX, payload.tileY, size);
390 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
391 const spriteName = potion
392 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
393 : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance));
394 let item = this.groundItems.get(payload.groundItemId);
395 if (!item)
396 {
397 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
398 this.scene.addObject(object);
399 item = { object };
400 this.groundItems.set(payload.groundItemId, item);
401 }
402 else if (item.object && this.game.images[spriteName])
403 { item.object.image = this.game.images[spriteName]; }
404 item.groundItemId = payload.groundItemId;
405 item.tileX = payload.tileX;
406 item.tileY = payload.tileY;
407 item.itemId = payload.itemId;
408 item.quantity = payload.quantity;
409 item.displayName = payload.displayName;
410 item.sprite = spriteName;
411 item.instance = payload.instance ?? null;
412 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
413 item.tintColor = resolveItemTint(stack, itemDefinition(payload.itemId));
414 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
415 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
416 }
417
418 despawnGroundItem (groundItemId)
419 {
420 const item = this.groundItems.get(groundItemId);
421 if (!item)
422 { return; }
423 item.object?.destroy();
424 this.groundItems.delete(groundItemId);
425 }
426
427 groundItemAtTile (tileX, tileY)
428 {
429 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
430 }
431
432 groundItemsAtTile (tileX, tileY)
433 {
434 const items = [];
435 for (const item of this.groundItems.values())
436 {
437 if (item.tileX === tileX && item.tileY === tileY)
438 { items.push(item); }
439 }
440 return items;
441 }
442
443 entitiesAtTile (tileX, tileY)
444 {
445 const matches = [];
446 for (const entity of this.entities.values())
447 {
448 if (entity.tileX === tileX && entity.tileY === tileY)
449 { matches.push(entity); }
450 }
451 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
452 return matches;
453 }
454
455 setZoom (zoom, limits = { min: 1, max: 4 })
456 {
457 const min = limits.min ?? 1;
458 const max = limits.max ?? 4;
459 this.zoom = Math.min(max, Math.max(min, zoom));
460 for (const snapshot of this.chunks.values())
461 {
462 this.#layoutBakedChunk(snapshot);
463 this.#rebuildChunk(snapshot);
464 }
465 const size = this.tileSize();
466 for (const entity of this.entities.values())
467 {
468 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
469 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
470 entity.fromX = entity.visualX;
471 entity.fromY = entity.visualY;
472 entity.targetX = entity.visualX;
473 entity.targetY = entity.visualY;
474 entity.lerpStarted = null;
475 this.#placeEntity(entity);
476 }
477 for (const item of this.groundItems.values())
478 {
479 const pivot = tilePivot(item.tileX, item.tileY, size);
480 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
481 }
482 this.#rebuildAllEdges();
483 this.#redrawPreview();
484 this.#relayoutEditorSpawners();
485 this.#relayoutSpawnRangeHighlight();
486 applyNearestToAllTextures(this.scene, this.game.images);
487 }
488
489 tileSize ()
490 {
491 return SPRITE_SIZE_PX * this.zoom;
492 }
493
494 screenToTile (mouseX, mouseY)
495 {
496 const size = this.tileSize();
497 const worldX = mouseX - this.scene.cameraPosition.x;
498 const worldY = mouseY - this.scene.cameraPosition.y;
499 return {
500 tileX: Math.floor(worldX / size),
501 tileY: Math.floor(worldY / size)
502 };
503 }
504
505 entityAtScreen (mouseX, mouseY)
506 {
507 let best = null;
508 let bestLayer = -Infinity;
509 for (const entity of this.entities.values())
510 {
511 const box = this.#entityScreenBox(entity);
512 if (!box)
513 { continue; }
514 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
515 {
516 const layer = entity.object?.layer ?? 0;
517 if (layer >= bestLayer)
518 {
519 best = entity;
520 bestLayer = layer;
521 }
522 }
523 }
524 return best;
525 }
526
527 nametagAnchor (entity)
528 {
529 const box = this.#entityScreenBox(entity);
530 if (!box)
531 { return null; }
532 return { x: (box.left + box.right) / 2, y: box.top };
533 }
534
535 #entityScreenBox (entity)
536 {
537 const object = entity?.object;
538 if (!object)
539 { return null; }
540 const size = object.transform.size;
541 const x = object.transform.position.x + this.scene.cameraPosition.x;
542 const y = object.transform.position.y + this.scene.cameraPosition.y;
543 return {
544 left: x - size.x / 2,
545 right: x + size.x / 2,
546 top: y - size.y / 2,
547 bottom: y + size.y / 2
548 };
549 }
550
551 update (deltaTime)
552 {
553 const now = performance.now();
554 const size = this.tileSize();
555 for (const entity of this.entities.values())
556 {
557 const target = entity.targetX != null && entity.targetY != null
558 ? { x: entity.targetX, y: entity.targetY }
559 : tilePivot(entity.tileX, entity.tileY, size);
560 if (entity.lerpStarted != null)
561 {
562 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
563 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
564 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
565 if (t >= 1)
566 { entity.lerpStarted = null; }
567 }
568 else
569 {
570 entity.visualX = target.x;
571 entity.visualY = target.y;
572 }
573 this.#updateShove(entity, now, size);
574 this.#placeEntity(entity, now);
575 }
576
577 this.#updateSwipes(now);
578 this.#updateDamageNumbers(now);
579 this.#centerCamera();
580 this.#updateShade(deltaTime);
581 }
582
583 #updateShove (entity, now, tileSize)
584 {
585 if (!entity.shove)
586 {
587 entity.shoveOffsetX = 0;
588 entity.shoveOffsetY = 0;
589 return;
590 }
591 const elapsed = now - entity.shove.started;
592 const t = Math.min(1, elapsed / entity.shove.durationMs);
593 const maxDist = tileSize * SHOVE_TILE_FRACTION;
594 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
595 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
596 const dist = Math.hypot(dx, dy) || 1;
597 const ux = dx / dist;
598 const uy = dy / dist;
599 let phase;
600 if (t < 0.45)
601 { phase = t / 0.45; }
602 else
603 { phase = 1 - (t - 0.45) / 0.55; }
604 entity.shoveOffsetX = ux * maxDist * phase;
605 entity.shoveOffsetY = uy * maxDist * phase;
606 if (t >= 1)
607 { entity.shove = null; }
608 }
609
610 spawnCombatSwing (payload)
611 {
612 const attacker = this.entities.get(payload.attackerId);
613 const target = this.entities.get(payload.targetId);
614 if (!attacker || !target)
615 { return; }
616 attacker.shove = {
617 startVisualX: attacker.visualX,
618 startVisualY: attacker.visualY,
619 targetVisualX: target.visualX,
620 targetVisualY: target.visualY,
621 started: performance.now(),
622 durationMs: SHOVE_MS
623 };
624 const midX = (attacker.visualX + target.visualX) / 2;
625 const midY = (attacker.visualY + target.visualY) / 2;
626 const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;
627 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
628 const spriteName = "fx:melee-swipe:melee-swipe";
629 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
630 if (object.transform)
631 { object.transform.rotation = angle; }
632 this.scene.addObject(object);
633 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
634 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
635 this.swipes.push({
636 object,
637 until: performance.now() + 500,
638 fromTileX: payload.fromTileX,
639 fromTileY: payload.fromTileY,
640 tileX: payload.tileX,
641 tileY: payload.tileY
642 });
643 }
644
645 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
646 spawnPhysicalProjectileFx (payload)
647 {
648 const spriteName = payload.sprite ?? "fx:projectile:projectile";
649 const image = this.game.images[spriteName];
650 if (!image)
651 { return; }
652 const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
653 const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
654 const midX = (fromPivot.x + toPivot.x) / 2;
655 const midY = (fromPivot.y + toPivot.y) / 2;
656 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
657 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
658 const object = new GameObject(0, 0, image, SORT_FX);
659 if (object.transform)
660 { object.transform.rotation = angle; }
661 this.scene.addObject(object);
662 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
663 this.#applyPhysicalCombatFxDarkness(
664 object,
665 payload.fromTileX,
666 payload.fromTileY,
667 payload.tileX,
668 payload.tileY
669 );
670 this.swipes.push({
671 object,
672 until: performance.now() + (payload.durationMs ?? 500),
673 fromTileX: payload.fromTileX,
674 fromTileY: payload.fromTileY,
675 tileX: payload.tileX,
676 tileY: payload.tileY
677 });
678 }
679
680 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
681 {
682 this.dynamicLights.push({
683 tileX: Math.floor(worldX),
684 tileY: Math.floor(worldY),
685 range: radiusTiles,
686 intensity,
687 until: performance.now() + durationMs
688 });
689 }
690
691 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
692 {
693 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
694 if (!snapshot)
695 { return; }
696 const index = localY * CHUNK_SIZE + localX;
697 if (ground !== undefined)
698 { snapshot.grounds[index] = ground; }
699 if (block !== undefined)
700 { snapshot.blocks[index] = block; }
701 if (light !== undefined)
702 { snapshot.light[index] = light; }
703 this.#rebuildChunk(snapshot);
704 }
705
706 /**
707 * Editor-only mob markers for authored spawners (invisible during play).
708 * @param {number} chunkX
709 * @param {number} chunkY
710 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
711 * @param {(mobTypeId: string) => string} resolveSprite
712 */
713 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
714 {
715 const prefix = `${chunkX},${chunkY}:`;
716 for (const [key, entry] of [...this.editorSpawners.entries()])
717 {
718 if (!key.startsWith(prefix))
719 { continue; }
720 entry.object?.destroy();
721 this.editorSpawners.delete(key);
722 }
723 for (const spawner of spawners ?? [])
724 {
725 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
726 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
727 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
728 if (!spriteName)
729 { continue; }
730 const key = `${prefix}${spawner.localX},${spawner.localY}`;
731 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
732 if (!object)
733 { continue; }
734 object.renderer.alpha = 0.85;
735 const pivot = tilePivot(tileX, tileY, this.tileSize());
736 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
737 this.#markUnlit(object);
738 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
739 }
740 }
741
742 clearEditorSpawners ()
743 {
744 for (const entry of this.editorSpawners.values())
745 { entry.object?.destroy(); }
746 this.editorSpawners.clear();
747 }
748
749 #relayoutEditorSpawners ()
750 {
751 const size = this.tileSize();
752 for (const entry of this.editorSpawners.values())
753 {
754 if (!entry.object)
755 { continue; }
756 const pivot = tilePivot(entry.tileX, entry.tileY, size);
757 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
758 }
759 }
760
761 /**
762 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
763 */
764 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
765 {
766 const spawnRadius = Math.max(0, spawnRange | 0);
767 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
768 if (this.spawnRangeHighlight
769 && this.wanderRangeHighlight
770 && this.spawnRangeHighlight.tileX === tileX
771 && this.spawnRangeHighlight.tileY === tileY
772 && this.spawnRangeHighlight.range === spawnRadius
773 && this.wanderRangeHighlight.range === wanderRadius)
774 {
775 this.#relayoutSpawnRangeHighlight();
776 return;
777 }
778 this.clearSpawnRangeHighlight();
779 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
780 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
781 if (wanderObject)
782 {
783 this.#markUnlit(wanderObject);
784 wanderObject.renderer.alpha = 1;
785 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
786 }
787 if (spawnObject)
788 {
789 this.#markUnlit(spawnObject);
790 spawnObject.renderer.alpha = 1;
791 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
792 }
793 this.#relayoutSpawnRangeHighlight();
794 }
795
796 clearSpawnRangeHighlight ()
797 {
798 this.spawnRangeHighlight?.object?.destroy();
799 this.wanderRangeHighlight?.object?.destroy();
800 this.spawnRangeHighlight = null;
801 this.wanderRangeHighlight = null;
802 }
803
804 #relayoutSpawnRangeHighlight ()
805 {
806 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
807 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
808 }
809
810 #layoutRangeOverlay (highlight, layer)
811 {
812 if (!highlight?.object)
813 { return; }
814 const size = this.tileSize();
815 const side = (2 * highlight.range + 1) * size;
816 const left = (highlight.tileX - highlight.range) * size;
817 const top = (highlight.tileY - highlight.range) * size;
818 highlight.object.transform.position.x = left + side / 2;
819 highlight.object.transform.position.y = top + side / 2;
820 highlight.object.transform.size = new vector(side, side);
821 highlight.object.layer = layer;
822 this.#markSortDirty();
823 }
824
825 setTilePreview (tileX, tileY, override)
826 {
827 const previous = this.preview;
828 this.preview = { tileX, tileY, ...override };
829 const chunkX = Math.floor(tileX / CHUNK_SIZE);
830 const chunkY = Math.floor(tileY / CHUNK_SIZE);
831 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
832 if (snapshot)
833 { this.#rebuildChunk(snapshot); }
834 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
835 {
836 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
837 if (prevSnapshot && prevSnapshot !== snapshot)
838 { this.#rebuildChunk(prevSnapshot); }
839 }
840 }
841
842 clearTilePreview ()
843 {
844 const previous = this.preview;
845 this.preview = null;
846 if (previous)
847 {
848 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
849 if (snapshot)
850 { this.#rebuildChunk(snapshot); }
851 }
852 }
853
854 #lerpMs (gait)
855 {
856 const walk = this.settings.walkTilesPerSecond || 2;
857 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
858 return seconds * 1000;
859 }
860
861 #centerCamera ()
862 {
863 if (!this.followPlayer)
864 { return; }
865 const local = this.entities.get(this.localEntityId);
866 if (!local)
867 { return; }
868 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
869 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
870 }
871
872 #upsertEntity (payload)
873 {
874 const size = this.tileSize();
875 const pivot = tilePivot(payload.tileX, payload.tileY, size);
876 let entity = this.entities.get(payload.entityId);
877 if (!entity)
878 {
879 const spriteName = payload.layers?.[0]?.sprite
880 ?? payload.sprite
881 ?? bodySpriteName(payload.sex);
882 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
883 this.scene.addObject(object);
884 this.#startIdleAnimation(object);
885 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
886 this.entities.set(payload.entityId, entity);
887 }
888 entity.entityId = payload.entityId;
889 entity.tileX = payload.tileX;
890 entity.tileY = payload.tileY;
891 entity.gait = payload.gait;
892 entity.sex = payload.sex ?? entity.sex;
893 entity.characterId = payload.characterId ?? entity.characterId ?? null;
894 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
895 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
896 entity.canFight = payload.canFight != null
897 ? !!payload.canFight
898 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
899 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
900 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
901 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
902 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
903 if (payload.health != null)
904 { entity.health = payload.health; }
905 if (payload.maxHealth != null)
906 { entity.maxHealth = payload.maxHealth; }
907 if (payload.firstName)
908 { entity.firstName = payload.firstName; }
909 if (payload.lastName)
910 { entity.lastName = payload.lastName; }
911 entity.firstName = entity.firstName ?? "";
912 entity.lastName = entity.lastName ?? "";
913 if (payload.worldX != null && payload.worldY != null)
914 {
915 entity.worldX = payload.worldX;
916 entity.worldY = payload.worldY;
917 entity.visualX = payload.worldX * size;
918 entity.visualY = payload.worldY * size;
919 entity.targetX = entity.visualX;
920 entity.targetY = entity.visualY;
921 }
922 else
923 {
924 entity.visualX = pivot.x;
925 entity.visualY = pivot.y;
926 entity.targetX = pivot.x;
927 entity.targetY = pivot.y;
928 }
929 entity.fromX = entity.visualX;
930 entity.fromY = entity.visualY;
931 if (payload.layers)
932 { this.#applyLayers(entity, payload.layers); }
933 this.#syncHpBar(entity);
934 this.#placeEntity(entity, performance.now());
935 }
936
937 #applyLayers (entity, layers)
938 {
939 const base = layers[0]?.sprite
940 ?? bodySpriteName(entity.sex);
941 if (this.game.images[base])
942 {
943 entity.object.renderer.sprite = this.game.images[base];
944 this.#startIdleAnimation(entity.object);
945 }
946 for (const overlay of entity.overlays ?? [])
947 { overlay.destroy(); }
948 for (const overlay of entity.bloomOverlays ?? [])
949 { overlay.destroy(); }
950 entity.overlays = [];
951 entity.overlayTints = [];
952 entity.bloomOverlays = [];
953 for (const layer of layers.slice(1))
954 {
955 const image = this.game.images[layer.sprite];
956 if (!image)
957 { continue; }
958 const object = new GameObject(0, 0, image, SORT_ENTITY);
959 this.scene.addObject(object);
960 entity.overlays.push(object);
961 entity.overlayTints.push(
962 layer.tint
963 ? normalizeRgb(layer.tint)
964 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
965 );
966 const bloomName = bloomCompanionName(layer.sprite);
967 const bloomImage = this.game.images[bloomName];
968 if (!bloomImage)
969 { continue; }
970 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
971 bloom.renderer.layer = RENDER_LAYER_BLOOM;
972 this.#markUnlit(bloom);
973 this.scene.addObject(bloom);
974 entity.bloomOverlays.push(bloom);
975 }
976 }
977
978 #placeEntity (entity, now = performance.now())
979 {
980 const zoom = this.zoom;
981 const offsetX = entity.shoveOffsetX ?? 0;
982 const offsetY = entity.shoveOffsetY ?? 0;
983 const pivotX = entity.visualX + offsetX;
984 const pivotY = entity.visualY + offsetY;
985 let walkTilt = 0;
986 if (entity.lerpStarted != null)
987 {
988 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
989 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
990 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
991 walkTilt = Math.sin(cycles) * tilt;
992 }
993 const flashStrength = (entity.damageFlashUntil ?? 0) > now
994 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
995 : 0;
996 const tileShade = this.#entityShadeAlpha(entity, now);
997 const wade = isWadeGround(this.#groundTypeAt(entity.tileX, entity.tileY));
998
999 entity.object.transform.rotation = walkTilt;
1000 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
1001 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
1002 for (let index = 0; index < (entity.overlays ?? []).length; index++)
1003 {
1004 const overlay = entity.overlays[index];
1005 const overlaySortY = entity.visualY + 0.5 * (index + 1);
1006 overlay.transform.rotation = walkTilt;
1007 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
1008 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
1009 }
1010 for (const overlay of entity.bloomOverlays ?? [])
1011 {
1012 overlay.transform.rotation = walkTilt;
1013 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1014 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
1015 }
1016 this.#placeHpBar(entity, pivotX, pivotY);
1017 }
1018
1019 #markUnlit (object)
1020 {
1021 if (!object?.renderer)
1022 { return; }
1023 object._lit = false;
1024 object.renderer.shader = null;
1025 object.renderer.shaderUniforms = null;
1026 object.renderer.secondaryMap = null;
1027 }
1028
1029 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
1030 {
1031 if (!object?.renderer || object._lit === false)
1032 { return; }
1033 object._lit = true;
1034 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1035 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1036 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1037 const tint = tintColor ? normalizeRgb(tintColor) : null;
1038 if (tint)
1039 {
1040 object.renderer.shader = getTintLitSpriteShader();
1041 object.renderer.shaderUniforms = {
1042 u_darkness: dark,
1043 u_strength: flash,
1044 u_wade: wade ? 1 : 0,
1045 u_spriteHeight: height,
1046 u_useTint: 1,
1047 u_tintColor: [tint.r, tint.g, tint.b]
1048 };
1049 }
1050 else
1051 {
1052 object.renderer.shader = getSpriteLightingShader();
1053 object.renderer.shaderUniforms = {
1054 u_darkness: dark,
1055 u_strength: flash,
1056 u_wade: wade ? 1 : 0,
1057 u_spriteHeight: height
1058 };
1059 }
1060 object.renderer.secondaryMap = null;
1061 }
1062
1063 #syncGroundItemSprite (item, darkness)
1064 {
1065 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
1066 }
1067
1068 #groundTypeAt (tileX, tileY)
1069 {
1070 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1071 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1072 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1073 if (!snapshot)
1074 { return null; }
1075 const localX = tileX - chunkX * CHUNK_SIZE;
1076 const localY = tileY - chunkY * CHUNK_SIZE;
1077 const index = localY * CHUNK_SIZE + localX;
1078 return normalizeGround(snapshot.grounds?.[index]).typeId;
1079 }
1080
1081 #waterCoastEdges (tileX, tileY)
1082 {
1083 return {
1084 n: !isWaterGround(this.#groundTypeAt(tileX, tileY - 1)) ? 1 : 0,
1085 e: !isWaterGround(this.#groundTypeAt(tileX + 1, tileY)) ? 1 : 0,
1086 s: !isWaterGround(this.#groundTypeAt(tileX, tileY + 1)) ? 1 : 0,
1087 w: !isWaterGround(this.#groundTypeAt(tileX - 1, tileY)) ? 1 : 0
1088 };
1089 }
1090
1091 #syncWaterGroundSprite (object, darkness, edges, timeSec)
1092 {
1093 if (!object?.renderer)
1094 { return; }
1095 object._lit = true;
1096 object.renderer.shader = getWaterGroundShader();
1097 object.renderer.secondaryMap = null;
1098 object.renderer.shaderUniforms = {
1099 u_darkness: Math.min(1, Math.max(0, darkness ?? 0)),
1100 u_time: timeSec,
1101 u_edgeN: edges?.n ?? 0,
1102 u_edgeE: edges?.e ?? 0,
1103 u_edgeS: edges?.s ?? 0,
1104 u_edgeW: edges?.w ?? 0
1105 };
1106 }
1107
1108 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
1109 {
1110 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
1111 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
1112 this.#syncLitSprite(object, (fromAlpha + toAlpha) / 2);
1113 }
1114
1115 #syncHpBar (entity)
1116 {
1117 const current = entity.health;
1118 const max = entity.maxHealth;
1119 const show = entity.mobTypeId != null
1120 && current != null
1121 && max != null
1122 && max > 0
1123 && current < max;
1124 if (!show)
1125 {
1126 entity.hpBar?.destroy();
1127 entity.hpBar = null;
1128 entity.hpBarCanvas = null;
1129 return;
1130 }
1131 if (!entity.hpBarCanvas)
1132 {
1133 entity.hpBarCanvas = document.createElement("canvas");
1134 entity.hpBarCanvas.width = HP_BAR_W;
1135 entity.hpBarCanvas.height = HP_BAR_H;
1136 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
1137 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
1138 this.#markUnlit(entity.hpBar);
1139 this.scene.addObject(entity.hpBar);
1140 }
1141 drawHpBar(entity.hpBarCanvas, current, max);
1142 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
1143 }
1144
1145 #placeHpBar (entity, pivotX, pivotY)
1146 {
1147 if (!entity.hpBar)
1148 { return; }
1149 const sprite = entity.object?.renderer?.sprite;
1150 if (!sprite)
1151 { return; }
1152 const zoom = this.zoom;
1153 const drawH = sprite.height * zoom;
1154 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
1155 const spriteTop = centerY - drawH / 2;
1156 const barW = HP_BAR_W * zoom;
1157 const barH = HP_BAR_H * zoom;
1158 entity.hpBar.transform.position.x = pivotX;
1159 entity.hpBar.transform.position.y = spriteTop - barH / 2;
1160 entity.hpBar.transform.size = new vector(barW, barH);
1161 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
1162 this.#markSortDirty();
1163 }
1164
1165 #rebuildChunk (snapshot)
1166 {
1167 this.#bakeAndPlaceChunk(snapshot);
1168 const tall = new Set(
1169 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
1170 .map((entry) => `${entry.tileX},${entry.tileY}`)
1171 );
1172 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1173 {
1174 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1175 {
1176 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
1177 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
1178 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
1179 }
1180 }
1181 }
1182
1183 #bakeAndPlaceChunk (snapshot)
1184 {
1185 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1186 const atlases = bakeChunkAtlases({
1187 snapshot,
1188 catalog: this.catalog,
1189 images: this.game.images,
1190 preview: this.preview
1191 });
1192 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
1193 let baked = this.bakedChunks.get(key);
1194 if (!baked)
1195 {
1196 const lightmapCanvas = makeLightmapCanvas(atlasPx);
1197 baked = {
1198 groundCanvas: atlases.ground,
1199 blockCanvases: atlases.blockRows,
1200 bloomCanvas: atlases.bloom,
1201 lightmapCanvas,
1202 groundImage: frameworkImageFromCanvas(atlases.ground),
1203 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
1204 bloomImage: frameworkImageFromCanvas(atlases.bloom),
1205 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
1206 groundObject: null,
1207 blockObjects: [],
1208 bloomObject: null,
1209 tallBlocks: atlases.tallBlocks,
1210 animatedGrounds: atlases.animatedGrounds,
1211 lightmapPixels: null
1212 };
1213 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
1214 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
1215 this.scene.addObject(baked.groundObject);
1216 for (let row = 0; row < CHUNK_SIZE; row++)
1217 {
1218 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
1219 this.#applyAtlasLighting(object, baked.lightmapImage, row);
1220 this.scene.addObject(object);
1221 baked.blockObjects.push(object);
1222 }
1223 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
1224 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
1225 this.#markUnlit(baked.bloomObject);
1226 this.scene.addObject(baked.bloomObject);
1227 this.bakedChunks.set(key, baked);
1228 }
1229 else
1230 {
1231 copyCanvas(atlases.ground, baked.groundCanvas);
1232 for (let row = 0; row < CHUNK_SIZE; row++)
1233 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
1234 copyCanvas(atlases.bloom, baked.bloomCanvas);
1235 invalidateCanvasTexture(this.scene, baked.groundCanvas);
1236 for (const canvas of baked.blockCanvases)
1237 { invalidateCanvasTexture(this.scene, canvas); }
1238 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1239 baked.tallBlocks = atlases.tallBlocks;
1240 baked.animatedGrounds = atlases.animatedGrounds;
1241 }
1242 baked.chunkX = snapshot.chunkX;
1243 baked.chunkY = snapshot.chunkY;
1244 this.#layoutBakedChunk(snapshot);
1245 }
1246
1247 #applyAtlasLighting (object, lightmapImage, lightRow)
1248 {
1249 if (!object?.renderer)
1250 { return; }
1251 object._lit = true;
1252 object.renderer.shader = getAtlasLightingShader();
1253 object.renderer.secondaryMap = lightmapImage;
1254 object.renderer.shaderUniforms = {
1255 u_ambientDark: 0,
1256 u_lightRow: lightRow
1257 };
1258 }
1259
1260 #layoutBakedChunk (snapshot)
1261 {
1262 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1263 const baked = this.bakedChunks.get(key);
1264 if (!baked)
1265 { return; }
1266 const size = this.tileSize();
1267 const left = snapshot.chunkX * CHUNK_SIZE * size;
1268 const top = snapshot.chunkY * CHUNK_SIZE * size;
1269 const chunkPx = CHUNK_SIZE * size;
1270 baked.groundObject.transform.position.x = left + chunkPx / 2;
1271 baked.groundObject.transform.position.y = top + chunkPx / 2;
1272 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
1273 baked.groundObject.layer = LAYER_GROUND;
1274
1275 for (let row = 0; row < CHUNK_SIZE; row++)
1276 {
1277 const object = baked.blockObjects[row];
1278 const rowY = top + row * size + size / 2;
1279 object.transform.position.x = left + chunkPx / 2;
1280 object.transform.position.y = rowY;
1281 object.transform.size = new vector(chunkPx, size);
1282 object.layer = ySortLayer(rowY, SORT_BLOCK);
1283 }
1284
1285 baked.bloomObject.transform.position.x = left + chunkPx / 2;
1286 baked.bloomObject.transform.position.y = top + chunkPx / 2;
1287 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
1288 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
1289 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
1290 this.#markSortDirty();
1291 setNearestFilter(this.scene, baked.groundCanvas);
1292 for (const canvas of baked.blockCanvases)
1293 { setNearestFilter(this.scene, canvas); }
1294 setNearestFilter(this.scene, baked.bloomCanvas);
1295 setNearestFilter(this.scene, baked.lightmapCanvas);
1296 }
1297
1298 #destroyBakedChunk (key)
1299 {
1300 const baked = this.bakedChunks.get(key);
1301 if (!baked)
1302 { return; }
1303 baked.groundObject?.destroy();
1304 for (const object of baked.blockObjects ?? [])
1305 { object.destroy(); }
1306 baked.bloomObject?.destroy();
1307 invalidateCanvasTexture(this.scene, baked.groundCanvas);
1308 for (const canvas of baked.blockCanvases ?? [])
1309 { invalidateCanvasTexture(this.scene, canvas); }
1310 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1311 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
1312 this.bakedChunks.delete(key);
1313 }
1314
1315 #redrawPreview ()
1316 {
1317 if (!this.preview)
1318 { return; }
1319 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
1320 if (snapshot)
1321 { this.#rebuildChunk(snapshot); }
1322 }
1323
1324 #refreshWaterCoastsNear (chunkX, chunkY)
1325 {
1326 const timeSec = performance.now() / 1000;
1327 for (const objects of this.tiles.values())
1328 {
1329 if (!objects.ground || !isWaterGround(objects.groundTypeId))
1330 { continue; }
1331 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1332 { continue; }
1333 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1334 this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, objects.waterEdges, timeSec);
1335 }
1336 }
1337
1338 #drawTile (tileX, tileY, forceTall = null)
1339 {
1340 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1341 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1342 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1343 if (!snapshot)
1344 { return; }
1345 const localX = tileX - chunkX * CHUNK_SIZE;
1346 const localY = tileY - chunkY * CHUNK_SIZE;
1347 const index = localY * CHUNK_SIZE + localX;
1348 const key = `${tileX},${tileY}`;
1349 let objects = this.tiles.get(key);
1350 if (!objects)
1351 {
1352 objects = { chunkX, chunkY, tileX, tileY };
1353 this.tiles.set(key, objects);
1354 }
1355 objects.tileX = tileX;
1356 objects.tileY = tileY;
1357 objects.chunkX = chunkX;
1358 objects.chunkY = chunkY;
1359 objects.light = snapshot.light[index] ?? 0;
1360
1361 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1362 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1363 if (animatedGround)
1364 {
1365 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
1366 if (objects.ground)
1367 {
1368 const size = this.tileSize();
1369 objects.ground.transform.position.x = tileX * size + size / 2;
1370 objects.ground.transform.position.y = tileY * size + size / 2;
1371 objects.ground.transform.size = new vector(size, size);
1372 objects.ground.layer = LAYER_GROUND;
1373 objects.groundTypeId = animatedGround.typeId;
1374 const edges = isWaterGround(animatedGround.typeId)
1375 ? this.#waterCoastEdges(tileX, tileY)
1376 : { n: 0, e: 0, s: 0, w: 0 };
1377 objects.waterEdges = edges;
1378 this.#syncWaterGroundSprite(objects.ground, objects.shadeAlpha ?? 0, edges, performance.now() / 1000);
1379 this.#markSortDirty();
1380 }
1381 if (animatedGround.bloom)
1382 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
1383 else
1384 {
1385 objects.groundBloom?.destroy();
1386 objects.groundBloom = null;
1387 }
1388 }
1389 else
1390 {
1391 objects.ground?.destroy();
1392 objects.ground = null;
1393 objects.groundBloom?.destroy();
1394 objects.groundBloom = null;
1395 objects.groundTypeId = null;
1396 objects.waterEdges = null;
1397 }
1398
1399 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1400 const isTall = forceTall === true || !!tallEntry;
1401 if (isTall && tallEntry)
1402 {
1403 const pivot = tilePivot(tileX, tileY, this.tileSize());
1404 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
1405 if (objects.block)
1406 {
1407 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
1408 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
1409 }
1410 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
1411 }
1412 else
1413 {
1414 objects.block?.destroy();
1415 objects.block = null;
1416 objects.blockBloom?.destroy();
1417 objects.blockBloom = null;
1418 }
1419 }
1420
1421 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
1422 {
1423 if (!name)
1424 {
1425 existing?.destroy();
1426 return null;
1427 }
1428 const object = this.#ensureSprite(existing, name, sortOrder);
1429 if (!object)
1430 { return null; }
1431 object.renderer.layer = RENDER_LAYER_BLOOM;
1432 this.#markUnlit(object);
1433 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
1434 return object;
1435 }
1436
1437 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
1438 {
1439 const sprite = object?.renderer?.sprite;
1440 if (!sprite)
1441 { return; }
1442 const zoom = this.zoom;
1443 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1444 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
1445 object.transform.position.x = center.x;
1446 object.transform.position.y = center.y;
1447 object.transform.size = new vector(draw.w, draw.h);
1448 object.layer = ySortLayer(sortY, subOrder);
1449 this.#markSortDirty();
1450 }
1451
1452 #ensureSprite (existing, name, layer)
1453 {
1454 const sprite = this.game.images[name];
1455 if (!sprite)
1456 {
1457 existing?.destroy();
1458 return null;
1459 }
1460 if (!existing || existing.renderer.sprite !== sprite)
1461 {
1462 existing?.destroy();
1463 existing = new GameObject(0, 0, sprite, layer);
1464 this.#syncLitSprite(existing, 0);
1465 this.scene.addObject(existing);
1466 this.#startIdleAnimation(existing);
1467 }
1468 return existing;
1469 }
1470
1471 #startIdleAnimation (object)
1472 {
1473 const sprite = object?.renderer?.sprite;
1474 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
1475 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
1476 }
1477
1478 #neighborClosed (snapshot, dir, dx, dy)
1479 {
1480 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
1481 if (other)
1482 { return !other.open; }
1483 return !!snapshot.closedEdges?.[dir];
1484 }
1485
1486 #rebuildAllEdges ()
1487 {
1488 const seen = new Set();
1489 for (const snapshot of this.chunks.values())
1490 {
1491 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1492 seen.add(key);
1493 this.#rebuildChunkEdges(snapshot);
1494 }
1495 for (const key of [...this.edges.keys()])
1496 {
1497 if (!seen.has(key))
1498 { this.#destroyEdges(key); }
1499 }
1500 }
1501
1502 #rebuildChunkEdges (snapshot)
1503 {
1504 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1505 let bars = this.edges.get(key);
1506 if (!bars)
1507 {
1508 bars = {};
1509 this.edges.set(key, bars);
1510 }
1511
1512 const size = this.tileSize();
1513 const chunkPx = CHUNK_SIZE * size;
1514 const left = snapshot.chunkX * CHUNK_SIZE * size;
1515 const top = snapshot.chunkY * CHUNK_SIZE * size;
1516 const centerX = left + chunkPx / 2;
1517 const centerY = top + chunkPx / 2;
1518 const thickness = Math.max(2, Math.round(2 * this.zoom));
1519 const draw = snapshot.open === true;
1520
1521 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
1522 centerX, top, chunkPx, thickness, true);
1523 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
1524 centerX, top + chunkPx, chunkPx, thickness, true);
1525 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
1526 left, centerY, chunkPx, thickness, false);
1527 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
1528 left + chunkPx, centerY, chunkPx, thickness, false);
1529 }
1530
1531 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
1532 {
1533 if (!visible)
1534 {
1535 if (existing)
1536 { existing.renderer.visible = false; }
1537 return existing;
1538 }
1539
1540 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
1541 this.#markUnlit(existing);
1542 existing.renderer.visible = true;
1543 existing.transform.position.x = x;
1544 existing.transform.position.y = y;
1545 existing.transform.size = horizontal
1546 ? new vector(length, thickness)
1547 : new vector(thickness, length);
1548 existing.layer = LAYER_EDGE;
1549 this.#markSortDirty();
1550 return existing;
1551 }
1552
1553 #destroyEdges (key)
1554 {
1555 const bars = this.edges.get(key);
1556 if (!bars)
1557 { return; }
1558 bars.north?.destroy();
1559 bars.east?.destroy();
1560 bars.south?.destroy();
1561 bars.west?.destroy();
1562 this.edges.delete(key);
1563 }
1564
1565 #entityShadeAlpha (entity, now)
1566 {
1567 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
1568 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
1569 { return toAlpha; }
1570 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
1571 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
1572 return fromAlpha + (toAlpha - fromAlpha) * t;
1573 }
1574
1575 #markSortDirty ()
1576 {
1577 this.scene._sortDirty = true;
1578 }
1579
1580 #updateShade ()
1581 {
1582 const hour = this.nightPreview ?? this.worldHour;
1583 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
1584 const now = performance.now();
1585 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1586
1587 const activeLights = [...this.dynamicLights];
1588 const tileSize = this.tileSize();
1589 for (const entity of this.entities.values())
1590 {
1591 const range = entity.lightRadiusTiles ?? 0;
1592 if (range <= 0)
1593 { continue; }
1594 activeLights.push({
1595 tileX: Math.floor(entity.visualX / tileSize),
1596 tileY: Math.floor(entity.visualY / tileSize),
1597 range,
1598 intensity: 1
1599 });
1600 }
1601
1602 const isPassable = makeSnapshotPassable(this.chunks);
1603
1604 for (const objects of this.tiles.values())
1605 {
1606 const intensity = this.#tileLightIntensity(objects, activeLights, isPassable);
1607 objects.shadeAlpha = ambientDark * (1 - intensity);
1608 if (objects.block)
1609 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1610 if (objects.ground && isWaterGround(objects.groundTypeId))
1611 {
1612 this.#syncWaterGroundSprite(
1613 objects.ground,
1614 objects.shadeAlpha,
1615 objects.waterEdges ?? this.#waterCoastEdges(objects.tileX, objects.tileY),
1616 now / 1000
1617 );
1618 }
1619 else if (objects.ground)
1620 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
1621 }
1622
1623 for (const baked of this.bakedChunks.values())
1624 {
1625 this.#writeChunkLightmap(baked, activeLights, isPassable);
1626 if (baked.groundObject?.renderer?.shaderUniforms)
1627 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1628 for (const object of baked.blockObjects ?? [])
1629 {
1630 if (object?.renderer?.shaderUniforms)
1631 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1632 }
1633 }
1634
1635 for (const item of this.groundItems.values())
1636 {
1637 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1638 this.#syncGroundItemSprite(item, alpha);
1639 }
1640 }
1641
1642 #tileLightIntensity (objects, activeLights, isPassable)
1643 {
1644 const baked = lightIntensity(objects.light ?? 0);
1645 const dynamic = dynamicLightAtTile(
1646 objects.tileX,
1647 objects.tileY,
1648 activeLights,
1649 isPassable
1650 );
1651 return Math.max(baked, dynamic);
1652 }
1653
1654 #writeChunkLightmap (baked, activeLights, isPassable)
1655 {
1656 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1657 if (!snapshot)
1658 { return; }
1659 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
1660 const pixelCount = atlasPx * atlasPx * 4;
1661 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
1662 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
1663 const pixels = baked.lightmapPixels;
1664 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1665 {
1666 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1667 {
1668 const tileX = baked.chunkX * CHUNK_SIZE + localX;
1669 const tileY = baked.chunkY * CHUNK_SIZE + localY;
1670 const index = localY * CHUNK_SIZE + localX;
1671 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
1672 let intensity;
1673 if (tileObjects)
1674 {
1675 intensity = this.#tileLightIntensity(tileObjects, activeLights, isPassable);
1676 }
1677 else
1678 {
1679 const baked = lightIntensity(snapshot.light[index] ?? 0);
1680 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, isPassable);
1681 intensity = Math.max(baked, dynamic);
1682 }
1683 const value = Math.round(Math.min(1, intensity) * 255);
1684 const baseX = localX * SPRITE_SIZE_PX;
1685 const baseY = localY * SPRITE_SIZE_PX;
1686 for (let py = 0; py < SPRITE_SIZE_PX; py++)
1687 {
1688 for (let px = 0; px < SPRITE_SIZE_PX; px++)
1689 {
1690 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
1691 pixels[offset] = value;
1692 pixels[offset + 1] = value;
1693 pixels[offset + 2] = value;
1694 pixels[offset + 3] = 255;
1695 }
1696 }
1697 }
1698 }
1699 const ctx = baked.lightmapCanvas.getContext("2d");
1700 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
1701 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
1702 }
1703
1704 #updateSwipes (now)
1705 {
1706 this.swipes = this.swipes.filter((swipe) =>
1707 {
1708 if (swipe.until > now)
1709 {
1710 if (swipe.fromTileX != null)
1711 {
1712 this.#applyPhysicalCombatFxDarkness(
1713 swipe.object,
1714 swipe.fromTileX,
1715 swipe.fromTileY,
1716 swipe.tileX,
1717 swipe.tileY
1718 );
1719 }
1720 return true;
1721 }
1722 swipe.object?.destroy();
1723 return false;
1724 });
1725 }
1726
1727 #updateDamageNumbers (now)
1728 {
1729 const layer = this.damageNumbersEl;
1730 if (!layer)
1731 { return; }
1732 this.damageFloats = this.damageFloats.filter((entry) =>
1733 {
1734 const elapsed = now - entry.started;
1735 if (elapsed >= DAMAGE_FLOAT_MS)
1736 {
1737 entry.element?.remove();
1738 return false;
1739 }
1740 const entity = this.entities.get(entry.entityId);
1741 if (!entity)
1742 {
1743 entry.element?.remove();
1744 return false;
1745 }
1746 if (!entry.element)
1747 {
1748 entry.element = document.createElement("span");
1749 entry.element.className = "damage-number";
1750 entry.element.textContent = String(entry.damage);
1751 layer.append(entry.element);
1752 }
1753 const anchor = this.nametagAnchor(entity);
1754 if (!anchor)
1755 { return true; }
1756 const t = elapsed / DAMAGE_FLOAT_MS;
1757 entry.element.style.left = `${anchor.x}px`;
1758 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
1759 entry.element.style.opacity = String(1 - t);
1760 return true;
1761 });
1762 }
1763
1764 #syncBloomLayer ()
1765 {
1766 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
1767 this.scene.setLayers([
1768 { name: "default" },
1769 {
1770 name: RENDER_LAYER_BLOOM,
1771 composite: "add",
1772 postShaders: Shader.getBloomPostChain({
1773 threshold: settings.bloomThreshold,
1774 softKnee: settings.bloomSoftKnee,
1775 intensity: settings.bloomIntensity,
1776 blurSize: settings.bloomBlurSize,
1777 saturation: settings.bloomSaturation,
1778 colorPreserve: settings.bloomColorPreserve,
1779 dilate: settings.bloomDilate,
1780 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
1781 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
1782 })
1783 }
1784 ]);
1785 }
1786}
1787
1788export function nightFactor (hour, nightDarkness = 0.72)
1789{
1790 const peak = Math.min(1, Math.max(0, nightDarkness));
1791 if (hour >= 8 && hour <= 16)
1792 { return 0; }
1793 if (hour >= 22 || hour <= 5)
1794 { return peak; }
1795 if (hour < 8)
1796 { return lerp(peak, 0, (hour - 5) / 3); }
1797 return lerp(0, peak, (hour - 16) / 6);
1798}
1799
1800function bodySpriteName (sex)
1801{
1802 const key = sex === "female" ? "player-body-female" : "player-body-male";
1803 return spriteImageName("character", key, key);
1804}
1805
1806function lerp (a, b, t)
1807{
1808 return a + (b - a) * Math.min(1, Math.max(0, t));
1809}
1810
1811function makeLightmapCanvas (size)
1812{
1813 const canvas = document.createElement("canvas");
1814 canvas.width = size;
1815 canvas.height = size;
1816 return canvas;
1817}
1818
1819function copyCanvas (source, dest)
1820{
1821 const ctx = dest.getContext("2d");
1822 ctx.imageSmoothingEnabled = false;
1823 ctx.clearRect(0, 0, dest.width, dest.height);
1824 ctx.drawImage(source, 0, 0);
1825}
1826
1827function drawHpBar (canvas, current, max)
1828{
1829 const ctx = canvas.getContext("2d");
1830 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
1831 ctx.fillStyle = "#000000";
1832 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
1833 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
1834 const fillW = Math.round(12 * ratio);
1835 if (fillW > 0)
1836 {
1837 ctx.fillStyle = "#ff0000";
1838 ctx.fillRect(1, 1, fillW, 2);
1839 }
1840}