BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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