BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 128.6 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js";
5import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
6import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
7import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb } from "/shared/render/tint.js";
8import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js";
9import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
10import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
11import { createChunkAtlasCache } from "./chunkAtlasCache.js";
12import
13{
14 frameworkImageFromCanvas,
15 invalidateCanvasTexture
16} from "./canvasSprite.js";
17import { setNearestFilter } from "./sprites.js";
18import { SeasonId, seasonIdAt } from "/shared/world/season.js";
19import
20{
21 OVERWORLD_ID,
22 normalizeDimensionId,
23 normalizeLightingMode,
24 normalizeSeasonMode,
25 resolveDimensionDarknessFactor,
26 resolveDimensionSeasonId
27} from "/shared/world/dimensions.js";
28import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
29import { skullTintColor } from "/shared/combat/skull.js";
30
31const LAYER_GROUND = 0;
32const LAYER_EDGE = 900000;
33const SORT_BLOCK = 2;
34const SORT_ENTITY = 3;
35const SORT_HP_BAR = 4;
36const SORT_FX = 5;
37const RENDER_LAYER_BLOOM = "bloom";
38const SKULL_SPRITE = "fx:skull:skull";
39
40const HP_BAR_W = 14;
41const HP_BAR_H = 4;
42const WALK_TILT_DEG = 6;
43const RUN_TILT_DEG = 8;
44const SHOVE_TILE_FRACTION = 0.25;
45const SHOVE_MS = 280;
46/** Soft reflow when stack circle targets change (join/leave a shared tile). */
47const STACK_SPREAD_LERP_MS = 280;
48/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
49const GATHER_TOOL_HOLD_MS = 1100;
50const DAMAGE_FLASH_MS = 180;
51const FLASH_COLOR_DAMAGE = Object.freeze([1.0, 0.12, 0.12]);
52const FLASH_COLOR_BLOCK = Object.freeze([1.0, 1.0, 1.0]);
53const DAMAGE_FLOAT_MS = 900;
54const SKILL_LEVEL_FLOAT_MS = 2800;
55/** Projectiles spawn this many sprite-pixels below the caster sprite top. */
56const PROJECTILE_LAUNCH_FROM_TOP_PX = 4;
57
58const SPRITE_LIGHTING_FRAG = [
59 "precision mediump float;",
60 "varying vec2 v_texCoord;",
61 "uniform sampler2D u_texture;",
62 "uniform float u_darkness;",
63 "uniform float u_strength;",
64 "uniform vec3 u_flashColor;",
65 "uniform float u_wade;",
66 "uniform float u_spriteHeight;",
67 "void main() {",
68 " vec4 color = texture2D(u_texture, v_texCoord);",
69 " if (color.a <= 0.0) { discard; }",
70 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
71 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
72 " vec3 rgb = color.rgb;",
73 " if (u_wade > 0.5 && fromBottom < 5.0) {",
74 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
75 " }",
76 " rgb = mix(rgb, vec3(0.0), u_darkness);",
77 " rgb = mix(rgb, u_flashColor, u_strength);",
78 " gl_FragColor = vec4(rgb, color.a);",
79 "}"
80].join("\n");
81
82const WATER_GROUND_FRAG = [
83 "precision mediump float;",
84 "varying vec2 v_texCoord;",
85 "uniform sampler2D u_texture;",
86 "uniform float u_ambientDark;",
87 "uniform float u_litNW;",
88 "uniform float u_litNE;",
89 "uniform float u_litSW;",
90 "uniform float u_litSE;",
91 "uniform float u_time;",
92 "uniform float u_edgeN;",
93 "uniform float u_edgeE;",
94 "uniform float u_edgeS;",
95 "uniform float u_edgeW;",
96 "void main() {",
97 " vec4 color = texture2D(u_texture, v_texCoord);",
98 " if (color.a <= 0.0) { discard; }",
99 " vec3 rgb = color.rgb;",
100 " float foam = 0.0;",
101 " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
102 " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
103 " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
104 " }",
105 " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
106 " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
107 " }",
108 " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
109 " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
110 " }",
111 " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
112 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
113 " }",
114 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
115 " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);",
116 " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);",
117 " float lit = mix(litTop, litBottom, v_texCoord.y);",
118 " float darkness = u_ambientDark * (1.0 - lit);",
119 " rgb = mix(rgb, vec3(0.0), darkness);",
120 " gl_FragColor = vec4(rgb, color.a);",
121 "}"
122].join("\n");
123
124/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
125const TINT_LIT_SPRITE_FRAG = [
126 "precision mediump float;",
127 "varying vec2 v_texCoord;",
128 "uniform sampler2D u_texture;",
129 "uniform float u_darkness;",
130 "uniform float u_strength;",
131 "uniform vec3 u_flashColor;",
132 "uniform float u_wade;",
133 "uniform float u_spriteHeight;",
134 "uniform float u_useTint;",
135 "uniform vec3 u_tintColor;",
136 "void main() {",
137 " vec4 color = texture2D(u_texture, v_texCoord);",
138 " if (color.a <= 0.0) { discard; }",
139 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
140 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
141 " vec3 rgb = color.rgb;",
142 " if (u_useTint > 0.5) {",
143 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
144 " float L = color.r;",
145 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
146 " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",
147 " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",
148 " }",
149 " }",
150 " if (u_wade > 0.5 && fromBottom < 5.0) {",
151 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
152 " }",
153 " rgb = mix(rgb, vec3(0.0), u_darkness);",
154 " rgb = mix(rgb, u_flashColor, u_strength);",
155 " gl_FragColor = vec4(rgb, color.a);",
156 "}"
157].join("\n");
158
159/** Dual/triple-channel tint: red = shaft, blue = tip, green = coat; then darkness.
160 * Equal non-dominant channels lighten the assigned tint toward white. */
161const DUAL_TINT_LIT_SPRITE_FRAG = [
162 "precision mediump float;",
163 "varying vec2 v_texCoord;",
164 "uniform sampler2D u_texture;",
165 "uniform float u_darkness;",
166 "uniform float u_strength;",
167 "uniform vec3 u_flashColor;",
168 "uniform float u_wade;",
169 "uniform float u_spriteHeight;",
170 "uniform vec3 u_shaftTint;",
171 "uniform vec3 u_tipTint;",
172 "uniform vec3 u_coatTint;",
173 "uniform float u_hasCoat;",
174 "vec3 channelTint(float L, float o1, float o2, vec3 tint) {",
175 " float equal = step(abs(o1 - o2), 0.04);",
176 " float blend = L > 0.0 ? clamp(mix(min(o1, o2), o1, equal) / L, 0.0, 1.0) : 0.0;",
177 " float tintLuma = dot(tint, vec3(0.2126, 0.7152, 0.0722));",
178 " vec3 toward = mix(vec3(tintLuma), vec3(1.0), equal);",
179 " return mix(tint, toward, blend) * L;",
180 "}",
181 "void main() {",
182 " vec4 color = texture2D(u_texture, v_texCoord);",
183 " if (color.a <= 0.0) { discard; }",
184 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
185 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
186 " vec3 rgb = color.rgb;",
187 " if (u_hasCoat > 0.5) {",
188 " float coatMask = clamp((color.g - max(color.r, color.b)) * 1.75, 0.0, 1.0);",
189 " if (coatMask > 0.0) {",
190 " vec3 coatCol = channelTint(color.g, color.r, color.b, u_coatTint);",
191 " rgb = mix(rgb, coatCol, coatMask);",
192 " }",
193 " }",
194 " float tipMask = clamp((color.b - max(color.r, color.g)) * 1.75, 0.0, 1.0);",
195 " if (tipMask > 0.0) {",
196 " vec3 tipCol = channelTint(color.b, color.r, color.g, u_tipTint);",
197 " rgb = mix(rgb, tipCol, tipMask);",
198 " }",
199 " float shaftMask = clamp((color.r - max(color.g, color.b)) * 1.75, 0.0, 1.0);",
200 " if (shaftMask > 0.0) {",
201 " vec3 shaftCol = channelTint(color.r, color.g, color.b, u_shaftTint);",
202 " rgb = mix(rgb, shaftCol, shaftMask);",
203 " }",
204 " if (u_wade > 0.5 && fromBottom < 5.0) {",
205 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
206 " }",
207 " rgb = mix(rgb, vec3(0.0), u_darkness);",
208 " rgb = mix(rgb, u_flashColor, u_strength);",
209 " gl_FragColor = vec4(rgb, color.a);",
210 "}"
211].join("\n");
212
213/** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
214/**
215 * Tight-fit: clip clothing alpha to the body silhouette in *pivot space*
216 * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from
217 * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art.
218 */
219const TIGHT_FIT_BODY_MASK_GLSL = [
220 "uniform vec2 u_clothSize;",
221 "uniform vec2 u_bodySize;",
222 "uniform float u_pivotFromBottom;",
223 "uniform vec4 u_clothUvRect;",
224 "uniform vec4 u_bodyUvRect;",
225 "float tightFitBodyAlpha() {",
226 " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));",
227 " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;",
228 " float ox = (nu.x - 0.5) * u_clothSize.x;",
229 " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);",
230 " vec2 bodySize = max(u_bodySize, vec2(1.0));",
231 " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);",
232 " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));",
233 " vec2 texel = 1.0 / bodySize;",
234 " float bodyA = 0.0;",
235 " for (int dy = -1; dy <= 1; dy++) {",
236 " for (int dx = -1; dx <= 1; dx++) {",
237 " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;",
238 " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }",
239 " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;",
240 " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);",
241 " }",
242 " }",
243 " return bodyA;",
244 "}"
245].join("\n");
246
247const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
248 "precision mediump float;",
249 "varying vec2 v_texCoord;",
250 "uniform sampler2D u_texture;",
251 "uniform sampler2D u_secondary;",
252 "uniform float u_darkness;",
253 "uniform float u_strength;",
254 "uniform vec3 u_flashColor;",
255 "uniform float u_wade;",
256 "uniform float u_spriteHeight;",
257 "uniform float u_useTint;",
258 "uniform vec3 u_tintColor;",
259 TIGHT_FIT_BODY_MASK_GLSL,
260 "void main() {",
261 " vec4 color = texture2D(u_texture, v_texCoord);",
262 " if (color.a <= 0.0) { discard; }",
263 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
264 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
265 " vec3 rgb = color.rgb;",
266 " if (u_useTint > 0.5) {",
267 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
268 " float L = color.r;",
269 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
270 " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",
271 " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",
272 " }",
273 " }",
274 " if (u_wade > 0.5 && fromBottom < 5.0) {",
275 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
276 " }",
277 " rgb = mix(rgb, vec3(0.0), u_darkness);",
278 " rgb = mix(rgb, u_flashColor, u_strength);",
279 " float alpha = min(tightFitBodyAlpha(), color.a);",
280 " if (alpha <= 0.0) { discard; }",
281 " gl_FragColor = vec4(rgb, alpha);",
282 "}"
283].join("\n");
284
285/** Body-clipped equip overlay without dye recolour. */
286const TIGHT_FIT_LIT_SPRITE_FRAG = [
287 "precision mediump float;",
288 "varying vec2 v_texCoord;",
289 "uniform sampler2D u_texture;",
290 "uniform sampler2D u_secondary;",
291 "uniform float u_darkness;",
292 "uniform float u_strength;",
293 "uniform vec3 u_flashColor;",
294 "uniform float u_wade;",
295 "uniform float u_spriteHeight;",
296 TIGHT_FIT_BODY_MASK_GLSL,
297 "void main() {",
298 " vec4 color = texture2D(u_texture, v_texCoord);",
299 " if (color.a <= 0.0) { discard; }",
300 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
301 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
302 " vec3 rgb = color.rgb;",
303 " if (u_wade > 0.5 && fromBottom < 5.0) {",
304 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
305 " }",
306 " rgb = mix(rgb, vec3(0.0), u_darkness);",
307 " rgb = mix(rgb, u_flashColor, u_strength);",
308 " float alpha = min(tightFitBodyAlpha(), color.a);",
309 " if (alpha <= 0.0) { discard; }",
310 " gl_FragColor = vec4(rgb, alpha);",
311 "}"
312].join("\n");
313
314const ATLAS_LIGHTING_FRAG = [
315 "precision mediump float;",
316 "varying vec2 v_texCoord;",
317 "uniform sampler2D u_texture;",
318 "uniform sampler2D u_secondary;",
319 "uniform float u_ambientDark;",
320 "uniform float u_lightRow;",
321 "void main() {",
322 " vec4 color = texture2D(u_texture, v_texCoord);",
323 " if (color.a <= 0.0) { discard; }",
324 " vec2 lightUV = v_texCoord;",
325 " if (u_lightRow >= 0.0) {",
326 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
327 " }",
328 " float lit = texture2D(u_secondary, lightUV).r;",
329 " float darkness = u_ambientDark * (1.0 - lit);",
330 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
331 " gl_FragColor = vec4(rgb, color.a);",
332 "}"
333].join("\n");
334
335let spriteLightingShader = null;
336let atlasLightingShader = null;
337let waterGroundShader = null;
338let tintLitSpriteShader = null;
339let dualTintLitSpriteShader = null;
340let tightFitTintLitSpriteShader = null;
341let tightFitLitSpriteShader = null;
342
343function getSpriteLightingShader ()
344{
345 if (!spriteLightingShader)
346 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
347 return spriteLightingShader;
348}
349
350function getAtlasLightingShader ()
351{
352 if (!atlasLightingShader)
353 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
354 return atlasLightingShader;
355}
356
357function getWaterGroundShader ()
358{
359 if (!waterGroundShader)
360 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
361 return waterGroundShader;
362}
363
364function getTintLitSpriteShader ()
365{
366 if (!tintLitSpriteShader)
367 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
368 return tintLitSpriteShader;
369}
370
371function getDualTintLitSpriteShader ()
372{
373 if (!dualTintLitSpriteShader)
374 { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); }
375 return dualTintLitSpriteShader;
376}
377
378function getTightFitTintLitSpriteShader ()
379{
380 if (!tightFitTintLitSpriteShader)
381 { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); }
382 return tightFitTintLitSpriteShader;
383}
384
385function getTightFitLitSpriteShader ()
386{
387 if (!tightFitLitSpriteShader)
388 { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); }
389 return tightFitLitSpriteShader;
390}
391
392export class WorldView
393{
394 #chunkRebuildKeys = new Set();
395 #chunkRebuildRaf = 0;
396 #edgesDirty = false;
397 #CHUNK_REBUILD_BATCH = 2;
398 #pendingTextureCanvases = [];
399 #pendingTextureCanvasSet = new Set();
400 #textureWarmRaf = 0;
401 #TEXTURE_WARM_BATCH = 3;
402 #atlasCache = createChunkAtlasCache();
403 #idlePrefetchId = 0;
404 #playerChunkX = null;
405 #playerChunkY = null;
406 #playerMoveChunkDx = 0;
407 #playerMoveChunkDy = 0;
408
409 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
410 {
411 this.game = game;
412 this.scene = scene;
413 this.catalog = catalog;
414 this.preview = null;
415 this.zoom = 2;
416 this.chunks = new Map();
417 this.bakedChunks = new Map();
418 this.tiles = new Map();
419 this.entities = new Map();
420 this.groundItems = new Map();
421 this.edges = new Map();
422 this.localEntityId = null;
423 this.localBlind = false;
424 /** @type {string} */
425 this.dimensionId = OVERWORLD_ID;
426 /** @type {string} */
427 this.dimensionLightingMode = "dayNight";
428 /** @type {string} */
429 this.dimensionSeasonMode = "auto";
430 /** Calendar season from worldStatus when dimension season is auto. */
431 this.calendarSeason = seasonIdAt();
432 /** @type {"soft"|"simple"} */
433 this.lightingMode = "soft";
434 /** @type {boolean} */
435 this.bloomEnabled = true;
436 /** Soft edge blend for blendable grounds (grass, dirt, …). */
437 this.softTerrain = false;
438 this.settings = { ...DEFAULT_WORLD_SETTINGS };
439 this.worldHour = 12;
440 /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
441 this.worldSeason = seasonIdAt();
442 this.nightPreview = null;
443 this.followPlayer = true;
444 this.dynamicLights = [];
445 /** Persistent Light-spell tile lights (server-driven). */
446 this.spellLights = new Map();
447 /** Persistent Dark-spell tile darkness (server-driven). */
448 this.spellDarks = new Map();
449 this.swipes = [];
450 this.damageFloats = [];
451 this.damageNumbersEl = document.getElementById("damage-numbers");
452 this.skillLevelFloats = [];
453 this.skillLevelFloatsEl = document.getElementById("skill-level-floats");
454 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
455 this.editorSpawners = new Map();
456 this.spawnRangeHighlight = null;
457 this.wanderRangeHighlight = null;
458 this.spellTargetHighlight = null;
459 this.#syncBloomLayer();
460 }
461
462 setSettings (settings)
463 {
464 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
465 this.#syncBloomLayer();
466 }
467
468 /**
469 * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain).
470 * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs
471 */
472 setGraphicsPrefs (prefs)
473 {
474 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
475 { this.lightingMode = prefs.lighting; }
476 if (prefs?.bloom === "off" || prefs?.bloom === "on")
477 {
478 const enabled = prefs.bloom !== "off";
479 if (enabled !== this.bloomEnabled)
480 {
481 this.bloomEnabled = enabled;
482 this.#syncBloomLayer();
483 }
484 else
485 { this.bloomEnabled = enabled; }
486 }
487 if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off")
488 {
489 const enabled = prefs.softTerrain === "on";
490 if (enabled !== this.softTerrain)
491 {
492 this.softTerrain = enabled;
493 this.#rebakeAllChunks();
494 }
495 }
496 }
497
498 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
499 setWorldSeason (season)
500 {
501 const calendar = season === SeasonId.spring
502 || season === SeasonId.fall
503 || season === SeasonId.winter
504 || season === SeasonId.summer
505 ? season
506 : seasonIdAt();
507 this.calendarSeason = calendar;
508 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
509 const next = forced ?? calendar;
510 if (next === this.worldSeason)
511 { return; }
512 this.worldSeason = next;
513 this.#rebakeAllChunks();
514 }
515
516 setDimensionId (dimensionId)
517 {
518 this.dimensionId = normalizeDimensionId(dimensionId);
519 }
520
521 setDimensionModes (lightingMode, seasonMode)
522 {
523 this.dimensionLightingMode = normalizeLightingMode(lightingMode);
524 this.dimensionSeasonMode = normalizeSeasonMode(seasonMode);
525 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
526 const next = forced ?? this.calendarSeason ?? seasonIdAt();
527 if (next !== this.worldSeason)
528 {
529 this.worldSeason = next;
530 this.#rebakeAllChunks();
531 }
532 }
533
534 clearAllChunks ()
535 {
536 for (const key of [...this.chunks.keys()])
537 {
538 const [chunkX, chunkY] = key.split(",").map(Number);
539 this.removeChunk(chunkX, chunkY);
540 }
541 for (const [id] of [...this.entities.entries()])
542 {
543 if (id === this.localEntityId)
544 { continue; }
545 this.despawnEntity(id);
546 }
547 for (const [id] of [...this.groundItems.entries()])
548 { this.despawnGroundItem(id); }
549 }
550
551 /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */
552 clearPlaySession ()
553 {
554 this.#cancelIdlePrefetch();
555 this.#chunkRebuildKeys.clear();
556 this.#playerChunkX = null;
557 this.#playerChunkY = null;
558 this.#playerMoveChunkDx = 0;
559 this.#playerMoveChunkDy = 0;
560 this.localEntityId = null;
561 for (const key of [...this.chunks.keys()])
562 {
563 const [chunkX, chunkY] = key.split(",").map(Number);
564 this.removeChunk(chunkX, chunkY);
565 }
566 for (const [id] of [...this.entities.entries()])
567 { this.despawnEntity(id); }
568 for (const [id] of [...this.groundItems.entries()])
569 { this.despawnGroundItem(id); }
570 }
571
572 applySnapshot (snapshot)
573 {
574 const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID);
575 if (normalizeDimensionId(this.dimensionId) !== snapDim)
576 { return; }
577 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
578 if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE)
579 {
580 snapshot.occlusion = bakeChunkOcclusion(snapshot);
581 }
582 this.chunks.set(key, snapshot);
583 this.#scheduleChunkRebuild(snapshot);
584 this.#redrawPreview();
585 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
586 if (snapshot.staticOnly)
587 {
588 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
589 this.#scheduleEdgeRebuild();
590 return;
591 }
592 for (const entity of snapshot.entities ?? [])
593 { this.#upsertEntity(entity); }
594 for (const [id, item] of [...this.groundItems.entries()])
595 {
596 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
597 { this.despawnGroundItem(id); }
598 }
599 for (const item of snapshot.groundItems ?? [])
600 { this.upsertGroundItem(item); }
601 this.#scheduleEdgeRebuild();
602 }
603
604 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0)
605 {
606 this.localEntityId = entityId;
607 this.#upsertEntity({
608 entityId,
609 characterId,
610 tileX,
611 tileY,
612 gait,
613 sex,
614 firstName,
615 lastName,
616 layers: layers ?? undefined,
617 skullValue: skullValue | 0,
618 ...(health != null ? { health } : {}),
619 ...(maxHealth != null ? { maxHealth } : {})
620 });
621 this.#notePlayerTile(tileX, tileY);
622 }
623
624 #stripChunkDynamic (chunkX, chunkY)
625 {
626 for (const [id, item] of [...this.groundItems.entries()])
627 {
628 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
629 { this.despawnGroundItem(id); }
630 }
631 for (const [id, entity] of [...this.entities.entries()])
632 {
633 if (id === this.localEntityId)
634 { continue; }
635 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
636 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
637 { this.despawnEntity(id); }
638 }
639 }
640
641 removeChunk (chunkX, chunkY)
642 {
643 const key = `${chunkX},${chunkY}`;
644 this.chunks.delete(key);
645 this.#destroyBakedChunk(key);
646 this.#destroyEdges(key);
647 const prefix = `${chunkX},${chunkY}:`;
648 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
649 {
650 if (!spawnerKey.startsWith(prefix))
651 { continue; }
652 entry.object?.destroy();
653 this.editorSpawners.delete(spawnerKey);
654 }
655 for (const [tileKey, objects] of [...this.tiles.entries()])
656 {
657 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
658 {
659 objects.ground?.destroy();
660 objects.groundBloom?.destroy();
661 objects.block?.destroy();
662 objects.blockBloom?.destroy();
663 this.tiles.delete(tileKey);
664 }
665 }
666 for (const [id, item] of [...this.groundItems.entries()])
667 {
668 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
669 { this.despawnGroundItem(id); }
670 }
671 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
672 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
673 for (const [id, entity] of [...this.entities.entries()])
674 {
675 if (id === this.localEntityId)
676 { continue; }
677 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
678 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
679 { this.despawnEntity(id); }
680 }
681 this.#rebuildAllEdges();
682 }
683
684 setChunkOpen (chunkX, chunkY, open)
685 {
686 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
687 if (!snapshot)
688 { return; }
689 snapshot.open = !!open;
690 this.#rebuildAllEdges();
691 }
692
693 spawnEntity (payload)
694 {
695 this.#upsertEntity(payload);
696 }
697
698 moveEntity (payload)
699 {
700 const existing = this.entities.get(payload.entityId);
701 if (!existing)
702 {
703 this.#upsertEntity(payload);
704 return;
705 }
706 const size = this.tileSize();
707 existing.fromX = existing.visualX;
708 existing.fromY = existing.visualY;
709 existing.shadeFromTileX = existing.tileX;
710 existing.shadeFromTileY = existing.tileY;
711 existing.tileX = payload.tileX;
712 existing.tileY = payload.tileY;
713 existing.gait = payload.gait;
714 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
715 if (payload.worldX != null && payload.worldY != null)
716 {
717 existing.worldX = payload.worldX;
718 existing.worldY = payload.worldY;
719 existing.targetX = payload.worldX * size;
720 existing.targetY = payload.worldY * size;
721 }
722 else
723 {
724 const pivot = tilePivot(payload.tileX, payload.tileY, size);
725 existing.targetX = pivot.x;
726 existing.targetY = pivot.y;
727 }
728 existing.lerpStarted = performance.now();
729 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
730 if (payload.entityId === this.localEntityId)
731 { this.#notePlayerTile(payload.tileX, payload.tileY); }
732 }
733
734 despawnEntity (entityId)
735 {
736 const existing = this.entities.get(entityId);
737 if (!existing)
738 { return; }
739 existing.object?.destroy();
740 existing.hpBar?.destroy();
741 existing.skullMarker?.destroy();
742 for (const overlay of existing.overlays ?? [])
743 { overlay.destroy(); }
744 for (const overlay of existing.bloomOverlays ?? [])
745 { overlay.destroy(); }
746 this.entities.delete(entityId);
747 }
748
749 updateEntitySkull (entityId, skullValue)
750 {
751 const entity = this.entities.get(entityId);
752 if (!entity)
753 { return; }
754 entity.skullValue = Math.max(0, skullValue | 0);
755 this.#syncSkullMarker(entity);
756 }
757
758 updateEntityHealth (entityId, health, maxHealth)
759 {
760 const entity = this.entities.get(entityId);
761 if (!entity)
762 { return; }
763 entity.health = health;
764 entity.maxHealth = maxHealth;
765 this.#syncHpBar(entity);
766 }
767
768 flashDamage (entityId)
769 {
770 this.#flashEntity(entityId, FLASH_COLOR_DAMAGE);
771 }
772
773 flashBlock (entityId)
774 {
775 this.#flashEntity(entityId, FLASH_COLOR_BLOCK);
776 }
777
778 #flashEntity (entityId, color)
779 {
780 const entity = this.entities.get(entityId);
781 if (!entity)
782 { return; }
783 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
784 entity.damageFlashColor = color ?? FLASH_COLOR_DAMAGE;
785 }
786
787 /** Target knocks back away from attacker (hit). */
788 spawnCombatKnockback (payload)
789 {
790 const attacker = this.entities.get(payload?.attackerId);
791 const target = this.entities.get(payload?.targetId);
792 if (!attacker || !target)
793 { return; }
794 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
795 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
796 const tx = target.visualX + (target.stackOffsetX ?? 0);
797 const ty = target.visualY + (target.stackOffsetY ?? 0);
798 this.#applyShoveInDirection(target, tx - ax, ty - ay);
799 }
800
801 /** Target sidesteps perpendicular to the attack (dodge / miss). */
802 spawnCombatDodge (payload)
803 {
804 const attacker = this.entities.get(payload?.attackerId);
805 const target = this.entities.get(payload?.targetId);
806 if (!attacker || !target)
807 { return; }
808 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
809 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
810 const tx = target.visualX + (target.stackOffsetX ?? 0);
811 const ty = target.visualY + (target.stackOffsetY ?? 0);
812 const dx = tx - ax;
813 const dy = ty - ay;
814 const side = Math.random() < 0.5 ? 1 : -1;
815 this.#applyShoveInDirection(target, -dy * side, dx * side);
816 }
817
818 spawnDamageNumber (entityId, damage)
819 {
820 const amount = damage | 0;
821 if (amount <= 0)
822 { return; }
823 this.damageFloats.push({
824 entityId,
825 damage: amount,
826 started: performance.now()
827 });
828 }
829
830 /**
831 * Queue combat-hit presentation until a matching in-flight projectile lands.
832 * Returns true when deferred; caller should apply immediately when false.
833 */
834 deferCombatHit (message, apply)
835 {
836 if (typeof apply !== "function" || message?.targetId == null)
837 { return false; }
838 const attackerId = message.attackerId ?? null;
839 const targetId = message.targetId;
840 const swipe = this.swipes.find((entry) =>
841 entry.lerp
842 && entry.onImpact == null
843 && entry.targetId === targetId
844 && (attackerId == null || entry.attackerId === attackerId)
845 && (entry.until ?? 0) > performance.now());
846 if (!swipe)
847 { return false; }
848 swipe.onImpact = apply;
849 swipe.trackTarget = true;
850 return true;
851 }
852
853 /** Stop tracking a living target (misses fly to a fixed tile). */
854 markProjectileMiss (message)
855 {
856 const attackerId = message?.attackerId ?? null;
857 const targetId = message?.targetId ?? null;
858 for (const swipe of this.swipes)
859 {
860 if (!swipe.lerp || swipe.onImpact != null)
861 { continue; }
862 if (targetId != null && swipe.targetId !== targetId)
863 { continue; }
864 if (attackerId != null && swipe.attackerId !== attackerId)
865 { continue; }
866 swipe.trackTarget = false;
867 if (message.tileX != null)
868 { swipe.tileX = message.tileX; }
869 if (message.tileY != null)
870 { swipe.tileY = message.tileY; }
871 }
872 }
873
874 spawnSkillLevelUp (entityId, payload)
875 {
876 const level = payload?.level | 0;
877 if (level <= 0 || !payload?.icon)
878 { return; }
879 this.skillLevelFloats.push({
880 entityId,
881 level,
882 icon: payload.icon,
883 displayName: payload.displayName ?? payload.skillId ?? "",
884 started: performance.now()
885 });
886 }
887
888 setAppearance (payload)
889 {
890 const existing = this.entities.get(payload.entityId);
891 if (!existing)
892 { return; }
893 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
894 if (payload.visualScale != null)
895 { existing.visualScale = Number(payload.visualScale) || 1; }
896 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
897 this.#placeEntity(existing);
898 }
899
900 /**
901 * Render the live entity (body + overlays, same tint/tight-fit shaders as the
902 * world, unlit) into an offscreen FBO, crop the top square, and return a
903 * pixel-scaled canvas for UI (e.g. dialogue speaker icons).
904 * @param {number} entityId
905 * @param {{ size?: number }} [options]
906 * @returns {HTMLCanvasElement | null}
907 */
908 captureEntityPortrait (entityId, { size = 64 } = {})
909 {
910 const entity = this.entities.get(entityId);
911 const body = entity?.object?.renderer?.sprite;
912 const glCtx = this.scene?.glContext;
913 const gl = glCtx?.gl;
914 if (!entity || !body || !gl)
915 { return null; }
916
917 const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX);
918 const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX);
919 if (!this.#ensurePortraitTarget(gl, frameW, frameH))
920 { return null; }
921
922 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
923 const prevViewport = gl.getParameter(gl.VIEWPORT);
924 const prevW = glCtx._lastWidth;
925 const prevH = glCtx._lastHeight;
926 const prevBlend = gl.isEnabled(gl.BLEND);
927
928 try
929 {
930 // drawSprite projects with _lastWidth/_lastHeight — match the FBO.
931 glCtx._lastWidth = frameW;
932 glCtx._lastHeight = frameH;
933 gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb);
934 gl.viewport(0, 0, frameW, frameH);
935 gl.enable(gl.BLEND);
936 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
937 gl.clearColor(0, 0, 0, 0);
938 gl.clear(gl.COLOR_BUFFER_BIT);
939
940 const pivotX = frameW * 0.5;
941 const pivotY = frameH - PIVOT_FROM_BOTTOM_PX;
942 this._portraitBodyMap = body.g_image ?? null;
943 this._portraitTightFitEntity = entity;
944 this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false);
945
946 const overlays = entity.overlays ?? [];
947 const tints = entity.overlayTints ?? [];
948 const dualTints = entity.overlayDualTints ?? [];
949 const tight = entity.overlayTightFit ?? [];
950 for (let index = 0; index < overlays.length; index++)
951 {
952 this.#drawPortraitLayer(
953 glCtx,
954 overlays[index],
955 pivotX,
956 pivotY,
957 tints[index] ?? null,
958 !!tight[index],
959 dualTints[index] ?? null
960 );
961 }
962 this._portraitBodyMap = null;
963 this._portraitTightFitEntity = null;
964
965 const pixels = this._portrait.pixels;
966 gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
967 }
968 finally
969 {
970 glCtx._lastWidth = prevW;
971 glCtx._lastHeight = prevH;
972 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
973 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
974 if (!prevBlend)
975 { gl.disable(gl.BLEND); }
976 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
977 }
978
979 return this.#portraitPixelsToCanvas(frameW, frameH, size);
980 }
981
982 #ensurePortraitTarget (gl, width, height)
983 {
984 const prev = this._portrait;
985 if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex)
986 { return true; }
987 if (prev?.fb)
988 { gl.deleteFramebuffer(prev.fb); }
989 if (prev?.tex)
990 { gl.deleteTexture(prev.tex); }
991
992 const tex = gl.createTexture();
993 gl.bindTexture(gl.TEXTURE_2D, tex);
994 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
995 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
996 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
997 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
998 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
999
1000 const fb = gl.createFramebuffer();
1001 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
1002 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
1003 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
1004 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
1005 if (status !== gl.FRAMEBUFFER_COMPLETE)
1006 {
1007 gl.deleteFramebuffer(fb);
1008 gl.deleteTexture(tex);
1009 this._portrait = null;
1010 return false;
1011 }
1012 this._portrait = {
1013 fb,
1014 tex,
1015 w: width,
1016 h: height,
1017 pixels: new Uint8Array(width * height * 4),
1018 scratch: document.createElement("canvas")
1019 };
1020 return true;
1021 }
1022
1023 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null)
1024 {
1025 const sprite = object?.renderer?.sprite;
1026 if (!sprite?.g_image)
1027 { return; }
1028 const subImage = object.renderer.subImage | 0;
1029 const height = sprite.height || SPRITE_SIZE_PX;
1030 const draw = spriteDrawSize(sprite.width, sprite.height, 1);
1031 const center = spriteCenterFromPivot(pivotX, pivotY, height, 1);
1032 const tint = tintColor ? normalizeRgb(tintColor) : null;
1033 let shader = glCtx.defaultShader;
1034 let uniforms = null;
1035 let secondaryHtml = null;
1036
1037 const bodyHtml = this._portraitBodyMap;
1038 const portraitEntity = this._portraitTightFitEntity;
1039 const maskUniforms = tightFit && portraitEntity
1040 ? this.#tightFitMaskUniforms(object, portraitEntity)
1041 : null;
1042 if (dualTint)
1043 {
1044 const shaft = normalizeRgb(dualTint.shaft);
1045 const tip = normalizeRgb(dualTint.tip);
1046 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
1047 shader = getDualTintLitSpriteShader();
1048 uniforms = {
1049 u_darkness: 0,
1050 u_strength: 0,
1051 u_flashColor: FLASH_COLOR_DAMAGE,
1052 u_wade: 0,
1053 u_spriteHeight: height,
1054 u_shaftTint: [shaft.r, shaft.g, shaft.b],
1055 u_tipTint: [tip.r, tip.g, tip.b],
1056 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
1057 u_hasCoat: coat ? 1 : 0
1058 };
1059 }
1060 else if (tightFit && bodyHtml && maskUniforms)
1061 {
1062 secondaryHtml = bodyHtml;
1063 if (tint)
1064 {
1065 shader = getTightFitTintLitSpriteShader();
1066 uniforms = {
1067 u_darkness: 0,
1068 u_strength: 0,
1069 u_flashColor: FLASH_COLOR_DAMAGE,
1070 u_wade: 0,
1071 u_spriteHeight: height,
1072 u_useTint: 1,
1073 u_tintColor: [tint.r, tint.g, tint.b],
1074 ...maskUniforms
1075 };
1076 }
1077 else
1078 {
1079 shader = getTightFitLitSpriteShader();
1080 uniforms = {
1081 u_darkness: 0,
1082 u_strength: 0,
1083 u_flashColor: FLASH_COLOR_DAMAGE,
1084 u_wade: 0,
1085 u_spriteHeight: height,
1086 ...maskUniforms
1087 };
1088 }
1089 }
1090 else if (tint)
1091 {
1092 shader = getTintLitSpriteShader();
1093 uniforms = {
1094 u_darkness: 0,
1095 u_strength: 0,
1096 u_flashColor: FLASH_COLOR_DAMAGE,
1097 u_wade: 0,
1098 u_spriteHeight: height,
1099 u_useTint: 1,
1100 u_tintColor: [tint.r, tint.g, tint.b]
1101 };
1102 }
1103 else
1104 {
1105 shader = getSpriteLightingShader();
1106 uniforms = {
1107 u_darkness: 0,
1108 u_strength: 0,
1109 u_flashColor: FLASH_COLOR_DAMAGE,
1110 u_wade: 0,
1111 u_spriteHeight: height
1112 };
1113 }
1114
1115 glCtx.drawSprite({
1116 texture: glCtx.getTexture(sprite.g_image),
1117 x: center.x,
1118 y: center.y,
1119 w: draw.w,
1120 h: draw.h,
1121 rotationDeg: 0,
1122 mirrorX: false,
1123 mirrorY: false,
1124 alpha: 1,
1125 uvRect: sprite.getUvRect(subImage),
1126 shader,
1127 uniforms,
1128 textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null,
1129 lights: null
1130 });
1131 }
1132
1133 #portraitPixelsToCanvas (frameW, frameH, size)
1134 {
1135 const pixels = this._portrait?.pixels;
1136 if (!pixels)
1137 { return null; }
1138 const scratch = this._portrait.scratch;
1139 scratch.width = frameW;
1140 scratch.height = frameH;
1141 const sctx = scratch.getContext("2d");
1142 const imageData = sctx.createImageData(frameW, frameH);
1143 // WebGL y=0 is bottom — flip to top-down image order.
1144 for (let y = 0; y < frameH; y++)
1145 {
1146 const src = (frameH - 1 - y) * frameW * 4;
1147 const dst = y * frameW * 4;
1148 imageData.data.set(pixels.subarray(src, src + frameW * 4), dst);
1149 }
1150 sctx.putImageData(imageData, 0, 0);
1151
1152 const crop = Math.min(frameW, frameH);
1153 const out = document.createElement("canvas");
1154 out.width = size;
1155 out.height = size;
1156 const octx = out.getContext("2d");
1157 octx.imageSmoothingEnabled = false;
1158 octx.clearRect(0, 0, size, size);
1159 octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size);
1160 return out;
1161 }
1162
1163 upsertGroundItem (payload)
1164 {
1165 const size = this.tileSize();
1166 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1167 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
1168 const spriteName = potion
1169 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
1170 : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance));
1171 let item = this.groundItems.get(payload.groundItemId);
1172 if (!item)
1173 {
1174 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
1175 this.scene.addObject(object);
1176 item = { object };
1177 this.groundItems.set(payload.groundItemId, item);
1178 }
1179 else if (item.object?.renderer && this.game.images[spriteName])
1180 { item.object.renderer.sprite = this.game.images[spriteName]; }
1181 item.groundItemId = payload.groundItemId;
1182 item.tileX = payload.tileX;
1183 item.tileY = payload.tileY;
1184 item.itemId = payload.itemId;
1185 item.quantity = payload.quantity;
1186 item.displayName = payload.displayName;
1187 item.sprite = spriteName;
1188 item.instance = payload.instance ?? null;
1189 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
1190 const def = itemDefinition(payload.itemId);
1191 item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
1192 item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
1193 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1194 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
1195 }
1196
1197 despawnGroundItem (groundItemId)
1198 {
1199 const item = this.groundItems.get(groundItemId);
1200 if (!item)
1201 { return; }
1202 item.object?.destroy();
1203 this.groundItems.delete(groundItemId);
1204 }
1205
1206 groundItemAtTile (tileX, tileY)
1207 {
1208 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
1209 }
1210
1211 groundItemsAtTile (tileX, tileY)
1212 {
1213 const items = [];
1214 for (const item of this.groundItems.values())
1215 {
1216 if (item.tileX === tileX && item.tileY === tileY)
1217 { items.push(item); }
1218 }
1219 return items;
1220 }
1221
1222 entitiesAtTile (tileX, tileY)
1223 {
1224 const matches = [];
1225 for (const entity of this.entities.values())
1226 {
1227 if (entity.tileX === tileX && entity.tileY === tileY)
1228 { matches.push(entity); }
1229 }
1230 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
1231 return matches;
1232 }
1233
1234 setZoom (zoom, limits = { min: 2, max: 4 })
1235 {
1236 const min = limits.min ?? 1;
1237 const max = limits.max ?? 4;
1238 this.zoom = Math.min(max, Math.max(min, zoom));
1239 for (const snapshot of this.chunks.values())
1240 { this.#relayoutChunk(snapshot); }
1241 const size = this.tileSize();
1242 for (const entity of this.entities.values())
1243 {
1244 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
1245 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
1246 entity.fromX = entity.visualX;
1247 entity.fromY = entity.visualY;
1248 entity.targetX = entity.visualX;
1249 entity.targetY = entity.visualY;
1250 entity.lerpStarted = null;
1251 this.#placeEntity(entity);
1252 }
1253 for (const item of this.groundItems.values())
1254 {
1255 const pivot = tilePivot(item.tileX, item.tileY, size);
1256 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1257 }
1258 this.#rebuildAllEdges();
1259 this.#relayoutEditorSpawners();
1260 this.#relayoutSpawnRangeHighlight();
1261 this.#relayoutSpellTargetHighlight();
1262 }
1263
1264 tileSize ()
1265 {
1266 return SPRITE_SIZE_PX * this.zoom;
1267 }
1268
1269 screenToTile (mouseX, mouseY)
1270 {
1271 const size = this.tileSize();
1272 const worldX = mouseX - this.scene.cameraPosition.x;
1273 const worldY = mouseY - this.scene.cameraPosition.y;
1274 return {
1275 tileX: Math.floor(worldX / size),
1276 tileY: Math.floor(worldY / size)
1277 };
1278 }
1279
1280 entityAtScreen (mouseX, mouseY)
1281 {
1282 let best = null;
1283 let bestLayer = -Infinity;
1284 for (const entity of this.entities.values())
1285 {
1286 const box = this.#entityScreenBox(entity);
1287 if (!box)
1288 { continue; }
1289 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
1290 {
1291 const layer = entity.object?.layer ?? 0;
1292 if (layer >= bestLayer)
1293 {
1294 best = entity;
1295 bestLayer = layer;
1296 }
1297 }
1298 }
1299 return best;
1300 }
1301
1302 nametagAnchor (entity)
1303 {
1304 const box = this.#entityScreenBox(entity);
1305 if (!box)
1306 { return null; }
1307 return { x: (box.left + box.right) / 2, y: box.top };
1308 }
1309
1310 #entityScreenBox (entity)
1311 {
1312 const object = entity?.object;
1313 if (!object)
1314 { return null; }
1315 const size = object.transform.size;
1316 const x = object.transform.position.x + this.scene.cameraPosition.x;
1317 const y = object.transform.position.y + this.scene.cameraPosition.y;
1318 return {
1319 left: x - size.x / 2,
1320 right: x + size.x / 2,
1321 top: y - size.y / 2,
1322 bottom: y + size.y / 2
1323 };
1324 }
1325
1326 update (deltaTime)
1327 {
1328 const now = performance.now();
1329 const size = this.tileSize();
1330 this.#refreshStackTargets();
1331 for (const entity of this.entities.values())
1332 {
1333 const target = entity.targetX != null && entity.targetY != null
1334 ? { x: entity.targetX, y: entity.targetY }
1335 : tilePivot(entity.tileX, entity.tileY, size);
1336 if (entity.lerpStarted != null)
1337 {
1338 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
1339 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
1340 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
1341 if (t >= 1)
1342 { entity.lerpStarted = null; }
1343 }
1344 else
1345 {
1346 entity.visualX = target.x;
1347 entity.visualY = target.y;
1348 }
1349 this.#updateStackOffset(entity, now);
1350 this.#updateShove(entity, now, size);
1351 this.#expireGatherToolOverlay(entity, now);
1352 this.#placeEntity(entity, now);
1353 }
1354
1355 this.#updateSwipes(now);
1356 this.#updateDamageNumbers(now);
1357 this.#updateSkillLevelFloats(now);
1358 this.#relayoutSpellTargetHighlight();
1359 this.#centerCamera();
1360 this.#cullOffscreenDrawables();
1361 this.#updateShade(deltaTime);
1362 }
1363
1364 /**
1365 * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}).
1366 * Stable assignment by entityId; free-flight entities stay unshifted.
1367 */
1368 #refreshStackTargets ()
1369 {
1370 const byTile = new Map();
1371 for (const entity of this.entities.values())
1372 {
1373 if (entity.freeFlight)
1374 {
1375 entity.stackTargetX = 0;
1376 entity.stackTargetY = 0;
1377 continue;
1378 }
1379 const key = `${entity.tileX},${entity.tileY}`;
1380 let list = byTile.get(key);
1381 if (!list)
1382 {
1383 list = [];
1384 byTile.set(key, list);
1385 }
1386 list.push(entity);
1387 }
1388 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
1389 for (const list of byTile.values())
1390 {
1391 if (list.length <= 1)
1392 {
1393 for (const entity of list)
1394 {
1395 entity.stackTargetX = 0;
1396 entity.stackTargetY = 0;
1397 }
1398 continue;
1399 }
1400 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
1401 const n = list.length;
1402 for (let i = 0; i < n; i++)
1403 {
1404 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
1405 list[i].stackTargetX = Math.cos(angle) * radius;
1406 list[i].stackTargetY = Math.sin(angle) * radius;
1407 }
1408 }
1409 }
1410
1411 #updateStackOffset (entity, now)
1412 {
1413 const tx = entity.stackTargetX ?? 0;
1414 const ty = entity.stackTargetY ?? 0;
1415 const cx = entity.stackOffsetX ?? 0;
1416 const cy = entity.stackOffsetY ?? 0;
1417 if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty)
1418 {
1419 entity.stackFromX = cx;
1420 entity.stackFromY = cy;
1421 entity.stackLerpToX = tx;
1422 entity.stackLerpToY = ty;
1423 entity.stackLerpStarted = now;
1424 }
1425 if (entity.stackLerpStarted == null)
1426 {
1427 entity.stackOffsetX = tx;
1428 entity.stackOffsetY = ty;
1429 return;
1430 }
1431 const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS);
1432 entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t;
1433 entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t;
1434 if (t >= 1)
1435 {
1436 entity.stackOffsetX = tx;
1437 entity.stackOffsetY = ty;
1438 entity.stackLerpStarted = null;
1439 }
1440 }
1441
1442 #updateShove (entity, now, tileSize)
1443 {
1444 if (!entity.shove)
1445 {
1446 entity.shoveOffsetX = 0;
1447 entity.shoveOffsetY = 0;
1448 return;
1449 }
1450 const elapsed = now - entity.shove.started;
1451 const t = Math.min(1, elapsed / entity.shove.durationMs);
1452 const maxDist = tileSize * SHOVE_TILE_FRACTION;
1453 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
1454 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
1455 const dist = Math.hypot(dx, dy) || 1;
1456 const ux = dx / dist;
1457 const uy = dy / dist;
1458 let phase;
1459 if (t < 0.45)
1460 { phase = t / 0.45; }
1461 else
1462 { phase = 1 - (t - 0.45) / 0.55; }
1463 entity.shoveOffsetX = ux * maxDist * phase;
1464 entity.shoveOffsetY = uy * maxDist * phase;
1465 if (t >= 1)
1466 { entity.shove = null; }
1467 }
1468
1469 spawnCombatSwing (payload)
1470 {
1471 const attacker = this.entities.get(payload.attackerId);
1472 const target = this.entities.get(payload.targetId);
1473 if (!attacker || !target)
1474 { return; }
1475 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1476 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1477 const tx = target.visualX + (target.stackOffsetX ?? 0);
1478 const ty = target.visualY + (target.stackOffsetY ?? 0);
1479 this.#applyShove(attacker, tx, ty);
1480 const midX = (ax + tx) / 2;
1481 const midY = (ay + ty) / 2;
1482 const sortY = Math.max(ay, ty) + 0.02;
1483 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
1484 const spriteName = "fx:melee-swipe:melee-swipe";
1485 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
1486 if (object.transform)
1487 { object.transform.rotation = angle; }
1488 this.scene.addObject(object);
1489 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
1490 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
1491 this.swipes.push({
1492 object,
1493 until: performance.now() + 500,
1494 fromTileX: payload.fromTileX,
1495 fromTileY: payload.fromTileY,
1496 tileX: payload.tileX,
1497 tileY: payload.tileY
1498 });
1499 }
1500
1501 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
1502 spawnGatherSwing (payload)
1503 {
1504 const attacker = this.entities.get(payload.attackerId);
1505 if (!attacker)
1506 { return; }
1507 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1508 this.#applyShove(attacker, pivot.x, pivot.y);
1509 if (payload.toolItemId != null)
1510 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
1511 }
1512
1513 #applyShove (entity, targetVisualX, targetVisualY)
1514 {
1515 entity.shove = {
1516 startVisualX: entity.visualX,
1517 startVisualY: entity.visualY,
1518 targetVisualX,
1519 targetVisualY,
1520 started: performance.now(),
1521 durationMs: SHOVE_MS
1522 };
1523 }
1524
1525 #applyShoveInDirection (entity, dirX, dirY)
1526 {
1527 const len = Math.hypot(dirX, dirY);
1528 if (len < 1e-4)
1529 { return; }
1530 const tileSize = this.tileSize();
1531 const ux = dirX / len;
1532 const uy = dirY / len;
1533 this.#applyShove(
1534 entity,
1535 entity.visualX + ux * tileSize,
1536 entity.visualY + uy * tileSize
1537 );
1538 }
1539
1540 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
1541 spawnPhysicalProjectileFx (payload)
1542 {
1543 const spriteName = payload.sprite ?? "fx:projectile:arrow";
1544 const image = this.game.images[spriteName];
1545 if (!image)
1546 { return; }
1547 const dualTint = this.#dualTintFromPayload(payload);
1548 const fromPivot = this.#projectileLaunchPoint(
1549 payload.attackerId ?? null,
1550 payload.fromTileX,
1551 payload.fromTileY
1552 );
1553 const toPivot = this.#projectileAimPoint(
1554 payload.targetId ?? null,
1555 payload.tileX,
1556 payload.tileY
1557 );
1558 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1559 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1560 const object = new GameObject(0, 0, image, SORT_FX);
1561 if (object.transform)
1562 { object.transform.rotation = angle; }
1563 this.scene.addObject(object);
1564 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1565 this.#applyPhysicalCombatFxDarkness(
1566 object,
1567 payload.fromTileX,
1568 payload.fromTileY,
1569 payload.tileX,
1570 payload.tileY,
1571 dualTint
1572 );
1573 const started = performance.now();
1574 const durationMs = payload.durationMs ?? 400;
1575 const trackTarget = payload.trackTarget !== false && payload.targetId != null;
1576 this.swipes.push({
1577 object,
1578 until: started + durationMs,
1579 started,
1580 durationMs,
1581 lerp: true,
1582 dualTint,
1583 fromTileX: payload.fromTileX,
1584 fromTileY: payload.fromTileY,
1585 tileX: payload.tileX,
1586 tileY: payload.tileY,
1587 attackerId: payload.attackerId ?? null,
1588 targetId: payload.targetId ?? null,
1589 trackTarget,
1590 onImpact: null
1591 });
1592 }
1593
1594 /** Bloom-layer spell projectiles — unlit, animated travel. */
1595 spawnSpellProjectileFx (payload)
1596 {
1597 const baseSprite = payload.sprite ?? "fx:projectile:spell-light";
1598 const image = this.#spellProjectileImage(baseSprite, 0);
1599 if (!image)
1600 { return; }
1601 const fromPivot = this.#projectileLaunchPoint(
1602 payload.casterId ?? null,
1603 payload.fromTileX,
1604 payload.fromTileY
1605 );
1606 const toPivot = this.#projectileAimPoint(
1607 payload.targetId ?? null,
1608 payload.tileX,
1609 payload.tileY
1610 );
1611 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1612 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1613 const object = new GameObject(0, 0, image, SORT_FX);
1614 object.renderer.layer = RENDER_LAYER_BLOOM;
1615 this.#markUnlit(object);
1616 if (object.transform)
1617 { object.transform.rotation = angle; }
1618 this.scene.addObject(object);
1619 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1620 const started = performance.now();
1621 const durationMs = payload.durationMs ?? 2000;
1622 this.swipes.push({
1623 object,
1624 until: started + durationMs,
1625 started,
1626 durationMs,
1627 lerp: true,
1628 spellProjectile: true,
1629 baseSprite,
1630 fromTileX: payload.fromTileX,
1631 fromTileY: payload.fromTileY,
1632 tileX: payload.tileX,
1633 tileY: payload.tileY,
1634 attackerId: payload.casterId ?? null,
1635 targetId: payload.targetId ?? null,
1636 trackTarget: payload.targetId != null,
1637 onImpact: null
1638 });
1639 }
1640
1641 spawnSpellFizzleFx (_payload)
1642 {
1643 // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
1644 }
1645
1646 /**
1647 * Authoritative Light-spell tile light from the server.
1648 * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
1649 */
1650 setSpellLight (payload)
1651 {
1652 const key = `${payload.tileX},${payload.tileY}`;
1653 this.spellLights.set(key, {
1654 tileX: payload.tileX,
1655 tileY: payload.tileY,
1656 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1657 range: payload.rangeTiles ?? 6,
1658 intensity: payload.intensity ?? 0.88
1659 });
1660 }
1661
1662 removeSpellLight (payload)
1663 {
1664 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
1665 }
1666
1667 setSpellDark (payload)
1668 {
1669 const key = `${payload.tileX},${payload.tileY}`;
1670 this.spellDarks.set(key, {
1671 tileX: payload.tileX,
1672 tileY: payload.tileY,
1673 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1674 range: payload.rangeTiles ?? 6,
1675 intensity: payload.intensity ?? 0.88
1676 });
1677 }
1678
1679 removeSpellDark (payload)
1680 {
1681 this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);
1682 }
1683
1684 #spellProjectileImage (baseSprite, frameIndex)
1685 {
1686 const frame = Math.max(0, Math.min(2, frameIndex | 0));
1687 const stem = baseSprite.split(":").pop() ?? "spell-light";
1688 const names = [
1689 `${baseSprite}-${frame}`,
1690 `fx:projectile:${stem}-${frame}`,
1691 baseSprite,
1692 `fx:projectile:${stem}`
1693 ];
1694 for (const name of names)
1695 {
1696 if (this.game.images[name])
1697 { return this.game.images[name]; }
1698 }
1699 return null;
1700 }
1701
1702 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
1703 {
1704 this.dynamicLights.push({
1705 tileX: Math.floor(worldX),
1706 tileY: Math.floor(worldY),
1707 range: radiusTiles,
1708 intensity,
1709 until: performance.now() + durationMs
1710 });
1711 }
1712
1713 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
1714 {
1715 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1716 if (!snapshot)
1717 { return; }
1718 const index = localY * CHUNK_SIZE + localX;
1719 if (ground !== undefined)
1720 { snapshot.grounds[index] = ground; }
1721 if (block !== undefined)
1722 { snapshot.blocks[index] = block; }
1723 if (light !== undefined)
1724 { snapshot.light[index] = light; }
1725 const tileX = chunkX * CHUNK_SIZE + localX;
1726 const tileY = chunkY * CHUNK_SIZE + localY;
1727 if (block !== undefined)
1728 {
1729 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
1730 this.#drawTile(tileX, tileY);
1731 return;
1732 }
1733 this.#scheduleChunkRebuild(snapshot);
1734 if (ground !== undefined)
1735 { this.#drawTile(tileX, tileY); }
1736 }
1737
1738 /**
1739 * Editor-only mob markers for authored spawners (invisible during play).
1740 * @param {number} chunkX
1741 * @param {number} chunkY
1742 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
1743 * @param {(mobTypeId: string) => string} resolveSprite
1744 */
1745 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
1746 {
1747 const prefix = `${chunkX},${chunkY}:`;
1748 for (const [key, entry] of [...this.editorSpawners.entries()])
1749 {
1750 if (!key.startsWith(prefix))
1751 { continue; }
1752 entry.object?.destroy();
1753 this.editorSpawners.delete(key);
1754 }
1755 for (const spawner of spawners ?? [])
1756 {
1757 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
1758 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
1759 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
1760 if (!spriteName)
1761 { continue; }
1762 const key = `${prefix}${spawner.localX},${spawner.localY}`;
1763 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
1764 if (!object)
1765 { continue; }
1766 object.renderer.alpha = 0.85;
1767 const pivot = tilePivot(tileX, tileY, this.tileSize());
1768 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1769 this.#markUnlit(object);
1770 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
1771 }
1772 }
1773
1774 clearEditorSpawners ()
1775 {
1776 for (const entry of this.editorSpawners.values())
1777 { entry.object?.destroy(); }
1778 this.editorSpawners.clear();
1779 }
1780
1781 #relayoutEditorSpawners ()
1782 {
1783 const size = this.tileSize();
1784 for (const entry of this.editorSpawners.values())
1785 {
1786 if (!entry.object)
1787 { continue; }
1788 const pivot = tilePivot(entry.tileX, entry.tileY, size);
1789 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1790 }
1791 }
1792
1793 /**
1794 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
1795 */
1796 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
1797 {
1798 const spawnRadius = Math.max(0, spawnRange | 0);
1799 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
1800 if (this.spawnRangeHighlight
1801 && this.wanderRangeHighlight
1802 && this.spawnRangeHighlight.tileX === tileX
1803 && this.spawnRangeHighlight.tileY === tileY
1804 && this.spawnRangeHighlight.range === spawnRadius
1805 && this.wanderRangeHighlight.range === wanderRadius)
1806 {
1807 this.#relayoutSpawnRangeHighlight();
1808 return;
1809 }
1810 this.clearSpawnRangeHighlight();
1811 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
1812 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
1813 if (wanderObject)
1814 {
1815 this.#markUnlit(wanderObject);
1816 wanderObject.renderer.alpha = 1;
1817 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
1818 }
1819 if (spawnObject)
1820 {
1821 this.#markUnlit(spawnObject);
1822 spawnObject.renderer.alpha = 1;
1823 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
1824 }
1825 this.#relayoutSpawnRangeHighlight();
1826 }
1827
1828 clearSpawnRangeHighlight ()
1829 {
1830 this.spawnRangeHighlight?.object?.destroy();
1831 this.wanderRangeHighlight?.object?.destroy();
1832 this.spawnRangeHighlight = null;
1833 this.wanderRangeHighlight = null;
1834 }
1835
1836 setSpellTargetHighlight (tileX, tileY, inRange = true)
1837 {
1838 if (
1839 this.spellTargetHighlight
1840 && this.spellTargetHighlight.mode === "tile"
1841 && this.spellTargetHighlight.tileX === tileX
1842 && this.spellTargetHighlight.tileY === tileY
1843 && this.spellTargetHighlight.inRange === inRange
1844 )
1845 {
1846 this.#relayoutSpellTargetHighlight();
1847 return;
1848 }
1849 this.clearSpellTargetHighlight();
1850 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
1851 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1852 if (!object)
1853 { return; }
1854 this.#markUnlit(object);
1855 object.renderer.alpha = 1;
1856 this.spellTargetHighlight = {
1857 mode: "tile",
1858 object,
1859 tileX,
1860 tileY,
1861 entityId: null,
1862 inRange,
1863 spriteName
1864 };
1865 this.#relayoutSpellTargetHighlight();
1866 }
1867
1868 /** Outline box around a living entity (mob / player) for entity-target spells. */
1869 setSpellEntityTargetHighlight (entityId, inRange = true)
1870 {
1871 const id = entityId | 0;
1872 if (
1873 this.spellTargetHighlight
1874 && this.spellTargetHighlight.mode === "entity"
1875 && this.spellTargetHighlight.entityId === id
1876 && this.spellTargetHighlight.inRange === inRange
1877 )
1878 {
1879 this.#relayoutSpellTargetHighlight();
1880 return;
1881 }
1882 this.clearSpellTargetHighlight();
1883 if (!this.entities.has(id))
1884 { return; }
1885 const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid";
1886 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1887 if (!object)
1888 { return; }
1889 this.#markUnlit(object);
1890 object.renderer.alpha = 1;
1891 this.spellTargetHighlight = {
1892 mode: "entity",
1893 object,
1894 tileX: 0,
1895 tileY: 0,
1896 entityId: id,
1897 inRange,
1898 spriteName
1899 };
1900 this.#relayoutSpellTargetHighlight();
1901 }
1902
1903 clearSpellTargetHighlight ()
1904 {
1905 this.spellTargetHighlight?.object?.destroy();
1906 this.spellTargetHighlight = null;
1907 }
1908
1909 #relayoutSpellTargetHighlight ()
1910 {
1911 const highlight = this.spellTargetHighlight;
1912 if (!highlight?.object)
1913 { return; }
1914 if (highlight.mode === "entity")
1915 {
1916 const entity = this.entities.get(highlight.entityId);
1917 if (!entity?.object)
1918 {
1919 this.clearSpellTargetHighlight();
1920 return;
1921 }
1922 const pad = this.tileSize() * 0.12;
1923 const src = entity.object.transform;
1924 highlight.object.transform.position.x = src.position.x;
1925 highlight.object.transform.position.y = src.position.y;
1926 highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad);
1927 highlight.object.layer = LAYER_EDGE - 1;
1928 highlight.tileX = entity.tileX;
1929 highlight.tileY = entity.tileY;
1930 this.#markSortDirty();
1931 return;
1932 }
1933 const size = this.tileSize();
1934 const left = highlight.tileX * size;
1935 const top = highlight.tileY * size;
1936 highlight.object.transform.position.x = left + size / 2;
1937 highlight.object.transform.position.y = top + size / 2;
1938 highlight.object.transform.size = new vector(size, size);
1939 highlight.object.layer = LAYER_EDGE - 1;
1940 this.#markSortDirty();
1941 }
1942
1943 #relayoutSpawnRangeHighlight ()
1944 {
1945 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
1946 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
1947 }
1948
1949 #layoutRangeOverlay (highlight, layer)
1950 {
1951 if (!highlight?.object)
1952 { return; }
1953 const size = this.tileSize();
1954 const side = (2 * highlight.range + 1) * size;
1955 const left = (highlight.tileX - highlight.range) * size;
1956 const top = (highlight.tileY - highlight.range) * size;
1957 highlight.object.transform.position.x = left + side / 2;
1958 highlight.object.transform.position.y = top + side / 2;
1959 highlight.object.transform.size = new vector(side, side);
1960 highlight.object.layer = layer;
1961 this.#markSortDirty();
1962 }
1963
1964 setTilePreview (tileX, tileY, override)
1965 {
1966 const next = { tileX, tileY, ...override };
1967 if (this.#previewEqual(this.preview, next))
1968 { return; }
1969 const previous = this.preview;
1970 this.preview = next;
1971 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1972 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1973 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
1974 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1975 {
1976 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
1977 if (prevKey !== `${chunkX},${chunkY}`)
1978 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
1979 }
1980 }
1981
1982 clearTilePreview ()
1983 {
1984 if (!this.preview)
1985 { return; }
1986 const previous = this.preview;
1987 this.preview = null;
1988 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1989 this.#scheduleChunkRebuild(snapshot);
1990 }
1991
1992 #lerpMs (gait)
1993 {
1994 const walk = this.settings.walkTilesPerSecond || 2;
1995 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
1996 return seconds * 1000;
1997 }
1998
1999 #centerCamera ()
2000 {
2001 if (!this.followPlayer)
2002 { return; }
2003 const local = this.entities.get(this.localEntityId);
2004 if (!local)
2005 { return; }
2006 const x = local.visualX + (local.stackOffsetX ?? 0);
2007 const y = local.visualY + (local.stackOffsetY ?? 0);
2008 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
2009 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
2010 }
2011
2012 /**
2013 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
2014 * Tiles fully outside this rect are not drawn.
2015 */
2016 #drawBounds ()
2017 {
2018 const pad = this.tileSize() * 0.5;
2019 const camX = this.scene.cameraPosition.x;
2020 const camY = this.scene.cameraPosition.y;
2021 const w = this.scene.real_size.x;
2022 const h = this.scene.real_size.y;
2023 return {
2024 left: -camX - pad,
2025 right: -camX + w + pad,
2026 top: -camY - pad,
2027 bottom: -camY + h + pad
2028 };
2029 }
2030
2031 #rectIntersects (left, top, right, bottom, bounds)
2032 {
2033 return right >= bounds.left
2034 && left <= bounds.right
2035 && bottom >= bounds.top
2036 && top <= bounds.bottom;
2037 }
2038
2039 #setRendererVisible (object, visible)
2040 {
2041 if (object?.renderer)
2042 { object.renderer.visible = !!visible; }
2043 }
2044
2045 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
2046 #cullOffscreenDrawables ()
2047 {
2048 const bounds = this.#drawBounds();
2049 const size = this.tileSize();
2050
2051 for (const baked of this.bakedChunks.values())
2052 {
2053 const left = baked.chunkX * CHUNK_SIZE * size;
2054 const top = baked.chunkY * CHUNK_SIZE * size;
2055 const chunkPx = CHUNK_SIZE * size;
2056 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
2057 this.#setRendererVisible(baked.groundObject, chunkVisible);
2058 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
2059 baked._inViewport = chunkVisible;
2060 for (let row = 0; row < CHUNK_SIZE; row++)
2061 {
2062 const rowTop = top + row * size;
2063 const rowVisible = chunkVisible && this.#rectIntersects(
2064 left, rowTop, left + chunkPx, rowTop + size, bounds
2065 );
2066 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
2067 }
2068 }
2069
2070 for (const objects of this.tiles.values())
2071 {
2072 const left = objects.tileX * size;
2073 const top = objects.tileY * size;
2074 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
2075 objects._inViewport = visible;
2076 this.#setRendererVisible(objects.ground, visible);
2077 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
2078 this.#setRendererVisible(objects.block, visible);
2079 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
2080 if (objects.waterEdges)
2081 {
2082 for (const edge of Object.values(objects.waterEdges))
2083 { this.#setRendererVisible(edge, visible); }
2084 }
2085 }
2086 }
2087
2088 #upsertEntity (payload)
2089 {
2090 const size = this.tileSize();
2091 const pivot = tilePivot(payload.tileX, payload.tileY, size);
2092 let entity = this.entities.get(payload.entityId);
2093 if (!entity)
2094 {
2095 const spriteName = payload.layers?.[0]?.sprite
2096 ?? payload.sprite
2097 ?? bodySpriteName(payload.sex);
2098 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
2099 this.scene.addObject(object);
2100 this.#startIdleAnimation(object);
2101 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
2102 this.entities.set(payload.entityId, entity);
2103 }
2104 entity.entityId = payload.entityId;
2105 entity.tileX = payload.tileX;
2106 entity.tileY = payload.tileY;
2107 entity.gait = payload.gait;
2108 entity.sex = payload.sex ?? entity.sex;
2109 entity.characterId = payload.characterId ?? entity.characterId ?? null;
2110 entity.accountId = payload.accountId ?? entity.accountId ?? null;
2111 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
2112 if (payload.level != null)
2113 { entity.level = payload.level | 0; }
2114 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
2115 entity.canFight = payload.canFight != null
2116 ? !!payload.canFight
2117 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
2118 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
2119 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
2120 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
2121 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
2122 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
2123 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
2124 if (payload.visualScale != null)
2125 { entity.visualScale = Number(payload.visualScale) || 1; }
2126 else if (entity.visualScale == null)
2127 { entity.visualScale = 1; }
2128 if (payload.health != null)
2129 { entity.health = payload.health; }
2130 if (payload.maxHealth != null)
2131 { entity.maxHealth = payload.maxHealth; }
2132 if (payload.skullValue != null)
2133 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
2134 else if (entity.skullValue == null)
2135 { entity.skullValue = 0; }
2136 if (payload.firstName)
2137 { entity.firstName = payload.firstName; }
2138 if (payload.lastName)
2139 { entity.lastName = payload.lastName; }
2140 entity.firstName = entity.firstName ?? "";
2141 entity.lastName = entity.lastName ?? "";
2142 if (payload.worldX != null && payload.worldY != null)
2143 {
2144 entity.worldX = payload.worldX;
2145 entity.worldY = payload.worldY;
2146 entity.visualX = payload.worldX * size;
2147 entity.visualY = payload.worldY * size;
2148 entity.targetX = entity.visualX;
2149 entity.targetY = entity.visualY;
2150 }
2151 else
2152 {
2153 entity.visualX = pivot.x;
2154 entity.visualY = pivot.y;
2155 entity.targetX = pivot.x;
2156 entity.targetY = pivot.y;
2157 }
2158 entity.fromX = entity.visualX;
2159 entity.fromY = entity.visualY;
2160 if (payload.layers)
2161 { this.#applyLayers(entity, payload.layers); }
2162 this.#syncHpBar(entity);
2163 this.#syncSkullMarker(entity);
2164 this.#placeEntity(entity, performance.now());
2165 }
2166
2167 #applyLayers (entity, layers)
2168 {
2169 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
2170 this.#rebuildOverlays(entity);
2171 }
2172
2173 #setGatherToolOverlay (entity, toolItemId)
2174 {
2175 entity.gatherToolItemId = toolItemId;
2176 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
2177 this.#rebuildOverlays(entity);
2178 this.#placeEntity(entity, performance.now());
2179 }
2180
2181 #expireGatherToolOverlay (entity, now)
2182 {
2183 if (entity.gatherToolItemId == null)
2184 { return; }
2185 if ((entity.gatherToolUntil ?? 0) > now)
2186 { return; }
2187 entity.gatherToolItemId = null;
2188 entity.gatherToolUntil = 0;
2189 this.#rebuildOverlays(entity);
2190 }
2191
2192 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
2193 #layersForDisplay (entity)
2194 {
2195 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
2196 const toolId = entity.gatherToolItemId;
2197 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
2198 { return layers; }
2199 const equip = itemEquipSprite(toolId);
2200 if (!equip || !this.game.images[equip])
2201 { return layers; }
2202 const replacement = {
2203 sprite: equip,
2204 itemId: toolId,
2205 tint: resolveEquipTint(toolId)
2206 };
2207 for (let index = layers.length - 1; index >= 1; index--)
2208 {
2209 const def = itemDefinition(layers[index].itemId);
2210 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
2211 {
2212 layers[index] = replacement;
2213 return layers;
2214 }
2215 }
2216 layers.push(replacement);
2217 return layers;
2218 }
2219
2220 #rebuildOverlays (entity)
2221 {
2222 const layers = this.#layersForDisplay(entity);
2223 const base = layers[0]?.sprite
2224 ?? bodySpriteName(entity.sex);
2225 if (this.game.images[base])
2226 {
2227 entity.object.renderer.sprite = this.game.images[base];
2228 this.#startIdleAnimation(entity.object);
2229 }
2230 entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2231 entity.bloomBody = !!layers[0]?.bloomBody;
2232 for (const overlay of entity.overlays ?? [])
2233 { overlay.destroy(); }
2234 for (const overlay of entity.bloomOverlays ?? [])
2235 { overlay.destroy(); }
2236 entity.overlays = [];
2237 entity.overlayTints = [];
2238 entity.overlayDualTints = [];
2239 entity.overlayTightFit = [];
2240 entity.bloomOverlays = [];
2241 entity.bloomOverlayTints = [];
2242 if (entity.bloomBody && this.game.images[base])
2243 {
2244 const bloomName = bloomCompanionName(base);
2245 const bloomImage = this.game.images[bloomName] ?? this.game.images[base];
2246 if (bloomImage)
2247 {
2248 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2249 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2250 this.#markUnlit(bloom);
2251 this.scene.addObject(bloom);
2252 entity.bloomOverlays.push(bloom);
2253 entity.bloomOverlayTints.push(entity.bodyTint);
2254 }
2255 }
2256 for (const layer of layers.slice(1))
2257 {
2258 const image = this.game.images[layer.sprite];
2259 if (!image)
2260 { continue; }
2261 const object = new GameObject(0, 0, image, SORT_ENTITY);
2262 this.scene.addObject(object);
2263 entity.overlays.push(object);
2264 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2265 entity.overlayTightFit.push(!!layerDef?.tightFit);
2266 const dualTint = layer.itemId != null
2267 ? resolveItemDualTint({ itemId: layer.itemId }, layerDef)
2268 : null;
2269 entity.overlayDualTints.push(dualTint);
2270 entity.overlayTints.push(
2271 dualTint
2272 ? null
2273 : (layer.tint
2274 ? normalizeRgb(layer.tint)
2275 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
2276 );
2277 const bloomName = bloomCompanionName(layer.sprite);
2278 const bloomImage = this.game.images[bloomName];
2279 if (!bloomImage)
2280 { continue; }
2281 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2282 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2283 this.#markUnlit(bloom);
2284 this.scene.addObject(bloom);
2285 entity.bloomOverlays.push(bloom);
2286 entity.bloomOverlayTints.push(
2287 layer.tint ? normalizeRgb(layer.tint) : null
2288 );
2289 }
2290 }
2291
2292 #placeEntity (entity, now = performance.now())
2293 {
2294 const zoom = this.zoom;
2295 const offsetX = entity.shoveOffsetX ?? 0;
2296 const offsetY = entity.shoveOffsetY ?? 0;
2297 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
2298 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
2299 let walkTilt = 0;
2300 if (entity.lerpStarted != null)
2301 {
2302 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
2303 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
2304 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
2305 walkTilt = Math.sin(cycles) * tilt;
2306 }
2307 const flashStrength = (entity.damageFlashUntil ?? 0) > now
2308 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
2309 : 0;
2310 const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE;
2311 const tileShade = this.#entityShadeAlpha(entity, now);
2312 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
2313
2314 entity.object.transform.rotation = walkTilt;
2315 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor);
2316 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1);
2317 for (let index = 0; index < (entity.overlays ?? []).length; index++)
2318 {
2319 const overlay = entity.overlays[index];
2320 const overlaySortY = pivotY + 0.5 * (index + 1);
2321 overlay.transform.rotation = walkTilt;
2322 const dualTint = entity.overlayDualTints?.[index] ?? null;
2323 if (dualTint)
2324 {
2325 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor);
2326 }
2327 else if (entity.overlayTightFit?.[index])
2328 {
2329 this.#syncTightFitLitSprite(
2330 overlay,
2331 entity,
2332 tileShade,
2333 flashStrength,
2334 wade,
2335 entity.overlayTints?.[index] ?? null,
2336 flashColor
2337 );
2338 }
2339 else
2340 {
2341 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor);
2342 }
2343 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
2344 }
2345 for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++)
2346 {
2347 const overlay = entity.bloomOverlays[index];
2348 this.#setRendererVisible(overlay, this.bloomEnabled);
2349 if (!this.bloomEnabled)
2350 { continue; }
2351 /** Body bloom must share the base sprite's animation frame (e.g. elemental sprites). */
2352 if (entity.bloomBody && index === 0 && entity.object?.renderer)
2353 {
2354 overlay.renderer.cycle = null;
2355 overlay.renderer.subImage = entity.object.renderer.subImage | 0;
2356 }
2357 overlay.transform.rotation = walkTilt;
2358 const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null;
2359 if (bloomTint)
2360 { this.#syncUnlitTintSprite(overlay, bloomTint); }
2361 else
2362 { this.#syncLitSprite(overlay, tileShade, flashStrength, wade, null, flashColor); }
2363 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
2364 }
2365 this.#placeHpBar(entity, pivotX, pivotY);
2366 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
2367 }
2368
2369 #markUnlit (object)
2370 {
2371 if (!object?.renderer)
2372 { return; }
2373 object._lit = false;
2374 object.renderer.shader = null;
2375 object.renderer.shaderUniforms = null;
2376 object.renderer.secondaryMap = null;
2377 }
2378
2379 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
2380 #syncUnlitTintSprite (object, tintColor)
2381 {
2382 if (!object?.renderer || !tintColor)
2383 { return; }
2384 const tint = normalizeRgb(tintColor);
2385 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2386 object.renderer.shader = getTintLitSpriteShader();
2387 object.renderer.shaderUniforms = {
2388 u_darkness: 0,
2389 u_strength: 0,
2390 u_flashColor: FLASH_COLOR_DAMAGE,
2391 u_wade: 0,
2392 u_spriteHeight: height,
2393 u_useTint: 1,
2394 u_tintColor: [tint.r, tint.g, tint.b]
2395 };
2396 object.renderer.secondaryMap = null;
2397 }
2398
2399 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
2400 {
2401 if (!object?.renderer || object._lit === false)
2402 { return; }
2403 object._lit = true;
2404 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2405 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2406 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2407 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
2408 const tint = tintColor ? normalizeRgb(tintColor) : null;
2409 if (tint)
2410 {
2411 object.renderer.shader = getTintLitSpriteShader();
2412 object.renderer.shaderUniforms = {
2413 u_darkness: dark,
2414 u_strength: flash,
2415 u_flashColor: flashRgb,
2416 u_wade: wade ? 1 : 0,
2417 u_spriteHeight: height,
2418 u_useTint: 1,
2419 u_tintColor: [tint.r, tint.g, tint.b]
2420 };
2421 }
2422 else
2423 {
2424 object.renderer.shader = getSpriteLightingShader();
2425 object.renderer.shaderUniforms = {
2426 u_darkness: dark,
2427 u_strength: flash,
2428 u_flashColor: flashRgb,
2429 u_wade: wade ? 1 : 0,
2430 u_spriteHeight: height
2431 };
2432 }
2433 object.renderer.secondaryMap = null;
2434 }
2435
2436 #bodySecondaryMap (entity)
2437 {
2438 return entity?.object?.renderer?.sprite?.g_image ?? null;
2439 }
2440
2441 #tightFitMaskUniforms (overlay, entity)
2442 {
2443 const bodyRenderer = entity?.object?.renderer;
2444 const clothRenderer = overlay?.renderer;
2445 const bodySprite = bodyRenderer?.sprite;
2446 const clothSprite = clothRenderer?.sprite;
2447 if (!bodySprite || !clothSprite)
2448 { return null; }
2449 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
2450 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2451 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
2452 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2453 return {
2454 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
2455 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
2456 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
2457 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
2458 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
2459 };
2460 }
2461
2462 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
2463 {
2464 if (!overlay?.renderer || entity?.object?.renderer == null)
2465 { return; }
2466 const bodyMap = this.#bodySecondaryMap(entity);
2467 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
2468 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
2469 if (!bodyMap || !maskUniforms)
2470 {
2471 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
2472 return;
2473 }
2474 overlay._lit = true;
2475 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2476 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2477 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2478 const tint = tintColor ? normalizeRgb(tintColor) : null;
2479 overlay.renderer.secondaryMap = bodyMap;
2480 if (tint)
2481 {
2482 overlay.renderer.shader = getTightFitTintLitSpriteShader();
2483 overlay.renderer.shaderUniforms = {
2484 u_darkness: dark,
2485 u_strength: flash,
2486 u_flashColor: flashRgb,
2487 u_wade: wade ? 1 : 0,
2488 u_spriteHeight: height,
2489 u_useTint: 1,
2490 u_tintColor: [tint.r, tint.g, tint.b],
2491 ...maskUniforms
2492 };
2493 }
2494 else
2495 {
2496 overlay.renderer.shader = getTightFitLitSpriteShader();
2497 overlay.renderer.shaderUniforms = {
2498 u_darkness: dark,
2499 u_strength: flash,
2500 u_flashColor: flashRgb,
2501 u_wade: wade ? 1 : 0,
2502 u_spriteHeight: height,
2503 ...maskUniforms
2504 };
2505 }
2506 }
2507
2508 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null)
2509 {
2510 if (!object?.renderer || object._lit === false || !dualTint)
2511 { return; }
2512 object._lit = true;
2513 const shaft = normalizeRgb(dualTint.shaft);
2514 const tip = normalizeRgb(dualTint.tip);
2515 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
2516 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2517 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2518 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2519 object.renderer.shader = getDualTintLitSpriteShader();
2520 object.renderer.shaderUniforms = {
2521 u_darkness: dark,
2522 u_strength: flash,
2523 u_flashColor: flashColor ?? FLASH_COLOR_DAMAGE,
2524 u_wade: wade ? 1 : 0,
2525 u_spriteHeight: height,
2526 u_shaftTint: [shaft.r, shaft.g, shaft.b],
2527 u_tipTint: [tip.r, tip.g, tip.b],
2528 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
2529 u_hasCoat: coat ? 1 : 0
2530 };
2531 object.renderer.secondaryMap = null;
2532 }
2533
2534 #syncGroundItemSprite (item, darkness)
2535 {
2536 if (item?.dualTint)
2537 {
2538 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
2539 return;
2540 }
2541 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
2542 }
2543
2544 #groundTypeAt (tileX, tileY)
2545 {
2546 const ground = this.#groundAtTile(tileX, tileY);
2547 return ground == null ? null : normalizeGround(ground).typeId;
2548 }
2549
2550 /** Ground entry at a world tile, including editor hover preview when present. */
2551 #groundAtTile (tileX, tileY)
2552 {
2553 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
2554 && this.preview.ground !== undefined)
2555 { return this.preview.ground; }
2556 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2557 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2558 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2559 if (!snapshot)
2560 { return null; }
2561 const localX = tileX - chunkX * CHUNK_SIZE;
2562 const localY = tileY - chunkY * CHUNK_SIZE;
2563 const index = localY * CHUNK_SIZE + localX;
2564 return snapshot.grounds?.[index] ?? null;
2565 }
2566
2567 #waterCoastEdges (tileX, tileY)
2568 {
2569 const season = this.worldSeason;
2570 return {
2571 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
2572 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
2573 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
2574 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
2575 };
2576 }
2577
2578 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
2579 {
2580 if (!object?.renderer)
2581 { return; }
2582 const lit = corners ?? {
2583 nw: fallbackLit,
2584 ne: fallbackLit,
2585 sw: fallbackLit,
2586 se: fallbackLit
2587 };
2588 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
2589 object._lit = true;
2590 object.renderer.shader = getWaterGroundShader();
2591 object.renderer.secondaryMap = null;
2592 object.renderer.shaderUniforms = {
2593 u_ambientDark: dark,
2594 u_litNW: lit.nw,
2595 u_litNE: lit.ne,
2596 u_litSW: lit.sw,
2597 u_litSE: lit.se,
2598 u_time: timeSec,
2599 u_edgeN: edges?.n ?? 0,
2600 u_edgeE: edges?.e ?? 0,
2601 u_edgeS: edges?.s ?? 0,
2602 u_edgeW: edges?.w ?? 0
2603 };
2604 }
2605
2606 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
2607 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
2608 {
2609 if (!objects?.ground)
2610 { return; }
2611 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
2612 {
2613 objects.waterEdges = null;
2614 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
2615 return;
2616 }
2617 const fallbackLit = ambientDark > 0
2618 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
2619 : 1;
2620 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
2621 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
2622 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
2623 const localX = objects.tileX - chunkX * CHUNK_SIZE;
2624 const localY = objects.tileY - chunkY * CHUNK_SIZE;
2625 let litCorners = null;
2626 if (chunkBaked)
2627 {
2628 if (this.lightingMode === "simple")
2629 {
2630 const gridW = CHUNK_SIZE + 2;
2631 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
2632 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
2633 }
2634 else
2635 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
2636 }
2637 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
2638 this.#syncWaterGroundSprite(
2639 objects.ground,
2640 litCorners,
2641 ambientDark,
2642 objects.waterEdges,
2643 timeSec,
2644 fallbackLit
2645 );
2646 }
2647
2648 #ambientDarkness ()
2649 {
2650 const hour = this.nightPreview ?? this.worldHour;
2651 const calendar = nightFactor(hour, this.settings.nightDarkness);
2652 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
2653 if (dark == null)
2654 { dark = calendar; }
2655 if (this.localBlind)
2656 { dark = Math.min(1, dark + 0.85); }
2657 return dark;
2658 }
2659
2660 setLocalBlind (blind)
2661 {
2662 this.localBlind = !!blind;
2663 }
2664
2665 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
2666 #blindVisionLight ()
2667 {
2668 if (!this.localBlind)
2669 { return null; }
2670 const local = this.entities.get(this.localEntityId);
2671 if (!local)
2672 { return null; }
2673 const tileSize = this.tileSize();
2674 return {
2675 tileX: Math.floor(local.visualX / tileSize),
2676 tileY: Math.floor(local.visualY / tileSize),
2677 range: 2.25,
2678 intensity: 1
2679 };
2680 }
2681
2682 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
2683 {
2684 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
2685 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
2686 const dark = (fromAlpha + toAlpha) / 2;
2687 if (dualTint)
2688 {
2689 this.#syncDualTintLitSprite(object, dark, dualTint);
2690 return;
2691 }
2692 this.#syncLitSprite(object, dark);
2693 }
2694
2695 #dualTintFromPayload (payload)
2696 {
2697 if (!payload?.shaftTint || !payload?.tipTint)
2698 { return null; }
2699 return {
2700 shaft: payload.shaftTint,
2701 tip: payload.tipTint,
2702 ...(payload.coatTint ? { coat: payload.coatTint } : {})
2703 };
2704 }
2705
2706 #syncHpBar (entity)
2707 {
2708 const current = entity.health;
2709 const max = entity.maxHealth;
2710 const show = current != null
2711 && max != null
2712 && max > 0
2713 && current < max;
2714 if (!show)
2715 {
2716 entity.hpBar?.destroy();
2717 entity.hpBar = null;
2718 entity.hpBarCanvas = null;
2719 return;
2720 }
2721 if (!entity.hpBarCanvas)
2722 {
2723 entity.hpBarCanvas = document.createElement("canvas");
2724 entity.hpBarCanvas.width = HP_BAR_W;
2725 entity.hpBarCanvas.height = HP_BAR_H;
2726 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
2727 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
2728 this.#markUnlit(entity.hpBar);
2729 this.scene.addObject(entity.hpBar);
2730 }
2731 drawHpBar(entity.hpBarCanvas, current, max);
2732 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
2733 }
2734
2735 #placeHpBar (entity, pivotX, pivotY)
2736 {
2737 if (!entity.hpBar)
2738 { return; }
2739 const sprite = entity.object?.renderer?.sprite;
2740 if (!sprite)
2741 { return; }
2742 const zoom = this.zoom;
2743 const drawH = sprite.height * zoom;
2744 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
2745 const spriteTop = centerY - drawH / 2;
2746 const barW = HP_BAR_W * zoom;
2747 const barH = HP_BAR_H * zoom;
2748 entity.hpBar.transform.position.x = pivotX;
2749 entity.hpBar.transform.position.y = spriteTop - barH / 2;
2750 entity.hpBar.transform.size = new vector(barW, barH);
2751 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
2752 this.#markSortDirty();
2753 }
2754
2755 #syncSkullMarker (entity)
2756 {
2757 if (!entity?.characterId)
2758 {
2759 entity.skullMarker?.destroy();
2760 entity.skullMarker = null;
2761 return;
2762 }
2763 const tint = skullTintColor(entity.skullValue | 0);
2764 if (!tint)
2765 {
2766 entity.skullMarker?.destroy();
2767 entity.skullMarker = null;
2768 return;
2769 }
2770 const image = this.game.images[SKULL_SPRITE];
2771 if (!image)
2772 { return; }
2773 if (!entity.skullMarker)
2774 {
2775 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
2776 this.scene.addObject(entity.skullMarker);
2777 }
2778 entity.skullTint = tint;
2779 entity.skullMarker.renderer.sprite = image;
2780 }
2781
2782 /**
2783 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
2784 */
2785 #placeSkullMarker (entity, pivotX, pivotY, darkness)
2786 {
2787 this.#syncSkullMarker(entity);
2788 if (!entity.skullMarker)
2789 { return; }
2790 const body = entity.object?.renderer?.sprite;
2791 const skull = entity.skullMarker.renderer?.sprite;
2792 if (!body || !skull)
2793 { return; }
2794 const zoom = this.zoom;
2795 const scale = entity.visualScale ?? 1;
2796 const bodyH = body.height * zoom * scale;
2797 const skullH = skull.height * zoom;
2798 const skullW = skull.width * zoom;
2799 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
2800 const bodyTop = bodyCenterY - bodyH / 2;
2801 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
2802 entity.skullMarker.transform.position.x = pivotX;
2803 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
2804 entity.skullMarker.transform.size = new vector(skullW, skullH);
2805 entity.skullMarker.layer = ySortLayer(pivotY, SORT_HP_BAR);
2806 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
2807 this.#markSortDirty();
2808 }
2809
2810 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2811 {
2812 this.#bakeAndPlaceChunk(snapshot);
2813 this.#relayoutChunkTiles(snapshot);
2814 if (this.softTerrain && refreshSoftNeighbors)
2815 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2816 }
2817
2818 #relayoutChunk (snapshot)
2819 {
2820 this.#layoutBakedChunk(snapshot);
2821 this.#relayoutChunkTiles(snapshot);
2822 }
2823
2824 #relayoutChunkTiles (snapshot)
2825 {
2826 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2827 {
2828 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2829 {
2830 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
2831 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
2832 this.#drawTile(tileX, tileY);
2833 }
2834 }
2835 }
2836
2837 #scheduleChunkRebuild (snapshot)
2838 {
2839 if (!snapshot)
2840 { return; }
2841 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
2842 this.#cancelIdlePrefetch();
2843 this.#ensureChunkFlushScheduled();
2844 }
2845
2846 #scheduleEdgeRebuild ()
2847 {
2848 this.#edgesDirty = true;
2849 this.#cancelIdlePrefetch();
2850 this.#ensureChunkFlushScheduled();
2851 }
2852
2853 #ensureChunkFlushScheduled ()
2854 {
2855 if (this.#chunkRebuildRaf)
2856 { return; }
2857 this.#cancelIdlePrefetch();
2858 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
2859 }
2860
2861 #notePlayerTile (tileX, tileY)
2862 {
2863 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2864 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2865 if (this.#playerChunkX != null
2866 && (chunkX !== this.#playerChunkX || chunkY !== this.#playerChunkY))
2867 {
2868 const dx = chunkX - this.#playerChunkX;
2869 const dy = chunkY - this.#playerChunkY;
2870 if (dx !== 0)
2871 { this.#playerMoveChunkDx = Math.sign(dx); }
2872 if (dy !== 0)
2873 { this.#playerMoveChunkDy = Math.sign(dy); }
2874 }
2875 this.#playerChunkX = chunkX;
2876 this.#playerChunkY = chunkY;
2877 }
2878
2879 #playerChunkCoords ()
2880 {
2881 const local = this.entities.get(this.localEntityId);
2882 if (local)
2883 {
2884 return {
2885 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
2886 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
2887 };
2888 }
2889 if (this.#playerChunkX != null && this.#playerChunkY != null)
2890 {
2891 return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
2892 }
2893 return null;
2894 }
2895
2896 /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
2897 #chunkRebuildScore (key, mode = "urgent")
2898 {
2899 const [chunkX, chunkY] = key.split(",").map(Number);
2900 const player = this.#playerChunkCoords();
2901 if (!player)
2902 { return 0; }
2903 const dx = chunkX - player.chunkX;
2904 const dy = chunkY - player.chunkY;
2905 const dist = Math.abs(dx) + Math.abs(dy);
2906 let ahead = 0;
2907 if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
2908 { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
2909 if (mode === "idle")
2910 {
2911 return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
2912 }
2913 return dist * 10 - Math.max(0, ahead) * 3;
2914 }
2915
2916 #sortedChunkRebuildKeys (mode = "urgent")
2917 {
2918 return [...this.#chunkRebuildKeys].sort((a, b) =>
2919 this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
2920 }
2921
2922 #discoverUnbakedChunks ()
2923 {
2924 for (const key of this.chunks.keys())
2925 {
2926 if (!this.bakedChunks.has(key))
2927 { this.#chunkRebuildKeys.add(key); }
2928 }
2929 }
2930
2931 #hasUnbakedChunks ()
2932 {
2933 for (const key of this.chunks.keys())
2934 {
2935 if (!this.bakedChunks.has(key))
2936 { return true; }
2937 }
2938 return false;
2939 }
2940
2941 #pickIdlePrefetchSnapshot ()
2942 {
2943 let best = null;
2944 let bestScore = Infinity;
2945 for (const snapshot of this.chunks.values())
2946 {
2947 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2948 if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))
2949 { continue; }
2950 const score = this.#chunkRebuildScore(key, "idle");
2951 if (score < bestScore)
2952 {
2953 bestScore = score;
2954 best = snapshot;
2955 }
2956 }
2957 return best;
2958 }
2959
2960 #cancelIdlePrefetch ()
2961 {
2962 if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
2963 { cancelIdleCallback(this.#idlePrefetchId); }
2964 this.#idlePrefetchId = 0;
2965 }
2966
2967 #scheduleIdleChunkPrefetch ()
2968 {
2969 if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
2970 { return; }
2971 if (typeof requestIdleCallback !== "function")
2972 { return; }
2973 if (!this.#hasUnbakedChunks())
2974 { return; }
2975 this.#idlePrefetchId = requestIdleCallback(
2976 (deadline) => this.#runIdleChunkPrefetch(deadline),
2977 { timeout: 2500 }
2978 );
2979 }
2980
2981 #runIdleChunkPrefetch (deadline)
2982 {
2983 this.#idlePrefetchId = 0;
2984 if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
2985 { return; }
2986 this.#discoverUnbakedChunks();
2987 if (this.#chunkRebuildKeys.size)
2988 {
2989 this.#ensureChunkFlushScheduled();
2990 return;
2991 }
2992 const snapshot = this.#pickIdlePrefetchSnapshot();
2993 if (!snapshot)
2994 { return; }
2995 if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
2996 {
2997 this.#scheduleIdleChunkPrefetch();
2998 return;
2999 }
3000 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
3001 if (this.#hasUnbakedChunks())
3002 { this.#scheduleIdleChunkPrefetch(); }
3003 }
3004
3005 #flushChunkWork ()
3006 {
3007 this.#chunkRebuildRaf = 0;
3008 const keys = this.#sortedChunkRebuildKeys("urgent");
3009 const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
3010 const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
3011 this.#chunkRebuildKeys.clear();
3012 for (const key of rest)
3013 { this.#chunkRebuildKeys.add(key); }
3014 for (const key of batch)
3015 {
3016 const snap = this.chunks.get(key);
3017 if (snap)
3018 { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }
3019 }
3020 if (this.#chunkRebuildKeys.size)
3021 {
3022 this.#ensureChunkFlushScheduled();
3023 return;
3024 }
3025 if (this.#edgesDirty)
3026 {
3027 this.#rebuildAllEdges();
3028 this.#edgesDirty = false;
3029 }
3030 this.#scheduleIdleChunkPrefetch();
3031 }
3032
3033 #previewEqual (a, b)
3034 {
3035 if (a === b)
3036 { return true; }
3037 if (!a || !b)
3038 { return false; }
3039 return a.tileX === b.tileX
3040 && a.tileY === b.tileY
3041 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
3042 && this.#previewPart(a.block) === this.#previewPart(b.block);
3043 }
3044
3045 #previewPart (value)
3046 {
3047 return value === undefined ? undefined : JSON.stringify(value);
3048 }
3049
3050 #rebuildSoftTerrainNeighborChunks (snapshot)
3051 {
3052 for (let dy = -1; dy <= 1; dy++)
3053 {
3054 for (let dx = -1; dx <= 1; dx++)
3055 {
3056 if (dx === 0 && dy === 0)
3057 { continue; }
3058 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3059 if (neighbor)
3060 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
3061 }
3062 }
3063 }
3064
3065 #rebakeAllChunks ()
3066 {
3067 for (const snapshot of this.chunks.values())
3068 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
3069 }
3070
3071 #bakeAndPlaceChunk (snapshot)
3072 {
3073 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3074 const atlases = bakeChunkAtlases({
3075 snapshot,
3076 catalog: this.catalog,
3077 images: this.game.images,
3078 preview: this.preview,
3079 season: this.worldSeason,
3080 softTerrain: this.softTerrain,
3081 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
3082 cache: this.#atlasCache
3083 });
3084 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
3085 let baked = this.bakedChunks.get(key);
3086 this.#releaseBakedAtlasRefs(baked);
3087
3088 const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
3089 const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
3090 ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
3091 const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
3092 ?? frameworkImageFromCanvas(atlases.bloom);
3093
3094 if (!baked)
3095 {
3096 const lightmapCanvas = makeLightmapCanvas(atlasPx);
3097 baked = {
3098 groundCanvas: atlases.ground,
3099 blockCanvases: atlases.blockRows,
3100 bloomCanvas: atlases.bloom,
3101 lightmapCanvas,
3102 groundImage,
3103 blockImages,
3104 bloomImage,
3105 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
3106 groundObject: null,
3107 blockObjects: [],
3108 bloomObject: null,
3109 tallBlocks: atlases.tallBlocks,
3110 animatedGrounds: atlases.animatedGrounds,
3111 lightmapPixels: null,
3112 atlasCacheRefs: atlases.cacheRefs
3113 };
3114 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
3115 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
3116 this.scene.addObject(baked.groundObject);
3117 for (let row = 0; row < CHUNK_SIZE; row++)
3118 {
3119 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
3120 this.#applyAtlasLighting(object, baked.lightmapImage, row);
3121 this.scene.addObject(object);
3122 baked.blockObjects.push(object);
3123 }
3124 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
3125 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3126 this.#markUnlit(baked.bloomObject);
3127 this.scene.addObject(baked.bloomObject);
3128 this.bakedChunks.set(key, baked);
3129 }
3130 else
3131 {
3132 if (baked.groundCanvas !== atlases.ground)
3133 {
3134 baked.groundCanvas = atlases.ground;
3135 baked.groundImage = groundImage;
3136 baked.groundObject.renderer.sprite = groundImage;
3137 }
3138 for (let row = 0; row < CHUNK_SIZE; row++)
3139 {
3140 if (baked.blockCanvases[row] !== atlases.blockRows[row])
3141 {
3142 baked.blockCanvases[row] = atlases.blockRows[row];
3143 baked.blockImages[row] = blockImages[row];
3144 baked.blockObjects[row].renderer.sprite = blockImages[row];
3145 }
3146 }
3147 if (baked.bloomCanvas !== atlases.bloom)
3148 {
3149 baked.bloomCanvas = atlases.bloom;
3150 baked.bloomImage = bloomImage;
3151 baked.bloomObject.renderer.sprite = bloomImage;
3152 }
3153 baked.tallBlocks = atlases.tallBlocks;
3154 baked.animatedGrounds = atlases.animatedGrounds;
3155 baked.atlasCacheRefs = atlases.cacheRefs;
3156 }
3157 baked.chunkX = snapshot.chunkX;
3158 baked.chunkY = snapshot.chunkY;
3159 baked.lightmapCacheKey = null;
3160 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
3161 this.#layoutBakedChunk(snapshot);
3162 this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
3163 }
3164
3165 #releaseBakedAtlasRefs (baked)
3166 {
3167 if (!baked?.atlasCacheRefs)
3168 { return; }
3169 this.#atlasCache.release(baked.atlasCacheRefs.ground);
3170 for (const entry of baked.atlasCacheRefs.blockRows ?? [])
3171 { this.#atlasCache.release(entry); }
3172 this.#atlasCache.release(baked.atlasCacheRefs.bloom);
3173 baked.atlasCacheRefs = null;
3174 }
3175
3176 #chunkTextureWarmPriority (chunkX, chunkY)
3177 {
3178 const local = this.entities.get(this.localEntityId);
3179 if (!local)
3180 { return 999; }
3181 const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
3182 const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
3183 return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
3184 }
3185
3186 #queueCanvasTextureWarm (canvas, chunkX, chunkY)
3187 {
3188 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
3189 { return; }
3190 this.#pendingTextureCanvasSet.add(canvas);
3191 this.#pendingTextureCanvases.push({
3192 canvas,
3193 priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
3194 });
3195 this.#scheduleTextureWarm();
3196 }
3197
3198 #queueBakedChunkTextures (baked, chunkX, chunkY)
3199 {
3200 if (!baked)
3201 { return; }
3202 const refs = baked.atlasCacheRefs;
3203 const maybeWarm = (canvas, entry) =>
3204 {
3205 if (!canvas)
3206 { return; }
3207 if (entry && this.#atlasCache.isWarmed(canvas))
3208 { return; }
3209 this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
3210 };
3211 maybeWarm(baked.groundCanvas, refs?.ground);
3212 for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
3213 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
3214 maybeWarm(baked.bloomCanvas, refs?.bloom);
3215 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
3216 }
3217
3218 #scheduleTextureWarm ()
3219 {
3220 if (this.#textureWarmRaf)
3221 { return; }
3222 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
3223 }
3224
3225 #flushTextureWarm ()
3226 {
3227 this.#textureWarmRaf = 0;
3228 if (!this.#pendingTextureCanvases.length)
3229 { return; }
3230 this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
3231 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
3232 for (const entry of batch)
3233 {
3234 this.#pendingTextureCanvasSet.delete(entry.canvas);
3235 setNearestFilter(this.scene, entry.canvas);
3236 this.#atlasCache.markWarmed(entry.canvas);
3237 }
3238 if (this.#pendingTextureCanvases.length)
3239 { this.#scheduleTextureWarm(); }
3240 }
3241
3242 #applyAtlasLighting (object, lightmapImage, lightRow)
3243 {
3244 if (!object?.renderer)
3245 { return; }
3246 object._lit = true;
3247 object.renderer.shader = getAtlasLightingShader();
3248 object.renderer.secondaryMap = lightmapImage;
3249 object.renderer.shaderUniforms = {
3250 u_ambientDark: 0,
3251 u_lightRow: lightRow
3252 };
3253 }
3254
3255 #layoutBakedChunk (snapshot)
3256 {
3257 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3258 const baked = this.bakedChunks.get(key);
3259 if (!baked)
3260 { return; }
3261 const size = this.tileSize();
3262 const left = snapshot.chunkX * CHUNK_SIZE * size;
3263 const top = snapshot.chunkY * CHUNK_SIZE * size;
3264 const chunkPx = CHUNK_SIZE * size;
3265 baked.groundObject.transform.position.x = left + chunkPx / 2;
3266 baked.groundObject.transform.position.y = top + chunkPx / 2;
3267 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
3268 baked.groundObject.layer = LAYER_GROUND;
3269
3270 for (let row = 0; row < CHUNK_SIZE; row++)
3271 {
3272 const object = baked.blockObjects[row];
3273 const rowY = top + row * size + size / 2;
3274 object.transform.position.x = left + chunkPx / 2;
3275 object.transform.position.y = rowY;
3276 object.transform.size = new vector(chunkPx, size);
3277 object.layer = ySortLayer(rowY, SORT_BLOCK);
3278 }
3279
3280 baked.bloomObject.transform.position.x = left + chunkPx / 2;
3281 baked.bloomObject.transform.position.y = top + chunkPx / 2;
3282 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
3283 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
3284 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3285 this.#markSortDirty();
3286 }
3287
3288 #destroyBakedChunk (key)
3289 {
3290 const baked = this.bakedChunks.get(key);
3291 if (!baked)
3292 { return; }
3293 this.#releaseBakedAtlasRefs(baked);
3294 baked.groundObject?.destroy();
3295 for (const object of baked.blockObjects ?? [])
3296 { object.destroy(); }
3297 baked.bloomObject?.destroy();
3298 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3299 this.bakedChunks.delete(key);
3300 }
3301
3302 #redrawPreview ()
3303 {
3304 if (!this.preview)
3305 { return; }
3306 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
3307 if (snapshot)
3308 { this.#rebuildChunk(snapshot); }
3309 }
3310
3311 #refreshWaterCoastsNear (chunkX, chunkY)
3312 {
3313 const timeSec = performance.now() / 1000;
3314 for (const objects of this.tiles.values())
3315 {
3316 if (!objects.ground || !isWaterGround(objects.groundTypeId))
3317 { continue; }
3318 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
3319 { continue; }
3320 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
3321 }
3322 }
3323
3324 #drawTile (tileX, tileY)
3325 {
3326 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3327 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3328 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3329 if (!snapshot)
3330 { return; }
3331 const localX = tileX - chunkX * CHUNK_SIZE;
3332 const localY = tileY - chunkY * CHUNK_SIZE;
3333 const index = localY * CHUNK_SIZE + localX;
3334 const key = `${tileX},${tileY}`;
3335 let objects = this.tiles.get(key);
3336 if (!objects)
3337 {
3338 objects = { chunkX, chunkY, tileX, tileY };
3339 this.tiles.set(key, objects);
3340 }
3341 objects.tileX = tileX;
3342 objects.tileY = tileY;
3343 objects.chunkX = chunkX;
3344 objects.chunkY = chunkY;
3345 objects.light = snapshot.light[index] ?? 0;
3346
3347 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
3348 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
3349 if (animatedGround)
3350 {
3351 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
3352 if (objects.ground)
3353 {
3354 const size = this.tileSize();
3355 objects.ground.transform.position.x = tileX * size + size / 2;
3356 objects.ground.transform.position.y = tileY * size + size / 2;
3357 objects.ground.transform.size = new vector(size, size);
3358 objects.ground.layer = LAYER_GROUND;
3359 objects.groundTypeId = animatedGround.typeId;
3360 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
3361 this.#markSortDirty();
3362 }
3363 if (animatedGround.bloom)
3364 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
3365 else
3366 {
3367 objects.groundBloom?.destroy();
3368 objects.groundBloom = null;
3369 }
3370 }
3371 else
3372 {
3373 objects.ground?.destroy();
3374 objects.ground = null;
3375 objects.groundBloom?.destroy();
3376 objects.groundBloom = null;
3377 objects.groundTypeId = null;
3378 objects.waterEdges = null;
3379 }
3380
3381 const tileBlock = tileBlockSpriteEntry(
3382 this.catalog,
3383 this.game.images,
3384 snapshot.blocks[index],
3385 this.worldSeason
3386 );
3387 if (tileBlock)
3388 {
3389 const pivot = tilePivot(tileX, tileY, this.tileSize());
3390 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, SORT_ENTITY);
3391 if (objects.block)
3392 {
3393 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
3394 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
3395 }
3396 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY);
3397 }
3398 else
3399 {
3400 objects.block?.destroy();
3401 objects.block = null;
3402 objects.blockBloom?.destroy();
3403 objects.blockBloom = null;
3404 }
3405 }
3406
3407 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
3408 {
3409 if (!name)
3410 {
3411 existing?.destroy();
3412 return null;
3413 }
3414 const object = this.#ensureSprite(existing, name, sortOrder);
3415 if (!object)
3416 { return null; }
3417 object.renderer.layer = RENDER_LAYER_BLOOM;
3418 this.#markUnlit(object);
3419 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
3420 return object;
3421 }
3422
3423 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
3424 {
3425 const sprite = object?.renderer?.sprite;
3426 if (!sprite)
3427 { return; }
3428 const zoom = this.zoom;
3429 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
3430 const factor = Math.max(0.1, Number(scale) || 1);
3431 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
3432 object.transform.position.x = center.x;
3433 object.transform.position.y = center.y;
3434 object.transform.size = new vector(draw.w * factor, draw.h * factor);
3435 object.layer = ySortLayer(sortY, subOrder);
3436 this.#markSortDirty();
3437 }
3438
3439 #ensureSprite (existing, name, layer)
3440 {
3441 const sprite = this.game.images[name];
3442 if (!sprite)
3443 {
3444 existing?.destroy();
3445 return null;
3446 }
3447 if (!existing || existing.renderer.sprite !== sprite)
3448 {
3449 existing?.destroy();
3450 existing = new GameObject(0, 0, sprite, layer);
3451 this.#syncLitSprite(existing, 0);
3452 this.scene.addObject(existing);
3453 this.#startIdleAnimation(existing);
3454 }
3455 return existing;
3456 }
3457
3458 #startIdleAnimation (object)
3459 {
3460 const sprite = object?.renderer?.sprite;
3461 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
3462 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
3463 }
3464
3465 #neighborClosed (snapshot, dir, dx, dy)
3466 {
3467 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3468 if (other)
3469 { return !other.open; }
3470 return !!snapshot.closedEdges?.[dir];
3471 }
3472
3473 #rebuildAllEdges ()
3474 {
3475 const seen = new Set();
3476 for (const snapshot of this.chunks.values())
3477 {
3478 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3479 seen.add(key);
3480 this.#rebuildChunkEdges(snapshot);
3481 }
3482 for (const key of [...this.edges.keys()])
3483 {
3484 if (!seen.has(key))
3485 { this.#destroyEdges(key); }
3486 }
3487 }
3488
3489 #rebuildChunkEdges (snapshot)
3490 {
3491 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3492 let bars = this.edges.get(key);
3493 if (!bars)
3494 {
3495 bars = {};
3496 this.edges.set(key, bars);
3497 }
3498
3499 const size = this.tileSize();
3500 const chunkPx = CHUNK_SIZE * size;
3501 const left = snapshot.chunkX * CHUNK_SIZE * size;
3502 const top = snapshot.chunkY * CHUNK_SIZE * size;
3503 const centerX = left + chunkPx / 2;
3504 const centerY = top + chunkPx / 2;
3505 const thickness = Math.max(2, Math.round(2 * this.zoom));
3506 const draw = snapshot.open === true;
3507
3508 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
3509 centerX, top, chunkPx, thickness, true);
3510 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
3511 centerX, top + chunkPx, chunkPx, thickness, true);
3512 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
3513 left, centerY, chunkPx, thickness, false);
3514 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
3515 left + chunkPx, centerY, chunkPx, thickness, false);
3516 }
3517
3518 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
3519 {
3520 if (!visible)
3521 {
3522 if (existing)
3523 { existing.renderer.visible = false; }
3524 return existing;
3525 }
3526
3527 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
3528 this.#markUnlit(existing);
3529 existing.renderer.visible = true;
3530 existing.transform.position.x = x;
3531 existing.transform.position.y = y;
3532 existing.transform.size = horizontal
3533 ? new vector(length, thickness)
3534 : new vector(thickness, length);
3535 existing.layer = LAYER_EDGE;
3536 this.#markSortDirty();
3537 return existing;
3538 }
3539
3540 #destroyEdges (key)
3541 {
3542 const bars = this.edges.get(key);
3543 if (!bars)
3544 { return; }
3545 bars.north?.destroy();
3546 bars.east?.destroy();
3547 bars.south?.destroy();
3548 bars.west?.destroy();
3549 this.edges.delete(key);
3550 }
3551
3552 #entityShadeAlpha (entity, now)
3553 {
3554 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
3555 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
3556 { return toAlpha; }
3557 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
3558 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
3559 return fromAlpha + (toAlpha - fromAlpha) * t;
3560 }
3561
3562 #markSortDirty ()
3563 {
3564 this.scene._sortDirty = true;
3565 }
3566
3567 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
3568 #activeLightingCenterChunk ()
3569 {
3570 const local = this.entities.get(this.localEntityId);
3571 if (!local)
3572 { return null; }
3573 return {
3574 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
3575 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
3576 };
3577 }
3578
3579 #isActiveLightingChunk (chunkX, chunkY)
3580 {
3581 const center = this.#activeLightingCenterChunk();
3582 if (!center)
3583 { return true; }
3584 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
3585 }
3586
3587 #isActiveLightingTile (tileX, tileY)
3588 {
3589 return this.#isActiveLightingChunk(
3590 Math.floor(tileX / CHUNK_SIZE),
3591 Math.floor(tileY / CHUNK_SIZE)
3592 );
3593 }
3594
3595 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
3596 #innerDynamicLights (activeLights)
3597 {
3598 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
3599 }
3600
3601 /**
3602 * Lights to simulate for one chunk: inner chunks get all inner sources; outer ring
3603 * chunks only receive inner sources close enough to reach the chunk bounds.
3604 */
3605 #dynamicLightsForChunk (chunkX, chunkY, activeLights)
3606 {
3607 const center = this.#activeLightingCenterChunk();
3608 if (!center)
3609 { return activeLights; }
3610 const inner = this.#innerDynamicLights(activeLights);
3611 if (this.#isActiveLightingChunk(chunkX, chunkY))
3612 { return inner; }
3613 return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3614 }
3615
3616 #dynamicLightsForTile (tileX, tileY, activeLights)
3617 {
3618 return this.#dynamicLightsForChunk(
3619 Math.floor(tileX / CHUNK_SIZE),
3620 Math.floor(tileY / CHUNK_SIZE),
3621 activeLights
3622 );
3623 }
3624
3625 #updateShade ()
3626 {
3627 const ambientDark = this.#ambientDarkness();
3628 const now = performance.now();
3629 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3630
3631 const activeLights = [...this.dynamicLights];
3632 for (const light of this.spellLights.values())
3633 {
3634 if (light.until <= now)
3635 { continue; }
3636 activeLights.push({
3637 tileX: light.tileX,
3638 tileY: light.tileY,
3639 range: light.range,
3640 intensity: light.intensity
3641 });
3642 }
3643 for (const key of [...this.spellLights.keys()])
3644 {
3645 if (this.spellLights.get(key).until <= now)
3646 { this.spellLights.delete(key); }
3647 }
3648 const activeDarks = [];
3649 for (const dark of this.spellDarks.values())
3650 {
3651 if (dark.until <= now)
3652 { continue; }
3653 activeDarks.push({
3654 tileX: dark.tileX,
3655 tileY: dark.tileY,
3656 range: dark.range,
3657 intensity: dark.intensity
3658 });
3659 }
3660 for (const key of [...this.spellDarks.keys()])
3661 {
3662 if (this.spellDarks.get(key).until <= now)
3663 { this.spellDarks.delete(key); }
3664 }
3665 this._activeSpellDarks = activeDarks;
3666 const tileSize = this.tileSize();
3667 const blindLight = this.#blindVisionLight();
3668 if (blindLight)
3669 { activeLights.push(blindLight); }
3670 for (const entity of this.entities.values())
3671 {
3672 const range = entity.lightRadiusTiles ?? 0;
3673 if (range <= 0)
3674 { continue; }
3675 activeLights.push({
3676 tileX: Math.floor(entity.visualX / tileSize),
3677 tileY: Math.floor(entity.visualY / tileSize),
3678 range,
3679 intensity: 1
3680 });
3681 }
3682
3683 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
3684
3685 for (const objects of this.tiles.values())
3686 {
3687 if (objects._inViewport === false)
3688 { continue; }
3689 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights);
3690 const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion);
3691 objects.shadeAlpha = ambientDark * (1 - intensity);
3692 }
3693
3694 for (const baked of this.bakedChunks.values())
3695 {
3696 if (baked._inViewport === false)
3697 { continue; }
3698 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3699 this.#writeChunkLightmap(baked, lights, lightOcclusion);
3700 if (baked.groundObject?.renderer?.shaderUniforms)
3701 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3702 for (const object of baked.blockObjects ?? [])
3703 {
3704 if (object?.renderer?.shaderUniforms)
3705 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3706 }
3707 }
3708
3709 const timeSec = now / 1000;
3710 for (const objects of this.tiles.values())
3711 {
3712 if (objects._inViewport === false)
3713 { continue; }
3714 if (objects.block)
3715 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
3716 if (objects.ground && isWaterGround(objects.groundTypeId))
3717 {
3718 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
3719 this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked);
3720 }
3721 else if (objects.ground)
3722 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
3723 }
3724
3725 for (const item of this.groundItems.values())
3726 {
3727 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
3728 this.#syncGroundItemSprite(item, alpha);
3729 }
3730 }
3731
3732 #tileLightIntensity (objects, activeLights, lightOcclusion)
3733 {
3734 const baked = lightIntensity(objects.light ?? 0);
3735 const dynamic = dynamicLightAtTile(
3736 objects.tileX,
3737 objects.tileY,
3738 activeLights,
3739 lightOcclusion
3740 );
3741 const dark = dynamicDarknessAtTile(
3742 objects.tileX,
3743 objects.tileY,
3744 this._activeSpellDarks ?? [],
3745 lightOcclusion
3746 );
3747 return Math.max(0, Math.max(baked, dynamic) - dark);
3748 }
3749
3750 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
3751 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
3752 {
3753 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
3754 if (tileObjects)
3755 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
3756 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3757 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3758 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3759 if (!snapshot)
3760 { return 0; }
3761 const localX = tileX - chunkX * CHUNK_SIZE;
3762 const localY = tileY - chunkY * CHUNK_SIZE;
3763 const index = localY * CHUNK_SIZE + localX;
3764 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
3765 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
3766 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
3767 return Math.max(0, Math.max(bakedLit, dynamic) - dark);
3768 }
3769
3770 /** True when ground or block on this tile occludes light rays (same rules as bake). */
3771 #tileOccludesLight (tileX, tileY)
3772 {
3773 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3774 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3775 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3776 if (!snapshot)
3777 { return false; }
3778 const localX = tileX - chunkX * CHUNK_SIZE;
3779 const localY = tileY - chunkY * CHUNK_SIZE;
3780 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
3781 { return false; }
3782 const index = localY * CHUNK_SIZE + localX;
3783 if (Array.isArray(snapshot.occlusion) && snapshot.occlusion.length > index)
3784 { return (snapshot.occlusion[index] | 0) >= LightOcclusion.solid; }
3785 const ground = normalizeGround(snapshot.grounds?.[index]);
3786 if (!isGroundPassable(ground.typeId))
3787 { return true; }
3788 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
3789 }
3790
3791 #fillChunkLightGrids (baked, activeLights, lightOcclusion)
3792 {
3793 const gridW = CHUNK_SIZE + 2;
3794 const gridSize = gridW * gridW;
3795 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
3796 { baked.lightIntensityGrid = new Float32Array(gridSize); }
3797 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
3798 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
3799 const grid = baked.lightIntensityGrid;
3800 const occlude = baked.lightOccludeGrid;
3801 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
3802 {
3803 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
3804 {
3805 const tileX = baked.chunkX * CHUNK_SIZE + lx;
3806 const tileY = baked.chunkY * CHUNK_SIZE + ly;
3807 const gi = (ly + 1) * gridW + (lx + 1);
3808 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
3809 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
3810 }
3811 }
3812 return { grid, occlude, gridW };
3813 }
3814
3815 #makeLightCornerSampler (grid, occlude, gridW)
3816 {
3817 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
3818 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
3819 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
3820 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
3821 {
3822 const home = sample(homeLx, homeLy);
3823 if (blocks(homeLx, homeLy))
3824 { return home; }
3825 let sum = home;
3826 let count = 1;
3827 sum += openSample(aLx, aLy);
3828 count += 1;
3829 sum += openSample(bLx, bLy);
3830 count += 1;
3831 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
3832 {
3833 sum += openSample(dLx, dLy);
3834 count += 1;
3835 }
3836 return sum / count;
3837 };
3838 return { smoothCorner };
3839 }
3840
3841 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
3842 #tileLitCorners (baked, localX, localY)
3843 {
3844 const grid = baked?.lightIntensityGrid;
3845 const occlude = baked?.lightOccludeGrid;
3846 if (!grid?.length || !occlude?.length)
3847 { return null; }
3848 const gridW = CHUNK_SIZE + 2;
3849 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
3850 return {
3851 nw: smoothCorner(
3852 localX, localY,
3853 localX - 1, localY,
3854 localX, localY - 1,
3855 localX - 1, localY - 1
3856 ),
3857 ne: smoothCorner(
3858 localX, localY,
3859 localX + 1, localY,
3860 localX, localY - 1,
3861 localX + 1, localY - 1
3862 ),
3863 sw: smoothCorner(
3864 localX, localY,
3865 localX - 1, localY,
3866 localX, localY + 1,
3867 localX - 1, localY + 1
3868 ),
3869 se: smoothCorner(
3870 localX, localY,
3871 localX + 1, localY,
3872 localX, localY + 1,
3873 localX + 1, localY + 1
3874 )
3875 };
3876 }
3877
3878 #hashUint8Array (values)
3879 {
3880 let hash = 2166136261;
3881 for (let i = 0; i < values.length; i++)
3882 {
3883 hash ^= values[i];
3884 hash = Math.imul(hash, 16777619);
3885 }
3886 return hash >>> 0;
3887 }
3888
3889 #lightAffectsChunkBounds (light, chunkX, chunkY)
3890 {
3891 const minX = chunkX * CHUNK_SIZE - 1;
3892 const minY = chunkY * CHUNK_SIZE - 1;
3893 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
3894 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
3895 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
3896 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
3897 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
3898 }
3899
3900 #chunkLightmapCacheKey (baked, activeLights)
3901 {
3902 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
3903 if (!snapshot?.light)
3904 { return null; }
3905 const bakedHash = this.#hashUint8Array(snapshot.light);
3906 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3907 if (!lights.length)
3908 { return `i:${bakedHash}`; }
3909 const mode = this.lightingMode === "simple" ? "s" : "f";
3910 let lightsKey = "";
3911 for (const light of lights)
3912 {
3913 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
3914 { continue; }
3915 lightsKey += `${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
3916 }
3917 return `a:${mode}:${bakedHash}:${lightsKey}`;
3918 }
3919
3920 #invalidateNeighborLightmapCaches (chunkX, chunkY)
3921 {
3922 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
3923 for (let dy = -2; dy <= 2; dy++)
3924 {
3925 for (let dx = -2; dx <= 2; dx++)
3926 {
3927 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
3928 if (baked)
3929 { baked.lightmapCacheKey = null; }
3930 }
3931 }
3932 }
3933
3934 /**
3935 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
3936 * occluding tiles stay flat and contribute 0 into others so light does not bleed
3937 * through a wall to the far side. Diagonals only when both cardinals are clear.
3938 */
3939 #writeChunkLightmap (baked, activeLights, lightOcclusion)
3940 {
3941 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
3942 if (!snapshot)
3943 { return; }
3944 const cacheKey = this.#chunkLightmapCacheKey(baked, activeLights);
3945 if (cacheKey && baked.lightmapCacheKey === cacheKey)
3946 { return; }
3947 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
3948 const pixelCount = atlasPx * atlasPx * 4;
3949 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
3950 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
3951 const pixels = baked.lightmapPixels;
3952
3953 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
3954 const simple = this.lightingMode === "simple";
3955
3956 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3957 {
3958 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3959 {
3960 const baseX = localX * SPRITE_SIZE_PX;
3961 const baseY = localY * SPRITE_SIZE_PX;
3962 if (simple)
3963 {
3964 const gridW = CHUNK_SIZE + 2;
3965 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
3966 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
3967 for (let py = 0; py < SPRITE_SIZE_PX; py++)
3968 {
3969 for (let px = 0; px < SPRITE_SIZE_PX; px++)
3970 {
3971 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
3972 pixels[offset] = value;
3973 pixels[offset + 1] = value;
3974 pixels[offset + 2] = value;
3975 pixels[offset + 3] = 255;
3976 }
3977 }
3978 continue;
3979 }
3980 const corners = this.#tileLitCorners(baked, localX, localY);
3981 const nw = corners.nw;
3982 const ne = corners.ne;
3983 const sw = corners.sw;
3984 const se = corners.se;
3985 for (let py = 0; py < SPRITE_SIZE_PX; py++)
3986 {
3987 const v = (py + 0.5) / SPRITE_SIZE_PX;
3988 const left = nw + (sw - nw) * v;
3989 const right = ne + (se - ne) * v;
3990 for (let px = 0; px < SPRITE_SIZE_PX; px++)
3991 {
3992 const u = (px + 0.5) / SPRITE_SIZE_PX;
3993 const intensity = left + (right - left) * u;
3994 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
3995 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
3996 pixels[offset] = value;
3997 pixels[offset + 1] = value;
3998 pixels[offset + 2] = value;
3999 pixels[offset + 3] = 255;
4000 }
4001 }
4002 }
4003 }
4004 const ctx = baked.lightmapCanvas.getContext("2d");
4005 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
4006 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4007 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
4008 baked.lightmapCacheKey = cacheKey;
4009 }
4010
4011 #updateSwipes (now)
4012 {
4013 this.swipes = this.swipes.filter((swipe) =>
4014 {
4015 if (swipe.lerp && swipe.started != null)
4016 {
4017 const durationMs = swipe.durationMs ?? 400;
4018 const t = Math.min(1, (now - swipe.started) / durationMs);
4019 const fromPivot = this.#projectileLaunchPoint(
4020 swipe.attackerId ?? null,
4021 swipe.fromTileX,
4022 swipe.fromTileY
4023 );
4024 const toPivot = this.#projectileEndPivot(swipe);
4025 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
4026 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
4027 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
4028 if (swipe.object?.transform)
4029 {
4030 swipe.object.transform.rotation = Math.atan2(
4031 toPivot.y - fromPivot.y,
4032 toPivot.x - fromPivot.x
4033 ) * (180 / Math.PI);
4034 }
4035 if (swipe.spellProjectile && swipe.baseSprite)
4036 {
4037 const frame = Math.floor((now - swipe.started) / SPELL_PROJECTILE_FRAME_MS) % 3;
4038 const image = this.#spellProjectileImage(swipe.baseSprite, frame);
4039 if (image && swipe.object?.renderer)
4040 { swipe.object.renderer.sprite = image; }
4041 }
4042 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
4043 if (!swipe.spellProjectile)
4044 {
4045 this.#applyPhysicalCombatFxDarkness(
4046 swipe.object,
4047 swipe.fromTileX,
4048 swipe.fromTileY,
4049 swipe.tileX,
4050 swipe.tileY,
4051 swipe.dualTint ?? null
4052 );
4053 }
4054 }
4055 else if (swipe.fromTileX != null && !swipe.spellProjectile)
4056 {
4057 this.#applyPhysicalCombatFxDarkness(
4058 swipe.object,
4059 swipe.fromTileX,
4060 swipe.fromTileY,
4061 swipe.tileX,
4062 swipe.tileY,
4063 swipe.dualTint ?? null
4064 );
4065 }
4066 if (swipe.until > now)
4067 { return true; }
4068 const onImpact = swipe.onImpact;
4069 swipe.onImpact = null;
4070 swipe.object?.destroy();
4071 if (typeof onImpact === "function")
4072 {
4073 try
4074 { onImpact(); }
4075 catch (_)
4076 { /* presentation only */ }
4077 }
4078 return false;
4079 });
4080 }
4081
4082 #projectileEndPivot (swipe)
4083 {
4084 if (swipe.trackTarget && swipe.targetId != null)
4085 { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }
4086 return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);
4087 }
4088
4089 /**
4090 * Launch point: 4px below the top of the caster sprite (falls back to tile centre).
4091 */
4092 #projectileLaunchPoint (entityId, tileX, tileY)
4093 {
4094 const entity = entityId != null ? this.entities.get(entityId) : null;
4095 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
4096 {
4097 const zoom = this.zoom;
4098 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
4099 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
4100 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
4101 const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;
4102 return {
4103 x: pivotX,
4104 y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom
4105 };
4106 }
4107 return tilePivot(tileX, tileY, this.tileSize());
4108 }
4109
4110 /**
4111 * Aim point: sprite centre for creatures, tile centre for tile targets.
4112 */
4113 #projectileAimPoint (entityId, tileX, tileY)
4114 {
4115 const entity = entityId != null ? this.entities.get(entityId) : null;
4116 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
4117 {
4118 const zoom = this.zoom;
4119 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
4120 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
4121 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
4122 return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);
4123 }
4124 return tilePivot(tileX, tileY, this.tileSize());
4125 }
4126
4127 #updateDamageNumbers (now)
4128 {
4129 const layer = this.damageNumbersEl;
4130 if (!layer)
4131 { return; }
4132 this.damageFloats = this.damageFloats.filter((entry) =>
4133 {
4134 const elapsed = now - entry.started;
4135 if (elapsed >= DAMAGE_FLOAT_MS)
4136 {
4137 entry.element?.remove();
4138 return false;
4139 }
4140 const entity = this.entities.get(entry.entityId);
4141 if (!entity)
4142 {
4143 entry.element?.remove();
4144 return false;
4145 }
4146 if (!entry.element)
4147 {
4148 entry.element = document.createElement("span");
4149 entry.element.className = "damage-number";
4150 entry.element.textContent = String(entry.damage);
4151 layer.append(entry.element);
4152 }
4153 const anchor = this.nametagAnchor(entity);
4154 if (!anchor)
4155 { return true; }
4156 const t = elapsed / DAMAGE_FLOAT_MS;
4157 entry.element.style.left = `${anchor.x}px`;
4158 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
4159 entry.element.style.opacity = String(1 - t);
4160 return true;
4161 });
4162 }
4163
4164 #updateSkillLevelFloats (now)
4165 {
4166 const layer = this.skillLevelFloatsEl;
4167 if (!layer)
4168 { return; }
4169 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
4170 {
4171 const elapsed = now - entry.started;
4172 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
4173 {
4174 entry.element?.remove();
4175 return false;
4176 }
4177 const entity = this.entities.get(entry.entityId);
4178 if (!entity)
4179 {
4180 entry.element?.remove();
4181 return false;
4182 }
4183 if (!entry.element)
4184 {
4185 const root = document.createElement("div");
4186 root.className = "skill-level-float";
4187
4188 const levelEl = document.createElement("div");
4189 levelEl.className = "skill-level-float-level";
4190 levelEl.textContent = `↑${entry.level}↑`;
4191
4192 const icon = document.createElement("img");
4193 icon.className = "skill-level-float-icon";
4194 icon.src = entry.icon;
4195 icon.alt = entry.displayName || "";
4196
4197 root.append(levelEl, icon);
4198 entry.element = root;
4199 layer.append(entry.element);
4200 }
4201 const anchor = this.nametagAnchor(entity);
4202 if (!anchor)
4203 { return true; }
4204 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
4205 entry.element.style.left = `${anchor.x}px`;
4206 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
4207 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
4208 return true;
4209 });
4210 }
4211
4212 #syncBloomLayer ()
4213 {
4214 if (!this.bloomEnabled)
4215 {
4216 this.scene.setLayers([{ name: "default" }]);
4217 return;
4218 }
4219 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
4220 this.scene.setLayers([
4221 { name: "default" },
4222 {
4223 name: RENDER_LAYER_BLOOM,
4224 composite: "add",
4225 postShaders: Shader.getBloomPostChain({
4226 threshold: settings.bloomThreshold,
4227 softKnee: settings.bloomSoftKnee,
4228 intensity: settings.bloomIntensity,
4229 blurSize: settings.bloomBlurSize,
4230 saturation: settings.bloomSaturation,
4231 colorPreserve: settings.bloomColorPreserve,
4232 dilate: settings.bloomDilate,
4233 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
4234 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
4235 })
4236 }
4237 ]);
4238 }
4239}
4240
4241export function nightFactor (hour, nightDarkness = 0.72)
4242{
4243 const peak = Math.min(1, Math.max(0, nightDarkness));
4244 if (hour >= 8 && hour <= 16)
4245 { return 0; }
4246 if (hour >= 22 || hour <= 5)
4247 { return peak; }
4248 if (hour < 8)
4249 { return lerp(peak, 0, (hour - 5) / 3); }
4250 return lerp(0, peak, (hour - 16) / 6);
4251}
4252
4253function bodySpriteName (sex)
4254{
4255 const key = sex === "female" ? "player-body-female" : "player-body-male";
4256 return spriteImageName("character", key, key);
4257}
4258
4259function lerp (a, b, t)
4260{
4261 return a + (b - a) * Math.min(1, Math.max(0, t));
4262}
4263
4264function makeLightmapCanvas (size)
4265{
4266 const canvas = document.createElement("canvas");
4267 canvas.width = size;
4268 canvas.height = size;
4269 return canvas;
4270}
4271
4272function copyCanvas (source, dest)
4273{
4274 const ctx = dest.getContext("2d");
4275 ctx.imageSmoothingEnabled = false;
4276 ctx.clearRect(0, 0, dest.width, dest.height);
4277 ctx.drawImage(source, 0, 0);
4278}
4279
4280function drawHpBar (canvas, current, max)
4281{
4282 const ctx = canvas.getContext("2d");
4283 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
4284 ctx.fillStyle = "#000000";
4285 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
4286 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
4287 const fillW = Math.round(12 * ratio);
4288 if (fillW > 0)
4289 {
4290 ctx.fillStyle = "#ff0000";
4291 ctx.fillRect(1, 1, fillW, 2);
4292 }
4293}