BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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