BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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