BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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