BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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