BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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