BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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