BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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