BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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