BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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