BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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