BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 99.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, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
6import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb } from "/shared/render/tint.js";
7import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight } from "/shared/definitions/tiles.js";
8import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
9import { bakeChunkAtlases } from "./chunkBake.js";
10import {
11 frameworkImageFromCanvas,
12 invalidateCanvasTexture
13} from "./canvasSprite.js";
14import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
15import { SeasonId, seasonIdAt } from "/shared/world/season.js";
16import {
17 OVERWORLD_ID,
18 normalizeDimensionId,
19 normalizeLightingMode,
20 normalizeSeasonMode,
21 resolveDimensionDarknessFactor,
22 resolveDimensionSeasonId
23} from "/shared/world/dimensions.js";
24import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
25
26const LAYER_GROUND = 0;
27const LAYER_EDGE = 900000;
28const SORT_BLOCK = 2;
29const SORT_ENTITY = 3;
30const SORT_HP_BAR = 4;
31const SORT_FX = 5;
32const RENDER_LAYER_BLOOM = "bloom";
33
34const HP_BAR_W = 14;
35const HP_BAR_H = 4;
36const WALK_TILT_DEG = 6;
37const RUN_TILT_DEG = 8;
38const SHOVE_TILE_FRACTION = 0.25;
39const SHOVE_MS = 280;
40/** Soft reflow when stack circle targets change (join/leave a shared tile). */
41const STACK_SPREAD_LERP_MS = 280;
42/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
43const GATHER_TOOL_HOLD_MS = 1100;
44const DAMAGE_FLASH_MS = 180;
45const DAMAGE_FLOAT_MS = 900;
46const SKILL_LEVEL_FLOAT_MS = 2800;
47
48const SPRITE_LIGHTING_FRAG = [
49 "precision mediump float;",
50 "varying vec2 v_texCoord;",
51 "uniform sampler2D u_texture;",
52 "uniform float u_darkness;",
53 "uniform float u_strength;",
54 "uniform float u_wade;",
55 "uniform float u_spriteHeight;",
56 "void main() {",
57 " vec4 color = texture2D(u_texture, v_texCoord);",
58 " if (color.a <= 0.0) { discard; }",
59 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
60 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
61 " vec3 rgb = color.rgb;",
62 " if (u_wade > 0.5 && fromBottom < 5.0) {",
63 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
64 " }",
65 " rgb = mix(rgb, vec3(0.0), u_darkness);",
66 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
67 " gl_FragColor = vec4(rgb, color.a);",
68 "}"
69].join("\n");
70
71const WATER_GROUND_FRAG = [
72 "precision mediump float;",
73 "varying vec2 v_texCoord;",
74 "uniform sampler2D u_texture;",
75 "uniform float u_ambientDark;",
76 "uniform float u_litNW;",
77 "uniform float u_litNE;",
78 "uniform float u_litSW;",
79 "uniform float u_litSE;",
80 "uniform float u_time;",
81 "uniform float u_edgeN;",
82 "uniform float u_edgeE;",
83 "uniform float u_edgeS;",
84 "uniform float u_edgeW;",
85 "void main() {",
86 " vec4 color = texture2D(u_texture, v_texCoord);",
87 " if (color.a <= 0.0) { discard; }",
88 " vec3 rgb = color.rgb;",
89 " float foam = 0.0;",
90 " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
91 " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
92 " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
93 " }",
94 " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
95 " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
96 " }",
97 " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
98 " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
99 " }",
100 " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
101 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
102 " }",
103 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
104 " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);",
105 " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);",
106 " float lit = mix(litTop, litBottom, v_texCoord.y);",
107 " float darkness = u_ambientDark * (1.0 - lit);",
108 " rgb = mix(rgb, vec3(0.0), darkness);",
109 " gl_FragColor = vec4(rgb, color.a);",
110 "}"
111].join("\n");
112
113/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
114const TINT_LIT_SPRITE_FRAG = [
115 "precision mediump float;",
116 "varying vec2 v_texCoord;",
117 "uniform sampler2D u_texture;",
118 "uniform float u_darkness;",
119 "uniform float u_strength;",
120 "uniform float u_wade;",
121 "uniform float u_spriteHeight;",
122 "uniform float u_useTint;",
123 "uniform vec3 u_tintColor;",
124 "void main() {",
125 " vec4 color = texture2D(u_texture, v_texCoord);",
126 " if (color.a <= 0.0) { discard; }",
127 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
128 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
129 " vec3 rgb = color.rgb;",
130 " if (u_useTint > 0.5) {",
131 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
132 " float L = color.r;",
133 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
134 " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",
135 " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",
136 " }",
137 " }",
138 " if (u_wade > 0.5 && fromBottom < 5.0) {",
139 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
140 " }",
141 " rgb = mix(rgb, vec3(0.0), u_darkness);",
142 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
143 " gl_FragColor = vec4(rgb, color.a);",
144 "}"
145].join("\n");
146
147/** Dual-channel arrow tint: red = shaft, blue = tip, white unchanged; then darkness. */
148const DUAL_TINT_LIT_SPRITE_FRAG = [
149 "precision mediump float;",
150 "varying vec2 v_texCoord;",
151 "uniform sampler2D u_texture;",
152 "uniform float u_darkness;",
153 "uniform float u_strength;",
154 "uniform float u_wade;",
155 "uniform float u_spriteHeight;",
156 "uniform vec3 u_shaftTint;",
157 "uniform vec3 u_tipTint;",
158 "void main() {",
159 " vec4 color = texture2D(u_texture, v_texCoord);",
160 " if (color.a <= 0.0) { discard; }",
161 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
162 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
163 " vec3 rgb = color.rgb;",
164 " float tipMask = clamp((color.b - max(color.r, color.g)) * 1.75, 0.0, 1.0);",
165 " if (tipMask > 0.0) {",
166 " float L = color.b;",
167 " float gBlend = L > 0.0 ? clamp(color.g / L, 0.0, 1.0) : 0.0;",
168 " float tipLuma = dot(u_tipTint, vec3(0.2126, 0.7152, 0.0722));",
169 " vec3 tipCol = mix(u_tipTint, vec3(tipLuma), gBlend) * L;",
170 " rgb = mix(rgb, tipCol, tipMask);",
171 " }",
172 " float shaftMask = clamp((color.r - max(color.g, color.b)) * 1.75, 0.0, 1.0);",
173 " if (shaftMask > 0.0) {",
174 " float L = color.r;",
175 " float gBlend = L > 0.0 ? clamp(color.g / L, 0.0, 1.0) : 0.0;",
176 " float shaftLuma = dot(u_shaftTint, vec3(0.2126, 0.7152, 0.0722));",
177 " vec3 shaftCol = mix(u_shaftTint, vec3(shaftLuma), gBlend) * L;",
178 " rgb = mix(rgb, shaftCol, shaftMask);",
179 " }",
180 " if (u_wade > 0.5 && fromBottom < 5.0) {",
181 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
182 " }",
183 " rgb = mix(rgb, vec3(0.0), u_darkness);",
184 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
185 " gl_FragColor = vec4(rgb, color.a);",
186 "}"
187].join("\n");
188
189/** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
190/**
191 * Tight-fit: clip clothing alpha to the body silhouette in *pivot space*
192 * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from
193 * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art.
194 */
195const TIGHT_FIT_BODY_MASK_GLSL = [
196 "uniform vec2 u_clothSize;",
197 "uniform vec2 u_bodySize;",
198 "uniform float u_pivotFromBottom;",
199 "uniform vec4 u_clothUvRect;",
200 "uniform vec4 u_bodyUvRect;",
201 "float tightFitBodyAlpha() {",
202 " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));",
203 " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;",
204 " float ox = (nu.x - 0.5) * u_clothSize.x;",
205 " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);",
206 " vec2 bodySize = max(u_bodySize, vec2(1.0));",
207 " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);",
208 " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));",
209 " vec2 texel = 1.0 / bodySize;",
210 " float bodyA = 0.0;",
211 " for (int dy = -1; dy <= 1; dy++) {",
212 " for (int dx = -1; dx <= 1; dx++) {",
213 " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;",
214 " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }",
215 " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;",
216 " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);",
217 " }",
218 " }",
219 " return bodyA;",
220 "}"
221].join("\n");
222
223const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
224 "precision mediump float;",
225 "varying vec2 v_texCoord;",
226 "uniform sampler2D u_texture;",
227 "uniform sampler2D u_secondary;",
228 "uniform float u_darkness;",
229 "uniform float u_strength;",
230 "uniform float u_wade;",
231 "uniform float u_spriteHeight;",
232 "uniform float u_useTint;",
233 "uniform vec3 u_tintColor;",
234 TIGHT_FIT_BODY_MASK_GLSL,
235 "void main() {",
236 " vec4 color = texture2D(u_texture, v_texCoord);",
237 " if (color.a <= 0.0) { discard; }",
238 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
239 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
240 " vec3 rgb = color.rgb;",
241 " if (u_useTint > 0.5) {",
242 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
243 " float L = color.r;",
244 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
245 " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",
246 " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",
247 " }",
248 " }",
249 " if (u_wade > 0.5 && fromBottom < 5.0) {",
250 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
251 " }",
252 " rgb = mix(rgb, vec3(0.0), u_darkness);",
253 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
254 " float alpha = min(tightFitBodyAlpha(), color.a);",
255 " if (alpha <= 0.0) { discard; }",
256 " gl_FragColor = vec4(rgb, alpha);",
257 "}"
258].join("\n");
259
260/** Body-clipped equip overlay without dye recolour. */
261const TIGHT_FIT_LIT_SPRITE_FRAG = [
262 "precision mediump float;",
263 "varying vec2 v_texCoord;",
264 "uniform sampler2D u_texture;",
265 "uniform sampler2D u_secondary;",
266 "uniform float u_darkness;",
267 "uniform float u_strength;",
268 "uniform float u_wade;",
269 "uniform float u_spriteHeight;",
270 TIGHT_FIT_BODY_MASK_GLSL,
271 "void main() {",
272 " vec4 color = texture2D(u_texture, v_texCoord);",
273 " if (color.a <= 0.0) { discard; }",
274 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
275 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
276 " vec3 rgb = color.rgb;",
277 " if (u_wade > 0.5 && fromBottom < 5.0) {",
278 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
279 " }",
280 " rgb = mix(rgb, vec3(0.0), u_darkness);",
281 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
282 " float alpha = min(tightFitBodyAlpha(), color.a);",
283 " if (alpha <= 0.0) { discard; }",
284 " gl_FragColor = vec4(rgb, alpha);",
285 "}"
286].join("\n");
287
288const ATLAS_LIGHTING_FRAG = [
289 "precision mediump float;",
290 "varying vec2 v_texCoord;",
291 "uniform sampler2D u_texture;",
292 "uniform sampler2D u_secondary;",
293 "uniform float u_ambientDark;",
294 "uniform float u_lightRow;",
295 "void main() {",
296 " vec4 color = texture2D(u_texture, v_texCoord);",
297 " if (color.a <= 0.0) { discard; }",
298 " vec2 lightUV = v_texCoord;",
299 " if (u_lightRow >= 0.0) {",
300 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
301 " }",
302 " float lit = texture2D(u_secondary, lightUV).r;",
303 " float darkness = u_ambientDark * (1.0 - lit);",
304 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
305 " gl_FragColor = vec4(rgb, color.a);",
306 "}"
307].join("\n");
308
309let spriteLightingShader = null;
310let atlasLightingShader = null;
311let waterGroundShader = null;
312let tintLitSpriteShader = null;
313let dualTintLitSpriteShader = null;
314let tightFitTintLitSpriteShader = null;
315let tightFitLitSpriteShader = null;
316
317function getSpriteLightingShader ()
318{
319 if (!spriteLightingShader)
320 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
321 return spriteLightingShader;
322}
323
324function getAtlasLightingShader ()
325{
326 if (!atlasLightingShader)
327 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
328 return atlasLightingShader;
329}
330
331function getWaterGroundShader ()
332{
333 if (!waterGroundShader)
334 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
335 return waterGroundShader;
336}
337
338function getTintLitSpriteShader ()
339{
340 if (!tintLitSpriteShader)
341 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
342 return tintLitSpriteShader;
343}
344
345function getDualTintLitSpriteShader ()
346{
347 if (!dualTintLitSpriteShader)
348 { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); }
349 return dualTintLitSpriteShader;
350}
351
352function getTightFitTintLitSpriteShader ()
353{
354 if (!tightFitTintLitSpriteShader)
355 { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); }
356 return tightFitTintLitSpriteShader;
357}
358
359function getTightFitLitSpriteShader ()
360{
361 if (!tightFitLitSpriteShader)
362 { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); }
363 return tightFitLitSpriteShader;
364}
365
366export class WorldView
367{
368 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
369 {
370 this.game = game;
371 this.scene = scene;
372 this.catalog = catalog;
373 this.preview = null;
374 this.zoom = 2;
375 this.chunks = new Map();
376 this.bakedChunks = new Map();
377 this.tiles = new Map();
378 this.entities = new Map();
379 this.groundItems = new Map();
380 this.edges = new Map();
381 this.localEntityId = null;
382 this.localBlind = false;
383 /** @type {string} */
384 this.dimensionId = OVERWORLD_ID;
385 /** @type {string} */
386 this.dimensionLightingMode = "dayNight";
387 /** @type {string} */
388 this.dimensionSeasonMode = "auto";
389 /** Calendar season from worldStatus when dimension season is auto. */
390 this.calendarSeason = seasonIdAt();
391 /** @type {"soft"|"simple"} */
392 this.lightingMode = "soft";
393 /** @type {boolean} */
394 this.bloomEnabled = true;
395 this.settings = { ...DEFAULT_WORLD_SETTINGS };
396 this.worldHour = 12;
397 /** Calendar season for seasonal ground/block visuals (`summer` / `fall` / `winter`). */
398 this.worldSeason = seasonIdAt();
399 this.nightPreview = null;
400 this.followPlayer = true;
401 this.dynamicLights = [];
402 this.spellLights = new Map();
403 this.swipes = [];
404 this.damageFloats = [];
405 this.damageNumbersEl = document.getElementById("damage-numbers");
406 this.skillLevelFloats = [];
407 this.skillLevelFloatsEl = document.getElementById("skill-level-floats");
408 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
409 this.editorSpawners = new Map();
410 this.spawnRangeHighlight = null;
411 this.wanderRangeHighlight = null;
412 this.spellTargetHighlight = null;
413 this.#syncBloomLayer();
414 }
415
416 setSettings (settings)
417 {
418 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
419 this.#syncBloomLayer();
420 }
421
422 /**
423 * Client graphics prefs (lighting Soft/Simple, bloom On/Off).
424 * @param {{ lighting?: string, bloom?: string }} prefs
425 */
426 setGraphicsPrefs (prefs)
427 {
428 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
429 { this.lightingMode = prefs.lighting; }
430 if (prefs?.bloom === "off" || prefs?.bloom === "on")
431 {
432 const enabled = prefs.bloom !== "off";
433 if (enabled !== this.bloomEnabled)
434 {
435 this.bloomEnabled = enabled;
436 this.#syncBloomLayer();
437 }
438 else
439 { this.bloomEnabled = enabled; }
440 }
441 }
442
443 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
444 setWorldSeason (season)
445 {
446 const calendar = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
447 ? season
448 : seasonIdAt();
449 this.calendarSeason = calendar;
450 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
451 const next = forced ?? calendar;
452 if (next === this.worldSeason)
453 { return; }
454 this.worldSeason = next;
455 this.#rebakeAllChunks();
456 }
457
458 setDimensionId (dimensionId)
459 {
460 this.dimensionId = normalizeDimensionId(dimensionId);
461 }
462
463 setDimensionModes (lightingMode, seasonMode)
464 {
465 this.dimensionLightingMode = normalizeLightingMode(lightingMode);
466 this.dimensionSeasonMode = normalizeSeasonMode(seasonMode);
467 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
468 const next = forced ?? this.calendarSeason ?? seasonIdAt();
469 if (next !== this.worldSeason)
470 {
471 this.worldSeason = next;
472 this.#rebakeAllChunks();
473 }
474 }
475
476 clearAllChunks ()
477 {
478 for (const key of [...this.chunks.keys()])
479 {
480 const [chunkX, chunkY] = key.split(",").map(Number);
481 this.removeChunk(chunkX, chunkY);
482 }
483 for (const [id] of [...this.entities.entries()])
484 {
485 if (id === this.localEntityId)
486 { continue; }
487 this.despawnEntity(id);
488 }
489 for (const [id] of [...this.groundItems.entries()])
490 { this.despawnGroundItem(id); }
491 }
492
493 applySnapshot (snapshot)
494 {
495 const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID);
496 if (normalizeDimensionId(this.dimensionId) !== snapDim)
497 { return; }
498 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
499 this.chunks.set(key, snapshot);
500 this.#rebuildChunk(snapshot);
501 this.#redrawPreview();
502 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
503 if (snapshot.staticOnly)
504 {
505 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
506 this.#rebuildAllEdges();
507 return;
508 }
509 for (const entity of snapshot.entities ?? [])
510 { this.#upsertEntity(entity); }
511 for (const [id, item] of [...this.groundItems.entries()])
512 {
513 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
514 { this.despawnGroundItem(id); }
515 }
516 for (const item of snapshot.groundItems ?? [])
517 { this.upsertGroundItem(item); }
518 this.#rebuildAllEdges();
519 }
520
521 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
522 {
523 this.localEntityId = entityId;
524 this.#upsertEntity({
525 entityId,
526 characterId,
527 tileX,
528 tileY,
529 gait,
530 sex,
531 firstName,
532 lastName,
533 layers: layers ?? undefined,
534 ...(health != null ? { health } : {}),
535 ...(maxHealth != null ? { maxHealth } : {})
536 });
537 }
538
539 #stripChunkDynamic (chunkX, chunkY)
540 {
541 for (const [id, item] of [...this.groundItems.entries()])
542 {
543 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
544 { this.despawnGroundItem(id); }
545 }
546 for (const [id, entity] of [...this.entities.entries()])
547 {
548 if (id === this.localEntityId)
549 { continue; }
550 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
551 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
552 { this.despawnEntity(id); }
553 }
554 }
555
556 removeChunk (chunkX, chunkY)
557 {
558 const key = `${chunkX},${chunkY}`;
559 this.chunks.delete(key);
560 this.#destroyBakedChunk(key);
561 this.#destroyEdges(key);
562 const prefix = `${chunkX},${chunkY}:`;
563 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
564 {
565 if (!spawnerKey.startsWith(prefix))
566 { continue; }
567 entry.object?.destroy();
568 this.editorSpawners.delete(spawnerKey);
569 }
570 for (const [tileKey, objects] of [...this.tiles.entries()])
571 {
572 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
573 {
574 objects.ground?.destroy();
575 objects.groundBloom?.destroy();
576 objects.block?.destroy();
577 objects.blockBloom?.destroy();
578 this.tiles.delete(tileKey);
579 }
580 }
581 for (const [id, item] of [...this.groundItems.entries()])
582 {
583 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
584 { this.despawnGroundItem(id); }
585 }
586 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
587 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
588 for (const [id, entity] of [...this.entities.entries()])
589 {
590 if (id === this.localEntityId)
591 { continue; }
592 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
593 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
594 { this.despawnEntity(id); }
595 }
596 this.#rebuildAllEdges();
597 }
598
599 setChunkOpen (chunkX, chunkY, open)
600 {
601 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
602 if (!snapshot)
603 { return; }
604 snapshot.open = !!open;
605 this.#rebuildAllEdges();
606 }
607
608 spawnEntity (payload)
609 {
610 this.#upsertEntity(payload);
611 }
612
613 moveEntity (payload)
614 {
615 const existing = this.entities.get(payload.entityId);
616 if (!existing)
617 {
618 this.#upsertEntity(payload);
619 return;
620 }
621 const size = this.tileSize();
622 existing.fromX = existing.visualX;
623 existing.fromY = existing.visualY;
624 existing.shadeFromTileX = existing.tileX;
625 existing.shadeFromTileY = existing.tileY;
626 existing.tileX = payload.tileX;
627 existing.tileY = payload.tileY;
628 existing.gait = payload.gait;
629 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
630 if (payload.worldX != null && payload.worldY != null)
631 {
632 existing.worldX = payload.worldX;
633 existing.worldY = payload.worldY;
634 existing.targetX = payload.worldX * size;
635 existing.targetY = payload.worldY * size;
636 }
637 else
638 {
639 const pivot = tilePivot(payload.tileX, payload.tileY, size);
640 existing.targetX = pivot.x;
641 existing.targetY = pivot.y;
642 }
643 existing.lerpStarted = performance.now();
644 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
645 }
646
647 despawnEntity (entityId)
648 {
649 const existing = this.entities.get(entityId);
650 if (!existing)
651 { return; }
652 existing.object?.destroy();
653 existing.hpBar?.destroy();
654 for (const overlay of existing.overlays ?? [])
655 { overlay.destroy(); }
656 for (const overlay of existing.bloomOverlays ?? [])
657 { overlay.destroy(); }
658 this.entities.delete(entityId);
659 }
660
661 updateEntityHealth (entityId, health, maxHealth)
662 {
663 const entity = this.entities.get(entityId);
664 if (!entity)
665 { return; }
666 entity.health = health;
667 entity.maxHealth = maxHealth;
668 this.#syncHpBar(entity);
669 }
670
671 flashDamage (entityId)
672 {
673 const entity = this.entities.get(entityId);
674 if (!entity)
675 { return; }
676 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
677 }
678
679 spawnDamageNumber (entityId, damage)
680 {
681 const amount = damage | 0;
682 if (amount <= 0)
683 { return; }
684 this.damageFloats.push({
685 entityId,
686 damage: amount,
687 started: performance.now()
688 });
689 }
690
691 spawnSkillLevelUp (entityId, payload)
692 {
693 const level = payload?.level | 0;
694 if (level <= 0 || !payload?.icon)
695 { return; }
696 this.skillLevelFloats.push({
697 entityId,
698 level,
699 icon: payload.icon,
700 displayName: payload.displayName ?? payload.skillId ?? "",
701 started: performance.now()
702 });
703 }
704
705 setAppearance (payload)
706 {
707 const existing = this.entities.get(payload.entityId);
708 if (!existing)
709 { return; }
710 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
711 if (payload.visualScale != null)
712 { existing.visualScale = Number(payload.visualScale) || 1; }
713 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
714 this.#placeEntity(existing);
715 }
716
717 /**
718 * Render the live entity (body + overlays, same tint/tight-fit shaders as the
719 * world, unlit) into an offscreen FBO, crop the top square, and return a
720 * pixel-scaled canvas for UI (e.g. dialogue speaker icons).
721 * @param {number} entityId
722 * @param {{ size?: number }} [options]
723 * @returns {HTMLCanvasElement | null}
724 */
725 captureEntityPortrait (entityId, { size = 64 } = {})
726 {
727 const entity = this.entities.get(entityId);
728 const body = entity?.object?.renderer?.sprite;
729 const glCtx = this.scene?.glContext;
730 const gl = glCtx?.gl;
731 if (!entity || !body || !gl)
732 { return null; }
733
734 const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX);
735 const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX);
736 if (!this.#ensurePortraitTarget(gl, frameW, frameH))
737 { return null; }
738
739 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
740 const prevViewport = gl.getParameter(gl.VIEWPORT);
741 const prevW = glCtx._lastWidth;
742 const prevH = glCtx._lastHeight;
743 const prevBlend = gl.isEnabled(gl.BLEND);
744
745 try
746 {
747 // drawSprite projects with _lastWidth/_lastHeight — match the FBO.
748 glCtx._lastWidth = frameW;
749 glCtx._lastHeight = frameH;
750 gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb);
751 gl.viewport(0, 0, frameW, frameH);
752 gl.enable(gl.BLEND);
753 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
754 gl.clearColor(0, 0, 0, 0);
755 gl.clear(gl.COLOR_BUFFER_BIT);
756
757 const pivotX = frameW * 0.5;
758 const pivotY = frameH - PIVOT_FROM_BOTTOM_PX;
759 this._portraitBodyMap = body.g_image ?? null;
760 this._portraitTightFitEntity = entity;
761 this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false);
762
763 const overlays = entity.overlays ?? [];
764 const tints = entity.overlayTints ?? [];
765 const tight = entity.overlayTightFit ?? [];
766 for (let index = 0; index < overlays.length; index++)
767 {
768 this.#drawPortraitLayer(
769 glCtx,
770 overlays[index],
771 pivotX,
772 pivotY,
773 tints[index] ?? null,
774 !!tight[index]
775 );
776 }
777 this._portraitBodyMap = null;
778 this._portraitTightFitEntity = null;
779
780 const pixels = this._portrait.pixels;
781 gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
782 }
783 finally
784 {
785 glCtx._lastWidth = prevW;
786 glCtx._lastHeight = prevH;
787 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
788 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
789 if (!prevBlend)
790 { gl.disable(gl.BLEND); }
791 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
792 }
793
794 return this.#portraitPixelsToCanvas(frameW, frameH, size);
795 }
796
797 #ensurePortraitTarget (gl, width, height)
798 {
799 const prev = this._portrait;
800 if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex)
801 { return true; }
802 if (prev?.fb)
803 { gl.deleteFramebuffer(prev.fb); }
804 if (prev?.tex)
805 { gl.deleteTexture(prev.tex); }
806
807 const tex = gl.createTexture();
808 gl.bindTexture(gl.TEXTURE_2D, tex);
809 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
810 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
811 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
812 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
813 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
814
815 const fb = gl.createFramebuffer();
816 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
817 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
818 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
819 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
820 if (status !== gl.FRAMEBUFFER_COMPLETE)
821 {
822 gl.deleteFramebuffer(fb);
823 gl.deleteTexture(tex);
824 this._portrait = null;
825 return false;
826 }
827 this._portrait = {
828 fb,
829 tex,
830 w: width,
831 h: height,
832 pixels: new Uint8Array(width * height * 4),
833 scratch: document.createElement("canvas")
834 };
835 return true;
836 }
837
838 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit)
839 {
840 const sprite = object?.renderer?.sprite;
841 if (!sprite?.g_image)
842 { return; }
843 const subImage = object.renderer.subImage | 0;
844 const height = sprite.height || SPRITE_SIZE_PX;
845 const draw = spriteDrawSize(sprite.width, sprite.height, 1);
846 const center = spriteCenterFromPivot(pivotX, pivotY, height, 1);
847 const tint = tintColor ? normalizeRgb(tintColor) : null;
848 let shader = glCtx.defaultShader;
849 let uniforms = null;
850 let secondaryHtml = null;
851
852 const bodyHtml = this._portraitBodyMap;
853 const portraitEntity = this._portraitTightFitEntity;
854 const maskUniforms = tightFit && portraitEntity
855 ? this.#tightFitMaskUniforms(object, portraitEntity)
856 : null;
857 if (tightFit && bodyHtml && maskUniforms)
858 {
859 secondaryHtml = bodyHtml;
860 if (tint)
861 {
862 shader = getTightFitTintLitSpriteShader();
863 uniforms = {
864 u_darkness: 0,
865 u_strength: 0,
866 u_wade: 0,
867 u_spriteHeight: height,
868 u_useTint: 1,
869 u_tintColor: [tint.r, tint.g, tint.b],
870 ...maskUniforms
871 };
872 }
873 else
874 {
875 shader = getTightFitLitSpriteShader();
876 uniforms = {
877 u_darkness: 0,
878 u_strength: 0,
879 u_wade: 0,
880 u_spriteHeight: height,
881 ...maskUniforms
882 };
883 }
884 }
885 else if (tint)
886 {
887 shader = getTintLitSpriteShader();
888 uniforms = {
889 u_darkness: 0,
890 u_strength: 0,
891 u_wade: 0,
892 u_spriteHeight: height,
893 u_useTint: 1,
894 u_tintColor: [tint.r, tint.g, tint.b]
895 };
896 }
897 else
898 {
899 shader = getSpriteLightingShader();
900 uniforms = {
901 u_darkness: 0,
902 u_strength: 0,
903 u_wade: 0,
904 u_spriteHeight: height
905 };
906 }
907
908 glCtx.drawSprite({
909 texture: glCtx.getTexture(sprite.g_image),
910 x: center.x,
911 y: center.y,
912 w: draw.w,
913 h: draw.h,
914 rotationDeg: 0,
915 mirrorX: false,
916 mirrorY: false,
917 alpha: 1,
918 uvRect: sprite.getUvRect(subImage),
919 shader,
920 uniforms,
921 textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null,
922 lights: null
923 });
924 }
925
926 #portraitPixelsToCanvas (frameW, frameH, size)
927 {
928 const pixels = this._portrait?.pixels;
929 if (!pixels)
930 { return null; }
931 const scratch = this._portrait.scratch;
932 scratch.width = frameW;
933 scratch.height = frameH;
934 const sctx = scratch.getContext("2d");
935 const imageData = sctx.createImageData(frameW, frameH);
936 // WebGL y=0 is bottom — flip to top-down image order.
937 for (let y = 0; y < frameH; y++)
938 {
939 const src = (frameH - 1 - y) * frameW * 4;
940 const dst = y * frameW * 4;
941 imageData.data.set(pixels.subarray(src, src + frameW * 4), dst);
942 }
943 sctx.putImageData(imageData, 0, 0);
944
945 const crop = Math.min(frameW, frameH);
946 const out = document.createElement("canvas");
947 out.width = size;
948 out.height = size;
949 const octx = out.getContext("2d");
950 octx.imageSmoothingEnabled = false;
951 octx.clearRect(0, 0, size, size);
952 octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size);
953 return out;
954 }
955
956 upsertGroundItem (payload)
957 {
958 const size = this.tileSize();
959 const pivot = tilePivot(payload.tileX, payload.tileY, size);
960 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
961 const spriteName = potion
962 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
963 : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance));
964 let item = this.groundItems.get(payload.groundItemId);
965 if (!item)
966 {
967 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
968 this.scene.addObject(object);
969 item = { object };
970 this.groundItems.set(payload.groundItemId, item);
971 }
972 else if (item.object && this.game.images[spriteName])
973 { item.object.image = this.game.images[spriteName]; }
974 item.groundItemId = payload.groundItemId;
975 item.tileX = payload.tileX;
976 item.tileY = payload.tileY;
977 item.itemId = payload.itemId;
978 item.quantity = payload.quantity;
979 item.displayName = payload.displayName;
980 item.sprite = spriteName;
981 item.instance = payload.instance ?? null;
982 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
983 item.dualTint = resolveItemDualTint(stack, itemDefinition(payload.itemId));
984 item.tintColor = item.dualTint ? null : resolveItemTint(stack, itemDefinition(payload.itemId));
985 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
986 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
987 }
988
989 despawnGroundItem (groundItemId)
990 {
991 const item = this.groundItems.get(groundItemId);
992 if (!item)
993 { return; }
994 item.object?.destroy();
995 this.groundItems.delete(groundItemId);
996 }
997
998 groundItemAtTile (tileX, tileY)
999 {
1000 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
1001 }
1002
1003 groundItemsAtTile (tileX, tileY)
1004 {
1005 const items = [];
1006 for (const item of this.groundItems.values())
1007 {
1008 if (item.tileX === tileX && item.tileY === tileY)
1009 { items.push(item); }
1010 }
1011 return items;
1012 }
1013
1014 entitiesAtTile (tileX, tileY)
1015 {
1016 const matches = [];
1017 for (const entity of this.entities.values())
1018 {
1019 if (entity.tileX === tileX && entity.tileY === tileY)
1020 { matches.push(entity); }
1021 }
1022 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
1023 return matches;
1024 }
1025
1026 setZoom (zoom, limits = { min: 2, max: 4 })
1027 {
1028 const min = limits.min ?? 1;
1029 const max = limits.max ?? 4;
1030 this.zoom = Math.min(max, Math.max(min, zoom));
1031 for (const snapshot of this.chunks.values())
1032 {
1033 this.#layoutBakedChunk(snapshot);
1034 this.#rebuildChunk(snapshot);
1035 }
1036 const size = this.tileSize();
1037 for (const entity of this.entities.values())
1038 {
1039 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
1040 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
1041 entity.fromX = entity.visualX;
1042 entity.fromY = entity.visualY;
1043 entity.targetX = entity.visualX;
1044 entity.targetY = entity.visualY;
1045 entity.lerpStarted = null;
1046 this.#placeEntity(entity);
1047 }
1048 for (const item of this.groundItems.values())
1049 {
1050 const pivot = tilePivot(item.tileX, item.tileY, size);
1051 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1052 }
1053 this.#rebuildAllEdges();
1054 this.#redrawPreview();
1055 this.#relayoutEditorSpawners();
1056 this.#relayoutSpawnRangeHighlight();
1057 this.#relayoutSpellTargetHighlight();
1058 applyNearestToAllTextures(this.scene, this.game.images);
1059 }
1060
1061 tileSize ()
1062 {
1063 return SPRITE_SIZE_PX * this.zoom;
1064 }
1065
1066 screenToTile (mouseX, mouseY)
1067 {
1068 const size = this.tileSize();
1069 const worldX = mouseX - this.scene.cameraPosition.x;
1070 const worldY = mouseY - this.scene.cameraPosition.y;
1071 return {
1072 tileX: Math.floor(worldX / size),
1073 tileY: Math.floor(worldY / size)
1074 };
1075 }
1076
1077 entityAtScreen (mouseX, mouseY)
1078 {
1079 let best = null;
1080 let bestLayer = -Infinity;
1081 for (const entity of this.entities.values())
1082 {
1083 const box = this.#entityScreenBox(entity);
1084 if (!box)
1085 { continue; }
1086 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
1087 {
1088 const layer = entity.object?.layer ?? 0;
1089 if (layer >= bestLayer)
1090 {
1091 best = entity;
1092 bestLayer = layer;
1093 }
1094 }
1095 }
1096 return best;
1097 }
1098
1099 nametagAnchor (entity)
1100 {
1101 const box = this.#entityScreenBox(entity);
1102 if (!box)
1103 { return null; }
1104 return { x: (box.left + box.right) / 2, y: box.top };
1105 }
1106
1107 #entityScreenBox (entity)
1108 {
1109 const object = entity?.object;
1110 if (!object)
1111 { return null; }
1112 const size = object.transform.size;
1113 const x = object.transform.position.x + this.scene.cameraPosition.x;
1114 const y = object.transform.position.y + this.scene.cameraPosition.y;
1115 return {
1116 left: x - size.x / 2,
1117 right: x + size.x / 2,
1118 top: y - size.y / 2,
1119 bottom: y + size.y / 2
1120 };
1121 }
1122
1123 update (deltaTime)
1124 {
1125 const now = performance.now();
1126 const size = this.tileSize();
1127 this.#refreshStackTargets();
1128 for (const entity of this.entities.values())
1129 {
1130 const target = entity.targetX != null && entity.targetY != null
1131 ? { x: entity.targetX, y: entity.targetY }
1132 : tilePivot(entity.tileX, entity.tileY, size);
1133 if (entity.lerpStarted != null)
1134 {
1135 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
1136 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
1137 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
1138 if (t >= 1)
1139 { entity.lerpStarted = null; }
1140 }
1141 else
1142 {
1143 entity.visualX = target.x;
1144 entity.visualY = target.y;
1145 }
1146 this.#updateStackOffset(entity, now);
1147 this.#updateShove(entity, now, size);
1148 this.#expireGatherToolOverlay(entity, now);
1149 this.#placeEntity(entity, now);
1150 }
1151
1152 this.#updateSwipes(now);
1153 this.#updateDamageNumbers(now);
1154 this.#updateSkillLevelFloats(now);
1155 this.#centerCamera();
1156 this.#cullOffscreenDrawables();
1157 this.#updateShade(deltaTime);
1158 }
1159
1160 /**
1161 * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}).
1162 * Stable assignment by entityId; free-flight entities stay unshifted.
1163 */
1164 #refreshStackTargets ()
1165 {
1166 const byTile = new Map();
1167 for (const entity of this.entities.values())
1168 {
1169 if (entity.freeFlight)
1170 {
1171 entity.stackTargetX = 0;
1172 entity.stackTargetY = 0;
1173 continue;
1174 }
1175 const key = `${entity.tileX},${entity.tileY}`;
1176 let list = byTile.get(key);
1177 if (!list)
1178 {
1179 list = [];
1180 byTile.set(key, list);
1181 }
1182 list.push(entity);
1183 }
1184 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
1185 for (const list of byTile.values())
1186 {
1187 if (list.length <= 1)
1188 {
1189 for (const entity of list)
1190 {
1191 entity.stackTargetX = 0;
1192 entity.stackTargetY = 0;
1193 }
1194 continue;
1195 }
1196 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
1197 const n = list.length;
1198 for (let i = 0; i < n; i++)
1199 {
1200 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
1201 list[i].stackTargetX = Math.cos(angle) * radius;
1202 list[i].stackTargetY = Math.sin(angle) * radius;
1203 }
1204 }
1205 }
1206
1207 #updateStackOffset (entity, now)
1208 {
1209 const tx = entity.stackTargetX ?? 0;
1210 const ty = entity.stackTargetY ?? 0;
1211 const cx = entity.stackOffsetX ?? 0;
1212 const cy = entity.stackOffsetY ?? 0;
1213 if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty)
1214 {
1215 entity.stackFromX = cx;
1216 entity.stackFromY = cy;
1217 entity.stackLerpToX = tx;
1218 entity.stackLerpToY = ty;
1219 entity.stackLerpStarted = now;
1220 }
1221 if (entity.stackLerpStarted == null)
1222 {
1223 entity.stackOffsetX = tx;
1224 entity.stackOffsetY = ty;
1225 return;
1226 }
1227 const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS);
1228 entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t;
1229 entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t;
1230 if (t >= 1)
1231 {
1232 entity.stackOffsetX = tx;
1233 entity.stackOffsetY = ty;
1234 entity.stackLerpStarted = null;
1235 }
1236 }
1237
1238 #updateShove (entity, now, tileSize)
1239 {
1240 if (!entity.shove)
1241 {
1242 entity.shoveOffsetX = 0;
1243 entity.shoveOffsetY = 0;
1244 return;
1245 }
1246 const elapsed = now - entity.shove.started;
1247 const t = Math.min(1, elapsed / entity.shove.durationMs);
1248 const maxDist = tileSize * SHOVE_TILE_FRACTION;
1249 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
1250 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
1251 const dist = Math.hypot(dx, dy) || 1;
1252 const ux = dx / dist;
1253 const uy = dy / dist;
1254 let phase;
1255 if (t < 0.45)
1256 { phase = t / 0.45; }
1257 else
1258 { phase = 1 - (t - 0.45) / 0.55; }
1259 entity.shoveOffsetX = ux * maxDist * phase;
1260 entity.shoveOffsetY = uy * maxDist * phase;
1261 if (t >= 1)
1262 { entity.shove = null; }
1263 }
1264
1265 spawnCombatSwing (payload)
1266 {
1267 const attacker = this.entities.get(payload.attackerId);
1268 const target = this.entities.get(payload.targetId);
1269 if (!attacker || !target)
1270 { return; }
1271 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1272 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1273 const tx = target.visualX + (target.stackOffsetX ?? 0);
1274 const ty = target.visualY + (target.stackOffsetY ?? 0);
1275 this.#applyShove(attacker, tx, ty);
1276 const midX = (ax + tx) / 2;
1277 const midY = (ay + ty) / 2;
1278 const sortY = Math.max(ay, ty) + 0.02;
1279 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
1280 const spriteName = "fx:melee-swipe:melee-swipe";
1281 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
1282 if (object.transform)
1283 { object.transform.rotation = angle; }
1284 this.scene.addObject(object);
1285 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
1286 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
1287 this.swipes.push({
1288 object,
1289 until: performance.now() + 500,
1290 fromTileX: payload.fromTileX,
1291 fromTileY: payload.fromTileY,
1292 tileX: payload.tileX,
1293 tileY: payload.tileY
1294 });
1295 }
1296
1297 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
1298 spawnGatherSwing (payload)
1299 {
1300 const attacker = this.entities.get(payload.attackerId);
1301 if (!attacker)
1302 { return; }
1303 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1304 this.#applyShove(attacker, pivot.x, pivot.y);
1305 if (payload.toolItemId != null)
1306 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
1307 }
1308
1309 #applyShove (entity, targetVisualX, targetVisualY)
1310 {
1311 entity.shove = {
1312 startVisualX: entity.visualX,
1313 startVisualY: entity.visualY,
1314 targetVisualX,
1315 targetVisualY,
1316 started: performance.now(),
1317 durationMs: SHOVE_MS
1318 };
1319 }
1320
1321 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
1322 spawnPhysicalProjectileFx (payload)
1323 {
1324 const spriteName = payload.sprite ?? "fx:projectile:arrow";
1325 const image = this.game.images[spriteName];
1326 if (!image)
1327 { return; }
1328 const dualTint = this.#dualTintFromPayload(payload);
1329 const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
1330 const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1331 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1332 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1333 const object = new GameObject(0, 0, image, SORT_FX);
1334 if (object.transform)
1335 { object.transform.rotation = angle; }
1336 this.scene.addObject(object);
1337 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1338 this.#applyPhysicalCombatFxDarkness(
1339 object,
1340 payload.fromTileX,
1341 payload.fromTileY,
1342 payload.tileX,
1343 payload.tileY,
1344 dualTint
1345 );
1346 const started = performance.now();
1347 const durationMs = payload.durationMs ?? 400;
1348 this.swipes.push({
1349 object,
1350 until: started + durationMs,
1351 started,
1352 durationMs,
1353 lerp: true,
1354 dualTint,
1355 fromTileX: payload.fromTileX,
1356 fromTileY: payload.fromTileY,
1357 tileX: payload.tileX,
1358 tileY: payload.tileY
1359 });
1360 }
1361
1362 /** Bloom-layer spell projectiles — unlit, animated, 2s travel. */
1363 spawnSpellProjectileFx (payload)
1364 {
1365 const baseSprite = payload.sprite ?? "fx:projectile:spell-light";
1366 const image = this.#spellProjectileImage(baseSprite, 0);
1367 if (!image)
1368 { return; }
1369 const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
1370 const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1371 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1372 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1373 const object = new GameObject(0, 0, image, SORT_FX);
1374 object.renderer.layer = RENDER_LAYER_BLOOM;
1375 this.#markUnlit(object);
1376 if (object.transform)
1377 { object.transform.rotation = angle; }
1378 this.scene.addObject(object);
1379 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1380 const started = performance.now();
1381 const durationMs = payload.durationMs ?? 2000;
1382 this.swipes.push({
1383 object,
1384 until: started + durationMs,
1385 started,
1386 durationMs,
1387 lerp: true,
1388 spellProjectile: true,
1389 baseSprite,
1390 fromTileX: payload.fromTileX,
1391 fromTileY: payload.fromTileY,
1392 tileX: payload.tileX,
1393 tileY: payload.tileY
1394 });
1395 }
1396
1397 spawnSpellFizzleFx (payload)
1398 {
1399 this.spawnSpellCastFlash({
1400 tileX: payload.tileX,
1401 tileY: payload.tileY,
1402 radiusTiles: 0.5,
1403 durationMs: 220,
1404 tier: 1
1405 });
1406 }
1407
1408 spawnSpellCastFlash (payload)
1409 {
1410 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1411 this.addDynamicLight({
1412 worldX: pivot.x,
1413 worldY: pivot.y,
1414 radiusTiles: payload.radiusTiles ?? 1,
1415 intensity: 0.55 + (payload.tier ?? 1) * 0.12,
1416 durationMs: payload.durationMs ?? 500
1417 });
1418 }
1419
1420 setSpellLight (payload)
1421 {
1422 const key = `${payload.tileX},${payload.tileY}`;
1423 this.spellLights.set(key, {
1424 tileX: payload.tileX,
1425 tileY: payload.tileY,
1426 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1427 range: payload.rangeTiles ?? 6,
1428 intensity: payload.intensity ?? 0.88
1429 });
1430 }
1431
1432 removeSpellLight (payload)
1433 {
1434 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
1435 }
1436
1437 #spellProjectileImage (baseSprite, frameIndex)
1438 {
1439 const frame = Math.max(0, Math.min(2, frameIndex | 0));
1440 const stem = baseSprite.split(":").pop() ?? "spell-light";
1441 const names = [
1442 `${baseSprite}-${frame}`,
1443 `fx:projectile:${stem}-${frame}`,
1444 baseSprite,
1445 `fx:projectile:${stem}`
1446 ];
1447 for (const name of names)
1448 {
1449 if (this.game.images[name])
1450 { return this.game.images[name]; }
1451 }
1452 return null;
1453 }
1454
1455 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
1456 {
1457 this.dynamicLights.push({
1458 tileX: Math.floor(worldX),
1459 tileY: Math.floor(worldY),
1460 range: radiusTiles,
1461 intensity,
1462 until: performance.now() + durationMs
1463 });
1464 }
1465
1466 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
1467 {
1468 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1469 if (!snapshot)
1470 { return; }
1471 const index = localY * CHUNK_SIZE + localX;
1472 if (ground !== undefined)
1473 { snapshot.grounds[index] = ground; }
1474 if (block !== undefined)
1475 { snapshot.blocks[index] = block; }
1476 if (light !== undefined)
1477 { snapshot.light[index] = light; }
1478 this.#rebuildChunk(snapshot);
1479 }
1480
1481 /**
1482 * Editor-only mob markers for authored spawners (invisible during play).
1483 * @param {number} chunkX
1484 * @param {number} chunkY
1485 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
1486 * @param {(mobTypeId: string) => string} resolveSprite
1487 */
1488 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
1489 {
1490 const prefix = `${chunkX},${chunkY}:`;
1491 for (const [key, entry] of [...this.editorSpawners.entries()])
1492 {
1493 if (!key.startsWith(prefix))
1494 { continue; }
1495 entry.object?.destroy();
1496 this.editorSpawners.delete(key);
1497 }
1498 for (const spawner of spawners ?? [])
1499 {
1500 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
1501 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
1502 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
1503 if (!spriteName)
1504 { continue; }
1505 const key = `${prefix}${spawner.localX},${spawner.localY}`;
1506 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
1507 if (!object)
1508 { continue; }
1509 object.renderer.alpha = 0.85;
1510 const pivot = tilePivot(tileX, tileY, this.tileSize());
1511 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1512 this.#markUnlit(object);
1513 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
1514 }
1515 }
1516
1517 clearEditorSpawners ()
1518 {
1519 for (const entry of this.editorSpawners.values())
1520 { entry.object?.destroy(); }
1521 this.editorSpawners.clear();
1522 }
1523
1524 #relayoutEditorSpawners ()
1525 {
1526 const size = this.tileSize();
1527 for (const entry of this.editorSpawners.values())
1528 {
1529 if (!entry.object)
1530 { continue; }
1531 const pivot = tilePivot(entry.tileX, entry.tileY, size);
1532 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1533 }
1534 }
1535
1536 /**
1537 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
1538 */
1539 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
1540 {
1541 const spawnRadius = Math.max(0, spawnRange | 0);
1542 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
1543 if (this.spawnRangeHighlight
1544 && this.wanderRangeHighlight
1545 && this.spawnRangeHighlight.tileX === tileX
1546 && this.spawnRangeHighlight.tileY === tileY
1547 && this.spawnRangeHighlight.range === spawnRadius
1548 && this.wanderRangeHighlight.range === wanderRadius)
1549 {
1550 this.#relayoutSpawnRangeHighlight();
1551 return;
1552 }
1553 this.clearSpawnRangeHighlight();
1554 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
1555 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
1556 if (wanderObject)
1557 {
1558 this.#markUnlit(wanderObject);
1559 wanderObject.renderer.alpha = 1;
1560 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
1561 }
1562 if (spawnObject)
1563 {
1564 this.#markUnlit(spawnObject);
1565 spawnObject.renderer.alpha = 1;
1566 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
1567 }
1568 this.#relayoutSpawnRangeHighlight();
1569 }
1570
1571 clearSpawnRangeHighlight ()
1572 {
1573 this.spawnRangeHighlight?.object?.destroy();
1574 this.wanderRangeHighlight?.object?.destroy();
1575 this.spawnRangeHighlight = null;
1576 this.wanderRangeHighlight = null;
1577 }
1578
1579 setSpellTargetHighlight (tileX, tileY, inRange = true)
1580 {
1581 if (
1582 this.spellTargetHighlight
1583 && this.spellTargetHighlight.tileX === tileX
1584 && this.spellTargetHighlight.tileY === tileY
1585 && this.spellTargetHighlight.inRange === inRange
1586 )
1587 {
1588 this.#relayoutSpellTargetHighlight();
1589 return;
1590 }
1591 this.clearSpellTargetHighlight();
1592 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
1593 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1594 if (!object)
1595 { return; }
1596 this.#markUnlit(object);
1597 object.renderer.alpha = 1;
1598 this.spellTargetHighlight = { object, tileX, tileY, inRange, spriteName };
1599 this.#relayoutSpellTargetHighlight();
1600 }
1601
1602 clearSpellTargetHighlight ()
1603 {
1604 this.spellTargetHighlight?.object?.destroy();
1605 this.spellTargetHighlight = null;
1606 }
1607
1608 #relayoutSpellTargetHighlight ()
1609 {
1610 const highlight = this.spellTargetHighlight;
1611 if (!highlight?.object)
1612 { return; }
1613 const size = this.tileSize();
1614 const left = highlight.tileX * size;
1615 const top = highlight.tileY * size;
1616 highlight.object.transform.position.x = left + size / 2;
1617 highlight.object.transform.position.y = top + size / 2;
1618 highlight.object.transform.size = new vector(size, size);
1619 highlight.object.layer = LAYER_EDGE - 1;
1620 this.#markSortDirty();
1621 }
1622
1623 #relayoutSpawnRangeHighlight ()
1624 {
1625 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
1626 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
1627 }
1628
1629 #layoutRangeOverlay (highlight, layer)
1630 {
1631 if (!highlight?.object)
1632 { return; }
1633 const size = this.tileSize();
1634 const side = (2 * highlight.range + 1) * size;
1635 const left = (highlight.tileX - highlight.range) * size;
1636 const top = (highlight.tileY - highlight.range) * size;
1637 highlight.object.transform.position.x = left + side / 2;
1638 highlight.object.transform.position.y = top + side / 2;
1639 highlight.object.transform.size = new vector(side, side);
1640 highlight.object.layer = layer;
1641 this.#markSortDirty();
1642 }
1643
1644 setTilePreview (tileX, tileY, override)
1645 {
1646 const previous = this.preview;
1647 this.preview = { tileX, tileY, ...override };
1648 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1649 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1650 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1651 if (snapshot)
1652 { this.#rebuildChunk(snapshot); }
1653 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1654 {
1655 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1656 if (prevSnapshot && prevSnapshot !== snapshot)
1657 { this.#rebuildChunk(prevSnapshot); }
1658 }
1659 }
1660
1661 clearTilePreview ()
1662 {
1663 const previous = this.preview;
1664 this.preview = null;
1665 if (previous)
1666 {
1667 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1668 if (snapshot)
1669 { this.#rebuildChunk(snapshot); }
1670 }
1671 }
1672
1673 #lerpMs (gait)
1674 {
1675 const walk = this.settings.walkTilesPerSecond || 2;
1676 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
1677 return seconds * 1000;
1678 }
1679
1680 #centerCamera ()
1681 {
1682 if (!this.followPlayer)
1683 { return; }
1684 const local = this.entities.get(this.localEntityId);
1685 if (!local)
1686 { return; }
1687 const x = local.visualX + (local.stackOffsetX ?? 0);
1688 const y = local.visualY + (local.stackOffsetY ?? 0);
1689 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
1690 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
1691 }
1692
1693 /**
1694 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
1695 * Tiles fully outside this rect are not drawn.
1696 */
1697 #drawBounds ()
1698 {
1699 const pad = this.tileSize() * 0.5;
1700 const camX = this.scene.cameraPosition.x;
1701 const camY = this.scene.cameraPosition.y;
1702 const w = this.scene.real_size.x;
1703 const h = this.scene.real_size.y;
1704 return {
1705 left: -camX - pad,
1706 right: -camX + w + pad,
1707 top: -camY - pad,
1708 bottom: -camY + h + pad
1709 };
1710 }
1711
1712 #rectIntersects (left, top, right, bottom, bounds)
1713 {
1714 return right >= bounds.left
1715 && left <= bounds.right
1716 && bottom >= bounds.top
1717 && top <= bounds.bottom;
1718 }
1719
1720 #setRendererVisible (object, visible)
1721 {
1722 if (object?.renderer)
1723 { object.renderer.visible = !!visible; }
1724 }
1725
1726 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
1727 #cullOffscreenDrawables ()
1728 {
1729 const bounds = this.#drawBounds();
1730 const size = this.tileSize();
1731
1732 for (const baked of this.bakedChunks.values())
1733 {
1734 const left = baked.chunkX * CHUNK_SIZE * size;
1735 const top = baked.chunkY * CHUNK_SIZE * size;
1736 const chunkPx = CHUNK_SIZE * size;
1737 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
1738 this.#setRendererVisible(baked.groundObject, chunkVisible);
1739 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
1740 baked._inViewport = chunkVisible;
1741 for (let row = 0; row < CHUNK_SIZE; row++)
1742 {
1743 const rowTop = top + row * size;
1744 const rowVisible = chunkVisible && this.#rectIntersects(
1745 left, rowTop, left + chunkPx, rowTop + size, bounds
1746 );
1747 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
1748 }
1749 }
1750
1751 for (const objects of this.tiles.values())
1752 {
1753 const left = objects.tileX * size;
1754 const top = objects.tileY * size;
1755 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
1756 objects._inViewport = visible;
1757 this.#setRendererVisible(objects.ground, visible);
1758 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
1759 this.#setRendererVisible(objects.block, visible);
1760 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
1761 if (objects.waterEdges)
1762 {
1763 for (const edge of Object.values(objects.waterEdges))
1764 { this.#setRendererVisible(edge, visible); }
1765 }
1766 }
1767 }
1768
1769 #upsertEntity (payload)
1770 {
1771 const size = this.tileSize();
1772 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1773 let entity = this.entities.get(payload.entityId);
1774 if (!entity)
1775 {
1776 const spriteName = payload.layers?.[0]?.sprite
1777 ?? payload.sprite
1778 ?? bodySpriteName(payload.sex);
1779 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
1780 this.scene.addObject(object);
1781 this.#startIdleAnimation(object);
1782 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
1783 this.entities.set(payload.entityId, entity);
1784 }
1785 entity.entityId = payload.entityId;
1786 entity.tileX = payload.tileX;
1787 entity.tileY = payload.tileY;
1788 entity.gait = payload.gait;
1789 entity.sex = payload.sex ?? entity.sex;
1790 entity.characterId = payload.characterId ?? entity.characterId ?? null;
1791 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1792 if (payload.level != null)
1793 { entity.level = payload.level | 0; }
1794 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
1795 entity.canFight = payload.canFight != null
1796 ? !!payload.canFight
1797 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1798 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1799 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
1800 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1801 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1802 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
1803 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1804 if (payload.visualScale != null)
1805 { entity.visualScale = Number(payload.visualScale) || 1; }
1806 else if (entity.visualScale == null)
1807 { entity.visualScale = 1; }
1808 if (payload.health != null)
1809 { entity.health = payload.health; }
1810 if (payload.maxHealth != null)
1811 { entity.maxHealth = payload.maxHealth; }
1812 if (payload.firstName)
1813 { entity.firstName = payload.firstName; }
1814 if (payload.lastName)
1815 { entity.lastName = payload.lastName; }
1816 entity.firstName = entity.firstName ?? "";
1817 entity.lastName = entity.lastName ?? "";
1818 if (payload.worldX != null && payload.worldY != null)
1819 {
1820 entity.worldX = payload.worldX;
1821 entity.worldY = payload.worldY;
1822 entity.visualX = payload.worldX * size;
1823 entity.visualY = payload.worldY * size;
1824 entity.targetX = entity.visualX;
1825 entity.targetY = entity.visualY;
1826 }
1827 else
1828 {
1829 entity.visualX = pivot.x;
1830 entity.visualY = pivot.y;
1831 entity.targetX = pivot.x;
1832 entity.targetY = pivot.y;
1833 }
1834 entity.fromX = entity.visualX;
1835 entity.fromY = entity.visualY;
1836 if (payload.layers)
1837 { this.#applyLayers(entity, payload.layers); }
1838 this.#syncHpBar(entity);
1839 this.#placeEntity(entity, performance.now());
1840 }
1841
1842 #applyLayers (entity, layers)
1843 {
1844 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
1845 this.#rebuildOverlays(entity);
1846 }
1847
1848 #setGatherToolOverlay (entity, toolItemId)
1849 {
1850 entity.gatherToolItemId = toolItemId;
1851 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
1852 this.#rebuildOverlays(entity);
1853 this.#placeEntity(entity, performance.now());
1854 }
1855
1856 #expireGatherToolOverlay (entity, now)
1857 {
1858 if (entity.gatherToolItemId == null)
1859 { return; }
1860 if ((entity.gatherToolUntil ?? 0) > now)
1861 { return; }
1862 entity.gatherToolItemId = null;
1863 entity.gatherToolUntil = 0;
1864 this.#rebuildOverlays(entity);
1865 }
1866
1867 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
1868 #layersForDisplay (entity)
1869 {
1870 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
1871 const toolId = entity.gatherToolItemId;
1872 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
1873 { return layers; }
1874 const equip = itemEquipSprite(toolId);
1875 if (!equip || !this.game.images[equip])
1876 { return layers; }
1877 const replacement = {
1878 sprite: equip,
1879 itemId: toolId,
1880 tint: resolveEquipTint(toolId)
1881 };
1882 for (let index = layers.length - 1; index >= 1; index--)
1883 {
1884 const def = itemDefinition(layers[index].itemId);
1885 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
1886 {
1887 layers[index] = replacement;
1888 return layers;
1889 }
1890 }
1891 layers.push(replacement);
1892 return layers;
1893 }
1894
1895 #rebuildOverlays (entity)
1896 {
1897 const layers = this.#layersForDisplay(entity);
1898 const base = layers[0]?.sprite
1899 ?? bodySpriteName(entity.sex);
1900 if (this.game.images[base])
1901 {
1902 entity.object.renderer.sprite = this.game.images[base];
1903 this.#startIdleAnimation(entity.object);
1904 }
1905 for (const overlay of entity.overlays ?? [])
1906 { overlay.destroy(); }
1907 for (const overlay of entity.bloomOverlays ?? [])
1908 { overlay.destroy(); }
1909 entity.overlays = [];
1910 entity.overlayTints = [];
1911 entity.overlayTightFit = [];
1912 entity.bloomOverlays = [];
1913 for (const layer of layers.slice(1))
1914 {
1915 const image = this.game.images[layer.sprite];
1916 if (!image)
1917 { continue; }
1918 const object = new GameObject(0, 0, image, SORT_ENTITY);
1919 this.scene.addObject(object);
1920 entity.overlays.push(object);
1921 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
1922 entity.overlayTightFit.push(!!layerDef?.tightFit);
1923 entity.overlayTints.push(
1924 layer.tint
1925 ? normalizeRgb(layer.tint)
1926 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
1927 );
1928 const bloomName = bloomCompanionName(layer.sprite);
1929 const bloomImage = this.game.images[bloomName];
1930 if (!bloomImage)
1931 { continue; }
1932 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
1933 bloom.renderer.layer = RENDER_LAYER_BLOOM;
1934 this.#markUnlit(bloom);
1935 this.scene.addObject(bloom);
1936 entity.bloomOverlays.push(bloom);
1937 }
1938 }
1939
1940 #placeEntity (entity, now = performance.now())
1941 {
1942 const zoom = this.zoom;
1943 const offsetX = entity.shoveOffsetX ?? 0;
1944 const offsetY = entity.shoveOffsetY ?? 0;
1945 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
1946 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
1947 let walkTilt = 0;
1948 if (entity.lerpStarted != null)
1949 {
1950 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
1951 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
1952 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
1953 walkTilt = Math.sin(cycles) * tilt;
1954 }
1955 const flashStrength = (entity.damageFlashUntil ?? 0) > now
1956 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
1957 : 0;
1958 const tileShade = this.#entityShadeAlpha(entity, now);
1959 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
1960
1961 entity.object.transform.rotation = walkTilt;
1962 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
1963 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1);
1964 for (let index = 0; index < (entity.overlays ?? []).length; index++)
1965 {
1966 const overlay = entity.overlays[index];
1967 const overlaySortY = pivotY + 0.5 * (index + 1);
1968 overlay.transform.rotation = walkTilt;
1969 if (entity.overlayTightFit?.[index])
1970 {
1971 this.#syncTightFitLitSprite(
1972 overlay,
1973 entity,
1974 tileShade,
1975 flashStrength,
1976 wade,
1977 entity.overlayTints?.[index] ?? null
1978 );
1979 }
1980 else
1981 {
1982 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
1983 }
1984 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
1985 }
1986 for (const overlay of entity.bloomOverlays ?? [])
1987 {
1988 this.#setRendererVisible(overlay, this.bloomEnabled);
1989 if (!this.bloomEnabled)
1990 { continue; }
1991 overlay.transform.rotation = walkTilt;
1992 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1993 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
1994 }
1995 this.#placeHpBar(entity, pivotX, pivotY);
1996 }
1997
1998 #markUnlit (object)
1999 {
2000 if (!object?.renderer)
2001 { return; }
2002 object._lit = false;
2003 object.renderer.shader = null;
2004 object.renderer.shaderUniforms = null;
2005 object.renderer.secondaryMap = null;
2006 }
2007
2008 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
2009 {
2010 if (!object?.renderer || object._lit === false)
2011 { return; }
2012 object._lit = true;
2013 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2014 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2015 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2016 const tint = tintColor ? normalizeRgb(tintColor) : null;
2017 if (tint)
2018 {
2019 object.renderer.shader = getTintLitSpriteShader();
2020 object.renderer.shaderUniforms = {
2021 u_darkness: dark,
2022 u_strength: flash,
2023 u_wade: wade ? 1 : 0,
2024 u_spriteHeight: height,
2025 u_useTint: 1,
2026 u_tintColor: [tint.r, tint.g, tint.b]
2027 };
2028 }
2029 else
2030 {
2031 object.renderer.shader = getSpriteLightingShader();
2032 object.renderer.shaderUniforms = {
2033 u_darkness: dark,
2034 u_strength: flash,
2035 u_wade: wade ? 1 : 0,
2036 u_spriteHeight: height
2037 };
2038 }
2039 object.renderer.secondaryMap = null;
2040 }
2041
2042 #bodySecondaryMap (entity)
2043 {
2044 return entity?.object?.renderer?.sprite?.g_image ?? null;
2045 }
2046
2047 #tightFitMaskUniforms (overlay, entity)
2048 {
2049 const bodyRenderer = entity?.object?.renderer;
2050 const clothRenderer = overlay?.renderer;
2051 const bodySprite = bodyRenderer?.sprite;
2052 const clothSprite = clothRenderer?.sprite;
2053 if (!bodySprite || !clothSprite)
2054 { return null; }
2055 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
2056 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2057 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
2058 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2059 return {
2060 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
2061 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
2062 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
2063 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
2064 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
2065 };
2066 }
2067
2068 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null)
2069 {
2070 if (!overlay?.renderer || entity?.object?.renderer == null)
2071 { return; }
2072 const bodyMap = this.#bodySecondaryMap(entity);
2073 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
2074 if (!bodyMap || !maskUniforms)
2075 {
2076 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor);
2077 return;
2078 }
2079 overlay._lit = true;
2080 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2081 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2082 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2083 const tint = tintColor ? normalizeRgb(tintColor) : null;
2084 overlay.renderer.secondaryMap = bodyMap;
2085 if (tint)
2086 {
2087 overlay.renderer.shader = getTightFitTintLitSpriteShader();
2088 overlay.renderer.shaderUniforms = {
2089 u_darkness: dark,
2090 u_strength: flash,
2091 u_wade: wade ? 1 : 0,
2092 u_spriteHeight: height,
2093 u_useTint: 1,
2094 u_tintColor: [tint.r, tint.g, tint.b],
2095 ...maskUniforms
2096 };
2097 }
2098 else
2099 {
2100 overlay.renderer.shader = getTightFitLitSpriteShader();
2101 overlay.renderer.shaderUniforms = {
2102 u_darkness: dark,
2103 u_strength: flash,
2104 u_wade: wade ? 1 : 0,
2105 u_spriteHeight: height,
2106 ...maskUniforms
2107 };
2108 }
2109 }
2110
2111 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false)
2112 {
2113 if (!object?.renderer || object._lit === false || !dualTint)
2114 { return; }
2115 object._lit = true;
2116 const shaft = normalizeRgb(dualTint.shaft);
2117 const tip = normalizeRgb(dualTint.tip);
2118 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2119 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2120 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2121 object.renderer.shader = getDualTintLitSpriteShader();
2122 object.renderer.shaderUniforms = {
2123 u_darkness: dark,
2124 u_strength: flash,
2125 u_wade: wade ? 1 : 0,
2126 u_spriteHeight: height,
2127 u_shaftTint: [shaft.r, shaft.g, shaft.b],
2128 u_tipTint: [tip.r, tip.g, tip.b]
2129 };
2130 object.renderer.secondaryMap = null;
2131 }
2132
2133 #syncGroundItemSprite (item, darkness)
2134 {
2135 if (item?.dualTint)
2136 {
2137 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
2138 return;
2139 }
2140 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
2141 }
2142
2143 #groundTypeAt (tileX, tileY)
2144 {
2145 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2146 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2147 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2148 if (!snapshot)
2149 { return null; }
2150 const localX = tileX - chunkX * CHUNK_SIZE;
2151 const localY = tileY - chunkY * CHUNK_SIZE;
2152 const index = localY * CHUNK_SIZE + localX;
2153 return normalizeGround(snapshot.grounds?.[index]).typeId;
2154 }
2155
2156 #waterCoastEdges (tileX, tileY)
2157 {
2158 const season = this.worldSeason;
2159 return {
2160 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
2161 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
2162 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
2163 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
2164 };
2165 }
2166
2167 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
2168 {
2169 if (!object?.renderer)
2170 { return; }
2171 const lit = corners ?? {
2172 nw: fallbackLit,
2173 ne: fallbackLit,
2174 sw: fallbackLit,
2175 se: fallbackLit
2176 };
2177 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
2178 object._lit = true;
2179 object.renderer.shader = getWaterGroundShader();
2180 object.renderer.secondaryMap = null;
2181 object.renderer.shaderUniforms = {
2182 u_ambientDark: dark,
2183 u_litNW: lit.nw,
2184 u_litNE: lit.ne,
2185 u_litSW: lit.sw,
2186 u_litSE: lit.se,
2187 u_time: timeSec,
2188 u_edgeN: edges?.n ?? 0,
2189 u_edgeE: edges?.e ?? 0,
2190 u_edgeS: edges?.s ?? 0,
2191 u_edgeW: edges?.w ?? 0
2192 };
2193 }
2194
2195 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
2196 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
2197 {
2198 if (!objects?.ground)
2199 { return; }
2200 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
2201 {
2202 objects.waterEdges = null;
2203 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
2204 return;
2205 }
2206 const fallbackLit = ambientDark > 0
2207 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
2208 : 1;
2209 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
2210 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
2211 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
2212 const localX = objects.tileX - chunkX * CHUNK_SIZE;
2213 const localY = objects.tileY - chunkY * CHUNK_SIZE;
2214 let litCorners = null;
2215 if (chunkBaked)
2216 {
2217 if (this.lightingMode === "simple")
2218 {
2219 const gridW = CHUNK_SIZE + 2;
2220 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
2221 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
2222 }
2223 else
2224 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
2225 }
2226 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
2227 this.#syncWaterGroundSprite(
2228 objects.ground,
2229 litCorners,
2230 ambientDark,
2231 objects.waterEdges,
2232 timeSec,
2233 fallbackLit
2234 );
2235 }
2236
2237 #ambientDarkness ()
2238 {
2239 const hour = this.nightPreview ?? this.worldHour;
2240 const calendar = nightFactor(hour, this.settings.nightDarkness);
2241 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
2242 if (dark == null)
2243 { dark = calendar; }
2244 if (this.localBlind)
2245 { dark = Math.min(1, dark + 0.85); }
2246 return dark;
2247 }
2248
2249 setLocalBlind (blind)
2250 {
2251 this.localBlind = !!blind;
2252 }
2253
2254 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
2255 #blindVisionLight ()
2256 {
2257 if (!this.localBlind)
2258 { return null; }
2259 const local = this.entities.get(this.localEntityId);
2260 if (!local)
2261 { return null; }
2262 const tileSize = this.tileSize();
2263 return {
2264 tileX: Math.floor(local.visualX / tileSize),
2265 tileY: Math.floor(local.visualY / tileSize),
2266 range: 2.25,
2267 intensity: 1
2268 };
2269 }
2270
2271 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
2272 {
2273 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
2274 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
2275 const dark = (fromAlpha + toAlpha) / 2;
2276 if (dualTint)
2277 {
2278 this.#syncDualTintLitSprite(object, dark, dualTint);
2279 return;
2280 }
2281 this.#syncLitSprite(object, dark);
2282 }
2283
2284 #dualTintFromPayload (payload)
2285 {
2286 if (!payload?.shaftTint || !payload?.tipTint)
2287 { return null; }
2288 return { shaft: payload.shaftTint, tip: payload.tipTint };
2289 }
2290
2291 #syncHpBar (entity)
2292 {
2293 const current = entity.health;
2294 const max = entity.maxHealth;
2295 const show = current != null
2296 && max != null
2297 && max > 0
2298 && current < max;
2299 if (!show)
2300 {
2301 entity.hpBar?.destroy();
2302 entity.hpBar = null;
2303 entity.hpBarCanvas = null;
2304 return;
2305 }
2306 if (!entity.hpBarCanvas)
2307 {
2308 entity.hpBarCanvas = document.createElement("canvas");
2309 entity.hpBarCanvas.width = HP_BAR_W;
2310 entity.hpBarCanvas.height = HP_BAR_H;
2311 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
2312 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
2313 this.#markUnlit(entity.hpBar);
2314 this.scene.addObject(entity.hpBar);
2315 }
2316 drawHpBar(entity.hpBarCanvas, current, max);
2317 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
2318 }
2319
2320 #placeHpBar (entity, pivotX, pivotY)
2321 {
2322 if (!entity.hpBar)
2323 { return; }
2324 const sprite = entity.object?.renderer?.sprite;
2325 if (!sprite)
2326 { return; }
2327 const zoom = this.zoom;
2328 const drawH = sprite.height * zoom;
2329 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
2330 const spriteTop = centerY - drawH / 2;
2331 const barW = HP_BAR_W * zoom;
2332 const barH = HP_BAR_H * zoom;
2333 entity.hpBar.transform.position.x = pivotX;
2334 entity.hpBar.transform.position.y = spriteTop - barH / 2;
2335 entity.hpBar.transform.size = new vector(barW, barH);
2336 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
2337 this.#markSortDirty();
2338 }
2339
2340 #rebuildChunk (snapshot)
2341 {
2342 this.#bakeAndPlaceChunk(snapshot);
2343 const tall = new Set(
2344 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
2345 .map((entry) => `${entry.tileX},${entry.tileY}`)
2346 );
2347 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2348 {
2349 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2350 {
2351 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
2352 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
2353 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
2354 }
2355 }
2356 }
2357
2358 #rebakeAllChunks ()
2359 {
2360 for (const snapshot of this.chunks.values())
2361 { this.#rebuildChunk(snapshot); }
2362 }
2363
2364 #bakeAndPlaceChunk (snapshot)
2365 {
2366 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2367 const atlases = bakeChunkAtlases({
2368 snapshot,
2369 catalog: this.catalog,
2370 images: this.game.images,
2371 preview: this.preview,
2372 season: this.worldSeason
2373 });
2374 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2375 let baked = this.bakedChunks.get(key);
2376 if (!baked)
2377 {
2378 const lightmapCanvas = makeLightmapCanvas(atlasPx);
2379 baked = {
2380 groundCanvas: atlases.ground,
2381 blockCanvases: atlases.blockRows,
2382 bloomCanvas: atlases.bloom,
2383 lightmapCanvas,
2384 groundImage: frameworkImageFromCanvas(atlases.ground),
2385 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
2386 bloomImage: frameworkImageFromCanvas(atlases.bloom),
2387 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
2388 groundObject: null,
2389 blockObjects: [],
2390 bloomObject: null,
2391 tallBlocks: atlases.tallBlocks,
2392 animatedGrounds: atlases.animatedGrounds,
2393 lightmapPixels: null
2394 };
2395 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
2396 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
2397 this.scene.addObject(baked.groundObject);
2398 for (let row = 0; row < CHUNK_SIZE; row++)
2399 {
2400 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
2401 this.#applyAtlasLighting(object, baked.lightmapImage, row);
2402 this.scene.addObject(object);
2403 baked.blockObjects.push(object);
2404 }
2405 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
2406 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
2407 this.#markUnlit(baked.bloomObject);
2408 this.scene.addObject(baked.bloomObject);
2409 this.bakedChunks.set(key, baked);
2410 }
2411 else
2412 {
2413 copyCanvas(atlases.ground, baked.groundCanvas);
2414 for (let row = 0; row < CHUNK_SIZE; row++)
2415 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
2416 copyCanvas(atlases.bloom, baked.bloomCanvas);
2417 invalidateCanvasTexture(this.scene, baked.groundCanvas);
2418 for (const canvas of baked.blockCanvases)
2419 { invalidateCanvasTexture(this.scene, canvas); }
2420 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
2421 baked.tallBlocks = atlases.tallBlocks;
2422 baked.animatedGrounds = atlases.animatedGrounds;
2423 }
2424 baked.chunkX = snapshot.chunkX;
2425 baked.chunkY = snapshot.chunkY;
2426 this.#layoutBakedChunk(snapshot);
2427 }
2428
2429 #applyAtlasLighting (object, lightmapImage, lightRow)
2430 {
2431 if (!object?.renderer)
2432 { return; }
2433 object._lit = true;
2434 object.renderer.shader = getAtlasLightingShader();
2435 object.renderer.secondaryMap = lightmapImage;
2436 object.renderer.shaderUniforms = {
2437 u_ambientDark: 0,
2438 u_lightRow: lightRow
2439 };
2440 }
2441
2442 #layoutBakedChunk (snapshot)
2443 {
2444 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2445 const baked = this.bakedChunks.get(key);
2446 if (!baked)
2447 { return; }
2448 const size = this.tileSize();
2449 const left = snapshot.chunkX * CHUNK_SIZE * size;
2450 const top = snapshot.chunkY * CHUNK_SIZE * size;
2451 const chunkPx = CHUNK_SIZE * size;
2452 baked.groundObject.transform.position.x = left + chunkPx / 2;
2453 baked.groundObject.transform.position.y = top + chunkPx / 2;
2454 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
2455 baked.groundObject.layer = LAYER_GROUND;
2456
2457 for (let row = 0; row < CHUNK_SIZE; row++)
2458 {
2459 const object = baked.blockObjects[row];
2460 const rowY = top + row * size + size / 2;
2461 object.transform.position.x = left + chunkPx / 2;
2462 object.transform.position.y = rowY;
2463 object.transform.size = new vector(chunkPx, size);
2464 object.layer = ySortLayer(rowY, SORT_BLOCK);
2465 }
2466
2467 baked.bloomObject.transform.position.x = left + chunkPx / 2;
2468 baked.bloomObject.transform.position.y = top + chunkPx / 2;
2469 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
2470 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
2471 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
2472 this.#markSortDirty();
2473 setNearestFilter(this.scene, baked.groundCanvas);
2474 for (const canvas of baked.blockCanvases)
2475 { setNearestFilter(this.scene, canvas); }
2476 setNearestFilter(this.scene, baked.bloomCanvas);
2477 setNearestFilter(this.scene, baked.lightmapCanvas);
2478 }
2479
2480 #destroyBakedChunk (key)
2481 {
2482 const baked = this.bakedChunks.get(key);
2483 if (!baked)
2484 { return; }
2485 baked.groundObject?.destroy();
2486 for (const object of baked.blockObjects ?? [])
2487 { object.destroy(); }
2488 baked.bloomObject?.destroy();
2489 invalidateCanvasTexture(this.scene, baked.groundCanvas);
2490 for (const canvas of baked.blockCanvases ?? [])
2491 { invalidateCanvasTexture(this.scene, canvas); }
2492 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
2493 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
2494 this.bakedChunks.delete(key);
2495 }
2496
2497 #redrawPreview ()
2498 {
2499 if (!this.preview)
2500 { return; }
2501 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
2502 if (snapshot)
2503 { this.#rebuildChunk(snapshot); }
2504 }
2505
2506 #refreshWaterCoastsNear (chunkX, chunkY)
2507 {
2508 const timeSec = performance.now() / 1000;
2509 for (const objects of this.tiles.values())
2510 {
2511 if (!objects.ground || !isWaterGround(objects.groundTypeId))
2512 { continue; }
2513 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
2514 { continue; }
2515 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
2516 }
2517 }
2518
2519 #drawTile (tileX, tileY, forceTall = null)
2520 {
2521 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2522 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2523 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2524 if (!snapshot)
2525 { return; }
2526 const localX = tileX - chunkX * CHUNK_SIZE;
2527 const localY = tileY - chunkY * CHUNK_SIZE;
2528 const index = localY * CHUNK_SIZE + localX;
2529 const key = `${tileX},${tileY}`;
2530 let objects = this.tiles.get(key);
2531 if (!objects)
2532 {
2533 objects = { chunkX, chunkY, tileX, tileY };
2534 this.tiles.set(key, objects);
2535 }
2536 objects.tileX = tileX;
2537 objects.tileY = tileY;
2538 objects.chunkX = chunkX;
2539 objects.chunkY = chunkY;
2540 objects.light = snapshot.light[index] ?? 0;
2541
2542 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
2543 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
2544 if (animatedGround)
2545 {
2546 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
2547 if (objects.ground)
2548 {
2549 const size = this.tileSize();
2550 objects.ground.transform.position.x = tileX * size + size / 2;
2551 objects.ground.transform.position.y = tileY * size + size / 2;
2552 objects.ground.transform.size = new vector(size, size);
2553 objects.ground.layer = LAYER_GROUND;
2554 objects.groundTypeId = animatedGround.typeId;
2555 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
2556 this.#markSortDirty();
2557 }
2558 if (animatedGround.bloom)
2559 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
2560 else
2561 {
2562 objects.groundBloom?.destroy();
2563 objects.groundBloom = null;
2564 }
2565 }
2566 else
2567 {
2568 objects.ground?.destroy();
2569 objects.ground = null;
2570 objects.groundBloom?.destroy();
2571 objects.groundBloom = null;
2572 objects.groundTypeId = null;
2573 objects.waterEdges = null;
2574 }
2575
2576 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
2577 const isTall = forceTall === true || !!tallEntry;
2578 if (isTall && tallEntry)
2579 {
2580 const pivot = tilePivot(tileX, tileY, this.tileSize());
2581 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
2582 if (objects.block)
2583 {
2584 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
2585 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
2586 }
2587 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
2588 }
2589 else
2590 {
2591 objects.block?.destroy();
2592 objects.block = null;
2593 objects.blockBloom?.destroy();
2594 objects.blockBloom = null;
2595 }
2596 }
2597
2598 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
2599 {
2600 if (!name)
2601 {
2602 existing?.destroy();
2603 return null;
2604 }
2605 const object = this.#ensureSprite(existing, name, sortOrder);
2606 if (!object)
2607 { return null; }
2608 object.renderer.layer = RENDER_LAYER_BLOOM;
2609 this.#markUnlit(object);
2610 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
2611 return object;
2612 }
2613
2614 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
2615 {
2616 const sprite = object?.renderer?.sprite;
2617 if (!sprite)
2618 { return; }
2619 const zoom = this.zoom;
2620 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
2621 const factor = Math.max(0.1, Number(scale) || 1);
2622 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
2623 object.transform.position.x = center.x;
2624 object.transform.position.y = center.y;
2625 object.transform.size = new vector(draw.w * factor, draw.h * factor);
2626 object.layer = ySortLayer(sortY, subOrder);
2627 this.#markSortDirty();
2628 }
2629
2630 #ensureSprite (existing, name, layer)
2631 {
2632 const sprite = this.game.images[name];
2633 if (!sprite)
2634 {
2635 existing?.destroy();
2636 return null;
2637 }
2638 if (!existing || existing.renderer.sprite !== sprite)
2639 {
2640 existing?.destroy();
2641 existing = new GameObject(0, 0, sprite, layer);
2642 this.#syncLitSprite(existing, 0);
2643 this.scene.addObject(existing);
2644 this.#startIdleAnimation(existing);
2645 }
2646 return existing;
2647 }
2648
2649 #startIdleAnimation (object)
2650 {
2651 const sprite = object?.renderer?.sprite;
2652 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
2653 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
2654 }
2655
2656 #neighborClosed (snapshot, dir, dx, dy)
2657 {
2658 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
2659 if (other)
2660 { return !other.open; }
2661 return !!snapshot.closedEdges?.[dir];
2662 }
2663
2664 #rebuildAllEdges ()
2665 {
2666 const seen = new Set();
2667 for (const snapshot of this.chunks.values())
2668 {
2669 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2670 seen.add(key);
2671 this.#rebuildChunkEdges(snapshot);
2672 }
2673 for (const key of [...this.edges.keys()])
2674 {
2675 if (!seen.has(key))
2676 { this.#destroyEdges(key); }
2677 }
2678 }
2679
2680 #rebuildChunkEdges (snapshot)
2681 {
2682 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2683 let bars = this.edges.get(key);
2684 if (!bars)
2685 {
2686 bars = {};
2687 this.edges.set(key, bars);
2688 }
2689
2690 const size = this.tileSize();
2691 const chunkPx = CHUNK_SIZE * size;
2692 const left = snapshot.chunkX * CHUNK_SIZE * size;
2693 const top = snapshot.chunkY * CHUNK_SIZE * size;
2694 const centerX = left + chunkPx / 2;
2695 const centerY = top + chunkPx / 2;
2696 const thickness = Math.max(2, Math.round(2 * this.zoom));
2697 const draw = snapshot.open === true;
2698
2699 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
2700 centerX, top, chunkPx, thickness, true);
2701 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
2702 centerX, top + chunkPx, chunkPx, thickness, true);
2703 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
2704 left, centerY, chunkPx, thickness, false);
2705 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
2706 left + chunkPx, centerY, chunkPx, thickness, false);
2707 }
2708
2709 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
2710 {
2711 if (!visible)
2712 {
2713 if (existing)
2714 { existing.renderer.visible = false; }
2715 return existing;
2716 }
2717
2718 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
2719 this.#markUnlit(existing);
2720 existing.renderer.visible = true;
2721 existing.transform.position.x = x;
2722 existing.transform.position.y = y;
2723 existing.transform.size = horizontal
2724 ? new vector(length, thickness)
2725 : new vector(thickness, length);
2726 existing.layer = LAYER_EDGE;
2727 this.#markSortDirty();
2728 return existing;
2729 }
2730
2731 #destroyEdges (key)
2732 {
2733 const bars = this.edges.get(key);
2734 if (!bars)
2735 { return; }
2736 bars.north?.destroy();
2737 bars.east?.destroy();
2738 bars.south?.destroy();
2739 bars.west?.destroy();
2740 this.edges.delete(key);
2741 }
2742
2743 #entityShadeAlpha (entity, now)
2744 {
2745 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
2746 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
2747 { return toAlpha; }
2748 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
2749 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
2750 return fromAlpha + (toAlpha - fromAlpha) * t;
2751 }
2752
2753 #markSortDirty ()
2754 {
2755 this.scene._sortDirty = true;
2756 }
2757
2758 #updateShade ()
2759 {
2760 const ambientDark = this.#ambientDarkness();
2761 const now = performance.now();
2762 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
2763
2764 const activeLights = [...this.dynamicLights];
2765 for (const light of this.spellLights.values())
2766 {
2767 if (light.until <= now)
2768 { continue; }
2769 activeLights.push({
2770 tileX: light.tileX,
2771 tileY: light.tileY,
2772 range: light.range,
2773 intensity: light.intensity
2774 });
2775 }
2776 for (const key of [...this.spellLights.keys()])
2777 {
2778 if (this.spellLights.get(key).until <= now)
2779 { this.spellLights.delete(key); }
2780 }
2781 const tileSize = this.tileSize();
2782 const blindLight = this.#blindVisionLight();
2783 if (blindLight)
2784 { activeLights.push(blindLight); }
2785 for (const entity of this.entities.values())
2786 {
2787 const range = entity.lightRadiusTiles ?? 0;
2788 if (range <= 0)
2789 { continue; }
2790 activeLights.push({
2791 tileX: Math.floor(entity.visualX / tileSize),
2792 tileY: Math.floor(entity.visualY / tileSize),
2793 range,
2794 intensity: 1
2795 });
2796 }
2797
2798 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
2799
2800 for (const objects of this.tiles.values())
2801 {
2802 if (objects._inViewport === false)
2803 { continue; }
2804 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
2805 objects.shadeAlpha = ambientDark * (1 - intensity);
2806 }
2807
2808 for (const baked of this.bakedChunks.values())
2809 {
2810 if (baked._inViewport === false)
2811 { continue; }
2812 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
2813 if (baked.groundObject?.renderer?.shaderUniforms)
2814 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
2815 for (const object of baked.blockObjects ?? [])
2816 {
2817 if (object?.renderer?.shaderUniforms)
2818 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
2819 }
2820 }
2821
2822 const timeSec = now / 1000;
2823 for (const objects of this.tiles.values())
2824 {
2825 if (objects._inViewport === false)
2826 { continue; }
2827 if (objects.block)
2828 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
2829 if (objects.ground && isWaterGround(objects.groundTypeId))
2830 {
2831 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
2832 this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked);
2833 }
2834 else if (objects.ground)
2835 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
2836 }
2837
2838 for (const item of this.groundItems.values())
2839 {
2840 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
2841 this.#syncGroundItemSprite(item, alpha);
2842 }
2843 }
2844
2845 #tileLightIntensity (objects, activeLights, lightOcclusion)
2846 {
2847 const baked = lightIntensity(objects.light ?? 0);
2848 const dynamic = dynamicLightAtTile(
2849 objects.tileX,
2850 objects.tileY,
2851 activeLights,
2852 lightOcclusion
2853 );
2854 return Math.max(baked, dynamic);
2855 }
2856
2857 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
2858 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
2859 {
2860 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
2861 if (tileObjects)
2862 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
2863 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2864 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2865 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2866 if (!snapshot)
2867 { return 0; }
2868 const localX = tileX - chunkX * CHUNK_SIZE;
2869 const localY = tileY - chunkY * CHUNK_SIZE;
2870 const index = localY * CHUNK_SIZE + localX;
2871 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
2872 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
2873 return Math.max(bakedLit, dynamic);
2874 }
2875
2876 /** True when ground or block on this tile occludes light rays (same rules as bake). */
2877 #tileOccludesLight (tileX, tileY)
2878 {
2879 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2880 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2881 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2882 if (!snapshot)
2883 { return false; }
2884 const localX = tileX - chunkX * CHUNK_SIZE;
2885 const localY = tileY - chunkY * CHUNK_SIZE;
2886 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
2887 { return false; }
2888 const index = localY * CHUNK_SIZE + localX;
2889 const ground = normalizeGround(snapshot.grounds?.[index]);
2890 if (!isGroundPassable(ground.typeId))
2891 { return true; }
2892 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
2893 }
2894
2895 #fillChunkLightGrids (baked, activeLights, lightOcclusion)
2896 {
2897 const gridW = CHUNK_SIZE + 2;
2898 const gridSize = gridW * gridW;
2899 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
2900 { baked.lightIntensityGrid = new Float32Array(gridSize); }
2901 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
2902 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
2903 const grid = baked.lightIntensityGrid;
2904 const occlude = baked.lightOccludeGrid;
2905 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
2906 {
2907 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
2908 {
2909 const tileX = baked.chunkX * CHUNK_SIZE + lx;
2910 const tileY = baked.chunkY * CHUNK_SIZE + ly;
2911 const gi = (ly + 1) * gridW + (lx + 1);
2912 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
2913 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
2914 }
2915 }
2916 return { grid, occlude, gridW };
2917 }
2918
2919 #makeLightCornerSampler (grid, occlude, gridW)
2920 {
2921 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
2922 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
2923 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
2924 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
2925 {
2926 const home = sample(homeLx, homeLy);
2927 if (blocks(homeLx, homeLy))
2928 { return home; }
2929 let sum = home;
2930 let count = 1;
2931 sum += openSample(aLx, aLy);
2932 count += 1;
2933 sum += openSample(bLx, bLy);
2934 count += 1;
2935 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
2936 {
2937 sum += openSample(dLx, dLy);
2938 count += 1;
2939 }
2940 return sum / count;
2941 };
2942 return { smoothCorner };
2943 }
2944
2945 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
2946 #tileLitCorners (baked, localX, localY)
2947 {
2948 const grid = baked?.lightIntensityGrid;
2949 const occlude = baked?.lightOccludeGrid;
2950 if (!grid?.length || !occlude?.length)
2951 { return null; }
2952 const gridW = CHUNK_SIZE + 2;
2953 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
2954 return {
2955 nw: smoothCorner(
2956 localX, localY,
2957 localX - 1, localY,
2958 localX, localY - 1,
2959 localX - 1, localY - 1
2960 ),
2961 ne: smoothCorner(
2962 localX, localY,
2963 localX + 1, localY,
2964 localX, localY - 1,
2965 localX + 1, localY - 1
2966 ),
2967 sw: smoothCorner(
2968 localX, localY,
2969 localX - 1, localY,
2970 localX, localY + 1,
2971 localX - 1, localY + 1
2972 ),
2973 se: smoothCorner(
2974 localX, localY,
2975 localX + 1, localY,
2976 localX, localY + 1,
2977 localX + 1, localY + 1
2978 )
2979 };
2980 }
2981
2982 /**
2983 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
2984 * occluding tiles stay flat and contribute 0 into others so light does not bleed
2985 * through a wall to the far side. Diagonals only when both cardinals are clear.
2986 */
2987 #writeChunkLightmap (baked, activeLights, lightOcclusion)
2988 {
2989 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
2990 if (!snapshot)
2991 { return; }
2992 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2993 const pixelCount = atlasPx * atlasPx * 4;
2994 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
2995 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
2996 const pixels = baked.lightmapPixels;
2997
2998 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
2999 const simple = this.lightingMode === "simple";
3000
3001 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3002 {
3003 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3004 {
3005 const baseX = localX * SPRITE_SIZE_PX;
3006 const baseY = localY * SPRITE_SIZE_PX;
3007 if (simple)
3008 {
3009 const gridW = CHUNK_SIZE + 2;
3010 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
3011 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
3012 for (let py = 0; py < SPRITE_SIZE_PX; py++)
3013 {
3014 for (let px = 0; px < SPRITE_SIZE_PX; px++)
3015 {
3016 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
3017 pixels[offset] = value;
3018 pixels[offset + 1] = value;
3019 pixels[offset + 2] = value;
3020 pixels[offset + 3] = 255;
3021 }
3022 }
3023 continue;
3024 }
3025 const corners = this.#tileLitCorners(baked, localX, localY);
3026 const nw = corners.nw;
3027 const ne = corners.ne;
3028 const sw = corners.sw;
3029 const se = corners.se;
3030 for (let py = 0; py < SPRITE_SIZE_PX; py++)
3031 {
3032 const v = (py + 0.5) / SPRITE_SIZE_PX;
3033 const left = nw + (sw - nw) * v;
3034 const right = ne + (se - ne) * v;
3035 for (let px = 0; px < SPRITE_SIZE_PX; px++)
3036 {
3037 const u = (px + 0.5) / SPRITE_SIZE_PX;
3038 const intensity = left + (right - left) * u;
3039 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
3040 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
3041 pixels[offset] = value;
3042 pixels[offset + 1] = value;
3043 pixels[offset + 2] = value;
3044 pixels[offset + 3] = 255;
3045 }
3046 }
3047 }
3048 }
3049 const ctx = baked.lightmapCanvas.getContext("2d");
3050 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
3051 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3052 }
3053
3054 #updateSwipes (now)
3055 {
3056 this.swipes = this.swipes.filter((swipe) =>
3057 {
3058 if (swipe.lerp && swipe.started != null)
3059 {
3060 const durationMs = swipe.durationMs ?? 400;
3061 const t = Math.min(1, (now - swipe.started) / durationMs);
3062 const fromPivot = tilePivot(swipe.fromTileX, swipe.fromTileY, this.tileSize());
3063 const toPivot = tilePivot(swipe.tileX, swipe.tileY, this.tileSize());
3064 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
3065 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
3066 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
3067 if (swipe.object?.transform)
3068 {
3069 swipe.object.transform.rotation = Math.atan2(
3070 toPivot.y - fromPivot.y,
3071 toPivot.x - fromPivot.x
3072 ) * (180 / Math.PI);
3073 }
3074 if (swipe.spellProjectile && swipe.baseSprite)
3075 {
3076 const frame = Math.floor((now - swipe.started) / SPELL_PROJECTILE_FRAME_MS) % 3;
3077 const image = this.#spellProjectileImage(swipe.baseSprite, frame);
3078 if (image && swipe.object?.renderer)
3079 { swipe.object.renderer.sprite = image; }
3080 }
3081 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
3082 if (!swipe.spellProjectile)
3083 {
3084 this.#applyPhysicalCombatFxDarkness(
3085 swipe.object,
3086 swipe.fromTileX,
3087 swipe.fromTileY,
3088 swipe.tileX,
3089 swipe.tileY,
3090 swipe.dualTint ?? null
3091 );
3092 }
3093 }
3094 else if (swipe.fromTileX != null && !swipe.spellProjectile)
3095 {
3096 this.#applyPhysicalCombatFxDarkness(
3097 swipe.object,
3098 swipe.fromTileX,
3099 swipe.fromTileY,
3100 swipe.tileX,
3101 swipe.tileY,
3102 swipe.dualTint ?? null
3103 );
3104 }
3105 if (swipe.until > now)
3106 { return true; }
3107 swipe.object?.destroy();
3108 return false;
3109 });
3110 }
3111
3112 #updateDamageNumbers (now)
3113 {
3114 const layer = this.damageNumbersEl;
3115 if (!layer)
3116 { return; }
3117 this.damageFloats = this.damageFloats.filter((entry) =>
3118 {
3119 const elapsed = now - entry.started;
3120 if (elapsed >= DAMAGE_FLOAT_MS)
3121 {
3122 entry.element?.remove();
3123 return false;
3124 }
3125 const entity = this.entities.get(entry.entityId);
3126 if (!entity)
3127 {
3128 entry.element?.remove();
3129 return false;
3130 }
3131 if (!entry.element)
3132 {
3133 entry.element = document.createElement("span");
3134 entry.element.className = "damage-number";
3135 entry.element.textContent = String(entry.damage);
3136 layer.append(entry.element);
3137 }
3138 const anchor = this.nametagAnchor(entity);
3139 if (!anchor)
3140 { return true; }
3141 const t = elapsed / DAMAGE_FLOAT_MS;
3142 entry.element.style.left = `${anchor.x}px`;
3143 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
3144 entry.element.style.opacity = String(1 - t);
3145 return true;
3146 });
3147 }
3148
3149 #updateSkillLevelFloats (now)
3150 {
3151 const layer = this.skillLevelFloatsEl;
3152 if (!layer)
3153 { return; }
3154 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
3155 {
3156 const elapsed = now - entry.started;
3157 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
3158 {
3159 entry.element?.remove();
3160 return false;
3161 }
3162 const entity = this.entities.get(entry.entityId);
3163 if (!entity)
3164 {
3165 entry.element?.remove();
3166 return false;
3167 }
3168 if (!entry.element)
3169 {
3170 const root = document.createElement("div");
3171 root.className = "skill-level-float";
3172
3173 const levelEl = document.createElement("div");
3174 levelEl.className = "skill-level-float-level";
3175 levelEl.textContent = `↑${entry.level}↑`;
3176
3177 const icon = document.createElement("img");
3178 icon.className = "skill-level-float-icon";
3179 icon.src = entry.icon;
3180 icon.alt = entry.displayName || "";
3181
3182 root.append(levelEl, icon);
3183 entry.element = root;
3184 layer.append(entry.element);
3185 }
3186 const anchor = this.nametagAnchor(entity);
3187 if (!anchor)
3188 { return true; }
3189 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
3190 entry.element.style.left = `${anchor.x}px`;
3191 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
3192 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
3193 return true;
3194 });
3195 }
3196
3197 #syncBloomLayer ()
3198 {
3199 if (!this.bloomEnabled)
3200 {
3201 this.scene.setLayers([{ name: "default" }]);
3202 return;
3203 }
3204 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
3205 this.scene.setLayers([
3206 { name: "default" },
3207 {
3208 name: RENDER_LAYER_BLOOM,
3209 composite: "add",
3210 postShaders: Shader.getBloomPostChain({
3211 threshold: settings.bloomThreshold,
3212 softKnee: settings.bloomSoftKnee,
3213 intensity: settings.bloomIntensity,
3214 blurSize: settings.bloomBlurSize,
3215 saturation: settings.bloomSaturation,
3216 colorPreserve: settings.bloomColorPreserve,
3217 dilate: settings.bloomDilate,
3218 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
3219 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
3220 })
3221 }
3222 ]);
3223 }
3224}
3225
3226export function nightFactor (hour, nightDarkness = 0.72)
3227{
3228 const peak = Math.min(1, Math.max(0, nightDarkness));
3229 if (hour >= 8 && hour <= 16)
3230 { return 0; }
3231 if (hour >= 22 || hour <= 5)
3232 { return peak; }
3233 if (hour < 8)
3234 { return lerp(peak, 0, (hour - 5) / 3); }
3235 return lerp(0, peak, (hour - 16) / 6);
3236}
3237
3238function bodySpriteName (sex)
3239{
3240 const key = sex === "female" ? "player-body-female" : "player-body-male";
3241 return spriteImageName("character", key, key);
3242}
3243
3244function lerp (a, b, t)
3245{
3246 return a + (b - a) * Math.min(1, Math.max(0, t));
3247}
3248
3249function makeLightmapCanvas (size)
3250{
3251 const canvas = document.createElement("canvas");
3252 canvas.width = size;
3253 canvas.height = size;
3254 return canvas;
3255}
3256
3257function copyCanvas (source, dest)
3258{
3259 const ctx = dest.getContext("2d");
3260 ctx.imageSmoothingEnabled = false;
3261 ctx.clearRect(0, 0, dest.width, dest.height);
3262 ctx.drawImage(source, 0, 0);
3263}
3264
3265function drawHpBar (canvas, current, max)
3266{
3267 const ctx = canvas.getContext("2d");
3268 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
3269 ctx.fillStyle = "#000000";
3270 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
3271 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
3272 const fillW = Math.round(12 * ratio);
3273 if (fillW > 0)
3274 {
3275 ctx.fillStyle = "#ff0000";
3276 ctx.fillRect(1, 1, fillW, 2);
3277 }
3278}