BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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