BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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