BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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