BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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