BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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