BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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