BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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