BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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