BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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