BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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