BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 75.7 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:arrow";
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 sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
866 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
867 const object = new GameObject(0, 0, image, SORT_FX);
868 if (object.transform)
869 { object.transform.rotation = angle; }
870 this.scene.addObject(object);
871 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
872 this.#applyPhysicalCombatFxDarkness(
873 object,
874 payload.fromTileX,
875 payload.fromTileY,
876 payload.tileX,
877 payload.tileY
878 );
879 const started = performance.now();
880 const durationMs = payload.durationMs ?? 400;
881 this.swipes.push({
882 object,
883 until: started + durationMs,
884 started,
885 durationMs,
886 lerp: true,
887 fromTileX: payload.fromTileX,
888 fromTileY: payload.fromTileY,
889 tileX: payload.tileX,
890 tileY: payload.tileY
891 });
892 }
893
894 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
895 {
896 this.dynamicLights.push({
897 tileX: Math.floor(worldX),
898 tileY: Math.floor(worldY),
899 range: radiusTiles,
900 intensity,
901 until: performance.now() + durationMs
902 });
903 }
904
905 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
906 {
907 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
908 if (!snapshot)
909 { return; }
910 const index = localY * CHUNK_SIZE + localX;
911 if (ground !== undefined)
912 { snapshot.grounds[index] = ground; }
913 if (block !== undefined)
914 { snapshot.blocks[index] = block; }
915 if (light !== undefined)
916 { snapshot.light[index] = light; }
917 this.#rebuildChunk(snapshot);
918 }
919
920 /**
921 * Editor-only mob markers for authored spawners (invisible during play).
922 * @param {number} chunkX
923 * @param {number} chunkY
924 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
925 * @param {(mobTypeId: string) => string} resolveSprite
926 */
927 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
928 {
929 const prefix = `${chunkX},${chunkY}:`;
930 for (const [key, entry] of [...this.editorSpawners.entries()])
931 {
932 if (!key.startsWith(prefix))
933 { continue; }
934 entry.object?.destroy();
935 this.editorSpawners.delete(key);
936 }
937 for (const spawner of spawners ?? [])
938 {
939 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
940 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
941 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
942 if (!spriteName)
943 { continue; }
944 const key = `${prefix}${spawner.localX},${spawner.localY}`;
945 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
946 if (!object)
947 { continue; }
948 object.renderer.alpha = 0.85;
949 const pivot = tilePivot(tileX, tileY, this.tileSize());
950 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
951 this.#markUnlit(object);
952 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
953 }
954 }
955
956 clearEditorSpawners ()
957 {
958 for (const entry of this.editorSpawners.values())
959 { entry.object?.destroy(); }
960 this.editorSpawners.clear();
961 }
962
963 #relayoutEditorSpawners ()
964 {
965 const size = this.tileSize();
966 for (const entry of this.editorSpawners.values())
967 {
968 if (!entry.object)
969 { continue; }
970 const pivot = tilePivot(entry.tileX, entry.tileY, size);
971 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
972 }
973 }
974
975 /**
976 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
977 */
978 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
979 {
980 const spawnRadius = Math.max(0, spawnRange | 0);
981 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
982 if (this.spawnRangeHighlight
983 && this.wanderRangeHighlight
984 && this.spawnRangeHighlight.tileX === tileX
985 && this.spawnRangeHighlight.tileY === tileY
986 && this.spawnRangeHighlight.range === spawnRadius
987 && this.wanderRangeHighlight.range === wanderRadius)
988 {
989 this.#relayoutSpawnRangeHighlight();
990 return;
991 }
992 this.clearSpawnRangeHighlight();
993 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
994 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
995 if (wanderObject)
996 {
997 this.#markUnlit(wanderObject);
998 wanderObject.renderer.alpha = 1;
999 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
1000 }
1001 if (spawnObject)
1002 {
1003 this.#markUnlit(spawnObject);
1004 spawnObject.renderer.alpha = 1;
1005 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
1006 }
1007 this.#relayoutSpawnRangeHighlight();
1008 }
1009
1010 clearSpawnRangeHighlight ()
1011 {
1012 this.spawnRangeHighlight?.object?.destroy();
1013 this.wanderRangeHighlight?.object?.destroy();
1014 this.spawnRangeHighlight = null;
1015 this.wanderRangeHighlight = null;
1016 }
1017
1018 #relayoutSpawnRangeHighlight ()
1019 {
1020 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
1021 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
1022 }
1023
1024 #layoutRangeOverlay (highlight, layer)
1025 {
1026 if (!highlight?.object)
1027 { return; }
1028 const size = this.tileSize();
1029 const side = (2 * highlight.range + 1) * size;
1030 const left = (highlight.tileX - highlight.range) * size;
1031 const top = (highlight.tileY - highlight.range) * size;
1032 highlight.object.transform.position.x = left + side / 2;
1033 highlight.object.transform.position.y = top + side / 2;
1034 highlight.object.transform.size = new vector(side, side);
1035 highlight.object.layer = layer;
1036 this.#markSortDirty();
1037 }
1038
1039 setTilePreview (tileX, tileY, override)
1040 {
1041 const previous = this.preview;
1042 this.preview = { tileX, tileY, ...override };
1043 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1044 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1045 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1046 if (snapshot)
1047 { this.#rebuildChunk(snapshot); }
1048 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1049 {
1050 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1051 if (prevSnapshot && prevSnapshot !== snapshot)
1052 { this.#rebuildChunk(prevSnapshot); }
1053 }
1054 }
1055
1056 clearTilePreview ()
1057 {
1058 const previous = this.preview;
1059 this.preview = null;
1060 if (previous)
1061 {
1062 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1063 if (snapshot)
1064 { this.#rebuildChunk(snapshot); }
1065 }
1066 }
1067
1068 #lerpMs (gait)
1069 {
1070 const walk = this.settings.walkTilesPerSecond || 2;
1071 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
1072 return seconds * 1000;
1073 }
1074
1075 #centerCamera ()
1076 {
1077 if (!this.followPlayer)
1078 { return; }
1079 const local = this.entities.get(this.localEntityId);
1080 if (!local)
1081 { return; }
1082 const x = local.visualX + (local.stackOffsetX ?? 0);
1083 const y = local.visualY + (local.stackOffsetY ?? 0);
1084 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
1085 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
1086 }
1087
1088 /**
1089 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
1090 * Tiles fully outside this rect are not drawn.
1091 */
1092 #drawBounds ()
1093 {
1094 const pad = this.tileSize() * 0.5;
1095 const camX = this.scene.cameraPosition.x;
1096 const camY = this.scene.cameraPosition.y;
1097 const w = this.scene.real_size.x;
1098 const h = this.scene.real_size.y;
1099 return {
1100 left: -camX - pad,
1101 right: -camX + w + pad,
1102 top: -camY - pad,
1103 bottom: -camY + h + pad
1104 };
1105 }
1106
1107 #rectIntersects (left, top, right, bottom, bounds)
1108 {
1109 return right >= bounds.left
1110 && left <= bounds.right
1111 && bottom >= bounds.top
1112 && top <= bounds.bottom;
1113 }
1114
1115 #setRendererVisible (object, visible)
1116 {
1117 if (object?.renderer)
1118 { object.renderer.visible = !!visible; }
1119 }
1120
1121 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
1122 #cullOffscreenDrawables ()
1123 {
1124 const bounds = this.#drawBounds();
1125 const size = this.tileSize();
1126
1127 for (const baked of this.bakedChunks.values())
1128 {
1129 const left = baked.chunkX * CHUNK_SIZE * size;
1130 const top = baked.chunkY * CHUNK_SIZE * size;
1131 const chunkPx = CHUNK_SIZE * size;
1132 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
1133 this.#setRendererVisible(baked.groundObject, chunkVisible);
1134 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
1135 baked._inViewport = chunkVisible;
1136 for (let row = 0; row < CHUNK_SIZE; row++)
1137 {
1138 const rowTop = top + row * size;
1139 const rowVisible = chunkVisible && this.#rectIntersects(
1140 left, rowTop, left + chunkPx, rowTop + size, bounds
1141 );
1142 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
1143 }
1144 }
1145
1146 for (const objects of this.tiles.values())
1147 {
1148 const left = objects.tileX * size;
1149 const top = objects.tileY * size;
1150 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
1151 objects._inViewport = visible;
1152 this.#setRendererVisible(objects.ground, visible);
1153 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
1154 this.#setRendererVisible(objects.block, visible);
1155 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
1156 if (objects.waterEdges)
1157 {
1158 for (const edge of Object.values(objects.waterEdges))
1159 { this.#setRendererVisible(edge, visible); }
1160 }
1161 }
1162 }
1163
1164 #upsertEntity (payload)
1165 {
1166 const size = this.tileSize();
1167 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1168 let entity = this.entities.get(payload.entityId);
1169 if (!entity)
1170 {
1171 const spriteName = payload.layers?.[0]?.sprite
1172 ?? payload.sprite
1173 ?? bodySpriteName(payload.sex);
1174 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
1175 this.scene.addObject(object);
1176 this.#startIdleAnimation(object);
1177 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
1178 this.entities.set(payload.entityId, entity);
1179 }
1180 entity.entityId = payload.entityId;
1181 entity.tileX = payload.tileX;
1182 entity.tileY = payload.tileY;
1183 entity.gait = payload.gait;
1184 entity.sex = payload.sex ?? entity.sex;
1185 entity.characterId = payload.characterId ?? entity.characterId ?? null;
1186 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1187 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
1188 entity.canFight = payload.canFight != null
1189 ? !!payload.canFight
1190 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1191 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1192 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1193 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1194 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
1195 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1196 if (payload.visualScale != null)
1197 { entity.visualScale = Number(payload.visualScale) || 1; }
1198 else if (entity.visualScale == null)
1199 { entity.visualScale = 1; }
1200 if (payload.health != null)
1201 { entity.health = payload.health; }
1202 if (payload.maxHealth != null)
1203 { entity.maxHealth = payload.maxHealth; }
1204 if (payload.firstName)
1205 { entity.firstName = payload.firstName; }
1206 if (payload.lastName)
1207 { entity.lastName = payload.lastName; }
1208 entity.firstName = entity.firstName ?? "";
1209 entity.lastName = entity.lastName ?? "";
1210 if (payload.worldX != null && payload.worldY != null)
1211 {
1212 entity.worldX = payload.worldX;
1213 entity.worldY = payload.worldY;
1214 entity.visualX = payload.worldX * size;
1215 entity.visualY = payload.worldY * size;
1216 entity.targetX = entity.visualX;
1217 entity.targetY = entity.visualY;
1218 }
1219 else
1220 {
1221 entity.visualX = pivot.x;
1222 entity.visualY = pivot.y;
1223 entity.targetX = pivot.x;
1224 entity.targetY = pivot.y;
1225 }
1226 entity.fromX = entity.visualX;
1227 entity.fromY = entity.visualY;
1228 if (payload.layers)
1229 { this.#applyLayers(entity, payload.layers); }
1230 this.#syncHpBar(entity);
1231 this.#placeEntity(entity, performance.now());
1232 }
1233
1234 #applyLayers (entity, layers)
1235 {
1236 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
1237 this.#rebuildOverlays(entity);
1238 }
1239
1240 #setGatherToolOverlay (entity, toolItemId)
1241 {
1242 entity.gatherToolItemId = toolItemId;
1243 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
1244 this.#rebuildOverlays(entity);
1245 this.#placeEntity(entity, performance.now());
1246 }
1247
1248 #expireGatherToolOverlay (entity, now)
1249 {
1250 if (entity.gatherToolItemId == null)
1251 { return; }
1252 if ((entity.gatherToolUntil ?? 0) > now)
1253 { return; }
1254 entity.gatherToolItemId = null;
1255 entity.gatherToolUntil = 0;
1256 this.#rebuildOverlays(entity);
1257 }
1258
1259 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
1260 #layersForDisplay (entity)
1261 {
1262 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
1263 const toolId = entity.gatherToolItemId;
1264 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
1265 { return layers; }
1266 const equip = itemEquipSprite(toolId);
1267 if (!equip || !this.game.images[equip])
1268 { return layers; }
1269 const replacement = {
1270 sprite: equip,
1271 itemId: toolId,
1272 tint: resolveEquipTint(toolId)
1273 };
1274 for (let index = layers.length - 1; index >= 1; index--)
1275 {
1276 const def = itemDefinition(layers[index].itemId);
1277 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
1278 {
1279 layers[index] = replacement;
1280 return layers;
1281 }
1282 }
1283 layers.push(replacement);
1284 return layers;
1285 }
1286
1287 #rebuildOverlays (entity)
1288 {
1289 const layers = this.#layersForDisplay(entity);
1290 const base = layers[0]?.sprite
1291 ?? bodySpriteName(entity.sex);
1292 if (this.game.images[base])
1293 {
1294 entity.object.renderer.sprite = this.game.images[base];
1295 this.#startIdleAnimation(entity.object);
1296 }
1297 for (const overlay of entity.overlays ?? [])
1298 { overlay.destroy(); }
1299 for (const overlay of entity.bloomOverlays ?? [])
1300 { overlay.destroy(); }
1301 entity.overlays = [];
1302 entity.overlayTints = [];
1303 entity.bloomOverlays = [];
1304 for (const layer of layers.slice(1))
1305 {
1306 const image = this.game.images[layer.sprite];
1307 if (!image)
1308 { continue; }
1309 const object = new GameObject(0, 0, image, SORT_ENTITY);
1310 this.scene.addObject(object);
1311 entity.overlays.push(object);
1312 entity.overlayTints.push(
1313 layer.tint
1314 ? normalizeRgb(layer.tint)
1315 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
1316 );
1317 const bloomName = bloomCompanionName(layer.sprite);
1318 const bloomImage = this.game.images[bloomName];
1319 if (!bloomImage)
1320 { continue; }
1321 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
1322 bloom.renderer.layer = RENDER_LAYER_BLOOM;
1323 this.#markUnlit(bloom);
1324 this.scene.addObject(bloom);
1325 entity.bloomOverlays.push(bloom);
1326 }
1327 }
1328
1329 #placeEntity (entity, now = performance.now())
1330 {
1331 const zoom = this.zoom;
1332 const offsetX = entity.shoveOffsetX ?? 0;
1333 const offsetY = entity.shoveOffsetY ?? 0;
1334 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
1335 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
1336 let walkTilt = 0;
1337 if (entity.lerpStarted != null)
1338 {
1339 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
1340 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
1341 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
1342 walkTilt = Math.sin(cycles) * tilt;
1343 }
1344 const flashStrength = (entity.damageFlashUntil ?? 0) > now
1345 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
1346 : 0;
1347 const tileShade = this.#entityShadeAlpha(entity, now);
1348 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
1349
1350 entity.object.transform.rotation = walkTilt;
1351 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
1352 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1);
1353 for (let index = 0; index < (entity.overlays ?? []).length; index++)
1354 {
1355 const overlay = entity.overlays[index];
1356 const overlaySortY = pivotY + 0.5 * (index + 1);
1357 overlay.transform.rotation = walkTilt;
1358 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
1359 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
1360 }
1361 for (const overlay of entity.bloomOverlays ?? [])
1362 {
1363 this.#setRendererVisible(overlay, this.bloomEnabled);
1364 if (!this.bloomEnabled)
1365 { continue; }
1366 overlay.transform.rotation = walkTilt;
1367 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1368 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
1369 }
1370 this.#placeHpBar(entity, pivotX, pivotY);
1371 }
1372
1373 #markUnlit (object)
1374 {
1375 if (!object?.renderer)
1376 { return; }
1377 object._lit = false;
1378 object.renderer.shader = null;
1379 object.renderer.shaderUniforms = null;
1380 object.renderer.secondaryMap = null;
1381 }
1382
1383 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
1384 {
1385 if (!object?.renderer || object._lit === false)
1386 { return; }
1387 object._lit = true;
1388 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1389 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1390 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1391 const tint = tintColor ? normalizeRgb(tintColor) : null;
1392 if (tint)
1393 {
1394 object.renderer.shader = getTintLitSpriteShader();
1395 object.renderer.shaderUniforms = {
1396 u_darkness: dark,
1397 u_strength: flash,
1398 u_wade: wade ? 1 : 0,
1399 u_spriteHeight: height,
1400 u_useTint: 1,
1401 u_tintColor: [tint.r, tint.g, tint.b]
1402 };
1403 }
1404 else
1405 {
1406 object.renderer.shader = getSpriteLightingShader();
1407 object.renderer.shaderUniforms = {
1408 u_darkness: dark,
1409 u_strength: flash,
1410 u_wade: wade ? 1 : 0,
1411 u_spriteHeight: height
1412 };
1413 }
1414 object.renderer.secondaryMap = null;
1415 }
1416
1417 #syncGroundItemSprite (item, darkness)
1418 {
1419 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
1420 }
1421
1422 #groundTypeAt (tileX, tileY)
1423 {
1424 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1425 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1426 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1427 if (!snapshot)
1428 { return null; }
1429 const localX = tileX - chunkX * CHUNK_SIZE;
1430 const localY = tileY - chunkY * CHUNK_SIZE;
1431 const index = localY * CHUNK_SIZE + localX;
1432 return normalizeGround(snapshot.grounds?.[index]).typeId;
1433 }
1434
1435 #waterCoastEdges (tileX, tileY)
1436 {
1437 const season = this.worldSeason;
1438 return {
1439 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
1440 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
1441 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
1442 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
1443 };
1444 }
1445
1446 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
1447 {
1448 if (!object?.renderer)
1449 { return; }
1450 const lit = corners ?? {
1451 nw: fallbackLit,
1452 ne: fallbackLit,
1453 sw: fallbackLit,
1454 se: fallbackLit
1455 };
1456 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
1457 object._lit = true;
1458 object.renderer.shader = getWaterGroundShader();
1459 object.renderer.secondaryMap = null;
1460 object.renderer.shaderUniforms = {
1461 u_ambientDark: dark,
1462 u_litNW: lit.nw,
1463 u_litNE: lit.ne,
1464 u_litSW: lit.sw,
1465 u_litSE: lit.se,
1466 u_time: timeSec,
1467 u_edgeN: edges?.n ?? 0,
1468 u_edgeE: edges?.e ?? 0,
1469 u_edgeS: edges?.s ?? 0,
1470 u_edgeW: edges?.w ?? 0
1471 };
1472 }
1473
1474 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
1475 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
1476 {
1477 if (!objects?.ground)
1478 { return; }
1479 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
1480 {
1481 objects.waterEdges = null;
1482 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
1483 return;
1484 }
1485 const fallbackLit = ambientDark > 0
1486 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
1487 : 1;
1488 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
1489 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
1490 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
1491 const localX = objects.tileX - chunkX * CHUNK_SIZE;
1492 const localY = objects.tileY - chunkY * CHUNK_SIZE;
1493 let litCorners = null;
1494 if (chunkBaked)
1495 {
1496 if (this.lightingMode === "simple")
1497 {
1498 const gridW = CHUNK_SIZE + 2;
1499 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
1500 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
1501 }
1502 else
1503 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
1504 }
1505 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1506 this.#syncWaterGroundSprite(
1507 objects.ground,
1508 litCorners,
1509 ambientDark,
1510 objects.waterEdges,
1511 timeSec,
1512 fallbackLit
1513 );
1514 }
1515
1516 #ambientDarkness ()
1517 {
1518 const hour = this.nightPreview ?? this.worldHour;
1519 let dark = nightFactor(hour, this.settings.nightDarkness);
1520 if (this.localBlind)
1521 { dark = Math.min(1, dark + 0.85); }
1522 return dark;
1523 }
1524
1525 setLocalBlind (blind)
1526 {
1527 this.localBlind = !!blind;
1528 }
1529
1530 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
1531 #blindVisionLight ()
1532 {
1533 if (!this.localBlind)
1534 { return null; }
1535 const local = this.entities.get(this.localEntityId);
1536 if (!local)
1537 { return null; }
1538 const tileSize = this.tileSize();
1539 return {
1540 tileX: Math.floor(local.visualX / tileSize),
1541 tileY: Math.floor(local.visualY / tileSize),
1542 range: 2.25,
1543 intensity: 1
1544 };
1545 }
1546
1547 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
1548 {
1549 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
1550 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
1551 this.#syncLitSprite(object, (fromAlpha + toAlpha) / 2);
1552 }
1553
1554 #syncHpBar (entity)
1555 {
1556 const current = entity.health;
1557 const max = entity.maxHealth;
1558 const show = current != null
1559 && max != null
1560 && max > 0
1561 && current < max;
1562 if (!show)
1563 {
1564 entity.hpBar?.destroy();
1565 entity.hpBar = null;
1566 entity.hpBarCanvas = null;
1567 return;
1568 }
1569 if (!entity.hpBarCanvas)
1570 {
1571 entity.hpBarCanvas = document.createElement("canvas");
1572 entity.hpBarCanvas.width = HP_BAR_W;
1573 entity.hpBarCanvas.height = HP_BAR_H;
1574 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
1575 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
1576 this.#markUnlit(entity.hpBar);
1577 this.scene.addObject(entity.hpBar);
1578 }
1579 drawHpBar(entity.hpBarCanvas, current, max);
1580 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
1581 }
1582
1583 #placeHpBar (entity, pivotX, pivotY)
1584 {
1585 if (!entity.hpBar)
1586 { return; }
1587 const sprite = entity.object?.renderer?.sprite;
1588 if (!sprite)
1589 { return; }
1590 const zoom = this.zoom;
1591 const drawH = sprite.height * zoom;
1592 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
1593 const spriteTop = centerY - drawH / 2;
1594 const barW = HP_BAR_W * zoom;
1595 const barH = HP_BAR_H * zoom;
1596 entity.hpBar.transform.position.x = pivotX;
1597 entity.hpBar.transform.position.y = spriteTop - barH / 2;
1598 entity.hpBar.transform.size = new vector(barW, barH);
1599 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
1600 this.#markSortDirty();
1601 }
1602
1603 #rebuildChunk (snapshot)
1604 {
1605 this.#bakeAndPlaceChunk(snapshot);
1606 const tall = new Set(
1607 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
1608 .map((entry) => `${entry.tileX},${entry.tileY}`)
1609 );
1610 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1611 {
1612 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1613 {
1614 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
1615 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
1616 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
1617 }
1618 }
1619 }
1620
1621 #rebakeAllChunks ()
1622 {
1623 for (const snapshot of this.chunks.values())
1624 { this.#rebuildChunk(snapshot); }
1625 }
1626
1627 #bakeAndPlaceChunk (snapshot)
1628 {
1629 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1630 const atlases = bakeChunkAtlases({
1631 snapshot,
1632 catalog: this.catalog,
1633 images: this.game.images,
1634 preview: this.preview,
1635 season: this.worldSeason
1636 });
1637 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
1638 let baked = this.bakedChunks.get(key);
1639 if (!baked)
1640 {
1641 const lightmapCanvas = makeLightmapCanvas(atlasPx);
1642 baked = {
1643 groundCanvas: atlases.ground,
1644 blockCanvases: atlases.blockRows,
1645 bloomCanvas: atlases.bloom,
1646 lightmapCanvas,
1647 groundImage: frameworkImageFromCanvas(atlases.ground),
1648 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
1649 bloomImage: frameworkImageFromCanvas(atlases.bloom),
1650 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
1651 groundObject: null,
1652 blockObjects: [],
1653 bloomObject: null,
1654 tallBlocks: atlases.tallBlocks,
1655 animatedGrounds: atlases.animatedGrounds,
1656 lightmapPixels: null
1657 };
1658 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
1659 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
1660 this.scene.addObject(baked.groundObject);
1661 for (let row = 0; row < CHUNK_SIZE; row++)
1662 {
1663 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
1664 this.#applyAtlasLighting(object, baked.lightmapImage, row);
1665 this.scene.addObject(object);
1666 baked.blockObjects.push(object);
1667 }
1668 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
1669 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
1670 this.#markUnlit(baked.bloomObject);
1671 this.scene.addObject(baked.bloomObject);
1672 this.bakedChunks.set(key, baked);
1673 }
1674 else
1675 {
1676 copyCanvas(atlases.ground, baked.groundCanvas);
1677 for (let row = 0; row < CHUNK_SIZE; row++)
1678 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
1679 copyCanvas(atlases.bloom, baked.bloomCanvas);
1680 invalidateCanvasTexture(this.scene, baked.groundCanvas);
1681 for (const canvas of baked.blockCanvases)
1682 { invalidateCanvasTexture(this.scene, canvas); }
1683 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1684 baked.tallBlocks = atlases.tallBlocks;
1685 baked.animatedGrounds = atlases.animatedGrounds;
1686 }
1687 baked.chunkX = snapshot.chunkX;
1688 baked.chunkY = snapshot.chunkY;
1689 this.#layoutBakedChunk(snapshot);
1690 }
1691
1692 #applyAtlasLighting (object, lightmapImage, lightRow)
1693 {
1694 if (!object?.renderer)
1695 { return; }
1696 object._lit = true;
1697 object.renderer.shader = getAtlasLightingShader();
1698 object.renderer.secondaryMap = lightmapImage;
1699 object.renderer.shaderUniforms = {
1700 u_ambientDark: 0,
1701 u_lightRow: lightRow
1702 };
1703 }
1704
1705 #layoutBakedChunk (snapshot)
1706 {
1707 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1708 const baked = this.bakedChunks.get(key);
1709 if (!baked)
1710 { return; }
1711 const size = this.tileSize();
1712 const left = snapshot.chunkX * CHUNK_SIZE * size;
1713 const top = snapshot.chunkY * CHUNK_SIZE * size;
1714 const chunkPx = CHUNK_SIZE * size;
1715 baked.groundObject.transform.position.x = left + chunkPx / 2;
1716 baked.groundObject.transform.position.y = top + chunkPx / 2;
1717 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
1718 baked.groundObject.layer = LAYER_GROUND;
1719
1720 for (let row = 0; row < CHUNK_SIZE; row++)
1721 {
1722 const object = baked.blockObjects[row];
1723 const rowY = top + row * size + size / 2;
1724 object.transform.position.x = left + chunkPx / 2;
1725 object.transform.position.y = rowY;
1726 object.transform.size = new vector(chunkPx, size);
1727 object.layer = ySortLayer(rowY, SORT_BLOCK);
1728 }
1729
1730 baked.bloomObject.transform.position.x = left + chunkPx / 2;
1731 baked.bloomObject.transform.position.y = top + chunkPx / 2;
1732 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
1733 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
1734 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
1735 this.#markSortDirty();
1736 setNearestFilter(this.scene, baked.groundCanvas);
1737 for (const canvas of baked.blockCanvases)
1738 { setNearestFilter(this.scene, canvas); }
1739 setNearestFilter(this.scene, baked.bloomCanvas);
1740 setNearestFilter(this.scene, baked.lightmapCanvas);
1741 }
1742
1743 #destroyBakedChunk (key)
1744 {
1745 const baked = this.bakedChunks.get(key);
1746 if (!baked)
1747 { return; }
1748 baked.groundObject?.destroy();
1749 for (const object of baked.blockObjects ?? [])
1750 { object.destroy(); }
1751 baked.bloomObject?.destroy();
1752 invalidateCanvasTexture(this.scene, baked.groundCanvas);
1753 for (const canvas of baked.blockCanvases ?? [])
1754 { invalidateCanvasTexture(this.scene, canvas); }
1755 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
1756 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
1757 this.bakedChunks.delete(key);
1758 }
1759
1760 #redrawPreview ()
1761 {
1762 if (!this.preview)
1763 { return; }
1764 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
1765 if (snapshot)
1766 { this.#rebuildChunk(snapshot); }
1767 }
1768
1769 #refreshWaterCoastsNear (chunkX, chunkY)
1770 {
1771 const timeSec = performance.now() / 1000;
1772 for (const objects of this.tiles.values())
1773 {
1774 if (!objects.ground || !isWaterGround(objects.groundTypeId))
1775 { continue; }
1776 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
1777 { continue; }
1778 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
1779 }
1780 }
1781
1782 #drawTile (tileX, tileY, forceTall = null)
1783 {
1784 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1785 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1786 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1787 if (!snapshot)
1788 { return; }
1789 const localX = tileX - chunkX * CHUNK_SIZE;
1790 const localY = tileY - chunkY * CHUNK_SIZE;
1791 const index = localY * CHUNK_SIZE + localX;
1792 const key = `${tileX},${tileY}`;
1793 let objects = this.tiles.get(key);
1794 if (!objects)
1795 {
1796 objects = { chunkX, chunkY, tileX, tileY };
1797 this.tiles.set(key, objects);
1798 }
1799 objects.tileX = tileX;
1800 objects.tileY = tileY;
1801 objects.chunkX = chunkX;
1802 objects.chunkY = chunkY;
1803 objects.light = snapshot.light[index] ?? 0;
1804
1805 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1806 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1807 if (animatedGround)
1808 {
1809 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
1810 if (objects.ground)
1811 {
1812 const size = this.tileSize();
1813 objects.ground.transform.position.x = tileX * size + size / 2;
1814 objects.ground.transform.position.y = tileY * size + size / 2;
1815 objects.ground.transform.size = new vector(size, size);
1816 objects.ground.layer = LAYER_GROUND;
1817 objects.groundTypeId = animatedGround.typeId;
1818 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
1819 this.#markSortDirty();
1820 }
1821 if (animatedGround.bloom)
1822 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
1823 else
1824 {
1825 objects.groundBloom?.destroy();
1826 objects.groundBloom = null;
1827 }
1828 }
1829 else
1830 {
1831 objects.ground?.destroy();
1832 objects.ground = null;
1833 objects.groundBloom?.destroy();
1834 objects.groundBloom = null;
1835 objects.groundTypeId = null;
1836 objects.waterEdges = null;
1837 }
1838
1839 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1840 const isTall = forceTall === true || !!tallEntry;
1841 if (isTall && tallEntry)
1842 {
1843 const pivot = tilePivot(tileX, tileY, this.tileSize());
1844 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
1845 if (objects.block)
1846 {
1847 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
1848 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
1849 }
1850 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
1851 }
1852 else
1853 {
1854 objects.block?.destroy();
1855 objects.block = null;
1856 objects.blockBloom?.destroy();
1857 objects.blockBloom = null;
1858 }
1859 }
1860
1861 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
1862 {
1863 if (!name)
1864 {
1865 existing?.destroy();
1866 return null;
1867 }
1868 const object = this.#ensureSprite(existing, name, sortOrder);
1869 if (!object)
1870 { return null; }
1871 object.renderer.layer = RENDER_LAYER_BLOOM;
1872 this.#markUnlit(object);
1873 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
1874 return object;
1875 }
1876
1877 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
1878 {
1879 const sprite = object?.renderer?.sprite;
1880 if (!sprite)
1881 { return; }
1882 const zoom = this.zoom;
1883 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1884 const factor = Math.max(0.1, Number(scale) || 1);
1885 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
1886 object.transform.position.x = center.x;
1887 object.transform.position.y = center.y;
1888 object.transform.size = new vector(draw.w * factor, draw.h * factor);
1889 object.layer = ySortLayer(sortY, subOrder);
1890 this.#markSortDirty();
1891 }
1892
1893 #ensureSprite (existing, name, layer)
1894 {
1895 const sprite = this.game.images[name];
1896 if (!sprite)
1897 {
1898 existing?.destroy();
1899 return null;
1900 }
1901 if (!existing || existing.renderer.sprite !== sprite)
1902 {
1903 existing?.destroy();
1904 existing = new GameObject(0, 0, sprite, layer);
1905 this.#syncLitSprite(existing, 0);
1906 this.scene.addObject(existing);
1907 this.#startIdleAnimation(existing);
1908 }
1909 return existing;
1910 }
1911
1912 #startIdleAnimation (object)
1913 {
1914 const sprite = object?.renderer?.sprite;
1915 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
1916 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
1917 }
1918
1919 #neighborClosed (snapshot, dir, dx, dy)
1920 {
1921 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
1922 if (other)
1923 { return !other.open; }
1924 return !!snapshot.closedEdges?.[dir];
1925 }
1926
1927 #rebuildAllEdges ()
1928 {
1929 const seen = new Set();
1930 for (const snapshot of this.chunks.values())
1931 {
1932 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1933 seen.add(key);
1934 this.#rebuildChunkEdges(snapshot);
1935 }
1936 for (const key of [...this.edges.keys()])
1937 {
1938 if (!seen.has(key))
1939 { this.#destroyEdges(key); }
1940 }
1941 }
1942
1943 #rebuildChunkEdges (snapshot)
1944 {
1945 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1946 let bars = this.edges.get(key);
1947 if (!bars)
1948 {
1949 bars = {};
1950 this.edges.set(key, bars);
1951 }
1952
1953 const size = this.tileSize();
1954 const chunkPx = CHUNK_SIZE * size;
1955 const left = snapshot.chunkX * CHUNK_SIZE * size;
1956 const top = snapshot.chunkY * CHUNK_SIZE * size;
1957 const centerX = left + chunkPx / 2;
1958 const centerY = top + chunkPx / 2;
1959 const thickness = Math.max(2, Math.round(2 * this.zoom));
1960 const draw = snapshot.open === true;
1961
1962 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
1963 centerX, top, chunkPx, thickness, true);
1964 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
1965 centerX, top + chunkPx, chunkPx, thickness, true);
1966 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
1967 left, centerY, chunkPx, thickness, false);
1968 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
1969 left + chunkPx, centerY, chunkPx, thickness, false);
1970 }
1971
1972 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
1973 {
1974 if (!visible)
1975 {
1976 if (existing)
1977 { existing.renderer.visible = false; }
1978 return existing;
1979 }
1980
1981 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
1982 this.#markUnlit(existing);
1983 existing.renderer.visible = true;
1984 existing.transform.position.x = x;
1985 existing.transform.position.y = y;
1986 existing.transform.size = horizontal
1987 ? new vector(length, thickness)
1988 : new vector(thickness, length);
1989 existing.layer = LAYER_EDGE;
1990 this.#markSortDirty();
1991 return existing;
1992 }
1993
1994 #destroyEdges (key)
1995 {
1996 const bars = this.edges.get(key);
1997 if (!bars)
1998 { return; }
1999 bars.north?.destroy();
2000 bars.east?.destroy();
2001 bars.south?.destroy();
2002 bars.west?.destroy();
2003 this.edges.delete(key);
2004 }
2005
2006 #entityShadeAlpha (entity, now)
2007 {
2008 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
2009 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
2010 { return toAlpha; }
2011 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
2012 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
2013 return fromAlpha + (toAlpha - fromAlpha) * t;
2014 }
2015
2016 #markSortDirty ()
2017 {
2018 this.scene._sortDirty = true;
2019 }
2020
2021 #updateShade ()
2022 {
2023 const ambientDark = this.#ambientDarkness();
2024 const now = performance.now();
2025 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
2026
2027 const activeLights = [...this.dynamicLights];
2028 const tileSize = this.tileSize();
2029 const blindLight = this.#blindVisionLight();
2030 if (blindLight)
2031 { activeLights.push(blindLight); }
2032 for (const entity of this.entities.values())
2033 {
2034 const range = entity.lightRadiusTiles ?? 0;
2035 if (range <= 0)
2036 { continue; }
2037 activeLights.push({
2038 tileX: Math.floor(entity.visualX / tileSize),
2039 tileY: Math.floor(entity.visualY / tileSize),
2040 range,
2041 intensity: 1
2042 });
2043 }
2044
2045 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
2046
2047 for (const objects of this.tiles.values())
2048 {
2049 if (objects._inViewport === false)
2050 { continue; }
2051 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
2052 objects.shadeAlpha = ambientDark * (1 - intensity);
2053 }
2054
2055 for (const baked of this.bakedChunks.values())
2056 {
2057 if (baked._inViewport === false)
2058 { continue; }
2059 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
2060 if (baked.groundObject?.renderer?.shaderUniforms)
2061 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
2062 for (const object of baked.blockObjects ?? [])
2063 {
2064 if (object?.renderer?.shaderUniforms)
2065 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
2066 }
2067 }
2068
2069 const timeSec = now / 1000;
2070 for (const objects of this.tiles.values())
2071 {
2072 if (objects._inViewport === false)
2073 { continue; }
2074 if (objects.block)
2075 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
2076 if (objects.ground && isWaterGround(objects.groundTypeId))
2077 {
2078 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
2079 this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked);
2080 }
2081 else if (objects.ground)
2082 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
2083 }
2084
2085 for (const item of this.groundItems.values())
2086 {
2087 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
2088 this.#syncGroundItemSprite(item, alpha);
2089 }
2090 }
2091
2092 #tileLightIntensity (objects, activeLights, lightOcclusion)
2093 {
2094 const baked = lightIntensity(objects.light ?? 0);
2095 const dynamic = dynamicLightAtTile(
2096 objects.tileX,
2097 objects.tileY,
2098 activeLights,
2099 lightOcclusion
2100 );
2101 return Math.max(baked, dynamic);
2102 }
2103
2104 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
2105 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
2106 {
2107 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
2108 if (tileObjects)
2109 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
2110 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2111 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2112 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2113 if (!snapshot)
2114 { return 0; }
2115 const localX = tileX - chunkX * CHUNK_SIZE;
2116 const localY = tileY - chunkY * CHUNK_SIZE;
2117 const index = localY * CHUNK_SIZE + localX;
2118 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
2119 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
2120 return Math.max(bakedLit, dynamic);
2121 }
2122
2123 /** True when ground or block on this tile occludes light rays (same rules as bake). */
2124 #tileOccludesLight (tileX, tileY)
2125 {
2126 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2127 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2128 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2129 if (!snapshot)
2130 { return false; }
2131 const localX = tileX - chunkX * CHUNK_SIZE;
2132 const localY = tileY - chunkY * CHUNK_SIZE;
2133 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
2134 { return false; }
2135 const index = localY * CHUNK_SIZE + localX;
2136 const ground = normalizeGround(snapshot.grounds?.[index]);
2137 if (!isGroundPassable(ground.typeId))
2138 { return true; }
2139 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
2140 }
2141
2142 #fillChunkLightGrids (baked, activeLights, lightOcclusion)
2143 {
2144 const gridW = CHUNK_SIZE + 2;
2145 const gridSize = gridW * gridW;
2146 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
2147 { baked.lightIntensityGrid = new Float32Array(gridSize); }
2148 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
2149 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
2150 const grid = baked.lightIntensityGrid;
2151 const occlude = baked.lightOccludeGrid;
2152 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
2153 {
2154 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
2155 {
2156 const tileX = baked.chunkX * CHUNK_SIZE + lx;
2157 const tileY = baked.chunkY * CHUNK_SIZE + ly;
2158 const gi = (ly + 1) * gridW + (lx + 1);
2159 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
2160 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
2161 }
2162 }
2163 return { grid, occlude, gridW };
2164 }
2165
2166 #makeLightCornerSampler (grid, occlude, gridW)
2167 {
2168 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
2169 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
2170 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
2171 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
2172 {
2173 const home = sample(homeLx, homeLy);
2174 if (blocks(homeLx, homeLy))
2175 { return home; }
2176 let sum = home;
2177 let count = 1;
2178 sum += openSample(aLx, aLy);
2179 count += 1;
2180 sum += openSample(bLx, bLy);
2181 count += 1;
2182 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
2183 {
2184 sum += openSample(dLx, dLy);
2185 count += 1;
2186 }
2187 return sum / count;
2188 };
2189 return { smoothCorner };
2190 }
2191
2192 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
2193 #tileLitCorners (baked, localX, localY)
2194 {
2195 const grid = baked?.lightIntensityGrid;
2196 const occlude = baked?.lightOccludeGrid;
2197 if (!grid?.length || !occlude?.length)
2198 { return null; }
2199 const gridW = CHUNK_SIZE + 2;
2200 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
2201 return {
2202 nw: smoothCorner(
2203 localX, localY,
2204 localX - 1, localY,
2205 localX, localY - 1,
2206 localX - 1, localY - 1
2207 ),
2208 ne: smoothCorner(
2209 localX, localY,
2210 localX + 1, localY,
2211 localX, localY - 1,
2212 localX + 1, localY - 1
2213 ),
2214 sw: smoothCorner(
2215 localX, localY,
2216 localX - 1, localY,
2217 localX, localY + 1,
2218 localX - 1, localY + 1
2219 ),
2220 se: smoothCorner(
2221 localX, localY,
2222 localX + 1, localY,
2223 localX, localY + 1,
2224 localX + 1, localY + 1
2225 )
2226 };
2227 }
2228
2229 /**
2230 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
2231 * occluding tiles stay flat and contribute 0 into others so light does not bleed
2232 * through a wall to the far side. Diagonals only when both cardinals are clear.
2233 */
2234 #writeChunkLightmap (baked, activeLights, lightOcclusion)
2235 {
2236 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
2237 if (!snapshot)
2238 { return; }
2239 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2240 const pixelCount = atlasPx * atlasPx * 4;
2241 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
2242 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
2243 const pixels = baked.lightmapPixels;
2244
2245 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
2246 const simple = this.lightingMode === "simple";
2247
2248 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2249 {
2250 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2251 {
2252 const baseX = localX * SPRITE_SIZE_PX;
2253 const baseY = localY * SPRITE_SIZE_PX;
2254 if (simple)
2255 {
2256 const gridW = CHUNK_SIZE + 2;
2257 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
2258 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
2259 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2260 {
2261 for (let px = 0; px < SPRITE_SIZE_PX; px++)
2262 {
2263 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
2264 pixels[offset] = value;
2265 pixels[offset + 1] = value;
2266 pixels[offset + 2] = value;
2267 pixels[offset + 3] = 255;
2268 }
2269 }
2270 continue;
2271 }
2272 const corners = this.#tileLitCorners(baked, localX, localY);
2273 const nw = corners.nw;
2274 const ne = corners.ne;
2275 const sw = corners.sw;
2276 const se = corners.se;
2277 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2278 {
2279 const v = (py + 0.5) / SPRITE_SIZE_PX;
2280 const left = nw + (sw - nw) * v;
2281 const right = ne + (se - ne) * v;
2282 for (let px = 0; px < SPRITE_SIZE_PX; px++)
2283 {
2284 const u = (px + 0.5) / SPRITE_SIZE_PX;
2285 const intensity = left + (right - left) * u;
2286 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
2287 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
2288 pixels[offset] = value;
2289 pixels[offset + 1] = value;
2290 pixels[offset + 2] = value;
2291 pixels[offset + 3] = 255;
2292 }
2293 }
2294 }
2295 }
2296 const ctx = baked.lightmapCanvas.getContext("2d");
2297 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
2298 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
2299 }
2300
2301 #updateSwipes (now)
2302 {
2303 this.swipes = this.swipes.filter((swipe) =>
2304 {
2305 if (swipe.lerp && swipe.started != null)
2306 {
2307 const durationMs = swipe.durationMs ?? 400;
2308 const t = Math.min(1, (now - swipe.started) / durationMs);
2309 const fromPivot = tilePivot(swipe.fromTileX, swipe.fromTileY, this.tileSize());
2310 const toPivot = tilePivot(swipe.tileX, swipe.tileY, this.tileSize());
2311 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
2312 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
2313 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
2314 if (swipe.object?.transform)
2315 {
2316 swipe.object.transform.rotation = Math.atan2(
2317 toPivot.y - fromPivot.y,
2318 toPivot.x - fromPivot.x
2319 ) * (180 / Math.PI);
2320 }
2321 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
2322 this.#applyPhysicalCombatFxDarkness(
2323 swipe.object,
2324 swipe.fromTileX,
2325 swipe.fromTileY,
2326 swipe.tileX,
2327 swipe.tileY
2328 );
2329 }
2330 else if (swipe.fromTileX != null)
2331 {
2332 this.#applyPhysicalCombatFxDarkness(
2333 swipe.object,
2334 swipe.fromTileX,
2335 swipe.fromTileY,
2336 swipe.tileX,
2337 swipe.tileY
2338 );
2339 }
2340 if (swipe.until > now)
2341 { return true; }
2342 swipe.object?.destroy();
2343 return false;
2344 });
2345 }
2346
2347 #updateDamageNumbers (now)
2348 {
2349 const layer = this.damageNumbersEl;
2350 if (!layer)
2351 { return; }
2352 this.damageFloats = this.damageFloats.filter((entry) =>
2353 {
2354 const elapsed = now - entry.started;
2355 if (elapsed >= DAMAGE_FLOAT_MS)
2356 {
2357 entry.element?.remove();
2358 return false;
2359 }
2360 const entity = this.entities.get(entry.entityId);
2361 if (!entity)
2362 {
2363 entry.element?.remove();
2364 return false;
2365 }
2366 if (!entry.element)
2367 {
2368 entry.element = document.createElement("span");
2369 entry.element.className = "damage-number";
2370 entry.element.textContent = String(entry.damage);
2371 layer.append(entry.element);
2372 }
2373 const anchor = this.nametagAnchor(entity);
2374 if (!anchor)
2375 { return true; }
2376 const t = elapsed / DAMAGE_FLOAT_MS;
2377 entry.element.style.left = `${anchor.x}px`;
2378 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
2379 entry.element.style.opacity = String(1 - t);
2380 return true;
2381 });
2382 }
2383
2384 #updateSkillLevelFloats (now)
2385 {
2386 const layer = this.skillLevelFloatsEl;
2387 if (!layer)
2388 { return; }
2389 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
2390 {
2391 const elapsed = now - entry.started;
2392 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
2393 {
2394 entry.element?.remove();
2395 return false;
2396 }
2397 const entity = this.entities.get(entry.entityId);
2398 if (!entity)
2399 {
2400 entry.element?.remove();
2401 return false;
2402 }
2403 if (!entry.element)
2404 {
2405 const root = document.createElement("div");
2406 root.className = "skill-level-float";
2407
2408 const levelEl = document.createElement("div");
2409 levelEl.className = "skill-level-float-level";
2410 levelEl.textContent = `↑${entry.level}↑`;
2411
2412 const icon = document.createElement("img");
2413 icon.className = "skill-level-float-icon";
2414 icon.src = entry.icon;
2415 icon.alt = entry.displayName || "";
2416
2417 root.append(levelEl, icon);
2418 entry.element = root;
2419 layer.append(entry.element);
2420 }
2421 const anchor = this.nametagAnchor(entity);
2422 if (!anchor)
2423 { return true; }
2424 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
2425 entry.element.style.left = `${anchor.x}px`;
2426 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
2427 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
2428 return true;
2429 });
2430 }
2431
2432 #syncBloomLayer ()
2433 {
2434 if (!this.bloomEnabled)
2435 {
2436 this.scene.setLayers([{ name: "default" }]);
2437 return;
2438 }
2439 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
2440 this.scene.setLayers([
2441 { name: "default" },
2442 {
2443 name: RENDER_LAYER_BLOOM,
2444 composite: "add",
2445 postShaders: Shader.getBloomPostChain({
2446 threshold: settings.bloomThreshold,
2447 softKnee: settings.bloomSoftKnee,
2448 intensity: settings.bloomIntensity,
2449 blurSize: settings.bloomBlurSize,
2450 saturation: settings.bloomSaturation,
2451 colorPreserve: settings.bloomColorPreserve,
2452 dilate: settings.bloomDilate,
2453 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
2454 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
2455 })
2456 }
2457 ]);
2458 }
2459}
2460
2461export function nightFactor (hour, nightDarkness = 0.72)
2462{
2463 const peak = Math.min(1, Math.max(0, nightDarkness));
2464 if (hour >= 8 && hour <= 16)
2465 { return 0; }
2466 if (hour >= 22 || hour <= 5)
2467 { return peak; }
2468 if (hour < 8)
2469 { return lerp(peak, 0, (hour - 5) / 3); }
2470 return lerp(0, peak, (hour - 16) / 6);
2471}
2472
2473function bodySpriteName (sex)
2474{
2475 const key = sex === "female" ? "player-body-female" : "player-body-male";
2476 return spriteImageName("character", key, key);
2477}
2478
2479function lerp (a, b, t)
2480{
2481 return a + (b - a) * Math.min(1, Math.max(0, t));
2482}
2483
2484function makeLightmapCanvas (size)
2485{
2486 const canvas = document.createElement("canvas");
2487 canvas.width = size;
2488 canvas.height = size;
2489 return canvas;
2490}
2491
2492function copyCanvas (source, dest)
2493{
2494 const ctx = dest.getContext("2d");
2495 ctx.imageSmoothingEnabled = false;
2496 ctx.clearRect(0, 0, dest.width, dest.height);
2497 ctx.drawImage(source, 0, 0);
2498}
2499
2500function drawHpBar (canvas, current, max)
2501{
2502 const ctx = canvas.getContext("2d");
2503 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
2504 ctx.fillStyle = "#000000";
2505 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
2506 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
2507 const fillW = Math.round(12 * ratio);
2508 if (fillW > 0)
2509 {
2510 ctx.fillStyle = "#ff0000";
2511 ctx.fillRect(1, 1, fillW, 2);
2512 }
2513}