BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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