BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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