BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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