BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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