BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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