BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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