BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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