BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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