BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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