BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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