BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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