BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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