BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 76.9 KiB Download Raw
1import { defaultLeftClickEntityAction } from "/shared/combat/entityClick.js";
2import { MessageType, GAIT, CHUNK_SIZE, STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
3import { validateCharacterNames } from "/shared/characters/names.js";
4import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
5import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
6import { OVERWORLD_ID } from "/shared/world/dimensions.js";
7import { findPathToNearestGoal } from "/shared/navigation/bfs.js";
8import { isAdjacentTile } from "/shared/navigation/adjacency.js";
9import { GameSocket, defaultSocketUrl } from "../net/socket.js";
10import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
11import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
12import { WorldView } from "../render/worldView.js";
13import { initSocial } from "./social.js";
14import { initChat } from "./chat.js";
15import { initInventory } from "./inventory.js";
16import { initSkills } from "./skills.js";
17import { initSpells } from "./spells.js";
18import { initCrafting } from "./crafting.js";
19import { initAlchemy } from "./alchemy.js";
20import { initTipArrows } from "./tipArrows.js";
21import { initStamina } from "./stamina.js";
22import { initHealth } from "./health.js";
23import { initStatusEffects } from "./statusEffects.js";
24import { initContextMenu } from "./contextMenu.js";
25import { initDeath } from "./death.js";
26import { initToasts } from "./toasts.js";
27import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
28import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";
29import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";
30import { initQuests } from "./quests.js";
31import { initDialogue } from "./dialogue.js";
32import { initShop } from "./shop.js";
33import { initMarket } from "./market.js";
34import { initBounty } from "./bounty.js";
35import { initBarber } from "./barber.js";
36import { bindHairControls } from "./hairControls.js";
37import { bindCreateClothingControls } from "./createClothingControls.js";
38import { paintCharacterPreview } from "./characterPreview.js";
39import { initGraphicsSettings } from "./graphicsSettings.js";
40import { CraftingStationId } from "/shared/definitions/craftingStations.js";
41import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
42import { formatQuantity } from "/shared/items/formatQuantity.js";
43import { ItemId, itemDefinition } from "/shared/definitions/items.js";
44import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
45import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
46import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
47import { countCoinsInSlots } from "/shared/items/inventory.js";
48
49const game = new Game();
50const hud = document.getElementById("hud");
51const overlay = document.getElementById("overlay");
52const statusEl = document.getElementById("status");
53const characterList = document.getElementById("character-list");
54const errorEl = document.getElementById("error");
55const assetLoadEl = document.getElementById("asset-load");
56const assetLoadBar = document.getElementById("asset-load-bar");
57const assetLoadLabel = document.getElementById("asset-load-label");
58const createCharacterOpen = document.getElementById("create-character-open");
59const worldTooltip = document.getElementById("world-tooltip");
60
61let socket;
62let session = null;
63let playing = false;
64let view = null;
65let graphicsSettingsUi = null;
66let scene = null;
67let gait = GAIT.walk;
68let catalog = { grounds: {}, blocks: {} };
69let social;
70let chat;
71let inventory;
72let skills;
73let spells;
74let crafting;
75let alchemy;
76let staminaUi;
77let healthUi;
78let statusEffectsUi;
79let contextMenu;
80let death;
81let toasts;
82let questsUi;
83let dialogueUi;
84let shop;
85let playZoomRaf = 0;
86let playZoomDelta = 0;
87let market;
88let bounty;
89let barber;
90let createHairControls;
91let createClothingControls;
92let createActiveTab = "appearance";
93let pendingPickup = null;
94/** @type {{ kind: "bank" | "doorway" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | { kind: "market" | "bounty" | "barber", tileX: number, tileY: number } | null } */
95let pendingInteract = null;
96/**
97 * Block/NPC the player currently has a station UI open for.
98 * Closed automatically when Chebyshev distance exceeds 1.
99 * @type {null | { kind: "bank" | "station" | "cauldron" | "market" | "bounty" | "barber", tileX: number, tileY: number } | { kind: "shop" | "dialogue", entityId: number }}
100 */
101let uiFocus = null;
102/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
103let approachMove = null;
104/** Client-tracked follow target; server follow owns gait while this is set. */
105let followTargetId = null;
106/** Destination of the active click/approach moveTo for autorun distance checks. */
107let moveDest = null;
108/** Entity / tile focus for server-driven approach (attack, cast) — no client moveTo. */
109let autorunFocusEntityId = null;
110let autorunFocusTile = null;
111/** After stamina hits 0 while autorunning, wait until ≥50% before running again. */
112let autorunWaitingStamina = false;
113/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
114let leftClickConsumed = false;
115
116const AUTORUN_DISTANCE_TILES = 3;
117const AUTORUN_STAMINA_RESUME_RATIO = 0.5;
118
119function sendPlayerMoveTo (tileX, tileY)
120{
121 followTargetId = null;
122 clearAutorunFocus();
123 moveDest = { tileX: tileX | 0, tileY: tileY | 0 };
124 socket.send({ type: MessageType.moveTo, tileX: moveDest.tileX, tileY: moveDest.tileY });
125 syncAutorun();
126}
127
128function sendPlayerFollow (targetEntityId)
129{
130 followTargetId = targetEntityId | 0;
131 moveDest = null;
132 clearAutorunFocus();
133 autorunWaitingStamina = false;
134 socket.send({ type: MessageType.follow, targetEntityId: followTargetId });
135}
136
137function clearAutorunFocus ()
138{
139 autorunFocusEntityId = null;
140 autorunFocusTile = null;
141}
142
143function setAutorunFocusEntity (entityId)
144{
145 moveDest = null;
146 autorunFocusTile = null;
147 autorunFocusEntityId = entityId | 0;
148 syncAutorun();
149}
150
151function setAutorunFocusTile (tileX, tileY)
152{
153 moveDest = null;
154 autorunFocusEntityId = null;
155 autorunFocusTile = { tileX: tileX | 0, tileY: tileY | 0 };
156 syncAutorun();
157}
158
159function resolveAutorunDest ()
160{
161 if (moveDest)
162 { return moveDest; }
163 if (autorunFocusEntityId != null)
164 {
165 const target = view?.entities?.get(autorunFocusEntityId);
166 if (!target)
167 { return null; }
168 return { tileX: target.tileX | 0, tileY: target.tileY | 0 };
169 }
170 return autorunFocusTile;
171}
172
173function localEntityIsMoving (local)
174{
175 if (!local)
176 { return false; }
177 if (local.lerpStarted != null)
178 { return true; }
179 const dx = (local.visualX ?? 0) - (local.targetX ?? local.visualX ?? 0);
180 const dy = (local.visualY ?? 0) - (local.targetY ?? local.visualY ?? 0);
181 return (dx * dx + dy * dy) > 0.25;
182}
183
184function requestGaitIfNeeded (next)
185{
186 if (next !== GAIT.walk && next !== GAIT.run)
187 { return; }
188 if (next === gait)
189 { return; }
190 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 0) <= 0)
191 { return; }
192 socket.send({ type: MessageType.setGait, gait: next });
193 if (next === GAIT.walk)
194 {
195 gait = next;
196 const el = document.getElementById("gait");
197 if (el)
198 { el.textContent = gait; }
199 }
200}
201
202function syncAutorun ()
203{
204 if (!playing || followTargetId != null)
205 { return; }
206 const settings = graphicsSettingsUi?.getSettings?.() ?? {};
207 if (settings.autorun !== "on")
208 { return; }
209 const local = view?.entities?.get(view.localEntityId);
210 const dest = resolveAutorunDest();
211 if (!local || !dest)
212 { return; }
213 if (moveDest && local.tileX === moveDest.tileX && local.tileY === moveDest.tileY)
214 {
215 moveDest = null;
216 autorunWaitingStamina = false;
217 requestGaitIfNeeded(GAIT.walk);
218 return;
219 }
220 // Attack / cast approach is server-pathed — only run while tiles are changing.
221 if (!moveDest && !localEntityIsMoving(local))
222 {
223 requestGaitIfNeeded(GAIT.walk);
224 return;
225 }
226 const dist = chebyshev(local.tileX, local.tileY, dest.tileX, dest.tileY);
227 const wantRun = dist > AUTORUN_DISTANCE_TILES;
228 const current = staminaUi?.getCurrent?.() ?? 0;
229 const max = Math.max(1, staminaUi?.getMax?.() ?? 1);
230 if (gait === GAIT.run && current <= 0)
231 { autorunWaitingStamina = true; }
232 if (autorunWaitingStamina)
233 {
234 if (wantRun && current / max >= AUTORUN_STAMINA_RESUME_RATIO)
235 {
236 autorunWaitingStamina = false;
237 requestGaitIfNeeded(GAIT.run);
238 }
239 else
240 { requestGaitIfNeeded(GAIT.walk); }
241 return;
242 }
243 if (wantRun)
244 {
245 if (current <= 0)
246 {
247 autorunWaitingStamina = true;
248 requestGaitIfNeeded(GAIT.walk);
249 }
250 else
251 { requestGaitIfNeeded(GAIT.run); }
252 }
253 else
254 { requestGaitIfNeeded(GAIT.walk); }
255}
256
257function consumeWorldClick ()
258{
259 leftClickConsumed = true;
260}
261
262function showError (message)
263{
264 errorEl.textContent = message ?? "";
265}
266
267function setAssetLoading (active, { loaded = 0, total = 0, phase = "" } = {})
268{
269 if (assetLoadEl)
270 { assetLoadEl.hidden = !active; }
271 if (characterList)
272 { characterList.hidden = active; }
273 if (createCharacterOpen)
274 { createCharacterOpen.hidden = active; }
275 if (!active)
276 { return; }
277 if (assetLoadBar && total > 0)
278 { assetLoadBar.value = Math.round((loaded / total) * 100); }
279 if (assetLoadLabel)
280 {
281 assetLoadLabel.textContent = phase
282 || (total > 0 ? `Loading assets… ${loaded}/${total}` : "Loading assets…");
283 }
284}
285
286function renderCharacters (characters)
287{
288 characterList.innerHTML = "";
289 for (const character of characters)
290 {
291 const row = document.createElement("div");
292 row.className = "character-row";
293 const pending = character.deletionScheduledAt
294 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
295 : "";
296 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
297 const play = document.createElement("button");
298 play.textContent = "Play";
299 play.disabled = !!character.deletionScheduledAt;
300 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
301 const del = document.createElement("button");
302 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
303 del.addEventListener("click", () =>
304 {
305 socket.send({
306 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
307 characterId: character.characterId
308 });
309 });
310 row.append(play, del);
311 characterList.append(row);
312 }
313}
314
315function uiBlocked ()
316{
317 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
318 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
319 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
320 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
321 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
322 || graphicsSettingsUi?.isBlocking?.()
323 || pointerOverSpellUi());
324}
325
326function pointerOverSpellUi ()
327{
328 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
329 if (!el)
330 { return false; }
331 return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
332}
333
334function applyGraphicsSettings (settings)
335{
336 view?.setGraphicsPrefs(settings);
337 if (socket && playing)
338 {
339 socket.send({
340 type: MessageType.setGraphicsSettings,
341 viewDistance: settings.viewDistance
342 });
343 }
344 syncAutorun();
345}
346
347function clearPendingPickup ()
348{
349 pendingPickup = null;
350}
351
352function clearPendingInteract ()
353{
354 pendingInteract = null;
355 approachMove = null;
356}
357
358function clearAllPendingActions ()
359{
360 clearPendingPickup();
361 clearPendingInteract();
362}
363
364function approachAdjacentTile (tileX, tileY)
365{
366 const local = view.entities.get(view.localEntityId);
367 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
368 {
369 approachMove = null;
370 return true;
371 }
372 if (!local)
373 { return false; }
374
375 const radius = Math.max(1, STATIC_CHUNK_RADIUS | 0) * CHUNK_SIZE;
376 const path = findPathToNearestGoal(
377 local.tileX,
378 local.tileY,
379 (x, y) => chebyshev(x, y, tileX, tileY) === 1 && isClientApproachable(x, y),
380 (x, y) => isClientApproachable(x, y),
381 local.tileX - radius,
382 local.tileY - radius,
383 local.tileX + radius,
384 local.tileY + radius
385 );
386 let best = path.length ? path[path.length - 1] : null;
387 if (!best)
388 {
389 // Fallback if BFS finds nothing (incomplete client map): nearest adjacent guess.
390 let bestAny = null;
391 let bestAnyDist = Infinity;
392 for (let dy = -1; dy <= 1; dy++)
393 {
394 for (let dx = -1; dx <= 1; dx++)
395 {
396 if (dx === 0 && dy === 0)
397 { continue; }
398 const destX = tileX + dx;
399 const destY = tileY + dy;
400 const dist = chebyshev(local.tileX, local.tileY, destX, destY);
401 if (dist < bestAnyDist)
402 {
403 bestAnyDist = dist;
404 bestAny = { tileX: destX, tileY: destY };
405 }
406 }
407 }
408 best = bestAny ? { x: bestAny.tileX, y: bestAny.tileY } : null;
409 }
410 if (!best)
411 { return false; }
412 const destX = best.x ?? best.tileX;
413 const destY = best.y ?? best.tileY;
414 if (
415 approachMove
416 && approachMove.focusX === tileX
417 && approachMove.focusY === tileY
418 && approachMove.destX === destX
419 && approachMove.destY === destY
420 )
421 { return false; }
422 approachMove = {
423 focusX: tileX,
424 focusY: tileY,
425 destX,
426 destY
427 };
428 sendPlayerMoveTo(destX, destY);
429 return false;
430}
431
432function requestOpenBank (tileX, tileY, { getCheques = false } = {})
433{
434 clearAllPendingActions();
435 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
436 const local = view?.entities.get(view.localEntityId);
437 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
438 { flushPendingInteract(); }
439 else
440 { approachAdjacentTile(tileX, tileY); }
441}
442
443function requestEnterDoorway (tileX, tileY)
444{
445 clearAllPendingActions();
446 pendingInteract = { kind: "doorway", tileX, tileY };
447 const local = view?.entities.get(view.localEntityId);
448 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
449 { flushPendingInteract(); }
450 else
451 { approachAdjacentTile(tileX, tileY); }
452}
453
454function requestOpenMarket (tileX, tileY)
455{
456 clearAllPendingActions();
457 pendingInteract = { kind: "market", tileX, tileY };
458 const local = view?.entities.get(view.localEntityId);
459 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
460 { flushPendingInteract(); }
461 else
462 { approachAdjacentTile(tileX, tileY); }
463}
464
465function requestOpenBounty (tileX, tileY)
466{
467 clearAllPendingActions();
468 pendingInteract = { kind: "bounty", tileX, tileY };
469 const local = view?.entities.get(view.localEntityId);
470 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
471 { flushPendingInteract(); }
472 else
473 { approachAdjacentTile(tileX, tileY); }
474}
475
476function requestOpenBarber (tileX, tileY)
477{
478 clearAllPendingActions();
479 pendingInteract = { kind: "barber", tileX, tileY };
480 const local = view?.entities.get(view.localEntityId);
481 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
482 { flushPendingInteract(); }
483 else
484 { approachAdjacentTile(tileX, tileY); }
485}
486
487function requestOpenCauldron (tileX, tileY)
488{
489 clearAllPendingActions();
490 pendingInteract = { kind: "cauldron", tileX, tileY };
491 const local = view?.entities.get(view.localEntityId);
492 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
493 { flushPendingInteract(); }
494 else
495 { approachAdjacentTile(tileX, tileY); }
496}
497
498function requestOpenFurnace (tileX, tileY)
499{
500 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
501}
502
503function requestOpenCraftStation (stationId, tileX, tileY)
504{
505 clearAllPendingActions();
506 pendingInteract = { kind: "station", stationId, tileX, tileY };
507 const local = view?.entities.get(view.localEntityId);
508 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
509 { flushPendingInteract(); }
510 else
511 { approachAdjacentTile(tileX, tileY); }
512}
513
514function requestStartFire (ground)
515{
516 if (!ground)
517 { return; }
518 clearAllPendingActions();
519 pendingInteract = {
520 kind: "start-fire",
521 groundItemId: ground.groundItemId,
522 tileX: ground.tileX,
523 tileY: ground.tileY
524 };
525 const local = view?.entities.get(view.localEntityId);
526 if (local && isAdjacentTile(local.tileX, local.tileY, ground.tileX, ground.tileY))
527 { flushPendingInteract(); }
528 else
529 { approachAdjacentTile(ground.tileX, ground.tileY); }
530}
531
532function requestFish (tileX, tileY)
533{
534 clearAllPendingActions();
535 pendingInteract = { kind: "fish", tileX, tileY };
536 const local = view?.entities.get(view.localEntityId);
537 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
538 { flushPendingInteract(); }
539 else
540 { approachAdjacentTile(tileX, tileY); }
541}
542
543function requestMine (tileX, tileY)
544{
545 clearAllPendingActions();
546 pendingInteract = { kind: "mine", tileX, tileY };
547 const local = view?.entities.get(view.localEntityId);
548 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
549 { flushPendingInteract(); }
550 else
551 { approachAdjacentTile(tileX, tileY); }
552}
553
554function requestChop (tileX, tileY)
555{
556 clearAllPendingActions();
557 pendingInteract = { kind: "chop", tileX, tileY };
558 const local = view?.entities.get(view.localEntityId);
559 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
560 { flushPendingInteract(); }
561 else
562 { approachAdjacentTile(tileX, tileY); }
563}
564
565function requestPick (tileX, tileY)
566{
567 clearAllPendingActions();
568 pendingInteract = { kind: "pick", tileX, tileY };
569 const local = view?.entities.get(view.localEntityId);
570 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
571 { flushPendingInteract(); }
572 else
573 { approachAdjacentTile(tileX, tileY); }
574}
575
576function requestTalk (targetEntityId, purpose = null)
577{
578 clearAllPendingActions();
579 pendingInteract = { kind: "talk", targetEntityId, purpose };
580 const target = view?.entities.get(targetEntityId);
581 if (!target)
582 {
583 clearPendingInteract();
584 return;
585 }
586 if (approachAdjacentTile(target.tileX, target.tileY))
587 { flushPendingInteract(); }
588}
589
590function playerHasShears ()
591{
592 const slots = inventory?.getInventorySlots?.() ?? [];
593 const equipment = inventory?.getEquipment?.() ?? {};
594 for (const stack of [...slots, equipment.weapon])
595 {
596 if (!stack?.itemId)
597 { continue; }
598 if (itemDefinition(stack.itemId)?.equipment?.kind === EquipmentKind.shears)
599 { return true; }
600 }
601 return false;
602}
603
604function entityCanShear (entity)
605{
606 if (!entity?.mobTypeId)
607 { return false; }
608 const def = mobDefinition(entity.mobTypeId);
609 const shearable = def?.shearable;
610 if (!shearable)
611 { return false; }
612 const sprite = entity.layers?.[0]?.sprite ?? entity.sprite ?? "";
613 if (String(sprite).endsWith(`:${shearable.shornState}`))
614 { return false; }
615 return playerHasShears();
616}
617
618function requestShear (targetEntityId)
619{
620 clearAllPendingActions();
621 pendingInteract = { kind: "shear", targetEntityId };
622 const target = view?.entities.get(targetEntityId);
623 if (!target)
624 {
625 clearPendingInteract();
626 return;
627 }
628 if (approachAdjacentTile(target.tileX, target.tileY))
629 { flushPendingInteract(); }
630}
631
632function setUiFocus (focus)
633{
634 uiFocus = focus;
635}
636
637function clearUiFocus ()
638{
639 uiFocus = null;
640}
641
642/** Close stations, bank, dialogue, and other overlays when the local player dies. */
643function closeCloseablePlayUi ()
644{
645 clearUiFocus();
646 inventory?.closeBank?.();
647 inventory?.closeOverlays?.();
648 if (crafting?.isOpen?.())
649 { crafting.close(); }
650 if (alchemy?.isOpen?.())
651 { alchemy.close(); }
652 if (market?.isOpen?.())
653 { market.close(); }
654 if (bounty?.isOpen?.())
655 { bounty.close(); }
656 if (barber?.isOpen?.())
657 { barber.close(); }
658 if (shop?.isOpen?.())
659 { shop.close(); }
660 if (dialogueUi?.isOpen?.())
661 { dialogueUi.close(); }
662 questsUi?.hide?.();
663 chat?.close?.();
664 social?.closeOverlays?.();
665 contextMenu?.hide();
666 spells?.handleSpellDisarmed?.();
667 graphicsSettingsUi?.close?.();
668}
669
670/** Close bank / station / NPC UIs when the player walks out of adjacency. */
671function closeOpenUiIfTooFar ()
672{
673 if (!uiFocus || !view)
674 { return; }
675 const local = view.entities.get(view.localEntityId);
676 if (!local)
677 { return; }
678
679 let tooFar = false;
680 if (uiFocus.entityId != null)
681 {
682 const target = view.entities.get(uiFocus.entityId);
683 tooFar = !target
684 || !isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY);
685 }
686 else if (uiFocus.tileX != null && uiFocus.tileY != null)
687 {
688 tooFar = !isAdjacentTile(local.tileX, local.tileY, uiFocus.tileX, uiFocus.tileY);
689 }
690 if (!tooFar)
691 { return; }
692
693 const kind = uiFocus.kind;
694 clearUiFocus();
695 switch (kind)
696 {
697 case "bank":
698 if (inventory?.isBankOpen?.())
699 { inventory.closeBank(); }
700 break;
701 case "station":
702 if (crafting?.isOpen?.())
703 { crafting.close(); }
704 break;
705 case "cauldron":
706 if (alchemy?.isOpen?.())
707 { alchemy.close(); }
708 break;
709 case "market":
710 if (market?.isOpen?.())
711 { market.close(); }
712 break;
713 case "bounty":
714 if (bounty?.isOpen?.())
715 { bounty.close(); }
716 break;
717 case "barber":
718 if (barber?.isOpen?.())
719 { barber.close(); }
720 break;
721 case "shop":
722 if (shop?.isOpen?.())
723 { shop.close(); }
724 break;
725 case "dialogue":
726 if (dialogueUi?.isOpen?.())
727 { dialogueUi.close(); }
728 break;
729 default:
730 break;
731 }
732}
733
734function flushPendingInteract ()
735{
736 if (!pendingInteract || !view)
737 { return; }
738 const local = view.entities.get(view.localEntityId);
739 if (!local)
740 { return; }
741
742 if (pendingInteract.kind === "bank")
743 {
744 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
745 { return; }
746 setUiFocus({
747 kind: "bank",
748 tileX: pendingInteract.tileX,
749 tileY: pendingInteract.tileY
750 });
751 const getCheques = !!pendingInteract.getCheques;
752 socket.send({ type: MessageType.openBank });
753 if (getCheques)
754 { inventory?.getBlankCheques(); }
755 clearPendingInteract();
756 return;
757 }
758
759 if (pendingInteract.kind === "doorway")
760 {
761 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
762 { return; }
763 socket.send({
764 type: MessageType.enterDoorway,
765 tileX: pendingInteract.tileX,
766 tileY: pendingInteract.tileY
767 });
768 clearPendingInteract();
769 return;
770 }
771
772 if (pendingInteract.kind === "market")
773 {
774 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
775 { return; }
776 setUiFocus({
777 kind: "market",
778 tileX: pendingInteract.tileX,
779 tileY: pendingInteract.tileY
780 });
781 socket.send({ type: MessageType.openMarket });
782 clearPendingInteract();
783 return;
784 }
785
786 if (pendingInteract.kind === "bounty")
787 {
788 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
789 { return; }
790 setUiFocus({
791 kind: "bounty",
792 tileX: pendingInteract.tileX,
793 tileY: pendingInteract.tileY
794 });
795 socket.send({ type: MessageType.openBounty });
796 clearPendingInteract();
797 return;
798 }
799
800 if (pendingInteract.kind === "barber")
801 {
802 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
803 { return; }
804 setUiFocus({
805 kind: "barber",
806 tileX: pendingInteract.tileX,
807 tileY: pendingInteract.tileY
808 });
809 socket.send({ type: MessageType.openBarber });
810 clearPendingInteract();
811 return;
812 }
813
814 if (pendingInteract.kind === "cauldron")
815 {
816 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
817 { return; }
818 setUiFocus({
819 kind: "cauldron",
820 tileX: pendingInteract.tileX,
821 tileY: pendingInteract.tileY
822 });
823 socket.send({ type: MessageType.openCauldron });
824 clearPendingInteract();
825 return;
826 }
827
828 if (pendingInteract.kind === "station")
829 {
830 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
831 { return; }
832 setUiFocus({
833 kind: "station",
834 tileX: pendingInteract.tileX,
835 tileY: pendingInteract.tileY
836 });
837 socket.send({
838 type: MessageType.openStation,
839 stationId: pendingInteract.stationId
840 });
841 clearPendingInteract();
842 return;
843 }
844
845 if (pendingInteract.kind === "mine")
846 {
847 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
848 { return; }
849 socket.send({
850 type: MessageType.mine,
851 tileX: pendingInteract.tileX,
852 tileY: pendingInteract.tileY
853 });
854 clearPendingInteract();
855 return;
856 }
857
858 if (pendingInteract.kind === "start-fire")
859 {
860 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
861 { return; }
862 socket.send({
863 type: MessageType.startFire,
864 groundItemId: pendingInteract.groundItemId
865 });
866 clearPendingInteract();
867 return;
868 }
869
870 if (pendingInteract.kind === "fish")
871 {
872 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
873 { return; }
874 socket.send({
875 type: MessageType.startFish,
876 tileX: pendingInteract.tileX,
877 tileY: pendingInteract.tileY
878 });
879 clearPendingInteract();
880 return;
881 }
882
883 if (pendingInteract.kind === "chop")
884 {
885 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
886 { return; }
887 socket.send({
888 type: MessageType.chop,
889 tileX: pendingInteract.tileX,
890 tileY: pendingInteract.tileY
891 });
892 clearPendingInteract();
893 return;
894 }
895
896 if (pendingInteract.kind === "pick")
897 {
898 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
899 { return; }
900 socket.send({
901 type: MessageType.pick,
902 tileX: pendingInteract.tileX,
903 tileY: pendingInteract.tileY
904 });
905 clearPendingInteract();
906 return;
907 }
908
909 if (pendingInteract.kind === "talk")
910 {
911 const target = view.entities.get(pendingInteract.targetEntityId);
912 if (!target)
913 {
914 clearPendingInteract();
915 return;
916 }
917 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY))
918 {
919 // Target may have moved — keep chasing.
920 approachAdjacentTile(target.tileX, target.tileY);
921 return;
922 }
923 socket.send({
924 type: MessageType.interact,
925 targetEntityId: pendingInteract.targetEntityId,
926 purpose: pendingInteract.purpose || undefined
927 });
928 // Shop vs dialogue is decided server-side; both use NPC adjacency.
929 setUiFocus({
930 kind: pendingInteract.purpose === "shop" ? "shop" : "dialogue",
931 entityId: pendingInteract.targetEntityId
932 });
933 clearPendingInteract();
934 return;
935 }
936
937 if (pendingInteract.kind === "shear")
938 {
939 const target = view.entities.get(pendingInteract.targetEntityId);
940 if (!target)
941 {
942 clearPendingInteract();
943 return;
944 }
945 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY))
946 {
947 approachAdjacentTile(target.tileX, target.tileY);
948 return;
949 }
950 socket.send({
951 type: MessageType.shear,
952 targetEntityId: pendingInteract.targetEntityId
953 });
954 clearPendingInteract();
955 }
956}
957
958function requestPickup (ground)
959{
960 if (!ground)
961 { return; }
962 clearPendingInteract();
963 pendingPickup = {
964 groundItemId: ground.groundItemId,
965 tileX: ground.tileX,
966 tileY: ground.tileY
967 };
968 const local = view.entities.get(view.localEntityId);
969 if (local && local.tileX === ground.tileX && local.tileY === ground.tileY)
970 {
971 flushPendingPickup();
972 return;
973 }
974 sendPlayerMoveTo(ground.tileX, ground.tileY);
975}
976
977function flushPendingPickup ()
978{
979 if (!pendingPickup || !view)
980 { return; }
981 const item = view.groundItems.get(pendingPickup.groundItemId);
982 if (!item)
983 {
984 clearPendingPickup();
985 return;
986 }
987 const local = view.entities.get(view.localEntityId);
988 if (!local)
989 { return; }
990 if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY)
991 { return; }
992 socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId });
993 clearPendingPickup();
994}
995
996function requestAttack (targetEntityId)
997{
998 clearAllPendingActions();
999 setAutorunFocusEntity(targetEntityId);
1000 socket.send({ type: MessageType.attack, targetEntityId });
1001}
1002
1003function isAttackableEntity (entity)
1004{
1005 if (!entity || entity.untargetable)
1006 { return false; }
1007 if (entity.canFight)
1008 { return true; }
1009 // Snapshots can omit canFight; mobs are still attackable via LMB.
1010 return !!entity.mobTypeId && !entity.talkable;
1011}
1012
1013function canTalkToEntity (entity)
1014{
1015 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
1016}
1017
1018function isApproachingCombatOrCast ()
1019{
1020 return autorunFocusEntityId != null || autorunFocusTile != null;
1021}
1022
1023function handleLeftClick (mouseX, mouseY)
1024{
1025 const tile = view.screenToTile(mouseX, mouseY);
1026 const armed = spells?.getArmedSpell?.();
1027 const approaching = isApproachingCombatOrCast();
1028
1029 // Entity-armed: cast only when a valid target is under the cursor. Empty ground
1030 // must fall through so walk cancels cast/attack approach (server moveTo clears it).
1031 if (armed?.target === "entity" && armed.canCast)
1032 {
1033 const snap = nearestSpellEntityAtCursor(mouseX, mouseY);
1034 if (snap && spells.tryCastAtEntity(snap.entityId))
1035 {
1036 setAutorunFocusEntity(snap.entityId);
1037 return;
1038 }
1039 }
1040 // Tile-armed while approaching: prefer walk-cancel over re-targeting the cast.
1041 else if (
1042 !approaching
1043 && armed?.target === "tile"
1044 && armed.canCast
1045 && spells.tryCastAtTile(tile.tileX, tile.tileY)
1046 )
1047 {
1048 setAutorunFocusTile(tile.tileX, tile.tileY);
1049 return;
1050 }
1051
1052 const entity = view.entityAtScreen(mouseX, mouseY);
1053 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
1054 {
1055 clearPendingPickup();
1056 const clickAction = defaultLeftClickEntityAction(entity);
1057 if (clickAction === "inspect")
1058 {
1059 clearPendingInteract();
1060 social.inspect(entity);
1061 return;
1062 }
1063 if (clickAction === "attack")
1064 {
1065 requestAttack(entity.entityId);
1066 return;
1067 }
1068 if (clickAction === "talk")
1069 {
1070 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
1071 ? "talk"
1072 : (entity.hasShop ? "shop" : "talk");
1073 requestTalk(entity.entityId, purpose);
1074 return;
1075 }
1076 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
1077 return;
1078 }
1079
1080 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
1081 if (ground)
1082 { requestPickup(ground); }
1083 else if (isBankTile(view, tile.tileX, tile.tileY))
1084 { requestOpenBank(tile.tileX, tile.tileY); }
1085 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
1086 { requestEnterDoorway(tile.tileX, tile.tileY); }
1087 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1088 { requestOpenMarket(tile.tileX, tile.tileY); }
1089 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1090 { requestOpenBounty(tile.tileX, tile.tileY); }
1091 else if (isBarberTile(view, tile.tileX, tile.tileY))
1092 { requestOpenBarber(tile.tileX, tile.tileY); }
1093 else if (isCauldronTile(view, tile.tileX, tile.tileY))
1094 { requestOpenCauldron(tile.tileX, tile.tileY); }
1095 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
1096 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
1097 else if (isOvenTile(view, tile.tileX, tile.tileY))
1098 { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); }
1099 else if (isCampfireTile(view, tile.tileX, tile.tileY))
1100 { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); }
1101 else if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1102 { requestFish(tile.tileX, tile.tileY); }
1103 else if (isAnvilTile(view, tile.tileX, tile.tileY))
1104 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
1105 else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1106 { requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }
1107 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1108 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
1109 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1110 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
1111 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1112 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
1113 else if (isLoomTile(view, tile.tileX, tile.tileY))
1114 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
1115 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1116 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
1117 else if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1118 { requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY); }
1119 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1120 { requestMine(tile.tileX, tile.tileY); }
1121 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1122 { requestChop(tile.tileX, tile.tileY); }
1123 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1124 { requestPick(tile.tileX, tile.tileY); }
1125 else
1126 {
1127 clearAllPendingActions();
1128 sendPlayerMoveTo(tile.tileX, tile.tileY);
1129 }
1130}
1131
1132function handleRightClick (event, mouseX, mouseY)
1133{
1134 event.preventDefault();
1135 if (spells?.isTargeting?.())
1136 {
1137 spells.cancelTargeting();
1138 view?.clearSpellTargetHighlight();
1139 return;
1140 }
1141 const tile = view.screenToTile(mouseX, mouseY);
1142 const items = [];
1143 const walkTileX = tile.tileX;
1144 const walkTileY = tile.tileY;
1145
1146 items.push({
1147 label: "Walk here",
1148 onSelect: () =>
1149 {
1150 clearAllPendingActions();
1151 sendPlayerMoveTo(walkTileX, walkTileY);
1152 }
1153 });
1154
1155 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY, { includePrevious: true }))
1156 {
1157 if (entity.entityId === view.localEntityId)
1158 {
1159 const equipment = { slots: inventory?.getEquipment?.() ?? {} };
1160 if (canTeleportToChurch(equipment))
1161 {
1162 items.push({
1163 label: "Teleport to Church",
1164 onSelect: () =>
1165 {
1166 clearAllPendingActions();
1167 socket.send({
1168 type: MessageType.jewelryTeleport,
1169 destination: "church"
1170 });
1171 }
1172 });
1173 }
1174 if (canTeleportToBank(equipment))
1175 {
1176 items.push({
1177 label: "Teleport to bank",
1178 onSelect: () =>
1179 {
1180 clearAllPendingActions();
1181 socket.send({
1182 type: MessageType.jewelryTeleport,
1183 destination: "bank"
1184 });
1185 }
1186 });
1187 }
1188 continue;
1189 }
1190 const targetName = entityLabel(entity);
1191 items.push({
1192 label: `Follow ${targetName}`,
1193 onSelect: () =>
1194 {
1195 clearAllPendingActions();
1196 sendPlayerFollow(entity.entityId);
1197 }
1198 });
1199 if (entity.untargetable)
1200 { continue; }
1201 const aggressive = !!(entity.aggressive || entity.hostile);
1202 const pushAttack = () =>
1203 {
1204 items.push({
1205 label: `Attack ${targetName}`,
1206 onSelect: () => requestAttack(entity.entityId)
1207 });
1208 };
1209 // Aggressive hostiles: Attack first (matches LMB default); Talk/Shop still available.
1210 if (aggressive && isAttackableEntity(entity))
1211 { pushAttack(); }
1212 if (entity.hasShop)
1213 {
1214 items.push({
1215 label: `Shop ${targetName}`,
1216 onSelect: () => requestTalk(entity.entityId, "shop")
1217 });
1218 }
1219 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
1220 {
1221 items.push({
1222 label: `Talk to ${targetName}`,
1223 onSelect: () => requestTalk(entity.entityId, "talk")
1224 });
1225 }
1226 if (entityCanShear(entity))
1227 {
1228 items.push({
1229 label: `Shear ${targetName}`,
1230 onSelect: () => requestShear(entity.entityId)
1231 });
1232 }
1233 if (entity.characterId)
1234 {
1235 items.push({
1236 label: `${targetName} info`,
1237 onSelect: () =>
1238 {
1239 clearAllPendingActions();
1240 social.inspect(entity);
1241 }
1242 });
1243 }
1244 if (!(aggressive && isAttackableEntity(entity)))
1245 { pushAttack(); }
1246 }
1247
1248 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1249 {
1250 const name = groundLabel(ground);
1251 items.push({
1252 label: `Pick up ${name}`,
1253 onSelect: () => requestPickup(ground)
1254 });
1255 if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
1256 {
1257 items.push({
1258 label: `Start Fire`,
1259 onSelect: () => requestStartFire(ground)
1260 });
1261 }
1262 }
1263
1264 if (isBankTile(view, tile.tileX, tile.tileY))
1265 {
1266 items.push({
1267 label: "Bank",
1268 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
1269 });
1270 items.push({
1271 label: "Get Blank Cheques",
1272 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
1273 });
1274 }
1275
1276 if (isDoorwayTile(view, tile.tileX, tile.tileY))
1277 {
1278 items.push({
1279 label: "Enter",
1280 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
1281 });
1282 }
1283
1284 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1285 {
1286 items.push({
1287 label: "Central Exchange",
1288 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
1289 });
1290 }
1291
1292 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1293 {
1294 items.push({
1295 label: "Bounty Office",
1296 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
1297 });
1298 }
1299
1300 if (isBarberTile(view, tile.tileX, tile.tileY))
1301 {
1302 items.push({
1303 label: "Barber",
1304 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
1305 });
1306 }
1307
1308 if (isCauldronTile(view, tile.tileX, tile.tileY))
1309 {
1310 items.push({
1311 label: "Alchemy",
1312 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
1313 });
1314 }
1315
1316 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1317 {
1318 items.push({
1319 label: "Smelt",
1320 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
1321 });
1322 }
1323
1324 if (isOvenTile(view, tile.tileX, tile.tileY))
1325 {
1326 items.push({
1327 label: "Cook",
1328 onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
1329 });
1330 }
1331
1332 if (isCampfireTile(view, tile.tileX, tile.tileY))
1333 {
1334 items.push({
1335 label: "Cook",
1336 onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
1337 });
1338 }
1339
1340 if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1341 {
1342 items.push({
1343 label: "Fish",
1344 onSelect: () => requestFish(tile.tileX, tile.tileY)
1345 });
1346 }
1347
1348 if (isAnvilTile(view, tile.tileX, tile.tileY))
1349 {
1350 items.push({
1351 label: "Smith",
1352 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
1353 });
1354 }
1355
1356 if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1357 {
1358 items.push({
1359 label: "Jewel",
1360 onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1361 });
1362 }
1363
1364 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1365 {
1366 items.push({
1367 label: "Woodwork",
1368 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
1369 });
1370 }
1371
1372 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1373 {
1374 items.push({
1375 label: "Craft",
1376 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
1377 });
1378 }
1379
1380 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1381 {
1382 items.push({
1383 label: "Spin",
1384 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
1385 });
1386 }
1387
1388 if (isLoomTile(view, tile.tileX, tile.tileY))
1389 {
1390 items.push({
1391 label: "Weave",
1392 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
1393 });
1394 }
1395
1396 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1397 {
1398 items.push({
1399 label: "Tailor",
1400 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
1401 });
1402 }
1403
1404 if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1405 {
1406 items.push({
1407 label: "Leatherwork",
1408 onSelect: () => requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY)
1409 });
1410 }
1411
1412 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1413 {
1414 items.push({
1415 label: "Mine",
1416 onSelect: () => requestMine(tile.tileX, tile.tileY)
1417 });
1418 }
1419
1420 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1421 {
1422 items.push({
1423 label: "Chop",
1424 onSelect: () => requestChop(tile.tileX, tile.tileY)
1425 });
1426 }
1427
1428 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1429 {
1430 items.push({
1431 label: "Pick",
1432 onSelect: () => requestPick(tile.tileX, tile.tileY)
1433 });
1434 }
1435
1436 contextMenu.show(event.clientX, event.clientY, items);
1437}
1438
1439function entityLabel (entity)
1440{
1441 if (entity?.mobTypeId)
1442 {
1443 const def = mobDefinition(entity.mobTypeId);
1444 const first = (entity?.firstName ?? "").trim();
1445 const last = (entity?.lastName ?? "").trim();
1446 // Fairies keep type name in tooltips ("Lv.n Fairy") even when firstName is "Ada's Fairy".
1447 const name = first && last
1448 ? `${first} ${last}`
1449 : (entity.mobTypeId === MobId.fairy
1450 ? (def?.displayName || "Fairy")
1451 : (first || def?.displayName || "Creature"));
1452 const level = entity?.level ?? def?.attackSkill ?? 1;
1453 return mobLevelDisplayName(level, name);
1454 }
1455 const first = (entity?.firstName ?? "").trim();
1456 const last = (entity?.lastName ?? "").trim();
1457 return first && last ? `${first} ${last}` : (first || "target");
1458}
1459
1460function groundLabel (ground)
1461{
1462 const name = (ground?.displayName ?? "").trim() || "item";
1463 const qty = ground?.quantity ?? 1;
1464 if (qty <= 1)
1465 { return name; }
1466 return `${name} (${formatQuantity(qty)})`;
1467}
1468
1469function startPlay (payload)
1470{
1471 playing = true;
1472 overlay.hidden = true;
1473 hud.hidden = false;
1474 const settingsToggle = document.getElementById("settings-toggle");
1475 if (settingsToggle)
1476 { settingsToggle.hidden = false; }
1477 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
1478 gait = payload.gait ?? GAIT.walk;
1479 document.getElementById("gait").textContent = gait;
1480 staminaUi?.show();
1481 healthUi?.show();
1482 statusEffectsUi?.show();
1483 if (payload.stamina != null)
1484 { staminaUi?.apply(payload.stamina); }
1485 if (payload.health != null || payload.maxHealth != null)
1486 {
1487 healthUi?.apply({
1488 current: payload.health ?? healthUi.getCurrent?.(),
1489 max: payload.maxHealth ?? healthUi.getMax?.()
1490 });
1491 }
1492 if (!scene)
1493 {
1494 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1495 game.loadScene(scene);
1496 useNearestNeighbour(scene, game.images);
1497 }
1498 if (!view)
1499 {
1500 view = new WorldView(game, scene, catalog);
1501 graphicsSettingsUi?.apply();
1502 const ticker = new GameObject(0, 0, null, 10);
1503 ticker.update = (dt) =>
1504 {
1505 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
1506 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
1507 if (!leftPressed && !leftHeld)
1508 { leftClickConsumed = false; }
1509 else if (!leftClickConsumed && playing && !uiBlocked())
1510 {
1511 leftClickConsumed = true;
1512 const canvas = scene.canvas;
1513 const rect = canvas.getBoundingClientRect();
1514 const mouseX = GameInput.mousePosition.x - rect.left;
1515 const mouseY = GameInput.mousePosition.y - rect.top;
1516 handleLeftClick(mouseX, mouseY);
1517 }
1518 if (GameInput.isPressed(82) && !uiBlocked())
1519 {
1520 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
1521 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
1522 { return; }
1523 socket.send({ type: MessageType.setGait, gait: next });
1524 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
1525 if (next === GAIT.walk)
1526 {
1527 gait = next;
1528 document.getElementById("gait").textContent = gait;
1529 }
1530 }
1531 if (playing && !death?.isBlocking())
1532 {
1533 flushPendingPickup();
1534 flushPendingInteract();
1535 syncAutorun();
1536 social?.updateNametag(view, scene, view.localEntityId);
1537 chat?.update(view, scene);
1538 updateSpellTargetHighlight();
1539 updateWorldTooltip();
1540 }
1541 else
1542 {
1543 hideWorldTooltip();
1544 view?.clearSpellTargetHighlight();
1545 }
1546 view.update(dt);
1547 };
1548 scene.addObject(ticker);
1549 window.addEventListener("resize", () =>
1550 {
1551 scene.size.x = window.innerWidth;
1552 scene.size.y = window.innerHeight;
1553 scene.g_fixSize();
1554 useNearestNeighbour(scene, game.images);
1555 });
1556 window.addEventListener("wheel", (event) =>
1557 {
1558 if (!playing || uiBlocked())
1559 { return; }
1560 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
1561 if (playZoomRaf)
1562 { return; }
1563 playZoomRaf = requestAnimationFrame(() =>
1564 {
1565 playZoomRaf = 0;
1566 if (!view || !playZoomDelta)
1567 { return; }
1568 view.setZoom(view.zoom + playZoomDelta);
1569 playZoomDelta = 0;
1570 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
1571 });
1572 }, { passive: true });
1573 scene.canvas.addEventListener("contextmenu", (event) =>
1574 {
1575 if (!playing || uiBlocked())
1576 { return; }
1577 const rect = scene.canvas.getBoundingClientRect();
1578 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
1579 });
1580 }
1581 view.setSettings(payload.settings ?? view.settings);
1582 chat?.syncSettings();
1583 view.worldHour = payload.worldTime?.hour ?? 12;
1584 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
1585 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
1586 view.setWorldSeason(payload.worldTime?.season);
1587 view.setLocalEntity(
1588 payload.entityId,
1589 payload.tileX,
1590 payload.tileY,
1591 payload.gait,
1592 payload.sex,
1593 payload.firstName,
1594 payload.lastName,
1595 payload.characterId,
1596 payload.layers,
1597 payload.health,
1598 payload.maxHealth,
1599 payload.skullValue
1600 );
1601 social?.setLocalIdentity?.({
1602 accountId: payload.accountId,
1603 characterId: payload.characterId
1604 });
1605 graphicsSettingsUi?.apply();
1606}
1607
1608async function main ()
1609{
1610 const authStatus = await fetchAuthStatus();
1611 updateAuthUi(authStatus);
1612 if (!authStatus.authenticated)
1613 {
1614 statusEl.textContent = "Sign in to play Questward.";
1615 showError("");
1616 return;
1617 }
1618
1619 setAssetLoading(true, { phase: "Loading catalog…" });
1620 catalog = await loadSpriteCatalog();
1621 const assetTotal = playImagesFromCatalog(catalog).length;
1622 setAssetLoading(true, { loaded: 0, total: assetTotal, phase: "Loading assets…" });
1623 await preloadCatalogImages(game, catalog, {
1624 onProgress ({ loaded, total })
1625 {
1626 setAssetLoading(true, { loaded, total });
1627 }
1628 });
1629 applySpriteSheets(game.images, catalog);
1630 if (!scene)
1631 {
1632 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1633 game.loadScene(scene);
1634 }
1635 setAssetLoading(false);
1636 statusEl.textContent = "Connecting…";
1637 createHairControls = bindHairControls({
1638 root: document.getElementById("create-hair"),
1639 resolveSpriteUrl (name)
1640 {
1641 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1642 },
1643 getSex: () => document.getElementById("sex")?.value ?? "male",
1644 getBag: () => null,
1645 hideHeadgear: true,
1646 onChange ()
1647 {
1648 if (createActiveTab === "clothing")
1649 { void refreshCreateClothingPreview(); }
1650 }
1651 });
1652 createClothingControls = bindCreateClothingControls({
1653 root: document.getElementById("create-clothing"),
1654 onChange ()
1655 {
1656 if (createActiveTab === "clothing")
1657 { void refreshCreateClothingPreview(); }
1658 }
1659 });
1660 initCreateTabs();
1661 document.getElementById("sex")?.addEventListener("change", () =>
1662 {
1663 createHairControls?.fillStyles();
1664 void createHairControls?.refreshPreview();
1665 if (createActiveTab === "clothing")
1666 { void refreshCreateClothingPreview(); }
1667 });
1668 void createHairControls?.refreshPreview();
1669 void refreshCreateClothingPreview();
1670 graphicsSettingsUi = initGraphicsSettings({
1671 onChange: applyGraphicsSettings,
1672 onSuppressWorldClick: consumeWorldClick
1673 });
1674 social = initSocial({
1675 socket: { send (payload) { socket.send(payload); } },
1676 MessageType,
1677 resolveSpriteUrl (name)
1678 {
1679 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1680 },
1681 resolveImage (name)
1682 {
1683 return game?.images?.[name] ?? null;
1684 }
1685 });
1686 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1687 const tipArrows = initTipArrows({
1688 socket: { send (payload) { socket.send(payload); } },
1689 MessageType,
1690 getInventoryBag ()
1691 {
1692 return inventory?.getBag?.() ?? null;
1693 }
1694 });
1695 inventory = initInventory({
1696 socket: { send (payload) { socket.send(payload); } },
1697 MessageType,
1698 contextMenu,
1699 tipArrows,
1700 resolveSpriteUrl (name)
1701 {
1702 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1703 },
1704 resolveImage (name)
1705 {
1706 return game?.images?.[name] ?? null;
1707 },
1708 getFriends ()
1709 {
1710 return social?.getFriends?.() ?? [];
1711 },
1712 getLocalName ()
1713 {
1714 const you = document.getElementById("you")?.textContent ?? "";
1715 return you.split("(")[0].trim() || "Unknown";
1716 },
1717 getSoftClaims ()
1718 {
1719 return alchemy?.listSoftClaims?.() ?? [];
1720 },
1721 knowsSpell (spellId)
1722 {
1723 return !!spells?.knowsSpell?.(spellId);
1724 },
1725 getSkillLevels ()
1726 {
1727 return skills?.getSkillLevels?.() ?? {};
1728 },
1729 getSettings ()
1730 {
1731 return view?.settings ?? null;
1732 },
1733 getKnownSpellIds ()
1734 {
1735 return spells?.getKnownSpellIds?.() ?? [];
1736 },
1737 onBagChanged ()
1738 {
1739 spells?.refreshMaxHitDisplay?.();
1740 }
1741 });
1742 skills = initSkills({
1743 getEquipmentSlots ()
1744 {
1745 return inventory?.getEquipment?.() ?? {};
1746 },
1747 getSettings ()
1748 {
1749 return view?.settings ?? null;
1750 }
1751 });
1752 spells = initSpells({
1753 socket: { send (payload) { socket.send(payload); } },
1754 MessageType,
1755 getSkillLevel (skillId)
1756 {
1757 return skills?.skillLevel?.(skillId) ?? 1;
1758 },
1759 getSkillLevels ()
1760 {
1761 return skills?.getSkillLevels?.() ?? {};
1762 },
1763 getEquipmentSlots ()
1764 {
1765 return inventory?.getEquipment?.() ?? {};
1766 },
1767 getSettings ()
1768 {
1769 return view?.settings ?? null;
1770 }
1771 });
1772 crafting = initCrafting({
1773 socket: { send (payload) { socket.send(payload); } },
1774 MessageType,
1775 getInventorySlots ()
1776 {
1777 return inventory?.getInventorySlots?.() ?? [];
1778 },
1779 getEquipment ()
1780 {
1781 return inventory?.getEquipment?.() ?? {};
1782 },
1783 getSkillLevel (skillId)
1784 {
1785 return skills?.skillLevel?.(skillId) ?? 1;
1786 }
1787 });
1788 alchemy = initAlchemy({
1789 socket: { send (payload) { socket.send(payload); } },
1790 MessageType,
1791 getInventorySlots ()
1792 {
1793 return inventory?.getInventorySlots?.() ?? [];
1794 }
1795 });
1796 alchemy?.setOnSoftClaimsChanged?.(() => inventory?.refreshBagDisplay?.());
1797 staminaUi = initStamina();
1798 healthUi = initHealth();
1799 statusEffectsUi = initStatusEffects();
1800 toasts = initToasts();
1801 questsUi = initQuests({
1802 socket: { send (payload) { socket.send(payload); } },
1803 MessageType,
1804 toasts
1805 });
1806 dialogueUi = initDialogue({
1807 socket: { send (payload) { socket.send(payload); } },
1808 MessageType,
1809 getEntity (id)
1810 {
1811 if (id === "local")
1812 { return view?.entities.get(view.localEntityId) ?? null; }
1813 return view?.entities.get(id) ?? null;
1814 },
1815 captureSpeakerIcon (entityId, size = 64)
1816 {
1817 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1818 }
1819 });
1820 shop = initShop({
1821 socket: { send (payload) { socket.send(payload); } },
1822 MessageType,
1823 onSuppressWorldClick: consumeWorldClick,
1824 getCoinCount ()
1825 {
1826 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1827 },
1828 getInventorySlots ()
1829 {
1830 return inventory?.getInventorySlots?.() ?? [];
1831 }
1832 });
1833 market = initMarket({
1834 socket: { send (payload) { socket.send(payload); } },
1835 MessageType,
1836 onSuppressWorldClick: consumeWorldClick,
1837 getCoinCount ()
1838 {
1839 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1840 },
1841 getInventorySlots ()
1842 {
1843 return inventory?.getInventorySlots?.() ?? [];
1844 },
1845 getLocalCharacterId ()
1846 {
1847 return inventory?.getLocalCharacterId?.() ?? null;
1848 }
1849 });
1850 bounty = initBounty({
1851 socket: { send (payload) { socket.send(payload); } },
1852 MessageType,
1853 onSuppressWorldClick: consumeWorldClick,
1854 resolveSpriteUrl (name)
1855 {
1856 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1857 },
1858 resolveImage (name)
1859 {
1860 return game?.images?.[name] ?? null;
1861 }
1862 });
1863 barber = initBarber({
1864 socket: { send (payload) { socket.send(payload); } },
1865 MessageType,
1866 onSuppressWorldClick: consumeWorldClick,
1867 resolveSpriteUrl (name)
1868 {
1869 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1870 },
1871 getInventoryBag ()
1872 {
1873 return {
1874 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1875 inventory: inventory?.getInventorySlots?.() ?? []
1876 };
1877 }
1878 });
1879 chat = initChat({
1880 socket: { send (payload) { socket.send(payload); } },
1881 MessageType,
1882 getSettings: () => view?.settings
1883 });
1884 death = initDeath({
1885 socket: { send (payload) { socket.send(payload); } },
1886 MessageType
1887 });
1888 game.startGame();
1889 useNearestNeighbour(scene, game.images);
1890
1891 socket = new GameSocket(defaultSocketUrl(), (message) =>
1892 {
1893 switch (message.type)
1894 {
1895 case MessageType.session:
1896 session = message;
1897 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1898 renderCharacters(message.characters);
1899 break;
1900 case MessageType.characterList:
1901 renderCharacters(message.characters);
1902 if (!playing)
1903 { overlay.hidden = false; }
1904 break;
1905 case MessageType.enterWorld:
1906 closeCreateModal();
1907 startPlay(message);
1908 inventory?.setLocalCharacterId(message.characterId);
1909 toasts?.applyRestartStatus?.(message.restartStatus);
1910 socket.send({ type: MessageType.requestQuests });
1911 break;
1912 case MessageType.chunkSnapshot:
1913 view?.applySnapshot(message);
1914 break;
1915 case MessageType.dimensionChanged:
1916 if (view)
1917 {
1918 view.setDimensionId(message.dimensionId);
1919 view.setDimensionModes(message.lightingMode, message.seasonMode);
1920 view.clearAllChunks();
1921 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1922 {
1923 view.moveEntity({
1924 entityId: view.localEntityId,
1925 tileX: message.tileX,
1926 tileY: message.tileY
1927 });
1928 }
1929 }
1930 closeOpenUiIfTooFar();
1931 break;
1932 case MessageType.chunkDelta:
1933 for (const tile of message.tiles ?? [])
1934 {
1935 view?.updateAuthoredTile(
1936 message.chunkX,
1937 message.chunkY,
1938 tile.localX,
1939 tile.localY,
1940 { ground: tile.ground, block: tile.block, light: tile.light }
1941 );
1942 }
1943 break;
1944 case MessageType.unsubscribeChunk:
1945 view?.removeChunk(message.chunkX, message.chunkY);
1946 break;
1947 case MessageType.entitySpawn:
1948 view?.spawnEntity(message);
1949 break;
1950 case MessageType.entityMove:
1951 view?.moveEntity(message);
1952 if (message.entityId === view?.localEntityId)
1953 {
1954 if (message.gait)
1955 {
1956 gait = message.gait;
1957 document.getElementById("gait").textContent = gait;
1958 }
1959 closeOpenUiIfTooFar();
1960 }
1961 else if (
1962 uiFocus?.entityId != null
1963 && message.entityId === uiFocus.entityId
1964 )
1965 { closeOpenUiIfTooFar(); }
1966 break;
1967 case MessageType.entityDespawn:
1968 if (message.entityId === autorunFocusEntityId)
1969 { clearAutorunFocus(); }
1970 view?.despawnEntity(message.entityId);
1971 break;
1972 case MessageType.entityAppearance:
1973 view?.setAppearance(message);
1974 break;
1975 case MessageType.entitySkull:
1976 view?.updateEntitySkull(message.entityId, message.skullValue);
1977 break;
1978 case MessageType.groundItemAppear:
1979 view?.upsertGroundItem(message);
1980 break;
1981 case MessageType.groundItemDespawn:
1982 view?.despawnGroundItem(message.groundItemId);
1983 break;
1984 case MessageType.inventory:
1985 inventory?.handleInventory(message);
1986 skills?.refresh?.();
1987 crafting?.refresh();
1988 alchemy?.refresh();
1989 shop?.refresh();
1990 market?.refresh();
1991 break;
1992 case MessageType.skills:
1993 skills?.render(message.skills, message.combatLevel);
1994 inventory?.refreshMaxHit?.();
1995 spells?.refreshMaxHitDisplay?.();
1996 crafting?.refresh();
1997 spells?.refreshCastGates?.();
1998 break;
1999 case MessageType.spells:
2000 case MessageType.spellsUpdated:
2001 spells?.render(message);
2002 inventory?.refreshMaxHit?.();
2003 break;
2004 case MessageType.spellArmed:
2005 spells?.handleSpellArmed(message);
2006 break;
2007 case MessageType.spellDisarmed:
2008 spells?.handleSpellDisarmed();
2009 break;
2010 case MessageType.spellProjectile:
2011 view?.spawnSpellProjectileFx(message);
2012 if (message.casterId === view?.localEntityId)
2013 { clearAutorunFocus(); }
2014 break;
2015 case MessageType.spellFizzle:
2016 view?.spawnSpellFizzleFx(message);
2017 if (message.casterId === view?.localEntityId)
2018 {
2019 clearAutorunFocus();
2020 toasts?.show("Failed to cast spell");
2021 }
2022 break;
2023 case MessageType.spellCastFlash:
2024 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
2025 if (message.casterId === view?.localEntityId)
2026 { clearAutorunFocus(); }
2027 break;
2028 case MessageType.spellLightAppear:
2029 case MessageType.spellLightUpdate:
2030 view?.setSpellLight(message);
2031 break;
2032 case MessageType.spellLightRemove:
2033 view?.removeSpellLight(message);
2034 break;
2035 case MessageType.spellDarkAppear:
2036 case MessageType.spellDarkUpdate:
2037 view?.setSpellDark(message);
2038 break;
2039 case MessageType.spellDarkRemove:
2040 view?.removeSpellDark(message);
2041 break;
2042 case MessageType.stamina:
2043 staminaUi?.apply(message);
2044 if (message.gait)
2045 {
2046 gait = message.gait;
2047 document.getElementById("gait").textContent = gait;
2048 if (gait === GAIT.walk && (staminaUi?.getCurrent?.() ?? 0) <= 0)
2049 { autorunWaitingStamina = true; }
2050 }
2051 syncAutorun();
2052 break;
2053 case MessageType.statusEffects:
2054 view?.setLocalBlind(!!message.blind);
2055 statusEffectsUi?.apply(message);
2056 break;
2057 case MessageType.bankSnapshot:
2058 inventory?.handleBank(message);
2059 break;
2060 case MessageType.cauldronSnapshot:
2061 if (message.open === false && uiFocus?.kind === "cauldron")
2062 { clearUiFocus(); }
2063 alchemy?.handleSnapshot(message);
2064 break;
2065 case MessageType.pigeonDispatched:
2066 inventory?.handlePigeonDispatched(message);
2067 break;
2068 case MessageType.pigeonDelivered:
2069 inventory?.handlePigeonDelivered(message);
2070 break;
2071 case MessageType.characterSearchResult:
2072 inventory?.handleCharacterSearch(message);
2073 break;
2074 case MessageType.craftResult:
2075 crafting?.handleCraftResult(message);
2076 break;
2077 case MessageType.worldStatus:
2078 if (view)
2079 {
2080 view.setSettings(message.settings ?? view.settings);
2081 view.worldHour = message.worldTime?.hour ?? view.worldHour;
2082 view.setWorldSeason(message.worldTime?.season);
2083 chat?.syncSettings();
2084 }
2085 skills?.refresh?.();
2086 toasts?.applyRestartStatus?.(message.restartStatus);
2087 break;
2088 case MessageType.restartStatus:
2089 toasts?.applyRestartStatus?.(message.restartStatus);
2090 break;
2091 case MessageType.chatBubble:
2092 chat?.showBubble(message);
2093 break;
2094 case MessageType.friends:
2095 social?.handleFriends(message);
2096 break;
2097 case MessageType.combatSwing:
2098 view?.spawnCombatSwing(message);
2099 break;
2100 case MessageType.combatProjectile:
2101 view?.spawnPhysicalProjectileFx({
2102 ...message,
2103 sprite: "fx:projectile:arrow"
2104 });
2105 break;
2106 case MessageType.combatNoArrows:
2107 toasts?.show("Out of arrows!");
2108 break;
2109 case MessageType.gatherSwing:
2110 case MessageType.tileShove:
2111 view?.spawnGatherSwing(message);
2112 break;
2113 case MessageType.stationOpen:
2114 if (message.stationId)
2115 { crafting?.openStation(message.stationId); }
2116 break;
2117 case MessageType.shopOpen:
2118 if (message.npcEntityId != null)
2119 { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); }
2120 shop?.handleShopOpen(message);
2121 break;
2122 case MessageType.shopClosed:
2123 if (uiFocus?.kind === "shop")
2124 { clearUiFocus(); }
2125 shop?.handleShopClosed(message);
2126 break;
2127 case MessageType.marketOpen:
2128 market?.handleOpen(message);
2129 break;
2130 case MessageType.marketClosed:
2131 if (uiFocus?.kind === "market")
2132 { clearUiFocus(); }
2133 market?.handleClosed(message);
2134 break;
2135 case MessageType.marketTrade:
2136 market?.handleTrade(message);
2137 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
2138 break;
2139 case MessageType.bountySnapshot:
2140 bounty?.handleSnapshot(message);
2141 break;
2142 case MessageType.closeBounty:
2143 if (uiFocus?.kind === "bounty")
2144 { clearUiFocus(); }
2145 bounty?.handleClosed(message);
2146 break;
2147 case MessageType.characterBounty:
2148 bounty?.handleCharacterBounty(message);
2149 social?.handleCharacterBounty(message);
2150 break;
2151 case MessageType.barberSnapshot:
2152 barber?.handleSnapshot(message);
2153 break;
2154 case MessageType.closeBarber:
2155 if (uiFocus?.kind === "barber")
2156 { clearUiFocus(); }
2157 barber?.handleClosed(message);
2158 break;
2159 case MessageType.itemBubble:
2160 chat?.showItemBubble(message);
2161 break;
2162 case MessageType.gatherComplete:
2163 crafting?.refresh();
2164 break;
2165 case MessageType.combatHit:
2166 {
2167 const applyHit = () =>
2168 {
2169 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
2170 view?.flashDamage(message.targetId);
2171 view?.spawnCombatKnockback?.(message);
2172 view?.spawnDamageNumber(message.targetId, message.damage);
2173 if (message.targetId === view?.localEntityId)
2174 {
2175 healthUi?.apply({
2176 current: message.health,
2177 max: message.maxHealth
2178 });
2179 }
2180 };
2181 if (!view?.deferCombatHit?.(message, applyHit))
2182 { applyHit(); }
2183 break;
2184 }
2185 case MessageType.combatMiss:
2186 view?.spawnCombatDodge?.(message);
2187 view?.markProjectileMiss?.(message);
2188 break;
2189 case MessageType.combatBlock:
2190 {
2191 const applyBlock = () =>
2192 {
2193 view?.flashBlock?.(message.targetId);
2194 if (message.health != null)
2195 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
2196 };
2197 if (!view?.deferCombatHit?.(message, applyBlock))
2198 { applyBlock(); }
2199 break;
2200 }
2201 case MessageType.entityHealth:
2202 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2203 if (message.entityId === view?.localEntityId)
2204 {
2205 healthUi?.apply({
2206 current: message.health,
2207 max: message.maxHealth
2208 });
2209 }
2210 break;
2211 case MessageType.skillLevelUp:
2212 view?.spawnSkillLevelUp(message.entityId, message);
2213 if (message.entityId === view?.localEntityId)
2214 {
2215 const level = message.level | 0;
2216 const previousLevel = message.previousLevel == null
2217 ? Math.max(0, level - 1)
2218 : message.previousLevel | 0;
2219 const unlockCount = skillUnlockMessages(message.skillId, previousLevel, level).length;
2220 toasts?.show(skillLevelUpToastText(message.skillId, level, previousLevel), {
2221 durationMs: 3500 + unlockCount * 1600
2222 });
2223 }
2224 break;
2225 case MessageType.playerDied:
2226 clearAllPendingActions();
2227 clearAutorunFocus();
2228 contextMenu?.hide();
2229 spells?.handleSpellDisarmed?.();
2230 closeCloseablePlayUi();
2231 death?.show();
2232 if (message.entityId === view?.localEntityId)
2233 {
2234 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
2235 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
2236 }
2237 // Red silhouette fade if despawn is delayed or already queued this tick.
2238 view?.beginDeathDissolve?.(message.entityId);
2239 break;
2240 case MessageType.playerRespawned:
2241 death?.hide();
2242 // Drop deferred killing-blow health=0 that may still be queued on a projectile.
2243 view?.cancelDeferredCombatHits?.(message.entityId);
2244 view?.finishDeathDissolve?.(message.entityId);
2245 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2246 if (message.skullValue != null)
2247 { view?.updateEntitySkull(message.entityId, message.skullValue); }
2248 if (message.entityId === view?.localEntityId)
2249 {
2250 healthUi?.apply({
2251 current: message.health,
2252 max: message.maxHealth
2253 });
2254 }
2255 if (message.stamina != null || message.maxStamina != null)
2256 {
2257 staminaUi?.apply({
2258 current: message.stamina ?? staminaUi.getCurrent?.(),
2259 max: message.maxStamina ?? staminaUi.getMax?.()
2260 });
2261 }
2262 break;
2263 case MessageType.error:
2264 if (playing)
2265 { toasts?.show(message.message); }
2266 else
2267 {
2268 const createPanel = document.getElementById("create-panel");
2269 const createError = document.getElementById("create-error");
2270 if (createPanel && !createPanel.hidden && createError)
2271 { createError.textContent = message.message ?? ""; }
2272 else
2273 { showError(message.message); }
2274 }
2275 social?.showError(message.message);
2276 break;
2277 case MessageType.toast:
2278 if (playing)
2279 { toasts?.show(message.message); }
2280 break;
2281 case MessageType.questsSnapshot:
2282 questsUi?.applySnapshot(message);
2283 break;
2284 case MessageType.questStepComplete:
2285 questsUi?.handleStepComplete(message);
2286 break;
2287 case MessageType.dialogueStep:
2288 if (message.npcEntityId != null)
2289 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2290 dialogueUi?.handleStep(message);
2291 break;
2292 case MessageType.dialogueItemRewards:
2293 if (message.npcEntityId != null)
2294 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2295 dialogueUi?.handleItemRewards(message);
2296 break;
2297 case MessageType.dialogueChoices:
2298 if (message.npcEntityId != null)
2299 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2300 dialogueUi?.handleChoices(message);
2301 break;
2302 case MessageType.dialogueClose:
2303 if (uiFocus?.kind === "dialogue")
2304 { clearUiFocus(); }
2305 dialogueUi?.handleClose(message);
2306 break;
2307 case MessageType.forceLogout:
2308 returnToMenu(message.reason);
2309 break;
2310 }
2311 }, {
2312 onClose (event)
2313 {
2314 if (playing)
2315 { returnToMenu(event.reason || "Disconnected from server."); }
2316 }
2317 });
2318 await socket.connect();
2319 if (typeof window !== "undefined")
2320 {
2321 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
2322 {
2323 crafting?.openStation(stationId);
2324 };
2325 }
2326}
2327
2328function returnToMenu (reason = "")
2329{
2330 playing = false;
2331 followTargetId = null;
2332 moveDest = null;
2333 clearAutorunFocus();
2334 autorunWaitingStamina = false;
2335 clearAllPendingActions();
2336 clearUiFocus();
2337 social?.reset();
2338 chat?.reset();
2339 inventory?.reset();
2340 crafting?.reset();
2341 alchemy?.reset();
2342 staminaUi?.hide();
2343 healthUi?.hide();
2344 statusEffectsUi?.hide();
2345 skills?.hide();
2346 spells?.hide();
2347 contextMenu?.hide();
2348 death?.reset();
2349 shop?.close({ notifyServer: false });
2350 bounty?.close();
2351 barber?.close();
2352 questsUi?.reset();
2353 dialogueUi?.reset();
2354 hideWorldTooltip();
2355 if (view)
2356 { view.clearPlaySession(); }
2357 overlay.hidden = false;
2358 hud.hidden = true;
2359 const settingsToggle = document.getElementById("settings-toggle");
2360 if (settingsToggle)
2361 { settingsToggle.hidden = true; }
2362 graphicsSettingsUi?.close();
2363 if (reason)
2364 { statusEl.textContent = reason; }
2365}
2366
2367document.getElementById("create-character-open")?.addEventListener("click", () =>
2368{
2369 showError("");
2370 const createError = document.getElementById("create-error");
2371 if (createError)
2372 { createError.textContent = ""; }
2373 document.getElementById("create-backdrop").hidden = false;
2374 document.getElementById("create-panel").hidden = false;
2375 setCreateTab("appearance");
2376 void createHairControls?.refreshPreview();
2377});
2378
2379function closeCreateModal ()
2380{
2381 document.getElementById("create-backdrop").hidden = true;
2382 document.getElementById("create-panel").hidden = true;
2383}
2384
2385document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
2386document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
2387
2388document.getElementById("create-form").addEventListener("submit", (event) =>
2389{
2390 event.preventDefault();
2391 showError("");
2392 const createError = document.getElementById("create-error");
2393 if (createError)
2394 { createError.textContent = ""; }
2395 const names = validateCharacterNames({
2396 firstName: document.getElementById("first-name").value,
2397 lastName: document.getElementById("last-name").value,
2398 isAdmin: !!session?.isAdmin
2399 });
2400 if (!names.ok)
2401 {
2402 if (createError)
2403 { createError.textContent = names.reason; }
2404 else
2405 { showError(names.reason); }
2406 return;
2407 }
2408 socket.send({
2409 type: MessageType.createCharacter,
2410 firstName: names.firstName,
2411 lastName: names.lastName,
2412 sex: document.getElementById("sex").value,
2413 hair: createHairControls?.currentHair?.() ?? null,
2414 clothing: createClothingControls?.currentClothing?.() ?? null
2415 });
2416});
2417
2418function initCreateTabs ()
2419{
2420 const tabs = document.querySelectorAll(".create-tab");
2421 for (const tab of tabs)
2422 {
2423 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
2424 }
2425 setCreateTab("appearance");
2426}
2427
2428function setCreateTab (name)
2429{
2430 createActiveTab = name === "clothing" ? "clothing" : "appearance";
2431 for (const tab of document.querySelectorAll(".create-tab"))
2432 {
2433 const on = tab.dataset.createTab === createActiveTab;
2434 tab.classList.toggle("active", on);
2435 tab.setAttribute("aria-selected", on ? "true" : "false");
2436 }
2437 for (const pane of document.querySelectorAll("[data-create-pane]"))
2438 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
2439 if (createActiveTab === "clothing")
2440 { void refreshCreateClothingPreview(); }
2441 else
2442 { void createHairControls?.refreshPreview(); }
2443}
2444
2445async function refreshCreateClothingPreview ()
2446{
2447 const canvas = document.getElementById("create-clothing-preview");
2448 if (!canvas || !createClothingControls)
2449 { return; }
2450 try
2451 {
2452 await paintCharacterPreview(canvas, {
2453 sex: document.getElementById("sex")?.value ?? "male",
2454 bag: createClothingControls.previewBag(),
2455 hair: createHairControls?.currentHair?.() ?? null,
2456 hideHeadgear: true,
2457 resolveSpriteUrl (name)
2458 {
2459 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2460 },
2461 scale: 4
2462 });
2463 }
2464 catch (error)
2465 { console.warn(error); }
2466}
2467
2468document.getElementById("leave").addEventListener("click", () =>
2469{
2470 socket.send({ type: MessageType.leaveWorld });
2471 returnToMenu();
2472});
2473
2474main().catch((error) =>
2475{
2476 showError(error.message);
2477 console.error(error);
2478});
2479
2480function isBankTile (view, tileX, tileY)
2481{
2482 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
2483}
2484
2485function isDoorwayTile (view, tileX, tileY)
2486{
2487 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
2488}
2489
2490function isMarketplaceTile (view, tileX, tileY)
2491{
2492 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
2493}
2494
2495function isBountyOfficeTile (view, tileX, tileY)
2496{
2497 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
2498}
2499
2500function isBarberTile (view, tileX, tileY)
2501{
2502 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
2503}
2504
2505function isCauldronTile (view, tileX, tileY)
2506{
2507 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2508}
2509
2510function isFurnaceTile (view, tileX, tileY)
2511{
2512 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2513}
2514
2515function isOvenTile (view, tileX, tileY)
2516{
2517 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2518}
2519
2520function isCampfireTile (view, tileX, tileY)
2521{
2522 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2523}
2524
2525function isFishingSpotTile (view, tileX, tileY)
2526{
2527 const block = blockAt(view, tileX, tileY);
2528 if (!block || block.typeId !== BlockType.fishingSpot)
2529 { return false; }
2530 return block.state !== "exhausted";
2531}
2532
2533function isAnvilTile (view, tileX, tileY)
2534{
2535 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2536}
2537
2538function isJeweleringStationTile (view, tileX, tileY)
2539{
2540 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2541}
2542
2543function isGroundWoodLog (ground)
2544{
2545 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2546 return def?.familyId === ItemFamilyId.log;
2547}
2548
2549function playerHasUsableTinderbox ()
2550{
2551 const slots = inventory?.getInventorySlots?.() ?? [];
2552 for (const slot of slots)
2553 {
2554 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2555 { continue; }
2556 const charges = slot.instance?.kind === "tinderbox"
2557 ? (slot.instance.charges | 0)
2558 : TINDERBOX_MAX_CHARGES;
2559 if (charges > 0)
2560 { return true; }
2561 }
2562 return false;
2563}
2564
2565function isWoodworkingBenchTile (view, tileX, tileY)
2566{
2567 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2568}
2569
2570function isCraftingBenchTile (view, tileX, tileY)
2571{
2572 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
2573}
2574
2575function isSpinningWheelTile (view, tileX, tileY)
2576{
2577 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
2578}
2579
2580function isLoomTile (view, tileX, tileY)
2581{
2582 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
2583}
2584
2585function isTailorBenchTile (view, tileX, tileY)
2586{
2587 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
2588}
2589
2590function isLeatherworkingTableTile (view, tileX, tileY)
2591{
2592 return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable;
2593}
2594
2595function isOreBoulderTile (view, tileX, tileY)
2596{
2597 const block = blockAt(view, tileX, tileY);
2598 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
2599}
2600
2601function isChopableTreeTile (view, tileX, tileY)
2602{
2603 return isChopableTreeBlock(blockAt(view, tileX, tileY));
2604}
2605
2606function isPickablePlantTile (view, tileX, tileY)
2607{
2608 return isPickablePlantBlock(blockAt(view, tileX, tileY));
2609}
2610
2611const SPELL_ENTITY_SNAP_TILES = 2;
2612
2613function updateSpellTargetHighlight ()
2614{
2615 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
2616 {
2617 view?.clearSpellTargetHighlight();
2618 return;
2619 }
2620 const canvas = scene?.canvas;
2621 if (!canvas)
2622 { return; }
2623 const rect = canvas.getBoundingClientRect();
2624 const mouseX = GameInput.mousePosition.x - rect.left;
2625 const mouseY = GameInput.mousePosition.y - rect.top;
2626 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2627 {
2628 view.clearSpellTargetHighlight();
2629 return;
2630 }
2631 const armed = spells.getArmedSpell?.();
2632 const local = view.entities.get(view.localEntityId);
2633 if (armed?.target === "entity")
2634 {
2635 const target = nearestSpellEntityAtCursor(mouseX, mouseY);
2636 if (!target)
2637 {
2638 view.clearSpellTargetHighlight();
2639 return;
2640 }
2641 const inRange = !local
2642 || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) <= COMBAT_RANGE_TILES;
2643 view.setSpellEntityTargetHighlight(target.entityId, inRange);
2644 return;
2645 }
2646 const tile = view.screenToTile(mouseX, mouseY);
2647 const inRange = !local
2648 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
2649 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
2650}
2651
2652/**
2653 * Nearest spell-targetable entity within {@link SPELL_ENTITY_SNAP_TILES} of the
2654 * cursor tile (uses both authoritative and visual tile for moving mobs).
2655 */
2656function nearestSpellEntityAtCursor (mouseX, mouseY)
2657{
2658 if (!view)
2659 { return null; }
2660 const cursor = view.screenToTile(mouseX, mouseY);
2661 const tileSize = view.tileSize();
2662 let best = null;
2663 let bestDist = Infinity;
2664 let bestScreen = Infinity;
2665 for (const entity of view.entities.values())
2666 {
2667 if (!isSpellEntityTarget(entity))
2668 { continue; }
2669 const visualTileX = Math.floor((entity.visualX + (entity.stackOffsetX ?? 0)) / tileSize);
2670 const visualTileY = Math.floor((entity.visualY + (entity.stackOffsetY ?? 0)) / tileSize);
2671 const dist = Math.min(
2672 chebyshev(cursor.tileX, cursor.tileY, entity.tileX, entity.tileY),
2673 chebyshev(cursor.tileX, cursor.tileY, visualTileX, visualTileY)
2674 );
2675 if (dist > SPELL_ENTITY_SNAP_TILES)
2676 { continue; }
2677 const box = view.nametagAnchor?.(entity);
2678 const screenDist = box
2679 ? Math.hypot(box.x - mouseX, box.y - mouseY)
2680 : dist;
2681 if (dist < bestDist || (dist === bestDist && screenDist < bestScreen))
2682 {
2683 best = entity;
2684 bestDist = dist;
2685 bestScreen = screenDist;
2686 }
2687 }
2688 return best;
2689}
2690
2691function isSpellEntityTarget (entity)
2692{
2693 if (!entity || entity.entityId === view?.localEntityId)
2694 { return false; }
2695 if (entity.untargetable || entity.freeFlight)
2696 { return false; }
2697 return isAttackableEntity(entity);
2698}
2699
2700function hideWorldTooltip ()
2701{
2702 if (worldTooltip)
2703 {
2704 worldTooltip.hidden = true;
2705 worldTooltip.classList.remove("friend-name");
2706 worldTooltip.style.color = "";
2707 }
2708}
2709
2710/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
2711function updateWorldTooltip ()
2712{
2713 if (!worldTooltip || !view || !scene || uiBlocked())
2714 {
2715 hideWorldTooltip();
2716 return;
2717 }
2718 const canvas = scene.canvas;
2719 const rect = canvas.getBoundingClientRect();
2720 const mouseX = GameInput.mousePosition.x - rect.left;
2721 const mouseY = GameInput.mousePosition.y - rect.top;
2722 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2723 {
2724 hideWorldTooltip();
2725 return;
2726 }
2727 const entity = view.entityAtScreen(mouseX, mouseY);
2728 if (entity && entity.entityId !== view.localEntityId)
2729 {
2730 const label = entityLabel(entity);
2731 worldTooltip.hidden = false;
2732 worldTooltip.textContent = label;
2733 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2734 worldTooltip.classList.toggle("friend-name", !!friend);
2735 worldTooltip.style.color = friend ? "#e8c84a" : "";
2736 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2737 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2738 return;
2739 }
2740 const tile = view.screenToTile(mouseX, mouseY);
2741 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
2742 if (!label)
2743 {
2744 hideWorldTooltip();
2745 return;
2746 }
2747 worldTooltip.hidden = false;
2748 worldTooltip.textContent = label;
2749 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2750 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2751}
2752
2753function blockTypeAt (view, tileX, tileY)
2754{
2755 return blockAt(view, tileX, tileY)?.typeId ?? null;
2756}
2757
2758function blockAt (view, tileX, tileY)
2759{
2760 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2761 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2762 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2763 if (!snapshot)
2764 { return null; }
2765 const localX = tileX - chunkX * CHUNK_SIZE;
2766 const localY = tileY - chunkY * CHUNK_SIZE;
2767 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
2768}
2769
2770function groundTypeAt (view, tileX, tileY)
2771{
2772 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2773 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2774 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2775 if (!snapshot)
2776 { return null; }
2777 const localX = tileX - chunkX * CHUNK_SIZE;
2778 const localY = tileY - chunkY * CHUNK_SIZE;
2779 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
2780}
2781
2782/** Best-effort client filter for approach destinations (server still authorizes paths). */
2783function isClientApproachable (tileX, tileY)
2784{
2785 if (!view)
2786 { return true; }
2787 const groundId = groundTypeAt(view, tileX, tileY);
2788 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
2789 if (groundDef && !groundDef.passable)
2790 { return false; }
2791 const block = blockAt(view, tileX, tileY);
2792 if (block?.typeId != null)
2793 {
2794 const blockDef = BLOCK_DEFINITIONS[block.typeId];
2795 if (blockDef && !blockDef.passable)
2796 { return false; }
2797 }
2798 for (const entity of view.entitiesAtTile(tileX, tileY))
2799 {
2800 if (entity.entityId === view.localEntityId)
2801 { continue; }
2802 if (entity.untargetable || entity.freeFlight)
2803 { continue; }
2804 return false;
2805 }
2806 return true;
2807}
2808
2809function chebyshev (ax, ay, bx, by)
2810{
2811 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
2812}
2813
2814function updateAuthUi (authStatus)
2815{
2816 const signIn = document.getElementById("auth-sign-in");
2817 const signOut = document.getElementById("auth-sign-out");
2818 const exportLink = document.getElementById("auth-export");
2819 if (signIn)
2820 {
2821 signIn.hidden = !!authStatus?.authenticated;
2822 signIn.href = loginUrl("/");
2823 }
2824 if (signOut)
2825 {
2826 signOut.hidden = !authStatus?.authenticated;
2827 signOut.href = logoutUrl("/");
2828 }
2829 if (exportLink)
2830 { exportLink.hidden = !authStatus?.authenticated; }
2831 if (createCharacterOpen)
2832 { createCharacterOpen.hidden = !authStatus?.authenticated; }
2833 if (authStatus?.authenticated && !session)
2834 {
2835 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
2836 }
2837}