BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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