BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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