BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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