BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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