BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 154.5 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, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";
5import { collectBlockLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";
6import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
8import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
9import
10{
11 resolveItemTint,
12 resolveEquipTint,
13 resolveItemDualTint,
14 resolveEquipDualTint,
15 normalizeRgb
16} from "/shared/render/tint.js";
17import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
18import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
19import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, LightOcclusion, blockDefinition, blockLightOcclusionForBlock } from "/shared/definitions/tiles.js";
20import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js";
21import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
22import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
23import { createChunkAtlasCache } from "./chunkAtlasCache.js";
24import
25{
26 frameworkImageFromCanvas,
27 invalidateCanvasTexture
28} from "./canvasSprite.js";
29import { setNearestFilter } from "./sprites.js";
30import { SeasonId, seasonIdAt } from "/shared/world/season.js";
31import
32{
33 OVERWORLD_ID,
34 normalizeDimensionId,
35 normalizeLightingMode,
36 normalizeSeasonMode,
37 resolveDimensionDarknessFactor,
38 resolveDimensionSeasonId
39} from "/shared/world/dimensions.js";
40import { spellDefinition, spellProjectileTint } from "/shared/definitions/spells.js";
41import { skullTintColor } from "/shared/combat/skull.js";
42
43const LAYER_GROUND = 0;
44const LAYER_EDGE = 900000;
45const SORT_BLOCK = 2;
46const SORT_ENTITY = 3;
47/** Equipment overlays use SORT_ENTITY + 1 + index (same sortY band). */
48const SORT_HP_BAR = 14;
49const SORT_FX = 5;
50const RENDER_LAYER_BLOOM = "bloom";
51const SKULL_SPRITE = "fx:skull:skull";
52
53const HP_BAR_W = 14;
54const HP_BAR_H = 4;
55const WALK_TILT_DEG = 6;
56const RUN_TILT_DEG = 8;
57const SHOVE_TILE_FRACTION = 0.25;
58const SHOVE_MS = 280;
59/** Soft reflow when stack circle targets change (join/leave a shared tile). */
60const STACK_SPREAD_LERP_MS = 280;
61/** Melee swipe fade: full opacity → transparent over this duration, then remove. */
62const MELEE_SWIPE_MS = 500;
63/** Extra random yaw (±deg) on top of aim rotation. */
64const MELEE_SWIPE_JITTER_DEG = 10;
65/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
66const GATHER_TOOL_HOLD_MS = 1100;
67const DAMAGE_FLASH_MS = 180;
68const FLASH_COLOR_DAMAGE = Object.freeze([1.0, 0.12, 0.12]);
69const FLASH_COLOR_BLOCK = Object.freeze([1.0, 1.0, 1.0]);
70/** Combat death: full red silhouette fades to transparent after the killing blow. */
71const DEATH_FADE_MS = 500;
72/** Interest leave / non-combat despawn: plain alpha fade (still lit / darkened). */
73const DESPAWN_FADE_MS = 500;
74const DAMAGE_FLOAT_MS = 900;
75const SKILL_LEVEL_FLOAT_MS = 2800;
76/** Projectiles spawn this many sprite-pixels below the caster sprite top. */
77const PROJECTILE_LAUNCH_FROM_TOP_PX = 4;
78
79const SPRITE_LIGHTING_FRAG = [
80 "precision mediump float;",
81 "varying vec2 v_texCoord;",
82 "uniform sampler2D u_texture;",
83 "uniform float u_alpha;",
84 "uniform float u_darkness;",
85 "uniform float u_strength;",
86 "uniform vec3 u_flashColor;",
87 "uniform float u_wade;",
88 "uniform float u_spriteHeight;",
89 "void main() {",
90 " vec4 color = texture2D(u_texture, v_texCoord);",
91 " if (color.a <= 0.0) { discard; }",
92 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
93 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
94 " vec3 rgb = color.rgb;",
95 " if (u_wade > 0.5 && fromBottom < 5.0) {",
96 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
97 " }",
98 " rgb = mix(rgb, vec3(0.0), u_darkness);",
99 " rgb = mix(rgb, u_flashColor, u_strength);",
100 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
101 "}"
102].join("\n");
103
104const WATER_GROUND_FRAG = [
105 "precision mediump float;",
106 "varying vec2 v_texCoord;",
107 "uniform sampler2D u_texture;",
108 "uniform float u_alpha;",
109 "uniform float u_ambientDark;",
110 "uniform float u_litNW;",
111 "uniform float u_litNE;",
112 "uniform float u_litSW;",
113 "uniform float u_litSE;",
114 "uniform float u_time;",
115 "uniform float u_edgeN;",
116 "uniform float u_edgeE;",
117 "uniform float u_edgeS;",
118 "uniform float u_edgeW;",
119 "void main() {",
120 " vec4 color = texture2D(u_texture, v_texCoord);",
121 " if (color.a <= 0.0) { discard; }",
122 " vec3 rgb = color.rgb;",
123 " float foam = 0.0;",
124 " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
125 " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
126 " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
127 " }",
128 " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
129 " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
130 " }",
131 " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
132 " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
133 " }",
134 " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
135 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
136 " }",
137 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
138 " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);",
139 " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);",
140 " float lit = mix(litTop, litBottom, v_texCoord.y);",
141 " float darkness = u_ambientDark * (1.0 - lit);",
142 " rgb = mix(rgb, vec3(0.0), darkness);",
143 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
144 "}"
145].join("\n");
146
147/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
148const TINT_LIT_SPRITE_FRAG = [
149 "precision mediump float;",
150 "varying vec2 v_texCoord;",
151 "uniform sampler2D u_texture;",
152 "uniform float u_alpha;",
153 "uniform float u_darkness;",
154 "uniform float u_strength;",
155 "uniform vec3 u_flashColor;",
156 "uniform float u_wade;",
157 "uniform float u_spriteHeight;",
158 "uniform float u_useTint;",
159 "uniform vec3 u_tintColor;",
160 "void main() {",
161 " vec4 color = texture2D(u_texture, v_texCoord);",
162 " if (color.a <= 0.0) { discard; }",
163 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
164 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
165 " vec3 rgb = color.rgb;",
166 " if (u_useTint > 0.5) {",
167 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
168 " float L = color.r;",
169 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
170 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
171 " }",
172 " }",
173 " if (u_wade > 0.5 && fromBottom < 5.0) {",
174 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
175 " }",
176 " rgb = mix(rgb, vec3(0.0), u_darkness);",
177 " rgb = mix(rgb, u_flashColor, u_strength);",
178 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
179 "}"
180].join("\n");
181
182/** Dual/triple-channel tint: red = shaft, blue = tip, green = coat; then darkness.
183 * Only when the primary channel is highest and the other two are equal;
184 * equal non-zero secondaries lighten the assigned tint toward white. */
185const DUAL_TINT_LIT_SPRITE_FRAG = [
186 "precision mediump float;",
187 "varying vec2 v_texCoord;",
188 "uniform sampler2D u_texture;",
189 "uniform float u_alpha;",
190 "uniform float u_darkness;",
191 "uniform float u_strength;",
192 "uniform vec3 u_flashColor;",
193 "uniform float u_wade;",
194 "uniform float u_spriteHeight;",
195 "uniform vec3 u_shaftTint;",
196 "uniform vec3 u_tipTint;",
197 "uniform vec3 u_coatTint;",
198 "uniform float u_hasCoat;",
199 "vec3 channelTint(float L, float secondary, vec3 tint) {",
200 " float blend = L > 0.0 ? clamp(secondary / L, 0.0, 1.0) : 0.0;",
201 " return mix(tint, vec3(1.0), blend) * L;",
202 "}",
203 "float channelMask(float primary, float o1, float o2) {",
204 " float equal = step(abs(o1 - o2), 0.04);",
205 " return clamp((primary - max(o1, o2)) * 1.75, 0.0, 1.0) * equal;",
206 "}",
207 "void main() {",
208 " vec4 color = texture2D(u_texture, v_texCoord);",
209 " if (color.a <= 0.0) { discard; }",
210 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
211 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
212 " vec3 rgb = color.rgb;",
213 " if (u_hasCoat > 0.5) {",
214 " float coatMask = channelMask(color.g, color.r, color.b);",
215 " if (coatMask > 0.0) {",
216 " vec3 coatCol = channelTint(color.g, color.r, u_coatTint);",
217 " rgb = mix(rgb, coatCol, coatMask);",
218 " }",
219 " }",
220 " float tipMask = channelMask(color.b, color.r, color.g);",
221 " if (tipMask > 0.0) {",
222 " vec3 tipCol = channelTint(color.b, color.r, u_tipTint);",
223 " rgb = mix(rgb, tipCol, tipMask);",
224 " }",
225 " float shaftMask = channelMask(color.r, color.g, color.b);",
226 " if (shaftMask > 0.0) {",
227 " vec3 shaftCol = channelTint(color.r, color.g, u_shaftTint);",
228 " rgb = mix(rgb, shaftCol, shaftMask);",
229 " }",
230 " if (u_wade > 0.5 && fromBottom < 5.0) {",
231 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
232 " }",
233 " rgb = mix(rgb, vec3(0.0), u_darkness);",
234 " rgb = mix(rgb, u_flashColor, u_strength);",
235 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
236 "}"
237].join("\n");
238
239/** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
240/**
241 * Tight-fit: clip clothing alpha to the body silhouette in *pivot space*
242 * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from
243 * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art.
244 */
245const TIGHT_FIT_BODY_MASK_GLSL = [
246 "uniform vec2 u_clothSize;",
247 "uniform vec2 u_bodySize;",
248 "uniform float u_pivotFromBottom;",
249 "uniform vec4 u_clothUvRect;",
250 "uniform vec4 u_bodyUvRect;",
251 "float tightFitBodyAlpha() {",
252 " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));",
253 " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;",
254 " float ox = (nu.x - 0.5) * u_clothSize.x;",
255 " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);",
256 " vec2 bodySize = max(u_bodySize, vec2(1.0));",
257 " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);",
258 " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));",
259 " vec2 texel = 1.0 / bodySize;",
260 " float bodyA = 0.0;",
261 " for (int dy = -1; dy <= 1; dy++) {",
262 " for (int dx = -1; dx <= 1; dx++) {",
263 " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;",
264 " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }",
265 " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;",
266 " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);",
267 " }",
268 " }",
269 " return bodyA;",
270 "}"
271].join("\n");
272
273const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
274 "precision mediump float;",
275 "varying vec2 v_texCoord;",
276 "uniform sampler2D u_texture;",
277 "uniform sampler2D u_secondary;",
278 "uniform float u_alpha;",
279 "uniform float u_darkness;",
280 "uniform float u_strength;",
281 "uniform vec3 u_flashColor;",
282 "uniform float u_wade;",
283 "uniform float u_spriteHeight;",
284 "uniform float u_useTint;",
285 "uniform vec3 u_tintColor;",
286 TIGHT_FIT_BODY_MASK_GLSL,
287 "void main() {",
288 " vec4 color = texture2D(u_texture, v_texCoord);",
289 " if (color.a <= 0.0) { discard; }",
290 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
291 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
292 " vec3 rgb = color.rgb;",
293 " if (u_useTint > 0.5) {",
294 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
295 " float L = color.r;",
296 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
297 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
298 " }",
299 " }",
300 " if (u_wade > 0.5 && fromBottom < 5.0) {",
301 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
302 " }",
303 " rgb = mix(rgb, vec3(0.0), u_darkness);",
304 " rgb = mix(rgb, u_flashColor, u_strength);",
305 " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;",
306 " if (alpha <= 0.0) { discard; }",
307 " gl_FragColor = vec4(rgb, alpha);",
308 "}"
309].join("\n");
310
311/** Body-clipped equip overlay without dye recolour. */
312const TIGHT_FIT_LIT_SPRITE_FRAG = [
313 "precision mediump float;",
314 "varying vec2 v_texCoord;",
315 "uniform sampler2D u_texture;",
316 "uniform sampler2D u_secondary;",
317 "uniform float u_alpha;",
318 "uniform float u_darkness;",
319 "uniform float u_strength;",
320 "uniform vec3 u_flashColor;",
321 "uniform float u_wade;",
322 "uniform float u_spriteHeight;",
323 TIGHT_FIT_BODY_MASK_GLSL,
324 "void main() {",
325 " vec4 color = texture2D(u_texture, v_texCoord);",
326 " if (color.a <= 0.0) { discard; }",
327 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
328 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
329 " vec3 rgb = color.rgb;",
330 " if (u_wade > 0.5 && fromBottom < 5.0) {",
331 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
332 " }",
333 " rgb = mix(rgb, vec3(0.0), u_darkness);",
334 " rgb = mix(rgb, u_flashColor, u_strength);",
335 " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;",
336 " if (alpha <= 0.0) { discard; }",
337 " gl_FragColor = vec4(rgb, alpha);",
338 "}"
339].join("\n");
340
341const ATLAS_LIGHTING_FRAG = [
342 "precision mediump float;",
343 "varying vec2 v_texCoord;",
344 "uniform sampler2D u_texture;",
345 "uniform sampler2D u_secondary;",
346 "uniform float u_alpha;",
347 "uniform float u_ambientDark;",
348 "uniform float u_lightRow;",
349 "void main() {",
350 " vec4 color = texture2D(u_texture, v_texCoord);",
351 " if (color.a <= 0.0) { discard; }",
352 " vec2 lightUV = v_texCoord;",
353 " if (u_lightRow >= 0.0) {",
354 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
355 " }",
356 " float lit = texture2D(u_secondary, lightUV).r;",
357 " float darkness = u_ambientDark * (1.0 - lit);",
358 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
359 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
360 "}"
361].join("\n");
362
363/**
364 * Per-tile cliff sprite: high-chroma / authored magenta top → sample this chunk's
365 * ground atlas (u_bump) at the cliff's tile-local UV. Only assigned to
366 * `cliffGroundTop` blocks — never to chunk block-row atlases (those keep normal
367 * lighting so magenta wood tints are not mistaken for cliff tops).
368 */
369const SPRITE_CLIFF_GROUND_TOP_FRAG = [
370 "precision mediump float;",
371 "varying vec2 v_texCoord;",
372 "uniform sampler2D u_texture;",
373 "uniform sampler2D u_bump;",
374 "uniform float u_alpha;",
375 "uniform float u_darkness;",
376 "uniform vec2 u_tileLocal;",
377 "void main() {",
378 " vec4 color = texture2D(u_texture, v_texCoord);",
379 " if (color.a <= 0.0) { discard; }",
380 " vec3 rgb = color.rgb;",
381 " float rbDiff = abs(rgb.r - rgb.b);",
382 " if (rbDiff < 0.02 && rgb.g < rgb.r) {",
383 " vec2 groundUV = (u_tileLocal + v_texCoord) / 16.0;",
384 " rgb = texture2D(u_bump, groundUV).rgb;",
385 " }",
386 " rgb = mix(rgb, vec3(0.0), u_darkness);",
387 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
388 "}"
389].join("\n");
390
391let spriteLightingShader = null;
392let atlasLightingShader = null;
393let cliffGroundTopShader = null;
394let waterGroundShader = null;
395let tintLitSpriteShader = null;
396let dualTintLitSpriteShader = null;
397let tightFitTintLitSpriteShader = null;
398let tightFitLitSpriteShader = null;
399
400function getSpriteLightingShader ()
401{
402 if (!spriteLightingShader)
403 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
404 return spriteLightingShader;
405}
406
407function getAtlasLightingShader ()
408{
409 if (!atlasLightingShader)
410 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
411 return atlasLightingShader;
412}
413
414function getCliffGroundTopShader ()
415{
416 if (!cliffGroundTopShader)
417 { cliffGroundTopShader = Shader.fragment(SPRITE_CLIFF_GROUND_TOP_FRAG); }
418 return cliffGroundTopShader;
419}
420
421function getWaterGroundShader ()
422{
423 if (!waterGroundShader)
424 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
425 return waterGroundShader;
426}
427
428function getTintLitSpriteShader ()
429{
430 if (!tintLitSpriteShader)
431 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
432 return tintLitSpriteShader;
433}
434
435function getDualTintLitSpriteShader ()
436{
437 if (!dualTintLitSpriteShader)
438 { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); }
439 return dualTintLitSpriteShader;
440}
441
442function getTightFitTintLitSpriteShader ()
443{
444 if (!tightFitTintLitSpriteShader)
445 { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); }
446 return tightFitTintLitSpriteShader;
447}
448
449function getTightFitLitSpriteShader ()
450{
451 if (!tightFitLitSpriteShader)
452 { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); }
453 return tightFitLitSpriteShader;
454}
455
456export class WorldView
457{
458 #chunkRebuildKeys = new Set();
459 #chunkRebuildRaf = 0;
460 #edgesDirty = false;
461 #CHUNK_REBUILD_BATCH = 2;
462 #pendingTextureCanvases = [];
463 #pendingTextureCanvasSet = new Set();
464 #textureWarmRaf = 0;
465 #TEXTURE_WARM_BATCH = 3;
466 #atlasCache = createChunkAtlasCache();
467 #idlePrefetchId = 0;
468 #playerChunkX = null;
469 #playerChunkY = null;
470 #playerMoveChunkDx = 0;
471 #playerMoveChunkDy = 0;
472
473 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
474 {
475 this.game = game;
476 this.scene = scene;
477 this.catalog = catalog;
478 this.preview = null;
479 this.zoom = 2;
480 /** World-Y origin for viewport-relative depth sort (see {@link #depthLayer}). */
481 this.ySortOrigin = 0;
482 this.chunks = new Map();
483 this.bakedChunks = new Map();
484 this.tiles = new Map();
485 this.entities = new Map();
486 this.groundItems = new Map();
487 this.edges = new Map();
488 this.localEntityId = null;
489 this.localBlind = false;
490 /** @type {string} */
491 this.dimensionId = OVERWORLD_ID;
492 /** @type {string} */
493 this.dimensionLightingMode = "dayNight";
494 /** @type {string} */
495 this.dimensionSeasonMode = "auto";
496 /** Calendar season from worldStatus when dimension season is auto. */
497 this.calendarSeason = seasonIdAt();
498 /** @type {"soft"|"simple"} */
499 this.lightingMode = "soft";
500 /** @type {boolean} */
501 this.bloomEnabled = true;
502 /** Soft edge blend for blendable grounds (grass, dirt, …). */
503 this.softTerrain = false;
504 this.settings = { ...DEFAULT_WORLD_SETTINGS };
505 this.worldHour = 12;
506 /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
507 this.worldSeason = seasonIdAt();
508 this.nightPreview = null;
509 this.followPlayer = true;
510 this.dynamicLights = [];
511 /** Persistent Light-spell tile lights (server-driven). */
512 this.spellLights = new Map();
513 /** Persistent Dark-spell tile darkness (server-driven). */
514 this.spellDarks = new Map();
515 this.swipes = [];
516 this.damageFloats = [];
517 this.damageNumbersEl = document.getElementById("damage-numbers");
518 this.skillLevelFloats = [];
519 this.skillLevelFloatsEl = document.getElementById("skill-level-floats");
520 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
521 this.editorSpawners = new Map();
522 this.spawnRangeHighlight = null;
523 this.wanderRangeHighlight = null;
524 this.spellTargetHighlight = null;
525 this.#syncBloomLayer();
526 }
527
528 setSettings (settings)
529 {
530 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
531 this.#syncBloomLayer();
532 }
533
534 /**
535 * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain).
536 * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs
537 */
538 setGraphicsPrefs (prefs)
539 {
540 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
541 { this.lightingMode = prefs.lighting; }
542 if (prefs?.bloom === "off" || prefs?.bloom === "on")
543 {
544 const enabled = prefs.bloom !== "off";
545 if (enabled !== this.bloomEnabled)
546 {
547 this.bloomEnabled = enabled;
548 this.#syncBloomLayer();
549 }
550 else
551 { this.bloomEnabled = enabled; }
552 }
553 if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off")
554 {
555 const enabled = prefs.softTerrain === "on";
556 if (enabled !== this.softTerrain)
557 {
558 this.softTerrain = enabled;
559 this.#rebakeAllChunks();
560 }
561 }
562 }
563
564 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
565 setWorldSeason (season)
566 {
567 const calendar = season === SeasonId.spring
568 || season === SeasonId.fall
569 || season === SeasonId.winter
570 || season === SeasonId.summer
571 ? season
572 : seasonIdAt();
573 this.calendarSeason = calendar;
574 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
575 const next = forced ?? calendar;
576 if (next === this.worldSeason)
577 { return; }
578 this.worldSeason = next;
579 this.#rebakeAllChunks();
580 }
581
582 setDimensionId (dimensionId)
583 {
584 this.dimensionId = normalizeDimensionId(dimensionId);
585 }
586
587 setDimensionModes (lightingMode, seasonMode)
588 {
589 this.dimensionLightingMode = normalizeLightingMode(lightingMode);
590 this.dimensionSeasonMode = normalizeSeasonMode(seasonMode);
591 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
592 const next = forced ?? this.calendarSeason ?? seasonIdAt();
593 if (next !== this.worldSeason)
594 {
595 this.worldSeason = next;
596 this.#rebakeAllChunks();
597 }
598 }
599
600 clearAllChunks ()
601 {
602 for (const key of [...this.chunks.keys()])
603 {
604 const [chunkX, chunkY] = key.split(",").map(Number);
605 this.removeChunk(chunkX, chunkY);
606 }
607 for (const [id] of [...this.entities.entries()])
608 {
609 if (id === this.localEntityId)
610 { continue; }
611 this.despawnEntity(id, { immediate: true });
612 }
613 for (const [id] of [...this.groundItems.entries()])
614 { this.despawnGroundItem(id); }
615 }
616
617 /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */
618 clearPlaySession ()
619 {
620 this.#cancelIdlePrefetch();
621 this.#chunkRebuildKeys.clear();
622 this.#playerChunkX = null;
623 this.#playerChunkY = null;
624 this.#playerMoveChunkDx = 0;
625 this.#playerMoveChunkDy = 0;
626 this.localEntityId = null;
627 for (const key of [...this.chunks.keys()])
628 {
629 const [chunkX, chunkY] = key.split(",").map(Number);
630 this.removeChunk(chunkX, chunkY);
631 }
632 for (const [id] of [...this.entities.entries()])
633 { this.despawnEntity(id, { immediate: true }); }
634 for (const [id] of [...this.groundItems.entries()])
635 { this.despawnGroundItem(id); }
636 }
637
638 applySnapshot (snapshot)
639 {
640 const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID);
641 if (normalizeDimensionId(this.dimensionId) !== snapDim)
642 { return; }
643 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
644 snapshot.occlusion = bakeChunkOcclusion(snapshot);
645 this.chunks.set(key, snapshot);
646 this.#scheduleChunkRebuild(snapshot);
647 this.#redrawPreview();
648 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
649 if (snapshot.staticOnly)
650 {
651 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
652 this.#scheduleEdgeRebuild();
653 return;
654 }
655 for (const entity of snapshot.entities ?? [])
656 { this.#upsertEntity(entity); }
657 for (const [id, item] of [...this.groundItems.entries()])
658 {
659 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
660 { this.despawnGroundItem(id); }
661 }
662 for (const item of snapshot.groundItems ?? [])
663 { this.upsertGroundItem(item); }
664 this.#scheduleEdgeRebuild();
665 }
666
667 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0)
668 {
669 this.localEntityId = entityId;
670 this.#upsertEntity({
671 entityId,
672 characterId,
673 tileX,
674 tileY,
675 gait,
676 sex,
677 firstName,
678 lastName,
679 layers: layers ?? undefined,
680 skullValue: skullValue | 0,
681 ...(health != null ? { health } : {}),
682 ...(maxHealth != null ? { maxHealth } : {})
683 });
684 this.#notePlayerTile(tileX, tileY);
685 }
686
687 #stripChunkDynamic (chunkX, chunkY)
688 {
689 for (const [id, item] of [...this.groundItems.entries()])
690 {
691 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
692 { this.despawnGroundItem(id); }
693 }
694 for (const [id, entity] of [...this.entities.entries()])
695 {
696 if (id === this.localEntityId)
697 { continue; }
698 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
699 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
700 { this.despawnEntity(id, { immediate: true }); }
701 }
702 }
703
704 removeChunk (chunkX, chunkY)
705 {
706 const key = `${chunkX},${chunkY}`;
707 this.chunks.delete(key);
708 this.#destroyBakedChunk(key);
709 this.#destroyEdges(key);
710 const prefix = `${chunkX},${chunkY}:`;
711 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
712 {
713 if (!spawnerKey.startsWith(prefix))
714 { continue; }
715 this.#destroyEditorSpawnerEntry(entry);
716 this.editorSpawners.delete(spawnerKey);
717 }
718 for (const [tileKey, objects] of [...this.tiles.entries()])
719 {
720 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
721 {
722 objects.ground?.destroy();
723 objects.groundBloom?.destroy();
724 objects.block?.destroy();
725 objects.blockBloom?.destroy();
726 this.tiles.delete(tileKey);
727 }
728 }
729 for (const [id, item] of [...this.groundItems.entries()])
730 {
731 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
732 { this.despawnGroundItem(id); }
733 }
734 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
735 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
736 for (const [id, entity] of [...this.entities.entries()])
737 {
738 if (id === this.localEntityId)
739 { continue; }
740 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
741 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
742 { this.despawnEntity(id, { immediate: true }); }
743 }
744 this.#rebuildAllEdges();
745 }
746
747 setChunkOpen (chunkX, chunkY, open)
748 {
749 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
750 if (!snapshot)
751 { return; }
752 snapshot.open = !!open;
753 this.#rebuildAllEdges();
754 }
755
756 spawnEntity (payload)
757 {
758 // Fresh spawn is authoritative; do not let an older deferred hit overwrite HP.
759 this.cancelDeferredCombatHits(payload?.entityId);
760 this.#upsertEntity(payload);
761 }
762
763 moveEntity (payload)
764 {
765 const existing = this.entities.get(payload.entityId);
766 // Move payloads lack appearance/mobTypeId — never invent a stub entity
767 // (that looked like a nameless humanoid "target"). Wait for entity-spawn.
768 if (!existing)
769 { return; }
770 // Fading corpses stay put; respawn restores via reviveAfterDeath / spawn.
771 if (existing.dying)
772 { return; }
773 const size = this.tileSize();
774 existing.fromX = existing.visualX;
775 existing.fromY = existing.visualY;
776 existing.shadeFromTileX = existing.tileX;
777 existing.shadeFromTileY = existing.tileY;
778 if (existing.tileX !== payload.tileX || existing.tileY !== payload.tileY)
779 {
780 existing.previousTileX = existing.tileX;
781 existing.previousTileY = existing.tileY;
782 }
783 existing.tileX = payload.tileX;
784 existing.tileY = payload.tileY;
785 existing.gait = payload.gait;
786 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
787 if (payload.worldX != null && payload.worldY != null)
788 {
789 existing.worldX = payload.worldX;
790 existing.worldY = payload.worldY;
791 existing.targetX = payload.worldX * size;
792 existing.targetY = payload.worldY * size;
793 }
794 else
795 {
796 const pivot = tilePivot(payload.tileX, payload.tileY, size);
797 existing.targetX = pivot.x;
798 existing.targetY = pivot.y;
799 }
800 existing.lerpStarted = performance.now();
801 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
802 if (payload.entityId === this.localEntityId)
803 { this.#notePlayerTile(payload.tileX, payload.tileY); }
804 }
805
806 despawnEntity (entityId, { immediate = false, combatDeath = false } = {})
807 {
808 const existing = this.entities.get(entityId);
809 if (!existing)
810 { return; }
811 if (existing.dying)
812 {
813 if (immediate)
814 { this.#finishEntityFade(entityId); }
815 else if (combatDeath)
816 { this.#upgradeToDeathDissolve(existing); }
817 return;
818 }
819 // Chunk unload / session wipe: drop instantly.
820 if (immediate)
821 {
822 this.cancelDeferredCombatHits(entityId);
823 this.#destroyEntityVisuals(existing);
824 this.entities.delete(entityId);
825 return;
826 }
827 // Combat death → red silhouette. Leaving 3×3 / summons / etc. → plain fade.
828 if (combatDeath)
829 { this.#beginDeathDissolve(existing); }
830 else
831 { this.#beginDespawnFade(existing); }
832 }
833
834 /**
835 * Start the red silhouette fade without requiring a despawn message
836 * (e.g. local playerDied arrives before entityDespawn).
837 */
838 beginDeathDissolve (entityId)
839 {
840 const existing = this.entities.get(entityId);
841 if (!existing)
842 { return; }
843 if (existing.dying)
844 {
845 this.#upgradeToDeathDissolve(existing);
846 return;
847 }
848 this.#beginDeathDissolve(existing);
849 }
850
851 /**
852 * Abort an in-progress (or finished) death fade and snap the sprite back.
853 * Local players are never entity-despawned, so respawn must restore — not
854 * destroy — the visual. Remotes get a fresh entity-spawn instead.
855 */
856 reviveAfterDeath (entityId, { tileX, tileY, health, maxHealth, skullValue } = {})
857 {
858 const entity = this.entities.get(entityId);
859 if (!entity)
860 { return false; }
861 this.#abortEntityFade(entity);
862 if (tileX != null && tileY != null)
863 { this.#snapEntityToTile(entity, tileX, tileY); }
864 if (health != null)
865 { entity.health = health; }
866 if (maxHealth != null)
867 { entity.maxHealth = maxHealth; }
868 if (skullValue != null)
869 { entity.skullValue = Math.max(0, skullValue | 0); }
870 this.#syncHpBar(entity);
871 this.#syncSkullMarker(entity);
872 this.#placeEntity(entity, performance.now());
873 return true;
874 }
875
876 #destroyEntityVisuals (existing)
877 {
878 existing.object?.destroy();
879 existing.hpBar?.destroy();
880 existing.skullMarker?.destroy();
881 for (const overlay of existing.overlays ?? [])
882 { overlay.destroy(); }
883 for (const overlay of existing.bloomOverlays ?? [])
884 { overlay.destroy(); }
885 }
886
887 #stripEntityChrome (entity)
888 {
889 entity.hpBar?.destroy();
890 entity.hpBar = null;
891 entity.skullMarker?.destroy();
892 entity.skullMarker = null;
893 }
894
895 #beginDespawnFade (entity)
896 {
897 const now = performance.now();
898 entity.dying = true;
899 entity.deathDissolve = false;
900 entity.untargetable = true;
901 entity.deathFadeStarted = now;
902 entity.deathFadeMs = DESPAWN_FADE_MS;
903 this.#stripEntityChrome(entity);
904 }
905
906 #beginDeathDissolve (entity)
907 {
908 const now = performance.now();
909 entity.dying = true;
910 entity.deathDissolve = true;
911 entity.untargetable = true;
912 entity.deathFadeStarted = now;
913 entity.deathFadeMs = DEATH_FADE_MS;
914 // Keep a full red silhouette for the whole fade (hit flash may already be running).
915 entity.damageFlashUntil = now + DEATH_FADE_MS;
916 entity.damageFlashColor = FLASH_COLOR_DAMAGE;
917 this.#stripEntityChrome(entity);
918 // Leave deferred projectile impacts queued so knockback / float still play on arrival.
919 }
920
921 /** Promote an in-progress plain despawn fade to the red combat dissolve. */
922 #upgradeToDeathDissolve (entity)
923 {
924 if (entity.deathDissolve)
925 { return; }
926 const now = performance.now();
927 const elapsed = Math.max(0, now - (entity.deathFadeStarted ?? now));
928 const remaining = Math.max(1, (entity.deathFadeMs ?? DESPAWN_FADE_MS) - elapsed);
929 entity.deathDissolve = true;
930 entity.deathFadeStarted = now;
931 entity.deathFadeMs = Math.min(DEATH_FADE_MS, remaining);
932 entity.damageFlashUntil = now + entity.deathFadeMs;
933 entity.damageFlashColor = FLASH_COLOR_DAMAGE;
934 }
935
936 #abortEntityFade (entity)
937 {
938 entity.dying = false;
939 entity.deathDissolve = false;
940 entity.untargetable = false;
941 entity.deathFadeStarted = null;
942 entity.deathFadeMs = null;
943 entity.damageFlashUntil = 0;
944 entity.damageFlashColor = null;
945 if (entity.object?.renderer)
946 { entity.object.renderer.alpha = 1; }
947 for (const overlay of entity.overlays ?? [])
948 {
949 if (overlay.renderer)
950 { overlay.renderer.alpha = 1; }
951 }
952 for (const overlay of entity.bloomOverlays ?? [])
953 {
954 if (overlay.renderer)
955 { overlay.renderer.alpha = 1; }
956 }
957 }
958
959 #snapEntityToTile (entity, tileX, tileY)
960 {
961 const size = this.tileSize();
962 const pivot = tilePivot(tileX, tileY, size);
963 entity.tileX = tileX;
964 entity.tileY = tileY;
965 entity.visualX = pivot.x;
966 entity.visualY = pivot.y;
967 entity.targetX = pivot.x;
968 entity.targetY = pivot.y;
969 entity.fromX = pivot.x;
970 entity.fromY = pivot.y;
971 entity.lerpStarted = null;
972 entity.previousTileX = null;
973 entity.previousTileY = null;
974 entity.shadeFromTileX = null;
975 entity.shadeFromTileY = null;
976 entity.shoveOffsetX = 0;
977 entity.shoveOffsetY = 0;
978 if (entity.entityId === this.localEntityId)
979 { this.#notePlayerTile(tileX, tileY); }
980 }
981
982 #finishEntityFade (entityId)
983 {
984 this.cancelDeferredCombatHits(entityId);
985 const existing = this.entities.get(entityId);
986 if (!existing)
987 { return; }
988 this.#destroyEntityVisuals(existing);
989 this.entities.delete(entityId);
990 }
991
992 /**
993 * Drop queued combat-hit/block presentation for a target.
994 * Killing blows often defer health=0 until a projectile lands; if the
995 * target already finished dissolving or respawned, that stale apply must not run.
996 */
997 cancelDeferredCombatHits (targetId)
998 {
999 if (targetId == null)
1000 { return; }
1001 for (const swipe of this.swipes)
1002 {
1003 if (swipe.targetId !== targetId)
1004 { continue; }
1005 swipe.onImpact = null;
1006 swipe.trackTarget = false;
1007 }
1008 }
1009
1010 updateEntitySkull (entityId, skullValue)
1011 {
1012 const entity = this.entities.get(entityId);
1013 if (!entity)
1014 { return; }
1015 entity.skullValue = Math.max(0, skullValue | 0);
1016 const pivotX = (entity.visualX ?? 0) + (entity.shoveOffsetX ?? 0) + (entity.stackOffsetX ?? 0);
1017 const pivotY = (entity.visualY ?? 0) + (entity.shoveOffsetY ?? 0) + (entity.stackOffsetY ?? 0);
1018 const tileShade = this.#entityShadeAlpha?.(entity, performance.now())
1019 ?? this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha
1020 ?? 0;
1021 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
1022 }
1023
1024 updateEntityHealth (entityId, health, maxHealth)
1025 {
1026 const entity = this.entities.get(entityId);
1027 if (!entity || entity.dying)
1028 { return; }
1029 entity.health = health;
1030 entity.maxHealth = maxHealth;
1031 this.#syncHpBar(entity);
1032 }
1033
1034 flashDamage (entityId)
1035 {
1036 this.#flashEntity(entityId, FLASH_COLOR_DAMAGE);
1037 }
1038
1039 flashBlock (entityId)
1040 {
1041 this.#flashEntity(entityId, FLASH_COLOR_BLOCK);
1042 }
1043
1044 #flashEntity (entityId, color)
1045 {
1046 const entity = this.entities.get(entityId);
1047 if (!entity)
1048 { return; }
1049 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
1050 entity.damageFlashColor = color ?? FLASH_COLOR_DAMAGE;
1051 }
1052
1053 /** Target knocks back away from attacker (hit). */
1054 spawnCombatKnockback (payload)
1055 {
1056 const attacker = this.entities.get(payload?.attackerId);
1057 const target = this.entities.get(payload?.targetId);
1058 if (!attacker || !target)
1059 { return; }
1060 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1061 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1062 const tx = target.visualX + (target.stackOffsetX ?? 0);
1063 const ty = target.visualY + (target.stackOffsetY ?? 0);
1064 this.#applyShoveInDirection(target, tx - ax, ty - ay);
1065 }
1066
1067 /** Target sidesteps perpendicular to the attack (dodge / miss). */
1068 spawnCombatDodge (payload)
1069 {
1070 const attacker = this.entities.get(payload?.attackerId);
1071 const target = this.entities.get(payload?.targetId);
1072 if (!attacker || !target)
1073 { return; }
1074 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1075 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1076 const tx = target.visualX + (target.stackOffsetX ?? 0);
1077 const ty = target.visualY + (target.stackOffsetY ?? 0);
1078 const dx = tx - ax;
1079 const dy = ty - ay;
1080 const side = Math.random() < 0.5 ? 1 : -1;
1081 this.#applyShoveInDirection(target, -dy * side, dx * side);
1082 }
1083
1084 spawnDamageNumber (entityId, damage)
1085 {
1086 const amount = damage | 0;
1087 if (amount <= 0)
1088 { return; }
1089 this.damageFloats.push({
1090 entityId,
1091 damage: amount,
1092 started: performance.now()
1093 });
1094 }
1095
1096 /**
1097 * Queue combat-hit presentation until a matching in-flight projectile lands.
1098 * Returns true when deferred; caller should apply immediately when false.
1099 */
1100 deferCombatHit (message, apply)
1101 {
1102 if (typeof apply !== "function" || message?.targetId == null)
1103 { return false; }
1104 const attackerId = message.attackerId ?? null;
1105 const targetId = message.targetId;
1106 const swipe = this.swipes.find((entry) =>
1107 entry.lerp
1108 && entry.onImpact == null
1109 && entry.targetId === targetId
1110 && (attackerId == null || entry.attackerId === attackerId)
1111 && (entry.until ?? 0) > performance.now());
1112 if (!swipe)
1113 { return false; }
1114 swipe.onImpact = apply;
1115 swipe.trackTarget = true;
1116 return true;
1117 }
1118
1119 /** Stop tracking a living target (misses fly to a fixed tile). */
1120 markProjectileMiss (message)
1121 {
1122 const attackerId = message?.attackerId ?? null;
1123 const targetId = message?.targetId ?? null;
1124 for (const swipe of this.swipes)
1125 {
1126 if (!swipe.lerp || swipe.onImpact != null)
1127 { continue; }
1128 if (targetId != null && swipe.targetId !== targetId)
1129 { continue; }
1130 if (attackerId != null && swipe.attackerId !== attackerId)
1131 { continue; }
1132 swipe.trackTarget = false;
1133 if (message.tileX != null)
1134 { swipe.tileX = message.tileX; }
1135 if (message.tileY != null)
1136 { swipe.tileY = message.tileY; }
1137 }
1138 }
1139
1140 spawnSkillLevelUp (entityId, payload)
1141 {
1142 const level = payload?.level | 0;
1143 if (level <= 0 || !payload?.icon)
1144 { return; }
1145 this.skillLevelFloats.push({
1146 entityId,
1147 level,
1148 icon: payload.icon,
1149 displayName: payload.displayName ?? payload.skillId ?? "",
1150 started: performance.now()
1151 });
1152 }
1153
1154 setAppearance (payload)
1155 {
1156 const existing = this.entities.get(payload.entityId);
1157 if (!existing)
1158 { return; }
1159 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
1160 if (payload.lightIntensity != null)
1161 { existing.lightIntensity = Number(payload.lightIntensity) || 1; }
1162 if (payload.visualScale != null)
1163 { existing.visualScale = Number(payload.visualScale) || 1; }
1164 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
1165 this.#placeEntity(existing);
1166 }
1167
1168 /**
1169 * Render the live entity (body + overlays, same tint/tight-fit shaders as the
1170 * world, unlit) into an offscreen FBO, crop the top square, and return a
1171 * pixel-scaled canvas for UI (e.g. dialogue speaker icons).
1172 * @param {number} entityId
1173 * @param {{ size?: number }} [options]
1174 * @returns {HTMLCanvasElement | null}
1175 */
1176 captureEntityPortrait (entityId, { size = 64 } = {})
1177 {
1178 const entity = this.entities.get(entityId);
1179 const body = entity?.object?.renderer?.sprite;
1180 const glCtx = this.scene?.glContext;
1181 const gl = glCtx?.gl;
1182 if (!entity || !body || !gl)
1183 { return null; }
1184
1185 const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX);
1186 const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX);
1187 if (!this.#ensurePortraitTarget(gl, frameW, frameH))
1188 { return null; }
1189
1190 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
1191 const prevViewport = gl.getParameter(gl.VIEWPORT);
1192 const prevW = glCtx._lastWidth;
1193 const prevH = glCtx._lastHeight;
1194 const prevBlend = gl.isEnabled(gl.BLEND);
1195
1196 try
1197 {
1198 // drawSprite projects with _lastWidth/_lastHeight — match the FBO.
1199 glCtx._lastWidth = frameW;
1200 glCtx._lastHeight = frameH;
1201 gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb);
1202 gl.viewport(0, 0, frameW, frameH);
1203 gl.enable(gl.BLEND);
1204 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
1205 gl.clearColor(0, 0, 0, 0);
1206 gl.clear(gl.COLOR_BUFFER_BIT);
1207
1208 const pivotX = frameW * 0.5;
1209 const pivotY = frameH - PIVOT_FROM_BOTTOM_PX;
1210 this._portraitBodyMap = body.g_image ?? null;
1211 this._portraitTightFitEntity = entity;
1212 this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false);
1213
1214 const overlays = entity.overlays ?? [];
1215 const tints = entity.overlayTints ?? [];
1216 const dualTints = entity.overlayDualTints ?? [];
1217 const tight = entity.overlayTightFit ?? [];
1218 for (let index = 0; index < overlays.length; index++)
1219 {
1220 this.#drawPortraitLayer(
1221 glCtx,
1222 overlays[index],
1223 pivotX,
1224 pivotY,
1225 tints[index] ?? null,
1226 !!tight[index],
1227 dualTints[index] ?? null
1228 );
1229 }
1230 this._portraitBodyMap = null;
1231 this._portraitTightFitEntity = null;
1232
1233 const pixels = this._portrait.pixels;
1234 gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
1235 }
1236 finally
1237 {
1238 glCtx._lastWidth = prevW;
1239 glCtx._lastHeight = prevH;
1240 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
1241 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
1242 if (!prevBlend)
1243 { gl.disable(gl.BLEND); }
1244 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
1245 }
1246
1247 return this.#portraitPixelsToCanvas(frameW, frameH, size);
1248 }
1249
1250 #ensurePortraitTarget (gl, width, height)
1251 {
1252 const prev = this._portrait;
1253 if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex)
1254 { return true; }
1255 if (prev?.fb)
1256 { gl.deleteFramebuffer(prev.fb); }
1257 if (prev?.tex)
1258 { gl.deleteTexture(prev.tex); }
1259
1260 const tex = gl.createTexture();
1261 gl.bindTexture(gl.TEXTURE_2D, tex);
1262 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1263 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1264 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1265 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1266 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
1267
1268 const fb = gl.createFramebuffer();
1269 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
1270 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
1271 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
1272 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
1273 if (status !== gl.FRAMEBUFFER_COMPLETE)
1274 {
1275 gl.deleteFramebuffer(fb);
1276 gl.deleteTexture(tex);
1277 this._portrait = null;
1278 return false;
1279 }
1280 this._portrait = {
1281 fb,
1282 tex,
1283 w: width,
1284 h: height,
1285 pixels: new Uint8Array(width * height * 4),
1286 scratch: document.createElement("canvas")
1287 };
1288 return true;
1289 }
1290
1291 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null)
1292 {
1293 const sprite = object?.renderer?.sprite;
1294 if (!sprite?.g_image)
1295 { return; }
1296 const subImage = object.renderer.subImage | 0;
1297 const height = sprite.height || SPRITE_SIZE_PX;
1298 const draw = spriteDrawSize(sprite.width, sprite.height, 1);
1299 const center = spriteCenterFromPivot(pivotX, pivotY, height, 1);
1300 const tint = tintColor ? normalizeRgb(tintColor) : null;
1301 let shader = glCtx.defaultShader;
1302 let uniforms = null;
1303 let secondaryHtml = null;
1304
1305 const bodyHtml = this._portraitBodyMap;
1306 const portraitEntity = this._portraitTightFitEntity;
1307 const maskUniforms = tightFit && portraitEntity
1308 ? this.#tightFitMaskUniforms(object, portraitEntity)
1309 : null;
1310 if (dualTint)
1311 {
1312 const shaft = normalizeRgb(dualTint.shaft);
1313 const tip = normalizeRgb(dualTint.tip);
1314 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
1315 shader = getDualTintLitSpriteShader();
1316 uniforms = {
1317 u_darkness: 0,
1318 u_strength: 0,
1319 u_flashColor: FLASH_COLOR_DAMAGE,
1320 u_wade: 0,
1321 u_spriteHeight: height,
1322 u_shaftTint: [shaft.r, shaft.g, shaft.b],
1323 u_tipTint: [tip.r, tip.g, tip.b],
1324 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
1325 u_hasCoat: coat ? 1 : 0
1326 };
1327 }
1328 else if (tightFit && bodyHtml && maskUniforms)
1329 {
1330 secondaryHtml = bodyHtml;
1331 if (tint)
1332 {
1333 shader = getTightFitTintLitSpriteShader();
1334 uniforms = {
1335 u_darkness: 0,
1336 u_strength: 0,
1337 u_flashColor: FLASH_COLOR_DAMAGE,
1338 u_wade: 0,
1339 u_spriteHeight: height,
1340 u_useTint: 1,
1341 u_tintColor: [tint.r, tint.g, tint.b],
1342 ...maskUniforms
1343 };
1344 }
1345 else
1346 {
1347 shader = getTightFitLitSpriteShader();
1348 uniforms = {
1349 u_darkness: 0,
1350 u_strength: 0,
1351 u_flashColor: FLASH_COLOR_DAMAGE,
1352 u_wade: 0,
1353 u_spriteHeight: height,
1354 ...maskUniforms
1355 };
1356 }
1357 }
1358 else if (tint)
1359 {
1360 shader = getTintLitSpriteShader();
1361 uniforms = {
1362 u_darkness: 0,
1363 u_strength: 0,
1364 u_flashColor: FLASH_COLOR_DAMAGE,
1365 u_wade: 0,
1366 u_spriteHeight: height,
1367 u_useTint: 1,
1368 u_tintColor: [tint.r, tint.g, tint.b]
1369 };
1370 }
1371 else
1372 {
1373 shader = getSpriteLightingShader();
1374 uniforms = {
1375 u_darkness: 0,
1376 u_strength: 0,
1377 u_flashColor: FLASH_COLOR_DAMAGE,
1378 u_wade: 0,
1379 u_spriteHeight: height
1380 };
1381 }
1382
1383 glCtx.drawSprite({
1384 texture: glCtx.getTexture(sprite.g_image),
1385 x: center.x,
1386 y: center.y,
1387 w: draw.w,
1388 h: draw.h,
1389 rotationDeg: 0,
1390 mirrorX: false,
1391 mirrorY: false,
1392 alpha: 1,
1393 uvRect: sprite.getUvRect(subImage),
1394 shader,
1395 uniforms,
1396 textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null,
1397 lights: null
1398 });
1399 }
1400
1401 #portraitPixelsToCanvas (frameW, frameH, size)
1402 {
1403 const pixels = this._portrait?.pixels;
1404 if (!pixels)
1405 { return null; }
1406 const scratch = this._portrait.scratch;
1407 scratch.width = frameW;
1408 scratch.height = frameH;
1409 const sctx = scratch.getContext("2d");
1410 const imageData = sctx.createImageData(frameW, frameH);
1411 // WebGL y=0 is bottom — flip to top-down image order.
1412 for (let y = 0; y < frameH; y++)
1413 {
1414 const src = (frameH - 1 - y) * frameW * 4;
1415 const dst = y * frameW * 4;
1416 imageData.data.set(pixels.subarray(src, src + frameW * 4), dst);
1417 }
1418 sctx.putImageData(imageData, 0, 0);
1419
1420 const crop = Math.min(frameW, frameH);
1421 const out = document.createElement("canvas");
1422 out.width = size;
1423 out.height = size;
1424 const octx = out.getContext("2d");
1425 octx.imageSmoothingEnabled = false;
1426 octx.clearRect(0, 0, size, size);
1427 octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size);
1428 return out;
1429 }
1430
1431 upsertGroundItem (payload)
1432 {
1433 const size = this.tileSize();
1434 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1435 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
1436 const spriteName = potion
1437 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
1438 : (payload.sprite ?? itemSpriteNameForStack({
1439 itemId: payload.itemId,
1440 instance: payload.instance,
1441 quantity: payload.quantity
1442 }));
1443 let item = this.groundItems.get(payload.groundItemId);
1444 if (!item)
1445 {
1446 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
1447 this.scene.addObject(object);
1448 item = { object };
1449 this.groundItems.set(payload.groundItemId, item);
1450 }
1451 else if (item.object?.renderer && this.game.images[spriteName])
1452 { item.object.renderer.sprite = this.game.images[spriteName]; }
1453 item.groundItemId = payload.groundItemId;
1454 item.tileX = payload.tileX;
1455 item.tileY = payload.tileY;
1456 item.itemId = payload.itemId;
1457 item.quantity = payload.quantity;
1458 item.displayName = payload.displayName;
1459 item.sprite = spriteName;
1460 item.instance = payload.instance ?? null;
1461 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
1462 const def = itemDefinition(payload.itemId);
1463 item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
1464 item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
1465 if (item.object?.renderer && itemMaxCharges(def) != null)
1466 { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }
1467 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1468 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
1469 }
1470
1471 despawnGroundItem (groundItemId)
1472 {
1473 const item = this.groundItems.get(groundItemId);
1474 if (!item)
1475 { return; }
1476 item.object?.destroy();
1477 this.groundItems.delete(groundItemId);
1478 }
1479
1480 groundItemAtTile (tileX, tileY)
1481 {
1482 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
1483 }
1484
1485 groundItemsAtTile (tileX, tileY)
1486 {
1487 const items = [];
1488 for (const item of this.groundItems.values())
1489 {
1490 if (item.tileX === tileX && item.tileY === tileY)
1491 { items.push(item); }
1492 }
1493 return items;
1494 }
1495
1496 entitiesAtTile (tileX, tileY, options = {})
1497 {
1498 const includePrevious = !!options.includePrevious;
1499 const matches = [];
1500 for (const entity of this.entities.values())
1501 {
1502 if (entity.tileX === tileX && entity.tileY === tileY)
1503 {
1504 matches.push(entity);
1505 continue;
1506 }
1507 if (
1508 includePrevious
1509 && entity.lerpStarted != null
1510 && entity.previousTileX === tileX
1511 && entity.previousTileY === tileY
1512 )
1513 { matches.push(entity); }
1514 }
1515 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
1516 return matches;
1517 }
1518
1519 setZoom (zoom, limits = { min: 2, max: 4 })
1520 {
1521 const min = limits.min ?? 1;
1522 const max = limits.max ?? 4;
1523 this.zoom = Math.min(max, Math.max(min, zoom));
1524 for (const snapshot of this.chunks.values())
1525 { this.#relayoutChunk(snapshot); }
1526 const size = this.tileSize();
1527 for (const entity of this.entities.values())
1528 {
1529 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
1530 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
1531 entity.fromX = entity.visualX;
1532 entity.fromY = entity.visualY;
1533 entity.targetX = entity.visualX;
1534 entity.targetY = entity.visualY;
1535 entity.lerpStarted = null;
1536 this.#placeEntity(entity);
1537 }
1538 for (const item of this.groundItems.values())
1539 {
1540 const pivot = tilePivot(item.tileX, item.tileY, size);
1541 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1542 }
1543 this.#rebuildAllEdges();
1544 this.#relayoutEditorSpawners();
1545 this.#relayoutSpawnRangeHighlight();
1546 this.#relayoutSpellTargetHighlight();
1547 // Play: recenter + refresh cull flags with the new tile size immediately.
1548 // Editor sets the camera via frameNeighborhood after setZoom — call refreshViewport there.
1549 if (this.followPlayer)
1550 { this.refreshViewport(); }
1551 }
1552
1553 /** Recenter (when following) and refresh off-screen cull flags after zoom/layout. */
1554 refreshViewport ()
1555 {
1556 this.#centerCamera();
1557 this.#syncYSortOrigin();
1558 this.#refreshDepthLayers();
1559 this.#cullOffscreenDrawables();
1560 }
1561
1562 tileSize ()
1563 {
1564 return SPRITE_SIZE_PX * this.zoom;
1565 }
1566
1567 screenToTile (mouseX, mouseY)
1568 {
1569 const size = this.tileSize();
1570 const worldX = mouseX - this.scene.cameraPosition.x;
1571 const worldY = mouseY - this.scene.cameraPosition.y;
1572 return {
1573 tileX: Math.floor(worldX / size),
1574 tileY: Math.floor(worldY / size)
1575 };
1576 }
1577
1578 entityAtScreen (mouseX, mouseY)
1579 {
1580 let best = null;
1581 let bestLayer = -Infinity;
1582 for (const entity of this.entities.values())
1583 {
1584 const box = this.#entityScreenBox(entity);
1585 if (!box)
1586 { continue; }
1587 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
1588 {
1589 const layer = entity.object?.layer ?? 0;
1590 if (layer >= bestLayer)
1591 {
1592 best = entity;
1593 bestLayer = layer;
1594 }
1595 }
1596 }
1597 return best;
1598 }
1599
1600 nametagAnchor (entity)
1601 {
1602 const box = this.#entityScreenBox(entity);
1603 if (!box)
1604 { return null; }
1605 return { x: (box.left + box.right) / 2, y: box.top };
1606 }
1607
1608 #entityScreenBox (entity)
1609 {
1610 const object = entity?.object;
1611 if (!object)
1612 { return null; }
1613 const size = object.transform.size;
1614 const x = object.transform.position.x + this.scene.cameraPosition.x;
1615 const y = object.transform.position.y + this.scene.cameraPosition.y;
1616 return {
1617 left: x - size.x / 2,
1618 right: x + size.x / 2,
1619 top: y - size.y / 2,
1620 bottom: y + size.y / 2
1621 };
1622 }
1623
1624 update (deltaTime)
1625 {
1626 const now = performance.now();
1627 const size = this.tileSize();
1628 this.#refreshStackTargets();
1629 for (const entity of this.entities.values())
1630 {
1631 const target = entity.targetX != null && entity.targetY != null
1632 ? { x: entity.targetX, y: entity.targetY }
1633 : tilePivot(entity.tileX, entity.tileY, size);
1634 if (entity.lerpStarted != null)
1635 {
1636 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
1637 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
1638 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
1639 if (t >= 1)
1640 {
1641 entity.lerpStarted = null;
1642 entity.previousTileX = null;
1643 entity.previousTileY = null;
1644 }
1645 }
1646 else
1647 {
1648 entity.visualX = target.x;
1649 entity.visualY = target.y;
1650 }
1651 this.#updateStackOffset(entity, now);
1652 this.#updateShove(entity, now, size);
1653 this.#expireGatherToolOverlay(entity, now);
1654 }
1655
1656 // The y-sort origin must settle before any layer is computed this frame,
1657 // otherwise entities and blocks end up sorted against different origins.
1658 this.#centerCamera();
1659 this.#syncYSortOrigin();
1660
1661 for (const entity of this.entities.values())
1662 { this.#placeEntity(entity, now); }
1663
1664 this.#updateSwipes(now);
1665 this.#updateDamageNumbers(now);
1666 this.#updateSkillLevelFloats(now);
1667 this.#relayoutSpellTargetHighlight();
1668 this.#refreshDepthLayers();
1669 this.#cullOffscreenDrawables();
1670 this.#updateShade(deltaTime);
1671 }
1672
1673 /**
1674 * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}).
1675 * Stable assignment by entityId; free-flight entities stay unshifted.
1676 */
1677 #refreshStackTargets ()
1678 {
1679 const byTile = new Map();
1680 for (const entity of this.entities.values())
1681 {
1682 if (entity.freeFlight || entity.dying)
1683 {
1684 entity.stackTargetX = 0;
1685 entity.stackTargetY = 0;
1686 continue;
1687 }
1688 const key = `${entity.tileX},${entity.tileY}`;
1689 let list = byTile.get(key);
1690 if (!list)
1691 {
1692 list = [];
1693 byTile.set(key, list);
1694 }
1695 list.push(entity);
1696 }
1697 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
1698 for (const list of byTile.values())
1699 {
1700 if (list.length <= 1)
1701 {
1702 for (const entity of list)
1703 {
1704 entity.stackTargetX = 0;
1705 entity.stackTargetY = 0;
1706 }
1707 continue;
1708 }
1709 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
1710 const n = list.length;
1711 for (let i = 0; i < n; i++)
1712 {
1713 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
1714 list[i].stackTargetX = Math.cos(angle) * radius;
1715 list[i].stackTargetY = Math.sin(angle) * radius;
1716 }
1717 }
1718 }
1719
1720 #updateStackOffset (entity, now)
1721 {
1722 const tx = entity.stackTargetX ?? 0;
1723 const ty = entity.stackTargetY ?? 0;
1724 const cx = entity.stackOffsetX ?? 0;
1725 const cy = entity.stackOffsetY ?? 0;
1726 if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty)
1727 {
1728 entity.stackFromX = cx;
1729 entity.stackFromY = cy;
1730 entity.stackLerpToX = tx;
1731 entity.stackLerpToY = ty;
1732 entity.stackLerpStarted = now;
1733 }
1734 if (entity.stackLerpStarted == null)
1735 {
1736 entity.stackOffsetX = tx;
1737 entity.stackOffsetY = ty;
1738 return;
1739 }
1740 const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS);
1741 entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t;
1742 entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t;
1743 if (t >= 1)
1744 {
1745 entity.stackOffsetX = tx;
1746 entity.stackOffsetY = ty;
1747 entity.stackLerpStarted = null;
1748 }
1749 }
1750
1751 #updateShove (entity, now, tileSize)
1752 {
1753 if (!entity.shove)
1754 {
1755 entity.shoveOffsetX = 0;
1756 entity.shoveOffsetY = 0;
1757 return;
1758 }
1759 const elapsed = now - entity.shove.started;
1760 const t = Math.min(1, elapsed / entity.shove.durationMs);
1761 const maxDist = tileSize * SHOVE_TILE_FRACTION;
1762 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
1763 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
1764 const dist = Math.hypot(dx, dy) || 1;
1765 const ux = dx / dist;
1766 const uy = dy / dist;
1767 let phase;
1768 if (t < 0.45)
1769 { phase = t / 0.45; }
1770 else
1771 { phase = 1 - (t - 0.45) / 0.55; }
1772 entity.shoveOffsetX = ux * maxDist * phase;
1773 entity.shoveOffsetY = uy * maxDist * phase;
1774 if (t >= 1)
1775 { entity.shove = null; }
1776 }
1777
1778 spawnCombatSwing (payload)
1779 {
1780 const attacker = this.entities.get(payload.attackerId);
1781 const target = this.entities.get(payload.targetId);
1782 if (!attacker || !target)
1783 { return; }
1784 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1785 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1786 const tx = target.visualX + (target.stackOffsetX ?? 0);
1787 const ty = target.visualY + (target.stackOffsetY ?? 0);
1788 this.#applyShove(attacker, tx, ty);
1789 const midX = (ax + tx) / 2;
1790 const midY = (ay + ty) / 2;
1791 const sortY = Math.max(ay, ty) + 0.02;
1792 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
1793 const jitter = (Math.random() * 2 - 1) * MELEE_SWIPE_JITTER_DEG;
1794 const spriteName = "fx:melee-swipe:melee-swipe";
1795 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
1796 if (object.transform)
1797 { object.transform.rotation = angle + jitter; }
1798 if (object.renderer)
1799 { object.renderer.alpha = 1; }
1800 this.scene.addObject(object);
1801 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
1802 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
1803 const started = performance.now();
1804 this.swipes.push({
1805 object,
1806 until: started + MELEE_SWIPE_MS,
1807 started,
1808 durationMs: MELEE_SWIPE_MS,
1809 sortY,
1810 fadeOpacity: true,
1811 fromTileX: payload.fromTileX,
1812 fromTileY: payload.fromTileY,
1813 tileX: payload.tileX,
1814 tileY: payload.tileY
1815 });
1816 }
1817
1818 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
1819 spawnGatherSwing (payload)
1820 {
1821 const attacker = this.entities.get(payload.attackerId);
1822 if (!attacker)
1823 { return; }
1824 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1825 this.#applyShove(attacker, pivot.x, pivot.y);
1826 if (payload.toolItemId != null)
1827 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
1828 }
1829
1830 #applyShove (entity, targetVisualX, targetVisualY)
1831 {
1832 entity.shove = {
1833 startVisualX: entity.visualX,
1834 startVisualY: entity.visualY,
1835 targetVisualX,
1836 targetVisualY,
1837 started: performance.now(),
1838 durationMs: SHOVE_MS
1839 };
1840 }
1841
1842 #applyShoveInDirection (entity, dirX, dirY)
1843 {
1844 const len = Math.hypot(dirX, dirY);
1845 if (len < 1e-4)
1846 { return; }
1847 const tileSize = this.tileSize();
1848 const ux = dirX / len;
1849 const uy = dirY / len;
1850 this.#applyShove(
1851 entity,
1852 entity.visualX + ux * tileSize,
1853 entity.visualY + uy * tileSize
1854 );
1855 }
1856
1857 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
1858 spawnPhysicalProjectileFx (payload)
1859 {
1860 const spriteName = payload.sprite ?? "fx:projectile:arrow";
1861 const image = this.game.images[spriteName];
1862 if (!image)
1863 { return; }
1864 const dualTint = this.#dualTintFromPayload(payload);
1865 const fromPivot = this.#projectileLaunchPoint(
1866 payload.attackerId ?? null,
1867 payload.fromTileX,
1868 payload.fromTileY
1869 );
1870 const toPivot = this.#projectileAimPoint(
1871 payload.targetId ?? null,
1872 payload.tileX,
1873 payload.tileY
1874 );
1875 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1876 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1877 const object = new GameObject(0, 0, image, SORT_FX);
1878 if (object.transform)
1879 { object.transform.rotation = angle; }
1880 this.scene.addObject(object);
1881 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1882 this.#applyPhysicalCombatFxDarkness(
1883 object,
1884 payload.fromTileX,
1885 payload.fromTileY,
1886 payload.tileX,
1887 payload.tileY,
1888 dualTint
1889 );
1890 const started = performance.now();
1891 const durationMs = payload.durationMs ?? 400;
1892 const trackTarget = payload.trackTarget !== false && payload.targetId != null;
1893 this.swipes.push({
1894 object,
1895 until: started + durationMs,
1896 started,
1897 durationMs,
1898 lerp: true,
1899 dualTint,
1900 fromTileX: payload.fromTileX,
1901 fromTileY: payload.fromTileY,
1902 tileX: payload.tileX,
1903 tileY: payload.tileY,
1904 attackerId: payload.attackerId ?? null,
1905 targetId: payload.targetId ?? null,
1906 trackTarget,
1907 onImpact: null
1908 });
1909 }
1910
1911 /** Bloom-layer spell projectiles — magenta-tinted, unique art per spell. */
1912 spawnSpellProjectileFx (payload)
1913 {
1914 const spellId = payload.spellId ?? null;
1915 const def = spellId != null ? spellDefinition(spellId) : null;
1916 const spriteName = payload.sprite
1917 ?? def?.projectileSprite
1918 ?? "fx:projectile:spell-none-1-mana-bullet";
1919 const image = this.game.images[spriteName];
1920 if (!image)
1921 { return; }
1922 const tint = spellProjectileTint(def?.element);
1923 const fromPivot = this.#projectileLaunchPoint(
1924 payload.casterId ?? null,
1925 payload.fromTileX,
1926 payload.fromTileY
1927 );
1928 const toPivot = this.#projectileAimPoint(
1929 payload.targetId ?? null,
1930 payload.tileX,
1931 payload.tileY
1932 );
1933 // Spell casts push the caster visually toward the spell's target.
1934 // (Presentation only; server authority remains combat-resolution.)
1935 const caster = payload.casterId != null
1936 ? this.entities.get(payload.casterId)
1937 : null;
1938 if (caster && !caster.dying)
1939 {
1940 const casterPivotX = caster.visualX + (caster.stackOffsetX ?? 0);
1941 const casterPivotY = caster.visualY + (caster.stackOffsetY ?? 0);
1942 this.#applyShoveInDirection(caster, toPivot.x - casterPivotX, toPivot.y - casterPivotY);
1943 }
1944 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1945 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1946 const object = new GameObject(0, 0, image, SORT_FX);
1947 object.renderer.layer = RENDER_LAYER_BLOOM;
1948 this.#markUnlit(object);
1949 this.#syncUnlitTintSprite(object, tint);
1950 if (object.transform)
1951 { object.transform.rotation = angle; }
1952 this.scene.addObject(object);
1953 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1954 const started = performance.now();
1955 const durationMs = payload.durationMs ?? 2000;
1956 this.swipes.push({
1957 object,
1958 until: started + durationMs,
1959 started,
1960 durationMs,
1961 lerp: true,
1962 spellProjectile: true,
1963 tint,
1964 fromTileX: payload.fromTileX,
1965 fromTileY: payload.fromTileY,
1966 tileX: payload.tileX,
1967 tileY: payload.tileY,
1968 attackerId: payload.casterId ?? null,
1969 targetId: payload.targetId ?? null,
1970 trackTarget: payload.targetId != null,
1971 onImpact: null
1972 });
1973 }
1974
1975 spawnSpellFizzleFx (_payload)
1976 {
1977 // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
1978 }
1979
1980 /**
1981 * Authoritative Light-spell tile light from the server.
1982 * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
1983 */
1984 setSpellLight (payload)
1985 {
1986 const key = `${payload.tileX},${payload.tileY}`;
1987 this.spellLights.set(key, {
1988 tileX: payload.tileX,
1989 tileY: payload.tileY,
1990 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1991 range: payload.rangeTiles ?? 6,
1992 intensity: payload.intensity ?? 0.88
1993 });
1994 this.#invalidateNeighborLightmapCaches(
1995 Math.floor(payload.tileX / CHUNK_SIZE),
1996 Math.floor(payload.tileY / CHUNK_SIZE)
1997 );
1998 }
1999
2000 removeSpellLight (payload)
2001 {
2002 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
2003 this.#invalidateNeighborLightmapCaches(
2004 Math.floor(payload.tileX / CHUNK_SIZE),
2005 Math.floor(payload.tileY / CHUNK_SIZE)
2006 );
2007 }
2008
2009 setSpellDark (payload)
2010 {
2011 const key = `${payload.tileX},${payload.tileY}`;
2012 this.spellDarks.set(key, {
2013 tileX: payload.tileX,
2014 tileY: payload.tileY,
2015 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
2016 range: payload.rangeTiles ?? 6,
2017 intensity: payload.intensity ?? 0.88
2018 });
2019 this.#invalidateNeighborLightmapCaches(
2020 Math.floor(payload.tileX / CHUNK_SIZE),
2021 Math.floor(payload.tileY / CHUNK_SIZE)
2022 );
2023 }
2024
2025 removeSpellDark (payload)
2026 {
2027 this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);
2028 this.#invalidateNeighborLightmapCaches(
2029 Math.floor(payload.tileX / CHUNK_SIZE),
2030 Math.floor(payload.tileY / CHUNK_SIZE)
2031 );
2032 }
2033
2034 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
2035 {
2036 this.dynamicLights.push({
2037 tileX: Math.floor(worldX),
2038 tileY: Math.floor(worldY),
2039 range: radiusTiles,
2040 intensity,
2041 until: performance.now() + durationMs
2042 });
2043 }
2044
2045 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
2046 {
2047 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2048 if (!snapshot)
2049 { return; }
2050 const index = localY * CHUNK_SIZE + localX;
2051 if (ground !== undefined)
2052 { snapshot.grounds[index] = ground; }
2053 if (block !== undefined)
2054 { snapshot.blocks[index] = block; }
2055 if (light !== undefined)
2056 { snapshot.light[index] = light; }
2057 if (ground !== undefined || block !== undefined)
2058 {
2059 if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE)
2060 { snapshot.occlusion = bakeChunkOcclusion(snapshot); }
2061 else
2062 { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); }
2063 }
2064 const tileX = chunkX * CHUNK_SIZE + localX;
2065 const tileY = chunkY * CHUNK_SIZE + localY;
2066 if (block !== undefined)
2067 {
2068 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
2069 this.#drawTile(tileX, tileY);
2070 return;
2071 }
2072 this.#scheduleChunkRebuild(snapshot);
2073 if (ground !== undefined)
2074 { this.#drawTile(tileX, tileY); }
2075 }
2076
2077 /**
2078 * Editor-only mob markers for authored spawners (invisible during play).
2079 * Humanoid / town guard / CE show body + equipment overlays.
2080 * @param {number} chunkX
2081 * @param {number} chunkY
2082 * @param {Array<{ localX: number, localY: number, config?: object }>} spawners
2083 * @param {(mobTypeId: number) => string} resolveSprite
2084 */
2085 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
2086 {
2087 const prefix = `${chunkX},${chunkY}:`;
2088 for (const [key, entry] of [...this.editorSpawners.entries()])
2089 {
2090 if (!key.startsWith(prefix))
2091 { continue; }
2092 this.#destroyEditorSpawnerEntry(entry);
2093 this.editorSpawners.delete(key);
2094 }
2095 const size = this.tileSize();
2096 for (const spawner of spawners ?? [])
2097 {
2098 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
2099 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
2100 const layers = layersFromSpawnerConfig(spawner.config);
2101 const bodySpriteName = layers?.[0]?.sprite
2102 ?? resolveSprite?.(spawner.config?.mobTypeId)
2103 ?? null;
2104 if (!bodySpriteName)
2105 { continue; }
2106 const key = `${prefix}${spawner.localX},${spawner.localY}`;
2107 const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY);
2108 if (!object)
2109 { continue; }
2110 object.renderer.alpha = 0.85;
2111 const bodyTint = layers?.[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2112 if (bodyTint)
2113 { this.#syncUnlitTintSprite(object, bodyTint); }
2114 else
2115 { this.#markUnlit(object); }
2116 const overlays = [];
2117 for (const layer of layers?.slice(1) ?? [])
2118 {
2119 const overlay = this.#ensureSprite(null, layer.sprite, SORT_ENTITY);
2120 if (!overlay)
2121 { continue; }
2122 overlay.renderer.alpha = 0.85;
2123 this.#applyEditorSpawnerOverlayLook(overlay, layer);
2124 overlays.push(overlay);
2125 }
2126 const pivot = tilePivot(tileX, tileY, size);
2127 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
2128 for (let i = 0; i < overlays.length; i++)
2129 {
2130 this.#placePivoted(
2131 overlays[i],
2132 pivot.x,
2133 pivot.y,
2134 pivot.y + 0.05 + 0.001 * (i + 1),
2135 SORT_ENTITY
2136 );
2137 }
2138 this.editorSpawners.set(key, {
2139 object,
2140 overlays,
2141 tileX,
2142 tileY,
2143 spriteName: bodySpriteName
2144 });
2145 }
2146 }
2147
2148 #destroyEditorSpawnerEntry (entry)
2149 {
2150 entry?.object?.destroy();
2151 for (const overlay of entry?.overlays ?? [])
2152 { overlay?.destroy(); }
2153 }
2154
2155 #applyEditorSpawnerOverlayLook (overlay, layer)
2156 {
2157 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2158 const dualTint = layerDef?.iconTintFromTier
2159 ? null
2160 : (layer.itemId != null
2161 ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef)
2162 : null);
2163 const tint = layer.tint
2164 ? normalizeRgb(layer.tint)
2165 : (dualTint
2166 ? null
2167 : (layerDef?.iconTintFromTier
2168 ? resolveItemTint({ itemId: layer.itemId }, layerDef)
2169 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)));
2170 if (dualTint)
2171 {
2172 overlay._lit = true;
2173 this.#syncDualTintLitSprite(overlay, 0, dualTint, 0, false);
2174 return;
2175 }
2176 if (tint)
2177 {
2178 this.#syncUnlitTintSprite(overlay, tint);
2179 return;
2180 }
2181 this.#markUnlit(overlay);
2182 }
2183
2184 clearEditorSpawners ()
2185 {
2186 for (const entry of this.editorSpawners.values())
2187 { this.#destroyEditorSpawnerEntry(entry); }
2188 this.editorSpawners.clear();
2189 }
2190
2191 #relayoutEditorSpawners ()
2192 {
2193 const size = this.tileSize();
2194 for (const entry of this.editorSpawners.values())
2195 {
2196 if (!entry.object)
2197 { continue; }
2198 const pivot = tilePivot(entry.tileX, entry.tileY, size);
2199 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
2200 const overlays = entry.overlays ?? [];
2201 for (let i = 0; i < overlays.length; i++)
2202 {
2203 this.#placePivoted(
2204 overlays[i],
2205 pivot.x,
2206 pivot.y,
2207 pivot.y + 0.05 + 0.001 * (i + 1),
2208 SORT_ENTITY
2209 );
2210 }
2211 }
2212 }
2213
2214 /**
2215 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
2216 */
2217 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
2218 {
2219 const spawnRadius = Math.max(0, spawnRange | 0);
2220 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
2221 if (this.spawnRangeHighlight
2222 && this.wanderRangeHighlight
2223 && this.spawnRangeHighlight.tileX === tileX
2224 && this.spawnRangeHighlight.tileY === tileY
2225 && this.spawnRangeHighlight.range === spawnRadius
2226 && this.wanderRangeHighlight.range === wanderRadius)
2227 {
2228 this.#relayoutSpawnRangeHighlight();
2229 return;
2230 }
2231 this.clearSpawnRangeHighlight();
2232 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
2233 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
2234 if (wanderObject)
2235 {
2236 this.#markUnlit(wanderObject);
2237 wanderObject.renderer.alpha = 1;
2238 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
2239 }
2240 if (spawnObject)
2241 {
2242 this.#markUnlit(spawnObject);
2243 spawnObject.renderer.alpha = 1;
2244 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
2245 }
2246 this.#relayoutSpawnRangeHighlight();
2247 }
2248
2249 clearSpawnRangeHighlight ()
2250 {
2251 this.spawnRangeHighlight?.object?.destroy();
2252 this.wanderRangeHighlight?.object?.destroy();
2253 this.spawnRangeHighlight = null;
2254 this.wanderRangeHighlight = null;
2255 }
2256
2257 setSpellTargetHighlight (tileX, tileY, inRange = true)
2258 {
2259 if (
2260 this.spellTargetHighlight
2261 && this.spellTargetHighlight.mode === "tile"
2262 && this.spellTargetHighlight.tileX === tileX
2263 && this.spellTargetHighlight.tileY === tileY
2264 && this.spellTargetHighlight.inRange === inRange
2265 )
2266 {
2267 this.#relayoutSpellTargetHighlight();
2268 return;
2269 }
2270 this.clearSpellTargetHighlight();
2271 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
2272 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
2273 if (!object)
2274 { return; }
2275 this.#markUnlit(object);
2276 object.renderer.alpha = 1;
2277 this.spellTargetHighlight = {
2278 mode: "tile",
2279 object,
2280 tileX,
2281 tileY,
2282 entityId: null,
2283 inRange,
2284 spriteName
2285 };
2286 this.#relayoutSpellTargetHighlight();
2287 }
2288
2289 /** Outline box around a living entity (mob / player) for entity-target spells. */
2290 setSpellEntityTargetHighlight (entityId, inRange = true)
2291 {
2292 const id = entityId | 0;
2293 if (
2294 this.spellTargetHighlight
2295 && this.spellTargetHighlight.mode === "entity"
2296 && this.spellTargetHighlight.entityId === id
2297 && this.spellTargetHighlight.inRange === inRange
2298 )
2299 {
2300 this.#relayoutSpellTargetHighlight();
2301 return;
2302 }
2303 this.clearSpellTargetHighlight();
2304 if (!this.entities.has(id))
2305 { return; }
2306 const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid";
2307 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
2308 if (!object)
2309 { return; }
2310 this.#markUnlit(object);
2311 object.renderer.alpha = 1;
2312 this.spellTargetHighlight = {
2313 mode: "entity",
2314 object,
2315 tileX: 0,
2316 tileY: 0,
2317 entityId: id,
2318 inRange,
2319 spriteName
2320 };
2321 this.#relayoutSpellTargetHighlight();
2322 }
2323
2324 clearSpellTargetHighlight ()
2325 {
2326 this.spellTargetHighlight?.object?.destroy();
2327 this.spellTargetHighlight = null;
2328 }
2329
2330 #relayoutSpellTargetHighlight ()
2331 {
2332 const highlight = this.spellTargetHighlight;
2333 if (!highlight?.object)
2334 { return; }
2335 if (highlight.mode === "entity")
2336 {
2337 const entity = this.entities.get(highlight.entityId);
2338 if (!entity?.object)
2339 {
2340 this.clearSpellTargetHighlight();
2341 return;
2342 }
2343 const pad = this.tileSize() * 0.12;
2344 const src = entity.object.transform;
2345 highlight.object.transform.position.x = src.position.x;
2346 highlight.object.transform.position.y = src.position.y;
2347 highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad);
2348 highlight.object.layer = LAYER_EDGE - 1;
2349 highlight.tileX = entity.tileX;
2350 highlight.tileY = entity.tileY;
2351 this.#markSortDirty();
2352 return;
2353 }
2354 const size = this.tileSize();
2355 const left = highlight.tileX * size;
2356 const top = highlight.tileY * size;
2357 highlight.object.transform.position.x = left + size / 2;
2358 highlight.object.transform.position.y = top + size / 2;
2359 highlight.object.transform.size = new vector(size, size);
2360 highlight.object.layer = LAYER_EDGE - 1;
2361 this.#markSortDirty();
2362 }
2363
2364 #relayoutSpawnRangeHighlight ()
2365 {
2366 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
2367 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
2368 }
2369
2370 #layoutRangeOverlay (highlight, layer)
2371 {
2372 if (!highlight?.object)
2373 { return; }
2374 const size = this.tileSize();
2375 const side = (2 * highlight.range + 1) * size;
2376 const left = (highlight.tileX - highlight.range) * size;
2377 const top = (highlight.tileY - highlight.range) * size;
2378 highlight.object.transform.position.x = left + side / 2;
2379 highlight.object.transform.position.y = top + side / 2;
2380 highlight.object.transform.size = new vector(side, side);
2381 highlight.object.layer = layer;
2382 this.#markSortDirty();
2383 }
2384
2385 setTilePreview (tileX, tileY, override)
2386 {
2387 const next = { tileX, tileY, ...override };
2388 if (this.#previewEqual(this.preview, next))
2389 { return; }
2390 const previous = this.preview;
2391 this.preview = next;
2392 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2393 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2394 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
2395 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
2396 {
2397 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
2398 if (prevKey !== `${chunkX},${chunkY}`)
2399 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
2400 // Per-tile blocks (doors, campfires, …) are not in the atlas — refresh sprites.
2401 this.#drawTile(previous.tileX, previous.tileY);
2402 }
2403 this.#drawTile(tileX, tileY);
2404 }
2405
2406 clearTilePreview ()
2407 {
2408 if (!this.preview)
2409 { return; }
2410 const previous = this.preview;
2411 this.preview = null;
2412 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
2413 this.#scheduleChunkRebuild(snapshot);
2414 this.#drawTile(previous.tileX, previous.tileY);
2415 }
2416
2417 #lerpMs (gait)
2418 {
2419 const walk = this.settings.walkTilesPerSecond || 2;
2420 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
2421 return seconds * 1000;
2422 }
2423
2424 #centerCamera ()
2425 {
2426 if (!this.followPlayer)
2427 { return; }
2428 const local = this.entities.get(this.localEntityId);
2429 if (!local)
2430 { return; }
2431 const x = local.visualX + (local.stackOffsetX ?? 0);
2432 const y = local.visualY + (local.stackOffsetY ?? 0);
2433 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
2434 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
2435 }
2436
2437 /**
2438 * World Y at the viewport centre. Depth sort uses worldY − this so layers stay
2439 * bounded (absolute tileY×zoom otherwise overflows past LAYER_EDGE).
2440 */
2441 #syncYSortOrigin ()
2442 {
2443 const camY = this.scene.cameraPosition.y;
2444 const screenH = this.scene.real_size.y;
2445 this.ySortOrigin = -camY + screenH / 2;
2446 }
2447
2448 /** Viewport-relative y-sort layer for world sprites. */
2449 #depthLayer (sortY, subOrder, flight = false)
2450 {
2451 const relative = sortY - (this.ySortOrigin ?? 0);
2452 return flight ? flightSortLayer(relative, subOrder) : ySortLayer(relative, subOrder);
2453 }
2454
2455 /**
2456 * Re-apply depth for every world sprite that is not repositioned each frame.
2457 * Their layer is relative to the y-sort origin, which moves with the camera,
2458 * so a layer assigned once at draw time drifts as the player walks.
2459 */
2460 #refreshDepthLayers ()
2461 {
2462 const size = this.tileSize();
2463 for (const baked of this.bakedChunks.values())
2464 {
2465 const top = baked.chunkY * CHUNK_SIZE * size;
2466 const chunkPx = CHUNK_SIZE * size;
2467 for (let row = 0; row < CHUNK_SIZE; row++)
2468 {
2469 const object = baked.blockObjects?.[row];
2470 if (!object)
2471 { continue; }
2472 const rowY = top + row * size + size / 2;
2473 object.layer = this.#depthLayer(rowY, SORT_BLOCK);
2474 }
2475 if (baked.bloomObject)
2476 { baked.bloomObject.layer = this.#depthLayer(top + chunkPx, SORT_BLOCK); }
2477 }
2478 // Unbaked tile sprites: tall blocks, doors and animated grounds.
2479 for (const objects of this.tiles.values())
2480 {
2481 if (!objects.block && !objects.blockBloom && !objects.groundBloom)
2482 { continue; }
2483 const pivotY = objects.tileY * size + size / 2;
2484 if (objects.block)
2485 { objects.block.layer = this.#depthLayer(pivotY, objects.blockSort ?? SORT_ENTITY); }
2486 if (objects.blockBloom)
2487 { objects.blockBloom.layer = this.#depthLayer(pivotY, SORT_ENTITY); }
2488 if (objects.groundBloom)
2489 { objects.groundBloom.layer = this.#depthLayer(pivotY, LAYER_GROUND); }
2490 }
2491 for (const item of this.groundItems.values())
2492 {
2493 if (!item.object)
2494 { continue; }
2495 item.object.layer = this.#depthLayer(item.tileY * size + size / 2 - 0.01, SORT_BLOCK);
2496 }
2497 // Lerping FX are re-placed in #updateSwipes; static ones need the refresh.
2498 for (const swipe of this.swipes)
2499 {
2500 if (swipe.lerp || swipe.sortY == null || !swipe.object)
2501 { continue; }
2502 swipe.object.layer = this.#depthLayer(swipe.sortY, SORT_FX);
2503 }
2504 for (const entry of this.editorSpawners.values())
2505 {
2506 const pivotY = entry.tileY * size + size / 2;
2507 if (entry.object)
2508 { entry.object.layer = this.#depthLayer(pivotY + 0.05, SORT_ENTITY); }
2509 const overlays = entry.overlays ?? [];
2510 for (let i = 0; i < overlays.length; i++)
2511 {
2512 if (overlays[i])
2513 { overlays[i].layer = this.#depthLayer(pivotY + 0.05 + 0.001 * (i + 1), SORT_ENTITY); }
2514 }
2515 }
2516 this.#markSortDirty();
2517 }
2518
2519 /**
2520 * World-pixel AABB of the screen, expanded for tall block sprites (zoom-aware).
2521 * Tiles fully outside this rect are not drawn.
2522 */
2523 #drawBounds ()
2524 {
2525 const pad = this.tileSize() * 2;
2526 const camX = this.scene.cameraPosition.x;
2527 const camY = this.scene.cameraPosition.y;
2528 const w = this.scene.real_size.x;
2529 const h = this.scene.real_size.y;
2530 return {
2531 left: -camX - pad,
2532 right: -camX + w + pad,
2533 top: -camY - pad,
2534 bottom: -camY + h + pad
2535 };
2536 }
2537
2538 #rectIntersects (left, top, right, bottom, bounds)
2539 {
2540 return right >= bounds.left
2541 && left <= bounds.right
2542 && bottom >= bounds.top
2543 && top <= bounds.bottom;
2544 }
2545
2546 #setRendererVisible (object, visible)
2547 {
2548 if (object?.renderer)
2549 { object.renderer.visible = !!visible; }
2550 }
2551
2552 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
2553 #cullOffscreenDrawables ()
2554 {
2555 const bounds = this.#drawBounds();
2556 const size = this.tileSize();
2557
2558 for (const baked of this.bakedChunks.values())
2559 {
2560 const left = baked.chunkX * CHUNK_SIZE * size;
2561 const top = baked.chunkY * CHUNK_SIZE * size;
2562 const chunkPx = CHUNK_SIZE * size;
2563 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
2564 this.#setRendererVisible(baked.groundObject, chunkVisible);
2565 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
2566 baked._inViewport = chunkVisible;
2567 for (let row = 0; row < CHUNK_SIZE; row++)
2568 {
2569 const rowTop = top + row * size;
2570 const rowVisible = chunkVisible && this.#rectIntersects(
2571 left, rowTop, left + chunkPx, rowTop + size, bounds
2572 );
2573 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
2574 }
2575 }
2576
2577 for (const objects of this.tiles.values())
2578 {
2579 const left = objects.tileX * size;
2580 const top = objects.tileY * size;
2581 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
2582 objects._inViewport = visible;
2583 this.#setRendererVisible(objects.ground, visible);
2584 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
2585 this.#setRendererVisible(objects.block, visible);
2586 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
2587 if (objects.waterEdges)
2588 {
2589 for (const edge of Object.values(objects.waterEdges))
2590 { this.#setRendererVisible(edge, visible); }
2591 }
2592 }
2593 }
2594
2595 #upsertEntity (payload)
2596 {
2597 const size = this.tileSize();
2598 const pivot = tilePivot(payload.tileX, payload.tileY, size);
2599 let entity = this.entities.get(payload.entityId);
2600 if (entity?.dying)
2601 {
2602 if (entity.entityId === this.localEntityId)
2603 { this.#abortEntityFade(entity); }
2604 else
2605 {
2606 this.#finishEntityFade(payload.entityId);
2607 entity = null;
2608 }
2609 }
2610 if (!entity)
2611 {
2612 const spriteName = payload.layers?.[0]?.sprite
2613 ?? payload.sprite
2614 ?? bodySpriteName(payload.sex);
2615 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
2616 this.scene.addObject(object);
2617 this.#startIdleAnimation(object);
2618 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
2619 this.entities.set(payload.entityId, entity);
2620 }
2621 entity.entityId = payload.entityId;
2622 entity.tileX = payload.tileX;
2623 entity.tileY = payload.tileY;
2624 entity.gait = payload.gait;
2625 entity.sex = payload.sex ?? entity.sex;
2626 entity.characterId = payload.characterId ?? entity.characterId ?? null;
2627 entity.accountId = payload.accountId ?? entity.accountId ?? null;
2628 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
2629 if (payload.level != null)
2630 { entity.level = payload.level | 0; }
2631 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
2632 entity.aggressive = payload.aggressive != null
2633 ? !!payload.aggressive
2634 : (payload.hostile != null ? !!payload.hostile : !!entity.aggressive);
2635 entity.canFight = payload.canFight != null
2636 ? !!payload.canFight
2637 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
2638 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
2639 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
2640 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
2641 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
2642 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
2643 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
2644 if (payload.lightIntensity != null)
2645 { entity.lightIntensity = Number(payload.lightIntensity) || 1; }
2646 else if (entity.lightIntensity == null)
2647 { entity.lightIntensity = 1; }
2648 if (payload.visualScale != null)
2649 { entity.visualScale = Number(payload.visualScale) || 1; }
2650 else if (entity.visualScale == null)
2651 { entity.visualScale = 1; }
2652 if (payload.health != null)
2653 { entity.health = payload.health; }
2654 if (payload.maxHealth != null)
2655 { entity.maxHealth = payload.maxHealth; }
2656 if (payload.skullValue != null)
2657 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
2658 else if (entity.skullValue == null)
2659 { entity.skullValue = 0; }
2660 if (payload.firstName)
2661 { entity.firstName = payload.firstName; }
2662 if (payload.lastName)
2663 { entity.lastName = payload.lastName; }
2664 entity.firstName = entity.firstName ?? "";
2665 entity.lastName = entity.lastName ?? "";
2666 if (payload.worldX != null && payload.worldY != null)
2667 {
2668 entity.worldX = payload.worldX;
2669 entity.worldY = payload.worldY;
2670 entity.visualX = payload.worldX * size;
2671 entity.visualY = payload.worldY * size;
2672 entity.targetX = entity.visualX;
2673 entity.targetY = entity.visualY;
2674 }
2675 else
2676 {
2677 entity.visualX = pivot.x;
2678 entity.visualY = pivot.y;
2679 entity.targetX = pivot.x;
2680 entity.targetY = pivot.y;
2681 }
2682 entity.fromX = entity.visualX;
2683 entity.fromY = entity.visualY;
2684 if (payload.layers)
2685 { this.#applyLayers(entity, payload.layers); }
2686 this.#syncHpBar(entity);
2687 this.#syncSkullMarker(entity);
2688 this.#placeEntity(entity, performance.now());
2689 }
2690
2691 #applyLayers (entity, layers)
2692 {
2693 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
2694 this.#rebuildOverlays(entity);
2695 }
2696
2697 #setGatherToolOverlay (entity, toolItemId)
2698 {
2699 entity.gatherToolItemId = toolItemId;
2700 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
2701 this.#rebuildOverlays(entity);
2702 this.#placeEntity(entity, performance.now());
2703 }
2704
2705 #expireGatherToolOverlay (entity, now)
2706 {
2707 if (entity.gatherToolItemId == null)
2708 { return; }
2709 if ((entity.gatherToolUntil ?? 0) > now)
2710 { return; }
2711 entity.gatherToolItemId = null;
2712 entity.gatherToolUntil = 0;
2713 this.#rebuildOverlays(entity);
2714 }
2715
2716 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
2717 #layersForDisplay (entity)
2718 {
2719 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
2720 const toolId = entity.gatherToolItemId;
2721 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
2722 { return layers; }
2723 const equip = itemEquipSprite(toolId);
2724 if (!equip || !this.game.images[equip])
2725 { return layers; }
2726 const replacement = {
2727 sprite: equip,
2728 itemId: toolId,
2729 tint: resolveEquipTint(toolId)
2730 };
2731 for (let index = layers.length - 1; index >= 1; index--)
2732 {
2733 const def = itemDefinition(layers[index].itemId);
2734 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
2735 {
2736 layers[index] = replacement;
2737 return layers;
2738 }
2739 }
2740 layers.push(replacement);
2741 return layers;
2742 }
2743
2744 #rebuildOverlays (entity)
2745 {
2746 const layers = this.#layersForDisplay(entity);
2747 const base = layers[0]?.sprite
2748 ?? bodySpriteName(entity.sex);
2749 if (this.game.images[base])
2750 {
2751 entity.object.renderer.sprite = this.game.images[base];
2752 this.#startIdleAnimation(entity.object);
2753 }
2754 entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2755 entity.bodyDualTint = layers[0]?.dualTint
2756 ? {
2757 shaft: normalizeRgb(layers[0].dualTint.shaft),
2758 tip: normalizeRgb(layers[0].dualTint.tip),
2759 ...(layers[0].dualTint.coat
2760 ? { coat: normalizeRgb(layers[0].dualTint.coat) }
2761 : {})
2762 }
2763 : null;
2764 entity.bloomBody = !!layers[0]?.bloomBody;
2765 for (const overlay of entity.overlays ?? [])
2766 { overlay.destroy(); }
2767 for (const overlay of entity.bloomOverlays ?? [])
2768 { overlay.destroy(); }
2769 entity.overlays = [];
2770 entity.overlayTints = [];
2771 entity.overlayDualTints = [];
2772 entity.overlayTightFit = [];
2773 entity.bloomOverlays = [];
2774 entity.bloomOverlayTints = [];
2775 entity.bloomOverlayDualTints = [];
2776 if (entity.bloomBody && this.game.images[base])
2777 {
2778 const bloomName = bloomCompanionName(base);
2779 const bloomImage = this.game.images[bloomName] ?? this.game.images[base];
2780 if (bloomImage)
2781 {
2782 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2783 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2784 this.#markUnlit(bloom);
2785 this.#startIdleAnimation(bloom);
2786 this.scene.addObject(bloom);
2787 entity.bloomOverlays.push(bloom);
2788 entity.bloomOverlayTints.push(entity.bodyTint);
2789 entity.bloomOverlayDualTints.push(entity.bodyDualTint);
2790 }
2791 }
2792 for (const layer of layers.slice(1))
2793 {
2794 const image = this.game.images[layer.sprite];
2795 if (!image)
2796 { continue; }
2797 const object = new GameObject(0, 0, image, SORT_ENTITY);
2798 this.scene.addObject(object);
2799 entity.overlays.push(object);
2800 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2801 entity.overlayTightFit.push(!!layerDef?.tightFit);
2802 const dualTint = layer.dualTint
2803 ? {
2804 shaft: normalizeRgb(layer.dualTint.shaft),
2805 tip: normalizeRgb(layer.dualTint.tip),
2806 ...(layer.dualTint.coat
2807 ? { coat: normalizeRgb(layer.dualTint.coat) }
2808 : {})
2809 }
2810 : (layer.itemId != null
2811 ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef)
2812 : null);
2813 entity.overlayDualTints.push(dualTint);
2814 entity.overlayTints.push(
2815 dualTint
2816 ? null
2817 : (layer.tint
2818 ? normalizeRgb(layer.tint)
2819 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
2820 );
2821 const bloomName = bloomCompanionName(layer.sprite);
2822 const bloomImage = this.game.images[bloomName];
2823 if (!bloomImage)
2824 { continue; }
2825 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2826 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2827 this.#markUnlit(bloom);
2828 this.scene.addObject(bloom);
2829 entity.bloomOverlays.push(bloom);
2830 entity.bloomOverlayTints.push(
2831 layer.tint ? normalizeRgb(layer.tint) : null
2832 );
2833 }
2834 }
2835
2836 #placeEntity (entity, now = performance.now())
2837 {
2838 const zoom = this.zoom;
2839 const offsetX = entity.shoveOffsetX ?? 0;
2840 const offsetY = entity.shoveOffsetY ?? 0;
2841 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
2842 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
2843 let walkTilt = 0;
2844 if (entity.lerpStarted != null)
2845 {
2846 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
2847 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
2848 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
2849 walkTilt = Math.sin(cycles) * tilt;
2850 }
2851 let flashStrength = (entity.damageFlashUntil ?? 0) > now
2852 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
2853 : 0;
2854 let deathAlpha = 1;
2855 if (entity.dying)
2856 {
2857 const fadeMs = Math.max(1, entity.deathFadeMs ?? DEATH_FADE_MS);
2858 const fadeT = (now - (entity.deathFadeStarted ?? now)) / fadeMs;
2859 if (fadeT >= 1 && entity.entityId !== this.localEntityId)
2860 {
2861 this.#finishEntityFade(entity.entityId);
2862 return;
2863 }
2864 deathAlpha = Math.max(0, 1 - fadeT);
2865 // Red silhouette only for combat death; plain despawn keeps lit colours + darkness.
2866 if (entity.deathDissolve)
2867 { flashStrength = 1; }
2868 }
2869 const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE;
2870 const tileShade = this.#entityShadeAlpha(entity, now);
2871 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
2872
2873 entity.object.transform.rotation = walkTilt;
2874 if (entity.object.renderer)
2875 { entity.object.renderer.alpha = deathAlpha; }
2876 if (entity.bodyDualTint)
2877 {
2878 this.#syncDualTintLitSprite(
2879 entity.object,
2880 tileShade,
2881 entity.bodyDualTint,
2882 flashStrength,
2883 wade,
2884 flashColor
2885 );
2886 }
2887 else
2888 {
2889 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor);
2890 }
2891 const flight = !!entity.freeFlight;
2892 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1, flight);
2893 for (let index = 0; index < (entity.overlays ?? []).length; index++)
2894 {
2895 const overlay = entity.overlays[index];
2896 const overlaySort = Math.min(SORT_HP_BAR - 2, SORT_ENTITY + 1 + index);
2897 overlay.transform.rotation = walkTilt;
2898 if (overlay.renderer)
2899 { overlay.renderer.alpha = deathAlpha; }
2900 const dualTint = entity.overlayDualTints?.[index] ?? null;
2901 if (dualTint)
2902 {
2903 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor);
2904 }
2905 else if (entity.overlayTightFit?.[index])
2906 {
2907 this.#syncTightFitLitSprite(
2908 overlay,
2909 entity,
2910 tileShade,
2911 flashStrength,
2912 wade,
2913 entity.overlayTints?.[index] ?? null,
2914 flashColor
2915 );
2916 }
2917 else
2918 {
2919 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor);
2920 }
2921 this.#placePivoted(overlay, pivotX, pivotY, pivotY, overlaySort, entity.visualScale ?? 1, flight);
2922 }
2923 for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++)
2924 {
2925 const overlay = entity.bloomOverlays[index];
2926 this.#setRendererVisible(overlay, this.bloomEnabled && deathAlpha > 0.02);
2927 if (!this.bloomEnabled)
2928 { continue; }
2929 /** Multi-frame body bloom locks to the base sprite; static bodies leave bloom free to animate. */
2930 if (entity.bloomBody && index === 0 && entity.object?.renderer)
2931 {
2932 const bodySprite = entity.object.renderer.sprite;
2933 const bloomSprite = overlay.renderer.sprite;
2934 const bodyFrames = Number(bodySprite?.subImages) || Number(bodySprite?.subImgTotal) || 1;
2935 const bloomFrames = Number(bloomSprite?.subImages) || Number(bloomSprite?.subImgTotal) || 1;
2936 if (bodyFrames > 1 && bloomFrames === bodyFrames)
2937 {
2938 overlay.renderer.cycle = null;
2939 overlay.renderer.subImage = entity.object.renderer.subImage | 0;
2940 }
2941 }
2942 overlay.transform.rotation = walkTilt;
2943 if (overlay.renderer)
2944 { overlay.renderer.alpha = deathAlpha; }
2945 const bloomDual = entity.bloomOverlayDualTints?.[index] ?? null;
2946 const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null;
2947 if (bloomDual)
2948 { this.#syncDualTintLitSprite(overlay, 0, bloomDual); }
2949 else if (bloomTint)
2950 { this.#syncUnlitTintSprite(overlay, bloomTint); }
2951 else
2952 { this.#markUnlit(overlay); }
2953 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1, flight);
2954 }
2955 if (!entity.dying)
2956 {
2957 this.#placeHpBar(entity, pivotX, pivotY);
2958 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
2959 }
2960 }
2961
2962 #markUnlit (object)
2963 {
2964 if (!object?.renderer)
2965 { return; }
2966 object._lit = false;
2967 object.renderer.shader = null;
2968 object.renderer.shaderUniforms = null;
2969 object.renderer.secondaryMap = null;
2970 }
2971
2972 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
2973 #syncUnlitTintSprite (object, tintColor)
2974 {
2975 if (!object?.renderer || !tintColor)
2976 { return; }
2977 const tint = normalizeRgb(tintColor);
2978 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2979 object.renderer.shader = getTintLitSpriteShader();
2980 object.renderer.shaderUniforms = {
2981 u_darkness: 0,
2982 u_strength: 0,
2983 u_flashColor: FLASH_COLOR_DAMAGE,
2984 u_wade: 0,
2985 u_spriteHeight: height,
2986 u_useTint: 1,
2987 u_tintColor: [tint.r, tint.g, tint.b]
2988 };
2989 object.renderer.secondaryMap = null;
2990 }
2991
2992 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
2993 {
2994 if (!object?.renderer || object._lit === false)
2995 { return; }
2996 object._lit = true;
2997 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2998 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2999 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3000 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3001 const tint = tintColor ? normalizeRgb(tintColor) : null;
3002 if (tint)
3003 {
3004 object.renderer.shader = getTintLitSpriteShader();
3005 object.renderer.shaderUniforms = {
3006 u_darkness: dark,
3007 u_strength: flash,
3008 u_flashColor: flashRgb,
3009 u_wade: wade ? 1 : 0,
3010 u_spriteHeight: height,
3011 u_useTint: 1,
3012 u_tintColor: [tint.r, tint.g, tint.b]
3013 };
3014 }
3015 else
3016 {
3017 object.renderer.shader = getSpriteLightingShader();
3018 object.renderer.shaderUniforms = {
3019 u_darkness: dark,
3020 u_strength: flash,
3021 u_flashColor: flashRgb,
3022 u_wade: wade ? 1 : 0,
3023 u_spriteHeight: height
3024 };
3025 }
3026 object.renderer.secondaryMap = null;
3027 }
3028
3029 #bodySecondaryMap (entity)
3030 {
3031 return entity?.object?.renderer?.sprite?.g_image ?? null;
3032 }
3033
3034 #tightFitMaskUniforms (overlay, entity)
3035 {
3036 const bodyRenderer = entity?.object?.renderer;
3037 const clothRenderer = overlay?.renderer;
3038 const bodySprite = bodyRenderer?.sprite;
3039 const clothSprite = clothRenderer?.sprite;
3040 if (!bodySprite || !clothSprite)
3041 { return null; }
3042 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
3043 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3044 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
3045 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3046 return {
3047 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
3048 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
3049 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
3050 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
3051 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
3052 };
3053 }
3054
3055 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
3056 {
3057 if (!overlay?.renderer || entity?.object?.renderer == null)
3058 { return; }
3059 const bodyMap = this.#bodySecondaryMap(entity);
3060 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
3061 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3062 if (!bodyMap || !maskUniforms)
3063 {
3064 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3065 return;
3066 }
3067 overlay._lit = true;
3068 const dark = Math.min(1, Math.max(0, darkness ?? 0));
3069 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3070 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3071 const tint = tintColor ? normalizeRgb(tintColor) : null;
3072 overlay.renderer.secondaryMap = bodyMap;
3073 if (tint)
3074 {
3075 overlay.renderer.shader = getTightFitTintLitSpriteShader();
3076 overlay.renderer.shaderUniforms = {
3077 u_darkness: dark,
3078 u_strength: flash,
3079 u_flashColor: flashRgb,
3080 u_wade: wade ? 1 : 0,
3081 u_spriteHeight: height,
3082 u_useTint: 1,
3083 u_tintColor: [tint.r, tint.g, tint.b],
3084 ...maskUniforms
3085 };
3086 }
3087 else
3088 {
3089 overlay.renderer.shader = getTightFitLitSpriteShader();
3090 overlay.renderer.shaderUniforms = {
3091 u_darkness: dark,
3092 u_strength: flash,
3093 u_flashColor: flashRgb,
3094 u_wade: wade ? 1 : 0,
3095 u_spriteHeight: height,
3096 ...maskUniforms
3097 };
3098 }
3099 }
3100
3101 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null)
3102 {
3103 if (!object?.renderer || !dualTint)
3104 { return; }
3105 const shaft = normalizeRgb(dualTint.shaft);
3106 const tip = normalizeRgb(dualTint.tip);
3107 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
3108 const dark = object._lit === false
3109 ? 0
3110 : Math.min(1, Math.max(0, darkness ?? 0));
3111 if (object._lit !== false)
3112 { object._lit = true; }
3113 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3114 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3115 object.renderer.shader = getDualTintLitSpriteShader();
3116 object.renderer.shaderUniforms = {
3117 u_darkness: dark,
3118 u_strength: flash,
3119 u_flashColor: flashColor ?? FLASH_COLOR_DAMAGE,
3120 u_wade: wade ? 1 : 0,
3121 u_spriteHeight: height,
3122 u_shaftTint: [shaft.r, shaft.g, shaft.b],
3123 u_tipTint: [tip.r, tip.g, tip.b],
3124 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
3125 u_hasCoat: coat ? 1 : 0
3126 };
3127 object.renderer.secondaryMap = null;
3128 }
3129
3130 #syncGroundItemSprite (item, darkness)
3131 {
3132 if (item?.dualTint)
3133 {
3134 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
3135 return;
3136 }
3137 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
3138 }
3139
3140 #groundTypeAt (tileX, tileY)
3141 {
3142 const ground = this.#groundAtTile(tileX, tileY);
3143 return ground == null ? null : normalizeGround(ground).typeId;
3144 }
3145
3146 /** Ground entry at a world tile, including editor hover preview when present. */
3147 #groundAtTile (tileX, tileY)
3148 {
3149 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
3150 && this.preview.ground !== undefined)
3151 { return this.preview.ground; }
3152 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3153 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3154 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3155 if (!snapshot)
3156 { return null; }
3157 const localX = tileX - chunkX * CHUNK_SIZE;
3158 const localY = tileY - chunkY * CHUNK_SIZE;
3159 const index = localY * CHUNK_SIZE + localX;
3160 return snapshot.grounds?.[index] ?? null;
3161 }
3162
3163 #waterCoastEdges (tileX, tileY)
3164 {
3165 const season = this.worldSeason;
3166 return {
3167 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
3168 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
3169 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
3170 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
3171 };
3172 }
3173
3174 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
3175 {
3176 if (!object?.renderer)
3177 { return; }
3178 const lit = corners ?? {
3179 nw: fallbackLit,
3180 ne: fallbackLit,
3181 sw: fallbackLit,
3182 se: fallbackLit
3183 };
3184 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
3185 object._lit = true;
3186 object.renderer.shader = getWaterGroundShader();
3187 object.renderer.secondaryMap = null;
3188 object.renderer.shaderUniforms = {
3189 u_ambientDark: dark,
3190 u_litNW: lit.nw,
3191 u_litNE: lit.ne,
3192 u_litSW: lit.sw,
3193 u_litSE: lit.se,
3194 u_time: timeSec,
3195 u_edgeN: edges?.n ?? 0,
3196 u_edgeE: edges?.e ?? 0,
3197 u_edgeS: edges?.s ?? 0,
3198 u_edgeW: edges?.w ?? 0
3199 };
3200 }
3201
3202 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
3203 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
3204 {
3205 if (!objects?.ground)
3206 { return; }
3207 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
3208 {
3209 objects.waterEdges = null;
3210 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
3211 return;
3212 }
3213 const fallbackLit = 1 - (objects.shadeAlpha ?? 0);
3214 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
3215 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
3216 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
3217 const localX = objects.tileX - chunkX * CHUNK_SIZE;
3218 const localY = objects.tileY - chunkY * CHUNK_SIZE;
3219 let litCorners = null;
3220 if (chunkBaked)
3221 {
3222 if (this.lightingMode === "simple")
3223 {
3224 const gridW = CHUNK_SIZE + 2;
3225 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
3226 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
3227 }
3228 else
3229 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
3230 }
3231 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
3232 this.#syncWaterGroundSprite(
3233 objects.ground,
3234 litCorners,
3235 ambientDark,
3236 objects.waterEdges,
3237 timeSec,
3238 fallbackLit
3239 );
3240 }
3241
3242 #ambientDarkness ()
3243 {
3244 const hour = this.nightPreview ?? this.worldHour;
3245 const calendar = nightFactor(hour, this.settings.nightDarkness);
3246 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
3247 if (dark == null)
3248 { dark = calendar; }
3249 if (this.localBlind)
3250 { dark = Math.min(1, dark + 0.85); }
3251 return dark;
3252 }
3253
3254 setLocalBlind (blind)
3255 {
3256 this.localBlind = !!blind;
3257 }
3258
3259 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
3260 #blindVisionLight ()
3261 {
3262 if (!this.localBlind)
3263 { return null; }
3264 const local = this.entities.get(this.localEntityId);
3265 if (!local)
3266 { return null; }
3267 const tileSize = this.tileSize();
3268 return {
3269 tileX: Math.floor(local.visualX / tileSize),
3270 tileY: Math.floor(local.visualY / tileSize),
3271 range: 2.25,
3272 intensity: 1
3273 };
3274 }
3275
3276 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
3277 {
3278 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
3279 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
3280 const dark = (fromAlpha + toAlpha) / 2;
3281 if (dualTint)
3282 {
3283 this.#syncDualTintLitSprite(object, dark, dualTint);
3284 return;
3285 }
3286 this.#syncLitSprite(object, dark);
3287 }
3288
3289 #dualTintFromPayload (payload)
3290 {
3291 if (!payload?.shaftTint || !payload?.tipTint)
3292 { return null; }
3293 return {
3294 shaft: payload.shaftTint,
3295 tip: payload.tipTint,
3296 ...(payload.coatTint ? { coat: payload.coatTint } : {})
3297 };
3298 }
3299
3300 #syncHpBar (entity)
3301 {
3302 const current = entity.health;
3303 const max = entity.maxHealth;
3304 const show = current != null
3305 && max != null
3306 && max > 0
3307 && current < max;
3308 if (!show)
3309 {
3310 entity.hpBar?.destroy();
3311 entity.hpBar = null;
3312 entity.hpBarCanvas = null;
3313 return;
3314 }
3315 if (!entity.hpBarCanvas)
3316 {
3317 entity.hpBarCanvas = document.createElement("canvas");
3318 entity.hpBarCanvas.width = HP_BAR_W;
3319 entity.hpBarCanvas.height = HP_BAR_H;
3320 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
3321 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
3322 this.#markUnlit(entity.hpBar);
3323 this.scene.addObject(entity.hpBar);
3324 }
3325 drawHpBar(entity.hpBarCanvas, current, max);
3326 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
3327 }
3328
3329 #placeHpBar (entity, pivotX, pivotY)
3330 {
3331 if (!entity.hpBar)
3332 { return; }
3333 const sprite = entity.object?.renderer?.sprite;
3334 if (!sprite)
3335 { return; }
3336 const zoom = this.zoom;
3337 const drawH = sprite.height * zoom;
3338 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
3339 const spriteTop = centerY - drawH / 2;
3340 const barW = HP_BAR_W * zoom;
3341 const barH = HP_BAR_H * zoom;
3342 entity.hpBar.transform.position.x = pivotX;
3343 entity.hpBar.transform.position.y = spriteTop - barH / 2;
3344 entity.hpBar.transform.size = new vector(barW, barH);
3345 entity.hpBar.layer = this.#depthLayer(pivotY, SORT_HP_BAR);
3346 this.#markSortDirty();
3347 }
3348
3349 #syncSkullMarker (entity)
3350 {
3351 if (!entity?.characterId)
3352 {
3353 entity.skullMarker?.destroy();
3354 entity.skullMarker = null;
3355 return;
3356 }
3357 const tint = skullTintColor(entity.skullValue | 0);
3358 if (!tint)
3359 {
3360 entity.skullMarker?.destroy();
3361 entity.skullMarker = null;
3362 return;
3363 }
3364 const image = this.game.images[SKULL_SPRITE]
3365 ?? this.game.images["item:skull:skull"];
3366 if (!image)
3367 { return; }
3368 if (!entity.skullMarker)
3369 {
3370 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
3371 this.scene.addObject(entity.skullMarker);
3372 }
3373 entity.skullTint = tint;
3374 entity.skullMarker.renderer.sprite = image;
3375 }
3376
3377 /**
3378 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
3379 */
3380 #placeSkullMarker (entity, pivotX, pivotY, darkness)
3381 {
3382 this.#syncSkullMarker(entity);
3383 if (!entity.skullMarker)
3384 { return; }
3385 const body = entity.object?.renderer?.sprite;
3386 const skull = entity.skullMarker.renderer?.sprite;
3387 if (!body || !skull)
3388 { return; }
3389 const zoom = this.zoom;
3390 const scale = entity.visualScale ?? 1;
3391 const bodyH = body.height * zoom * scale;
3392 const skullH = skull.height * zoom;
3393 const skullW = skull.width * zoom;
3394 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
3395 const bodyTop = bodyCenterY - bodyH / 2;
3396 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
3397 entity.skullMarker.transform.position.x = pivotX;
3398 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
3399 entity.skullMarker.transform.size = new vector(skullW, skullH);
3400 entity.skullMarker.layer = this.#depthLayer(pivotY, SORT_HP_BAR);
3401 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
3402 this.#markSortDirty();
3403 }
3404
3405 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
3406 {
3407 this.#bakeAndPlaceChunk(snapshot);
3408 this.#relayoutChunkTiles(snapshot);
3409 if (this.softTerrain && refreshSoftNeighbors)
3410 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
3411 }
3412
3413 #relayoutChunk (snapshot)
3414 {
3415 this.#layoutBakedChunk(snapshot);
3416 this.#relayoutChunkTiles(snapshot);
3417 }
3418
3419 #relayoutChunkTiles (snapshot)
3420 {
3421 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3422 {
3423 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3424 {
3425 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
3426 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
3427 this.#drawTile(tileX, tileY);
3428 }
3429 }
3430 }
3431
3432 #scheduleChunkRebuild (snapshot)
3433 {
3434 if (!snapshot)
3435 { return; }
3436 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
3437 this.#cancelIdlePrefetch();
3438 this.#ensureChunkFlushScheduled();
3439 }
3440
3441 #scheduleEdgeRebuild ()
3442 {
3443 this.#edgesDirty = true;
3444 this.#cancelIdlePrefetch();
3445 this.#ensureChunkFlushScheduled();
3446 }
3447
3448 #ensureChunkFlushScheduled ()
3449 {
3450 if (this.#chunkRebuildRaf)
3451 { return; }
3452 this.#cancelIdlePrefetch();
3453 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
3454 }
3455
3456 #notePlayerTile (tileX, tileY)
3457 {
3458 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3459 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3460 const prevX = this.#playerChunkX;
3461 const prevY = this.#playerChunkY;
3462 if (prevX != null
3463 && (chunkX !== prevX || chunkY !== prevY))
3464 {
3465 const dx = chunkX - prevX;
3466 const dy = chunkY - prevY;
3467 if (dx !== 0)
3468 { this.#playerMoveChunkDx = Math.sign(dx); }
3469 if (dy !== 0)
3470 { this.#playerMoveChunkDy = Math.sign(dy); }
3471 this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY);
3472 }
3473 this.#playerChunkX = chunkX;
3474 this.#playerChunkY = chunkY;
3475 }
3476
3477 /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */
3478 #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY)
3479 {
3480 this.#invalidateNeighborLightmapCaches(prevChunkX, prevChunkY);
3481 this.#invalidateNeighborLightmapCaches(chunkX, chunkY);
3482 const doorChunks = new Set();
3483 for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]])
3484 {
3485 for (let dy = -1; dy <= 1; dy++)
3486 {
3487 for (let dx = -1; dx <= 1; dx++)
3488 { doorChunks.add(`${cx + dx},${cy + dy}`); }
3489 }
3490 }
3491 for (const key of doorChunks)
3492 {
3493 const [cx, cy] = key.split(",").map(Number);
3494 this.#redrawDoorTilesInChunk(cx, cy);
3495 }
3496 }
3497
3498 #redrawDoorTilesInChunk (chunkX, chunkY)
3499 {
3500 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3501 if (!snapshot?.blocks)
3502 { return; }
3503 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3504 {
3505 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3506 {
3507 const block = snapshot.blocks[localY * CHUNK_SIZE + localX];
3508 if (!blockDefinition(block?.typeId)?.door)
3509 { continue; }
3510 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
3511 }
3512 }
3513 }
3514
3515 #playerChunkCoords ()
3516 {
3517 const local = this.entities.get(this.localEntityId);
3518 if (local)
3519 {
3520 return {
3521 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
3522 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
3523 };
3524 }
3525 if (this.#playerChunkX != null && this.#playerChunkY != null)
3526 {
3527 return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
3528 }
3529 return null;
3530 }
3531
3532 /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
3533 #chunkRebuildScore (key, mode = "urgent")
3534 {
3535 const [chunkX, chunkY] = key.split(",").map(Number);
3536 const player = this.#playerChunkCoords();
3537 if (!player)
3538 { return 0; }
3539 const dx = chunkX - player.chunkX;
3540 const dy = chunkY - player.chunkY;
3541 const dist = Math.abs(dx) + Math.abs(dy);
3542 let ahead = 0;
3543 if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
3544 { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
3545 if (mode === "idle")
3546 {
3547 return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
3548 }
3549 return dist * 10 - Math.max(0, ahead) * 3;
3550 }
3551
3552 #sortedChunkRebuildKeys (mode = "urgent")
3553 {
3554 return [...this.#chunkRebuildKeys].sort((a, b) =>
3555 this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
3556 }
3557
3558 #discoverUnbakedChunks ()
3559 {
3560 for (const key of this.chunks.keys())
3561 {
3562 if (!this.bakedChunks.has(key))
3563 { this.#chunkRebuildKeys.add(key); }
3564 }
3565 }
3566
3567 #hasUnbakedChunks ()
3568 {
3569 for (const key of this.chunks.keys())
3570 {
3571 if (!this.bakedChunks.has(key))
3572 { return true; }
3573 }
3574 return false;
3575 }
3576
3577 #pickIdlePrefetchSnapshot ()
3578 {
3579 let best = null;
3580 let bestScore = Infinity;
3581 for (const snapshot of this.chunks.values())
3582 {
3583 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3584 if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))
3585 { continue; }
3586 const score = this.#chunkRebuildScore(key, "idle");
3587 if (score < bestScore)
3588 {
3589 bestScore = score;
3590 best = snapshot;
3591 }
3592 }
3593 return best;
3594 }
3595
3596 #cancelIdlePrefetch ()
3597 {
3598 if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
3599 { cancelIdleCallback(this.#idlePrefetchId); }
3600 this.#idlePrefetchId = 0;
3601 }
3602
3603 #scheduleIdleChunkPrefetch ()
3604 {
3605 if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
3606 { return; }
3607 if (typeof requestIdleCallback !== "function")
3608 { return; }
3609 if (!this.#hasUnbakedChunks())
3610 { return; }
3611 this.#idlePrefetchId = requestIdleCallback(
3612 (deadline) => this.#runIdleChunkPrefetch(deadline),
3613 { timeout: 2500 }
3614 );
3615 }
3616
3617 #runIdleChunkPrefetch (deadline)
3618 {
3619 this.#idlePrefetchId = 0;
3620 if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
3621 { return; }
3622 this.#discoverUnbakedChunks();
3623 if (this.#chunkRebuildKeys.size)
3624 {
3625 this.#ensureChunkFlushScheduled();
3626 return;
3627 }
3628 const snapshot = this.#pickIdlePrefetchSnapshot();
3629 if (!snapshot)
3630 { return; }
3631 if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
3632 {
3633 this.#scheduleIdleChunkPrefetch();
3634 return;
3635 }
3636 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
3637 if (this.#hasUnbakedChunks())
3638 { this.#scheduleIdleChunkPrefetch(); }
3639 }
3640
3641 #flushChunkWork ()
3642 {
3643 this.#chunkRebuildRaf = 0;
3644 const keys = this.#sortedChunkRebuildKeys("urgent");
3645 const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
3646 const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
3647 this.#chunkRebuildKeys.clear();
3648 for (const key of rest)
3649 { this.#chunkRebuildKeys.add(key); }
3650 for (const key of batch)
3651 {
3652 const snap = this.chunks.get(key);
3653 if (snap)
3654 { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }
3655 }
3656 if (this.#chunkRebuildKeys.size)
3657 {
3658 this.#ensureChunkFlushScheduled();
3659 return;
3660 }
3661 if (this.#edgesDirty)
3662 {
3663 this.#rebuildAllEdges();
3664 this.#edgesDirty = false;
3665 }
3666 this.#scheduleIdleChunkPrefetch();
3667 }
3668
3669 #previewEqual (a, b)
3670 {
3671 if (a === b)
3672 { return true; }
3673 if (!a || !b)
3674 { return false; }
3675 return a.tileX === b.tileX
3676 && a.tileY === b.tileY
3677 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
3678 && this.#previewPart(a.block) === this.#previewPart(b.block);
3679 }
3680
3681 #previewPart (value)
3682 {
3683 return value === undefined ? undefined : JSON.stringify(value);
3684 }
3685
3686 #rebuildSoftTerrainNeighborChunks (snapshot)
3687 {
3688 for (let dy = -1; dy <= 1; dy++)
3689 {
3690 for (let dx = -1; dx <= 1; dx++)
3691 {
3692 if (dx === 0 && dy === 0)
3693 { continue; }
3694 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3695 if (neighbor)
3696 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
3697 }
3698 }
3699 }
3700
3701 #rebakeAllChunks ()
3702 {
3703 for (const snapshot of this.chunks.values())
3704 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
3705 }
3706
3707 #bakeAndPlaceChunk (snapshot)
3708 {
3709 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3710 const atlases = bakeChunkAtlases({
3711 snapshot,
3712 catalog: this.catalog,
3713 images: this.game.images,
3714 preview: this.preview,
3715 season: this.worldSeason,
3716 softTerrain: this.softTerrain,
3717 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
3718 cache: this.#atlasCache
3719 });
3720 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
3721 let baked = this.bakedChunks.get(key);
3722 this.#releaseBakedAtlasRefs(baked);
3723
3724 const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
3725 const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
3726 ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
3727 const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
3728 ?? frameworkImageFromCanvas(atlases.bloom);
3729
3730 if (!baked)
3731 {
3732 const lightmapCanvas = makeLightmapCanvas(atlasPx);
3733 baked = {
3734 groundCanvas: atlases.ground,
3735 blockCanvases: atlases.blockRows,
3736 bloomCanvas: atlases.bloom,
3737 lightmapCanvas,
3738 groundImage,
3739 blockImages,
3740 bloomImage,
3741 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
3742 groundObject: null,
3743 blockObjects: [],
3744 bloomObject: null,
3745 tallBlocks: atlases.tallBlocks,
3746 animatedGrounds: atlases.animatedGrounds,
3747 lightmapPixels: null,
3748 atlasCacheRefs: atlases.cacheRefs
3749 };
3750 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
3751 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
3752 this.scene.addObject(baked.groundObject);
3753 for (let row = 0; row < CHUNK_SIZE; row++)
3754 {
3755 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
3756 this.#applyAtlasLighting(object, baked.lightmapImage, row);
3757 this.scene.addObject(object);
3758 baked.blockObjects.push(object);
3759 }
3760 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
3761 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3762 this.#markUnlit(baked.bloomObject);
3763 this.scene.addObject(baked.bloomObject);
3764 this.bakedChunks.set(key, baked);
3765 }
3766 else
3767 {
3768 if (baked.groundCanvas !== atlases.ground)
3769 {
3770 baked.groundCanvas = atlases.ground;
3771 baked.groundImage = groundImage;
3772 baked.groundObject.renderer.sprite = groundImage;
3773 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
3774 }
3775 for (let row = 0; row < CHUNK_SIZE; row++)
3776 {
3777 if (baked.blockCanvases[row] !== atlases.blockRows[row])
3778 {
3779 baked.blockCanvases[row] = atlases.blockRows[row];
3780 baked.blockImages[row] = blockImages[row];
3781 baked.blockObjects[row].renderer.sprite = blockImages[row];
3782 }
3783 this.#applyAtlasLighting(
3784 baked.blockObjects[row],
3785 baked.lightmapImage,
3786 row
3787 );
3788 }
3789 if (baked.bloomCanvas !== atlases.bloom)
3790 {
3791 baked.bloomCanvas = atlases.bloom;
3792 baked.bloomImage = bloomImage;
3793 baked.bloomObject.renderer.sprite = bloomImage;
3794 }
3795 baked.tallBlocks = atlases.tallBlocks;
3796 baked.animatedGrounds = atlases.animatedGrounds;
3797 baked.atlasCacheRefs = atlases.cacheRefs;
3798 }
3799 baked.chunkX = snapshot.chunkX;
3800 baked.chunkY = snapshot.chunkY;
3801 baked.lightmapCacheKey = null;
3802 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
3803 this.#layoutBakedChunk(snapshot);
3804 this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
3805 }
3806
3807 #releaseBakedAtlasRefs (baked)
3808 {
3809 if (!baked?.atlasCacheRefs)
3810 { return; }
3811 this.#atlasCache.release(baked.atlasCacheRefs.ground);
3812 for (const entry of baked.atlasCacheRefs.blockRows ?? [])
3813 { this.#atlasCache.release(entry); }
3814 this.#atlasCache.release(baked.atlasCacheRefs.bloom);
3815 baked.atlasCacheRefs = null;
3816 }
3817
3818 #chunkTextureWarmPriority (chunkX, chunkY)
3819 {
3820 const local = this.entities.get(this.localEntityId);
3821 if (!local)
3822 { return 999; }
3823 const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
3824 const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
3825 return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
3826 }
3827
3828 #queueCanvasTextureWarm (canvas, chunkX, chunkY)
3829 {
3830 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
3831 { return; }
3832 this.#pendingTextureCanvasSet.add(canvas);
3833 this.#pendingTextureCanvases.push({
3834 canvas,
3835 priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
3836 });
3837 this.#scheduleTextureWarm();
3838 }
3839
3840 #queueBakedChunkTextures (baked, chunkX, chunkY)
3841 {
3842 if (!baked)
3843 { return; }
3844 const refs = baked.atlasCacheRefs;
3845 const maybeWarm = (canvas, entry) =>
3846 {
3847 if (!canvas)
3848 { return; }
3849 if (entry && this.#atlasCache.isWarmed(canvas))
3850 { return; }
3851 this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
3852 };
3853 maybeWarm(baked.groundCanvas, refs?.ground);
3854 for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
3855 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
3856 maybeWarm(baked.bloomCanvas, refs?.bloom);
3857 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
3858 }
3859
3860 #scheduleTextureWarm ()
3861 {
3862 if (this.#textureWarmRaf)
3863 { return; }
3864 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
3865 }
3866
3867 #flushTextureWarm ()
3868 {
3869 this.#textureWarmRaf = 0;
3870 if (!this.#pendingTextureCanvases.length)
3871 { return; }
3872 this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
3873 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
3874 for (const entry of batch)
3875 {
3876 this.#pendingTextureCanvasSet.delete(entry.canvas);
3877 setNearestFilter(this.scene, entry.canvas);
3878 this.#atlasCache.markWarmed(entry.canvas);
3879 }
3880 if (this.#pendingTextureCanvases.length)
3881 { this.#scheduleTextureWarm(); }
3882 }
3883
3884 #applyAtlasLighting (object, lightmapImage, lightRow)
3885 {
3886 if (!object?.renderer)
3887 { return; }
3888 object._lit = true;
3889 object.renderer.shader = getAtlasLightingShader();
3890 object.renderer.bumpMap = null;
3891 object.renderer.secondaryMap = lightmapImage;
3892 object.renderer.shaderUniforms = {
3893 u_ambientDark: 0,
3894 u_lightRow: lightRow
3895 };
3896 }
3897
3898 #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY)
3899 {
3900 if (!object?.renderer)
3901 { return; }
3902 object._lit = true;
3903 const dark = Math.min(1, Math.max(0, darkness ?? 0));
3904 object.renderer.shader = getCliffGroundTopShader();
3905 object.renderer.bumpMap = groundImage ?? null;
3906 object.renderer.secondaryMap = null;
3907 object.renderer.shaderUniforms = {
3908 u_darkness: dark,
3909 u_tileLocal: [localX, localY]
3910 };
3911 }
3912
3913 #layoutBakedChunk (snapshot)
3914 {
3915 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3916 const baked = this.bakedChunks.get(key);
3917 if (!baked)
3918 { return; }
3919 const size = this.tileSize();
3920 const left = snapshot.chunkX * CHUNK_SIZE * size;
3921 const top = snapshot.chunkY * CHUNK_SIZE * size;
3922 const chunkPx = CHUNK_SIZE * size;
3923 baked.groundObject.transform.position.x = left + chunkPx / 2;
3924 baked.groundObject.transform.position.y = top + chunkPx / 2;
3925 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
3926 baked.groundObject.layer = LAYER_GROUND;
3927
3928 for (let row = 0; row < CHUNK_SIZE; row++)
3929 {
3930 const object = baked.blockObjects[row];
3931 const rowY = top + row * size + size / 2;
3932 object.transform.position.x = left + chunkPx / 2;
3933 object.transform.position.y = rowY;
3934 object.transform.size = new vector(chunkPx, size);
3935 object.layer = this.#depthLayer(rowY, SORT_BLOCK);
3936 }
3937
3938 baked.bloomObject.transform.position.x = left + chunkPx / 2;
3939 baked.bloomObject.transform.position.y = top + chunkPx / 2;
3940 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
3941 baked.bloomObject.layer = this.#depthLayer(top + chunkPx, SORT_BLOCK);
3942 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3943 this.#markSortDirty();
3944 }
3945
3946 #destroyBakedChunk (key)
3947 {
3948 const baked = this.bakedChunks.get(key);
3949 if (!baked)
3950 { return; }
3951 this.#releaseBakedAtlasRefs(baked);
3952 baked.groundObject?.destroy();
3953 for (const object of baked.blockObjects ?? [])
3954 { object.destroy(); }
3955 baked.bloomObject?.destroy();
3956 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3957 this.bakedChunks.delete(key);
3958 }
3959
3960 #redrawPreview ()
3961 {
3962 if (!this.preview)
3963 { return; }
3964 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
3965 if (snapshot)
3966 { this.#rebuildChunk(snapshot); }
3967 }
3968
3969 #refreshWaterCoastsNear (chunkX, chunkY)
3970 {
3971 const timeSec = performance.now() / 1000;
3972 for (const objects of this.tiles.values())
3973 {
3974 if (!objects.ground || !isWaterGround(objects.groundTypeId))
3975 { continue; }
3976 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
3977 { continue; }
3978 // Light intensity grid is visible light (1 − shade); water shader uses ambient=1.
3979 this.#syncGroundWaterFx(objects, 1, timeSec);
3980 }
3981 }
3982
3983 #drawTile (tileX, tileY)
3984 {
3985 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3986 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3987 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3988 if (!snapshot)
3989 { return; }
3990 const localX = tileX - chunkX * CHUNK_SIZE;
3991 const localY = tileY - chunkY * CHUNK_SIZE;
3992 const index = localY * CHUNK_SIZE + localX;
3993 const key = `${tileX},${tileY}`;
3994 let objects = this.tiles.get(key);
3995 if (!objects)
3996 {
3997 objects = { chunkX, chunkY, tileX, tileY };
3998 this.tiles.set(key, objects);
3999 }
4000 objects.tileX = tileX;
4001 objects.tileY = tileY;
4002 objects.chunkX = chunkX;
4003 objects.chunkY = chunkY;
4004 objects.light = snapshot.light[index] ?? 0;
4005
4006 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
4007 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
4008 if (animatedGround)
4009 {
4010 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
4011 if (objects.ground)
4012 {
4013 const size = this.tileSize();
4014 objects.ground.transform.position.x = tileX * size + size / 2;
4015 objects.ground.transform.position.y = tileY * size + size / 2;
4016 objects.ground.transform.size = new vector(size, size);
4017 objects.ground.layer = LAYER_GROUND;
4018 objects.groundTypeId = animatedGround.typeId;
4019 this.#syncGroundWaterFx(objects, 1, performance.now() / 1000);
4020 this.#markSortDirty();
4021 }
4022 if (animatedGround.bloom)
4023 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
4024 else
4025 {
4026 objects.groundBloom?.destroy();
4027 objects.groundBloom = null;
4028 }
4029 }
4030 else
4031 {
4032 objects.ground?.destroy();
4033 objects.ground = null;
4034 objects.groundBloom?.destroy();
4035 objects.groundBloom = null;
4036 objects.groundTypeId = null;
4037 objects.waterEdges = null;
4038 }
4039
4040 let blockSource = snapshot.blocks[index];
4041 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined)
4042 { blockSource = this.preview.block; }
4043 // Outer map ring: always show doors at resting (matches baked light; no entities there).
4044 if (
4045 blockSource
4046 && blockDefinition(blockSource.typeId)?.door
4047 && !this.#isActiveLightingChunk(chunkX, chunkY)
4048 )
4049 {
4050 const resting = doorRestingState(blockSource);
4051 if (resting && resting !== blockSource.state)
4052 { blockSource = { ...blockSource, state: resting }; }
4053 }
4054 const tileBlock = tileBlockSpriteEntry(
4055 this.catalog,
4056 this.game.images,
4057 blockSource,
4058 this.worldSeason
4059 );
4060 if (tileBlock)
4061 {
4062 const pivot = tilePivot(tileX, tileY, this.tileSize());
4063 const blockEntry = normalizeBlock(blockSource);
4064 const blockDef = blockDefinition(blockEntry?.typeId);
4065 const blockSort = blockDef?.door
4066 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
4067 : SORT_ENTITY;
4068 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
4069 objects.blockSort = blockSort;
4070 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
4071 if (objects.block)
4072 {
4073 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort);
4074 if (objects.cliffGroundTop)
4075 {
4076 const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4077 const localY = ((tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4078 this.#syncCliffGroundTopSprite(
4079 objects.block,
4080 objects.shadeAlpha ?? 0,
4081 baked?.groundImage ?? null,
4082 localX,
4083 localY
4084 );
4085 }
4086 else
4087 { this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); }
4088 }
4089 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY);
4090 }
4091 else
4092 {
4093 objects.block?.destroy();
4094 objects.block = null;
4095 objects.blockSort = null;
4096 objects.blockBloom?.destroy();
4097 objects.blockBloom = null;
4098 objects.cliffGroundTop = false;
4099 }
4100 }
4101
4102 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
4103 {
4104 if (!name)
4105 {
4106 existing?.destroy();
4107 return null;
4108 }
4109 const object = this.#ensureSprite(existing, name, sortOrder);
4110 if (!object)
4111 { return null; }
4112 object.renderer.layer = RENDER_LAYER_BLOOM;
4113 this.#markUnlit(object);
4114 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
4115 return object;
4116 }
4117
4118 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1, flight = false)
4119 {
4120 const sprite = object?.renderer?.sprite;
4121 if (!sprite)
4122 { return; }
4123 const zoom = this.zoom;
4124 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
4125 const factor = Math.max(0.1, Number(scale) || 1);
4126 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
4127 object.transform.position.x = center.x;
4128 object.transform.position.y = center.y;
4129 object.transform.size = new vector(draw.w * factor, draw.h * factor);
4130 object.layer = this.#depthLayer(sortY, subOrder, flight);
4131 this.#markSortDirty();
4132 }
4133
4134 #ensureSprite (existing, name, layer)
4135 {
4136 const sprite = this.game.images[name];
4137 if (!sprite)
4138 {
4139 existing?.destroy();
4140 return null;
4141 }
4142 if (!existing || existing.renderer.sprite !== sprite)
4143 {
4144 existing?.destroy();
4145 existing = new GameObject(0, 0, sprite, layer);
4146 this.#syncLitSprite(existing, 0);
4147 this.scene.addObject(existing);
4148 this.#startIdleAnimation(existing);
4149 }
4150 return existing;
4151 }
4152
4153 #startIdleAnimation (object)
4154 {
4155 const sprite = object?.renderer?.sprite;
4156 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
4157 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
4158 }
4159
4160 #neighborClosed (snapshot, dir, dx, dy)
4161 {
4162 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
4163 if (other)
4164 { return !other.open; }
4165 return !!snapshot.closedEdges?.[dir];
4166 }
4167
4168 #rebuildAllEdges ()
4169 {
4170 const seen = new Set();
4171 for (const snapshot of this.chunks.values())
4172 {
4173 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4174 seen.add(key);
4175 this.#rebuildChunkEdges(snapshot);
4176 }
4177 for (const key of [...this.edges.keys()])
4178 {
4179 if (!seen.has(key))
4180 { this.#destroyEdges(key); }
4181 }
4182 }
4183
4184 #rebuildChunkEdges (snapshot)
4185 {
4186 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4187 let bars = this.edges.get(key);
4188 if (!bars)
4189 {
4190 bars = {};
4191 this.edges.set(key, bars);
4192 }
4193
4194 const size = this.tileSize();
4195 const chunkPx = CHUNK_SIZE * size;
4196 const left = snapshot.chunkX * CHUNK_SIZE * size;
4197 const top = snapshot.chunkY * CHUNK_SIZE * size;
4198 const centerX = left + chunkPx / 2;
4199 const centerY = top + chunkPx / 2;
4200 const thickness = Math.max(2, Math.round(2 * this.zoom));
4201 const draw = snapshot.open === true;
4202
4203 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
4204 centerX, top, chunkPx, thickness, true);
4205 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
4206 centerX, top + chunkPx, chunkPx, thickness, true);
4207 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
4208 left, centerY, chunkPx, thickness, false);
4209 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
4210 left + chunkPx, centerY, chunkPx, thickness, false);
4211 }
4212
4213 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
4214 {
4215 if (!visible)
4216 {
4217 if (existing)
4218 { existing.renderer.visible = false; }
4219 return existing;
4220 }
4221
4222 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
4223 this.#markUnlit(existing);
4224 existing.renderer.visible = true;
4225 existing.transform.position.x = x;
4226 existing.transform.position.y = y;
4227 existing.transform.size = horizontal
4228 ? new vector(length, thickness)
4229 : new vector(thickness, length);
4230 existing.layer = LAYER_EDGE;
4231 this.#markSortDirty();
4232 return existing;
4233 }
4234
4235 #destroyEdges (key)
4236 {
4237 const bars = this.edges.get(key);
4238 if (!bars)
4239 { return; }
4240 bars.north?.destroy();
4241 bars.east?.destroy();
4242 bars.south?.destroy();
4243 bars.west?.destroy();
4244 this.edges.delete(key);
4245 }
4246
4247 #entityShadeAlpha (entity, now)
4248 {
4249 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
4250 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
4251 { return toAlpha; }
4252 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
4253 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
4254 return fromAlpha + (toAlpha - fromAlpha) * t;
4255 }
4256
4257 #markSortDirty ()
4258 {
4259 this.scene._sortDirty = true;
4260 }
4261
4262 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
4263 #activeLightingCenterChunk ()
4264 {
4265 const local = this.entities.get(this.localEntityId);
4266 if (!local)
4267 { return null; }
4268 return {
4269 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
4270 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
4271 };
4272 }
4273
4274 #isActiveLightingChunk (chunkX, chunkY)
4275 {
4276 const center = this.#activeLightingCenterChunk();
4277 if (!center)
4278 { return true; }
4279 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
4280 }
4281
4282 #isActiveLightingTile (tileX, tileY)
4283 {
4284 return this.#isActiveLightingChunk(
4285 Math.floor(tileX / CHUNK_SIZE),
4286 Math.floor(tileY / CHUNK_SIZE)
4287 );
4288 }
4289
4290 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
4291 #innerDynamicLights (activeLights)
4292 {
4293 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
4294 }
4295
4296 /**
4297 * Lights to simulate for one chunk.
4298 * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk.
4299 * Outer ring: baked base + spill from any dynamic source that originates inside the 3×3
4300 * (lanterns, spells, and torches) so the boundary stays seamless.
4301 */
4302 #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = [])
4303 {
4304 const center = this.#activeLightingCenterChunk();
4305 if (!center)
4306 { return [...mobileLights, ...blockLights]; }
4307 if (this.#isActiveLightingChunk(chunkX, chunkY))
4308 {
4309 const inner = this.#innerDynamicLights(mobileLights);
4310 const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
4311 return [...inner, ...blocks];
4312 }
4313 const spill = this.#innerDynamicLights([...mobileLights, ...blockLights]);
4314 return spill.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
4315 }
4316
4317 #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = [])
4318 {
4319 return this.#dynamicLightsForChunk(
4320 Math.floor(tileX / CHUNK_SIZE),
4321 Math.floor(tileY / CHUNK_SIZE),
4322 mobileLights,
4323 blockLights
4324 );
4325 }
4326
4327 /** Authored torches/furnaces in chunks that can light the active 3×3 (or all chunks in editor). */
4328 #collectBlockLightsForShading ()
4329 {
4330 const center = this.#activeLightingCenterChunk();
4331 const maxRange = maxBlockLightRangeTiles();
4332 const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1;
4333 const sources = [];
4334 if (!center)
4335 {
4336 for (const snapshot of this.chunks.values())
4337 { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); }
4338 return sources;
4339 }
4340 for (let dy = -1 - halo; dy <= 1 + halo; dy++)
4341 {
4342 for (let dx = -1 - halo; dx <= 1 + halo; dx++)
4343 {
4344 const snapshot = this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`);
4345 if (!snapshot?.blocks)
4346 { continue; }
4347 sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks));
4348 }
4349 }
4350 return sources;
4351 }
4352
4353 #updateShade ()
4354 {
4355 const ambientDark = this.#ambientDarkness();
4356 const now = performance.now();
4357 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
4358
4359 const mobileLights = [...this.dynamicLights];
4360 for (const light of this.spellLights.values())
4361 {
4362 if (light.until <= now)
4363 { continue; }
4364 mobileLights.push({
4365 tileX: light.tileX,
4366 tileY: light.tileY,
4367 range: light.range,
4368 intensity: light.intensity
4369 });
4370 }
4371 for (const key of [...this.spellLights.keys()])
4372 {
4373 if (this.spellLights.get(key).until <= now)
4374 {
4375 const expired = this.spellLights.get(key);
4376 this.spellLights.delete(key);
4377 this.#invalidateNeighborLightmapCaches(
4378 Math.floor(expired.tileX / CHUNK_SIZE),
4379 Math.floor(expired.tileY / CHUNK_SIZE)
4380 );
4381 }
4382 }
4383 const activeDarks = [];
4384 for (const dark of this.spellDarks.values())
4385 {
4386 if (dark.until <= now)
4387 { continue; }
4388 activeDarks.push({
4389 tileX: dark.tileX,
4390 tileY: dark.tileY,
4391 range: dark.range,
4392 intensity: dark.intensity
4393 });
4394 }
4395 for (const key of [...this.spellDarks.keys()])
4396 {
4397 if (this.spellDarks.get(key).until <= now)
4398 {
4399 const expired = this.spellDarks.get(key);
4400 this.spellDarks.delete(key);
4401 this.#invalidateNeighborLightmapCaches(
4402 Math.floor(expired.tileX / CHUNK_SIZE),
4403 Math.floor(expired.tileY / CHUNK_SIZE)
4404 );
4405 }
4406 }
4407 this._activeSpellDarks = activeDarks;
4408 const tileSize = this.tileSize();
4409 const blindLight = this.#blindVisionLight();
4410 if (blindLight)
4411 { mobileLights.push(blindLight); }
4412 for (const entity of this.entities.values())
4413 {
4414 const range = entity.lightRadiusTiles ?? 0;
4415 if (range <= 0)
4416 { continue; }
4417 mobileLights.push({
4418 tileX: Math.floor(entity.visualX / tileSize),
4419 tileY: Math.floor(entity.visualY / tileSize),
4420 range,
4421 intensity: entity.lightIntensity ?? 1
4422 });
4423 }
4424 const blockLights = this.#collectBlockLightsForShading();
4425
4426 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
4427
4428 for (const objects of this.tiles.values())
4429 {
4430 if (objects._inViewport === false)
4431 { continue; }
4432 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights);
4433 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
4434 }
4435
4436 for (const baked of this.bakedChunks.values())
4437 {
4438 if (baked._inViewport === false)
4439 { continue; }
4440 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights);
4441 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
4442 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
4443 if (baked.groundObject?.renderer?.shaderUniforms)
4444 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = 1; }
4445 for (const object of baked.blockObjects ?? [])
4446 {
4447 if (object?.renderer?.shaderUniforms)
4448 { object.renderer.shaderUniforms.u_ambientDark = 1; }
4449 }
4450 }
4451
4452 const timeSec = now / 1000;
4453 for (const objects of this.tiles.values())
4454 {
4455 if (objects._inViewport === false)
4456 { continue; }
4457 if (objects.block)
4458 {
4459 if (objects.cliffGroundTop)
4460 {
4461 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
4462 const localX = ((objects.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4463 const localY = ((objects.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4464 this.#syncCliffGroundTopSprite(
4465 objects.block,
4466 objects.shadeAlpha,
4467 baked?.groundImage ?? null,
4468 localX,
4469 localY
4470 );
4471 }
4472 else
4473 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
4474 }
4475 if (objects.ground && isWaterGround(objects.groundTypeId))
4476 {
4477 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
4478 // Light intensity grid is visible light (1 − shade); water shader uses ambient=1.
4479 this.#syncGroundWaterFx(objects, 1, timeSec, baked);
4480 }
4481 else if (objects.ground)
4482 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
4483 }
4484
4485 for (const item of this.groundItems.values())
4486 {
4487 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
4488 this.#syncGroundItemSprite(item, alpha);
4489 }
4490 }
4491
4492 #tileLightSources (objects, activeLights, lightOcclusion)
4493 {
4494 // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps.
4495 const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY);
4496 const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0;
4497 const dynamic = dynamicLightAtTile(
4498 objects.tileX,
4499 objects.tileY,
4500 activeLights,
4501 lightOcclusion
4502 );
4503 const dark = dynamicDarknessAtTile(
4504 objects.tileX,
4505 objects.tileY,
4506 this._activeSpellDarks ?? [],
4507 lightOcclusion
4508 );
4509 return { lights: Math.max(baked, dynamic), dark };
4510 }
4511
4512 /** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */
4513 #tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark)
4514 {
4515 const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion);
4516 return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
4517 }
4518
4519 #tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
4520 {
4521 return 1 - this.#tileShadeAlpha(objects, activeLights, lightOcclusion, ambientDark);
4522 }
4523
4524 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
4525 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
4526 {
4527 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
4528 if (tileObjects)
4529 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); }
4530 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4531 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4532 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4533 if (!snapshot)
4534 { return 1 - Math.min(1, Math.max(0, ambientDark)); }
4535 const localX = tileX - chunkX * CHUNK_SIZE;
4536 const localY = tileY - chunkY * CHUNK_SIZE;
4537 const index = localY * CHUNK_SIZE + localX;
4538 const useBaked = !this.#isActiveLightingTile(tileX, tileY);
4539 const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0;
4540 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
4541 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
4542 const lights = Math.max(bakedLit, dynamic);
4543 const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
4544 return 1 - shade;
4545 }
4546
4547 /** True when ground or block on this tile occludes light rays (same rules as bake). */
4548 #tileOccludesLight (tileX, tileY)
4549 {
4550 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4551 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4552 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4553 if (!snapshot)
4554 { return false; }
4555 const localX = tileX - chunkX * CHUNK_SIZE;
4556 const localY = tileY - chunkY * CHUNK_SIZE;
4557 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
4558 { return false; }
4559 const index = localY * CHUNK_SIZE + localX;
4560 const ground = normalizeGround(snapshot.grounds?.[index]);
4561 if (!isGroundPassable(ground.typeId))
4562 { return true; }
4563 return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid;
4564 }
4565
4566 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark)
4567 {
4568 const gridW = CHUNK_SIZE + 2;
4569 const gridSize = gridW * gridW;
4570 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
4571 { baked.lightIntensityGrid = new Float32Array(gridSize); }
4572 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
4573 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
4574 const grid = baked.lightIntensityGrid;
4575 const occlude = baked.lightOccludeGrid;
4576 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
4577 {
4578 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
4579 {
4580 const tileX = baked.chunkX * CHUNK_SIZE + lx;
4581 const tileY = baked.chunkY * CHUNK_SIZE + ly;
4582 const gi = (ly + 1) * gridW + (lx + 1);
4583 // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve
4584 // sources per tile so corner blends match the neighbour chunk's shading.
4585 const lights = this.#dynamicLightsForTile(tileX, tileY, mobileLights, blockLights);
4586 grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark);
4587 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
4588 }
4589 }
4590 return { grid, occlude, gridW };
4591 }
4592
4593 #makeLightCornerSampler (grid, occlude, gridW)
4594 {
4595 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
4596 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
4597 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => smoothLitCorner({
4598 homeLit: sample(homeLx, homeLy),
4599 homeBlocks: blocks(homeLx, homeLy),
4600 aLit: sample(aLx, aLy),
4601 aBlocks: blocks(aLx, aLy),
4602 bLit: sample(bLx, bLy),
4603 bBlocks: blocks(bLx, bLy),
4604 dLit: sample(dLx, dLy),
4605 dBlocks: blocks(dLx, dLy)
4606 });
4607 return { smoothCorner };
4608 }
4609
4610 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
4611 #tileLitCorners (baked, localX, localY)
4612 {
4613 const grid = baked?.lightIntensityGrid;
4614 const occlude = baked?.lightOccludeGrid;
4615 if (!grid?.length || !occlude?.length)
4616 { return null; }
4617 const gridW = CHUNK_SIZE + 2;
4618 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
4619 return {
4620 nw: smoothCorner(
4621 localX, localY,
4622 localX - 1, localY,
4623 localX, localY - 1,
4624 localX - 1, localY - 1
4625 ),
4626 ne: smoothCorner(
4627 localX, localY,
4628 localX + 1, localY,
4629 localX, localY - 1,
4630 localX + 1, localY - 1
4631 ),
4632 sw: smoothCorner(
4633 localX, localY,
4634 localX - 1, localY,
4635 localX, localY + 1,
4636 localX - 1, localY + 1
4637 ),
4638 se: smoothCorner(
4639 localX, localY,
4640 localX + 1, localY,
4641 localX, localY + 1,
4642 localX + 1, localY + 1
4643 )
4644 };
4645 }
4646
4647 #hashUint8Array (values)
4648 {
4649 let hash = 2166136261;
4650 for (let i = 0; i < values.length; i++)
4651 {
4652 hash ^= values[i];
4653 hash = Math.imul(hash, 16777619);
4654 }
4655 return hash >>> 0;
4656 }
4657
4658 #lightAffectsChunkBounds (light, chunkX, chunkY)
4659 {
4660 const minX = chunkX * CHUNK_SIZE - 1;
4661 const minY = chunkY * CHUNK_SIZE - 1;
4662 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
4663 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
4664 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
4665 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
4666 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
4667 }
4668
4669 #chunkLightmapCacheKey (baked, activeLights, ambientDark = this.#ambientDarkness())
4670 {
4671 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4672 if (!snapshot?.light)
4673 { return null; }
4674 const bakedHash = this.#hashUint8Array(snapshot.light);
4675 // Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring).
4676 const lights = activeLights;
4677 const darks = this._activeSpellDarks ?? [];
4678 const mode = this.lightingMode === "simple" ? "s" : "f";
4679 const ambientKey = Math.round(Math.max(0, ambientDark) * 1000);
4680 let lightsKey = "";
4681 for (const light of lights)
4682 {
4683 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
4684 { continue; }
4685 lightsKey += `l${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
4686 }
4687 let darksKey = "";
4688 for (const dark of darks)
4689 {
4690 if (!this.#lightAffectsChunkBounds(dark, baked.chunkX, baked.chunkY))
4691 { continue; }
4692 darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`;
4693 }
4694 return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`;
4695 }
4696
4697 #invalidateNeighborLightmapCaches (chunkX, chunkY)
4698 {
4699 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
4700 for (let dy = -2; dy <= 2; dy++)
4701 {
4702 for (let dx = -2; dx <= 2; dx++)
4703 {
4704 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
4705 if (baked)
4706 { baked.lightmapCacheKey = null; }
4707 }
4708 }
4709 }
4710
4711 /**
4712 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
4713 * occluding tiles stay flat and contribute 0 into others so light does not bleed
4714 * through a wall to the far side. Diagonals only when both cardinals are clear.
4715 * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples).
4716 * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary.
4717 */
4718 #writeChunkLightmap (
4719 baked,
4720 chunkLights,
4721 mobileLights,
4722 blockLights,
4723 lightOcclusion,
4724 ambientDark = this.#ambientDarkness()
4725 )
4726 {
4727 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4728 if (!snapshot)
4729 { return; }
4730 const cacheKey = this.#chunkLightmapCacheKey(baked, chunkLights, ambientDark);
4731 if (cacheKey && baked.lightmapCacheKey === cacheKey)
4732 { return; }
4733 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
4734 const pixelCount = atlasPx * atlasPx * 4;
4735 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
4736 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
4737 const pixels = baked.lightmapPixels;
4738
4739 this.#fillChunkLightGrids(baked, mobileLights, blockLights, lightOcclusion, ambientDark);
4740 const simple = this.lightingMode === "simple";
4741
4742 for (let localY = 0; localY < CHUNK_SIZE; localY++)
4743 {
4744 for (let localX = 0; localX < CHUNK_SIZE; localX++)
4745 {
4746 const baseX = localX * SPRITE_SIZE_PX;
4747 const baseY = localY * SPRITE_SIZE_PX;
4748 if (simple)
4749 {
4750 const gridW = CHUNK_SIZE + 2;
4751 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
4752 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
4753 for (let py = 0; py < SPRITE_SIZE_PX; py++)
4754 {
4755 for (let px = 0; px < SPRITE_SIZE_PX; px++)
4756 {
4757 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
4758 pixels[offset] = value;
4759 pixels[offset + 1] = value;
4760 pixels[offset + 2] = value;
4761 pixels[offset + 3] = 255;
4762 }
4763 }
4764 continue;
4765 }
4766 const corners = this.#tileLitCorners(baked, localX, localY);
4767 const nw = corners.nw;
4768 const ne = corners.ne;
4769 const sw = corners.sw;
4770 const se = corners.se;
4771 for (let py = 0; py < SPRITE_SIZE_PX; py++)
4772 {
4773 const v = (py + 0.5) / SPRITE_SIZE_PX;
4774 const left = nw + (sw - nw) * v;
4775 const right = ne + (se - ne) * v;
4776 for (let px = 0; px < SPRITE_SIZE_PX; px++)
4777 {
4778 const u = (px + 0.5) / SPRITE_SIZE_PX;
4779 const intensity = left + (right - left) * u;
4780 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
4781 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
4782 pixels[offset] = value;
4783 pixels[offset + 1] = value;
4784 pixels[offset + 2] = value;
4785 pixels[offset + 3] = 255;
4786 }
4787 }
4788 }
4789 }
4790 const ctx = baked.lightmapCanvas.getContext("2d");
4791 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
4792 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4793 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
4794 baked.lightmapCacheKey = cacheKey;
4795 }
4796
4797 #updateSwipes (now)
4798 {
4799 this.swipes = this.swipes.filter((swipe) =>
4800 {
4801 if (swipe.lerp && swipe.started != null)
4802 {
4803 const durationMs = swipe.durationMs ?? 400;
4804 const t = Math.min(1, (now - swipe.started) / durationMs);
4805 const fromPivot = this.#projectileLaunchPoint(
4806 swipe.attackerId ?? null,
4807 swipe.fromTileX,
4808 swipe.fromTileY
4809 );
4810 const toPivot = this.#projectileEndPivot(swipe);
4811 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
4812 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
4813 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
4814 if (swipe.object?.transform)
4815 {
4816 swipe.object.transform.rotation = Math.atan2(
4817 toPivot.y - fromPivot.y,
4818 toPivot.x - fromPivot.x
4819 ) * (180 / Math.PI);
4820 }
4821 if (swipe.spellProjectile && swipe.tint)
4822 { this.#syncUnlitTintSprite(swipe.object, swipe.tint); }
4823 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
4824 if (!swipe.spellProjectile)
4825 {
4826 this.#applyPhysicalCombatFxDarkness(
4827 swipe.object,
4828 swipe.fromTileX,
4829 swipe.fromTileY,
4830 swipe.tileX,
4831 swipe.tileY,
4832 swipe.dualTint ?? null
4833 );
4834 }
4835 }
4836 else if (swipe.fromTileX != null && !swipe.spellProjectile)
4837 {
4838 this.#applyPhysicalCombatFxDarkness(
4839 swipe.object,
4840 swipe.fromTileX,
4841 swipe.fromTileY,
4842 swipe.tileX,
4843 swipe.tileY,
4844 swipe.dualTint ?? null
4845 );
4846 }
4847 if (swipe.fadeOpacity && swipe.started != null && swipe.object?.renderer)
4848 {
4849 const durationMs = swipe.durationMs ?? MELEE_SWIPE_MS;
4850 const t = Math.min(1, Math.max(0, (now - swipe.started) / durationMs));
4851 swipe.object.renderer.alpha = 1 - t;
4852 }
4853 if (swipe.until > now)
4854 { return true; }
4855 const onImpact = swipe.onImpact;
4856 swipe.onImpact = null;
4857 swipe.object?.destroy();
4858 if (typeof onImpact === "function")
4859 {
4860 try
4861 { onImpact(); }
4862 catch (_)
4863 { /* presentation only */ }
4864 }
4865 return false;
4866 });
4867 }
4868
4869 #projectileEndPivot (swipe)
4870 {
4871 if (swipe.trackTarget && swipe.targetId != null)
4872 { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }
4873 return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);
4874 }
4875
4876 /**
4877 * Launch point: 4px below the top of the caster sprite (falls back to tile centre).
4878 */
4879 #projectileLaunchPoint (entityId, tileX, tileY)
4880 {
4881 const entity = entityId != null ? this.entities.get(entityId) : null;
4882 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
4883 {
4884 const zoom = this.zoom;
4885 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
4886 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
4887 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
4888 const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;
4889 return {
4890 x: pivotX,
4891 y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom
4892 };
4893 }
4894 return tilePivot(tileX, tileY, this.tileSize());
4895 }
4896
4897 /**
4898 * Aim point: sprite centre for creatures, tile centre for tile targets.
4899 */
4900 #projectileAimPoint (entityId, tileX, tileY)
4901 {
4902 const entity = entityId != null ? this.entities.get(entityId) : null;
4903 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
4904 {
4905 const zoom = this.zoom;
4906 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
4907 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
4908 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
4909 return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);
4910 }
4911 return tilePivot(tileX, tileY, this.tileSize());
4912 }
4913
4914 #updateDamageNumbers (now)
4915 {
4916 const layer = this.damageNumbersEl;
4917 if (!layer)
4918 { return; }
4919 this.damageFloats = this.damageFloats.filter((entry) =>
4920 {
4921 const elapsed = now - entry.started;
4922 if (elapsed >= DAMAGE_FLOAT_MS)
4923 {
4924 entry.element?.remove();
4925 return false;
4926 }
4927 const entity = this.entities.get(entry.entityId);
4928 if (!entity)
4929 {
4930 entry.element?.remove();
4931 return false;
4932 }
4933 if (!entry.element)
4934 {
4935 entry.element = document.createElement("span");
4936 entry.element.className = "damage-number";
4937 entry.element.textContent = String(entry.damage);
4938 layer.append(entry.element);
4939 }
4940 const anchor = this.nametagAnchor(entity);
4941 if (!anchor)
4942 { return true; }
4943 const t = elapsed / DAMAGE_FLOAT_MS;
4944 entry.element.style.left = `${anchor.x}px`;
4945 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
4946 entry.element.style.opacity = String(1 - t);
4947 return true;
4948 });
4949 }
4950
4951 #updateSkillLevelFloats (now)
4952 {
4953 const layer = this.skillLevelFloatsEl;
4954 if (!layer)
4955 { return; }
4956 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
4957 {
4958 const elapsed = now - entry.started;
4959 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
4960 {
4961 entry.element?.remove();
4962 return false;
4963 }
4964 const entity = this.entities.get(entry.entityId);
4965 if (!entity)
4966 {
4967 entry.element?.remove();
4968 return false;
4969 }
4970 if (!entry.element)
4971 {
4972 const root = document.createElement("div");
4973 root.className = "skill-level-float";
4974
4975 const levelEl = document.createElement("div");
4976 levelEl.className = "skill-level-float-level";
4977 levelEl.textContent = `↑${entry.level}↑`;
4978
4979 const icon = document.createElement("img");
4980 icon.className = "skill-level-float-icon";
4981 icon.src = entry.icon;
4982 icon.alt = entry.displayName || "";
4983
4984 root.append(levelEl, icon);
4985 entry.element = root;
4986 layer.append(entry.element);
4987 }
4988 const anchor = this.nametagAnchor(entity);
4989 if (!anchor)
4990 { return true; }
4991 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
4992 entry.element.style.left = `${anchor.x}px`;
4993 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
4994 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
4995 return true;
4996 });
4997 }
4998
4999 #syncBloomLayer ()
5000 {
5001 if (!this.bloomEnabled)
5002 {
5003 this.scene.setLayers([{ name: "default" }]);
5004 return;
5005 }
5006 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
5007 this.scene.setLayers([
5008 { name: "default" },
5009 {
5010 name: RENDER_LAYER_BLOOM,
5011 composite: "add",
5012 postShaders: Shader.getBloomPostChain({
5013 threshold: settings.bloomThreshold,
5014 softKnee: settings.bloomSoftKnee,
5015 intensity: settings.bloomIntensity,
5016 blurSize: settings.bloomBlurSize,
5017 saturation: settings.bloomSaturation,
5018 colorPreserve: settings.bloomColorPreserve,
5019 dilate: settings.bloomDilate,
5020 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
5021 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
5022 })
5023 }
5024 ]);
5025 }
5026}
5027
5028export function nightFactor (hour, nightDarkness = 0.72)
5029{
5030 const peak = Math.min(1, Math.max(0, nightDarkness));
5031 if (hour >= 8 && hour <= 16)
5032 { return 0; }
5033 if (hour >= 22 || hour <= 5)
5034 { return peak; }
5035 if (hour < 8)
5036 { return lerp(peak, 0, (hour - 5) / 3); }
5037 return lerp(0, peak, (hour - 16) / 6);
5038}
5039
5040function bodySpriteName (sex)
5041{
5042 const key = sex === "female" ? "player-body-female" : "player-body-male";
5043 return spriteImageName("character", key, key);
5044}
5045
5046function lerp (a, b, t)
5047{
5048 return a + (b - a) * Math.min(1, Math.max(0, t));
5049}
5050
5051function makeLightmapCanvas (size)
5052{
5053 const canvas = document.createElement("canvas");
5054 canvas.width = size;
5055 canvas.height = size;
5056 return canvas;
5057}
5058
5059function copyCanvas (source, dest)
5060{
5061 const ctx = dest.getContext("2d");
5062 ctx.imageSmoothingEnabled = false;
5063 ctx.clearRect(0, 0, dest.width, dest.height);
5064 ctx.drawImage(source, 0, 0);
5065}
5066
5067function drawHpBar (canvas, current, max)
5068{
5069 const ctx = canvas.getContext("2d");
5070 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
5071 ctx.fillStyle = "#000000";
5072 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
5073 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
5074 const fillW = Math.round(12 * ratio);
5075 if (fillW > 0)
5076 {
5077 ctx.fillStyle = "#ff0000";
5078 ctx.fillRect(1, 1, fillW, 2);
5079 }
5080}