BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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