BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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