BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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