BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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