BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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