BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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