BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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