BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 73.8 KiB Download Raw
1import { MessageType, GAIT, CHUNK_SIZE, STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
3import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
4import { OVERWORLD_ID } from "/shared/world/dimensions.js";
5import { findPathToNearestGoal } from "/shared/navigation/bfs.js";
6import { GameSocket, defaultSocketUrl } from "../net/socket.js";
7import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
8import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
9import { WorldView } from "../render/worldView.js";
10import { initSocial } from "./social.js";
11import { initChat } from "./chat.js";
12import { initInventory } from "./inventory.js";
13import { initSkills } from "./skills.js";
14import { initSpells } from "./spells.js";
15import { initCrafting } from "./crafting.js";
16import { initAlchemy } from "./alchemy.js";
17import { initTipArrows } from "./tipArrows.js";
18import { initStamina } from "./stamina.js";
19import { initHealth } from "./health.js";
20import { initStatusEffects } from "./statusEffects.js";
21import { initContextMenu } from "./contextMenu.js";
22import { initDeath } from "./death.js";
23import { initToasts } from "./toasts.js";
24import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
25import { initQuests } from "./quests.js";
26import { initDialogue } from "./dialogue.js";
27import { initShop } from "./shop.js";
28import { initMarket } from "./market.js";
29import { initBounty } from "./bounty.js";
30import { initBarber } from "./barber.js";
31import { bindHairControls } from "./hairControls.js";
32import { bindCreateClothingControls } from "./createClothingControls.js";
33import { paintCharacterPreview } from "./characterPreview.js";
34import { initGraphicsSettings } from "./graphicsSettings.js";
35import { CraftingStationId } from "/shared/definitions/craftingStations.js";
36import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
37import { formatQuantity } from "/shared/items/formatQuantity.js";
38import { ItemId, itemDefinition } from "/shared/definitions/items.js";
39import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
40import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
41import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
42import { mobDefinition } from "/shared/definitions/mobs.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 }
931
932 if (pendingInteract.kind === "shear")
933 {
934 const target = view.entities.get(pendingInteract.targetEntityId);
935 if (!target)
936 {
937 clearPendingInteract();
938 return;
939 }
940 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
941 {
942 approachAdjacentTile(target.tileX, target.tileY);
943 return;
944 }
945 socket.send({
946 type: MessageType.shear,
947 targetEntityId: pendingInteract.targetEntityId
948 });
949 clearPendingInteract();
950 }
951}
952
953function requestPickup (ground)
954{
955 if (!ground)
956 { return; }
957 clearPendingInteract();
958 pendingPickup = {
959 groundItemId: ground.groundItemId,
960 tileX: ground.tileX,
961 tileY: ground.tileY
962 };
963 const local = view.entities.get(view.localEntityId);
964 if (local && local.tileX === ground.tileX && local.tileY === ground.tileY)
965 {
966 flushPendingPickup();
967 return;
968 }
969 sendPlayerMoveTo(ground.tileX, ground.tileY);
970}
971
972function flushPendingPickup ()
973{
974 if (!pendingPickup || !view)
975 { return; }
976 const item = view.groundItems.get(pendingPickup.groundItemId);
977 if (!item)
978 {
979 clearPendingPickup();
980 return;
981 }
982 const local = view.entities.get(view.localEntityId);
983 if (!local)
984 { return; }
985 if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY)
986 { return; }
987 socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId });
988 clearPendingPickup();
989}
990
991function requestAttack (targetEntityId)
992{
993 clearAllPendingActions();
994 setAutorunFocusEntity(targetEntityId);
995 socket.send({ type: MessageType.attack, targetEntityId });
996}
997
998function isAttackableEntity (entity)
999{
1000 if (!entity || entity.untargetable)
1001 { return false; }
1002 if (entity.canFight)
1003 { return true; }
1004 // Snapshots can omit canFight; mobs are still attackable via LMB.
1005 return !!entity.mobTypeId && !entity.talkable;
1006}
1007
1008function canTalkToEntity (entity)
1009{
1010 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
1011}
1012
1013function isApproachingCombatOrCast ()
1014{
1015 return autorunFocusEntityId != null || autorunFocusTile != null;
1016}
1017
1018function handleLeftClick (mouseX, mouseY)
1019{
1020 const tile = view.screenToTile(mouseX, mouseY);
1021 const armed = spells?.getArmedSpell?.();
1022 const approaching = isApproachingCombatOrCast();
1023
1024 // Entity-armed: cast only when a valid target is under the cursor. Empty ground
1025 // must fall through so walk cancels cast/attack approach (server moveTo clears it).
1026 if (armed?.target === "entity" && armed.canCast)
1027 {
1028 const snap = nearestSpellEntityAtCursor(mouseX, mouseY);
1029 if (snap && spells.tryCastAtEntity(snap.entityId))
1030 {
1031 setAutorunFocusEntity(snap.entityId);
1032 return;
1033 }
1034 }
1035 // Tile-armed while approaching: prefer walk-cancel over re-targeting the cast.
1036 else if (
1037 !approaching
1038 && armed?.target === "tile"
1039 && armed.canCast
1040 && spells.tryCastAtTile(tile.tileX, tile.tileY)
1041 )
1042 {
1043 setAutorunFocusTile(tile.tileX, tile.tileY);
1044 return;
1045 }
1046
1047 const entity = view.entityAtScreen(mouseX, mouseY);
1048 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
1049 {
1050 clearPendingPickup();
1051 if (entity.characterId)
1052 {
1053 clearPendingInteract();
1054 social.inspect(entity);
1055 return;
1056 }
1057 // Dialogue (or shop/talkable) wins over attack as the default click.
1058 if (canTalkToEntity(entity))
1059 {
1060 // Same intent as context-menu Talk / Shop so dialogue pin matches.
1061 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
1062 ? "talk"
1063 : (entity.hasShop ? "shop" : "talk");
1064 requestTalk(entity.entityId, purpose);
1065 return;
1066 }
1067 if (isAttackableEntity(entity))
1068 {
1069 requestAttack(entity.entityId);
1070 return;
1071 }
1072 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
1073 return;
1074 }
1075
1076 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
1077 if (ground)
1078 { requestPickup(ground); }
1079 else if (isBankTile(view, tile.tileX, tile.tileY))
1080 { requestOpenBank(tile.tileX, tile.tileY); }
1081 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
1082 { requestEnterDoorway(tile.tileX, tile.tileY); }
1083 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1084 { requestOpenMarket(tile.tileX, tile.tileY); }
1085 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1086 { requestOpenBounty(tile.tileX, tile.tileY); }
1087 else if (isBarberTile(view, tile.tileX, tile.tileY))
1088 { requestOpenBarber(tile.tileX, tile.tileY); }
1089 else if (isCauldronTile(view, tile.tileX, tile.tileY))
1090 { requestOpenCauldron(tile.tileX, tile.tileY); }
1091 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
1092 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
1093 else if (isOvenTile(view, tile.tileX, tile.tileY))
1094 { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); }
1095 else if (isCampfireTile(view, tile.tileX, tile.tileY))
1096 { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); }
1097 else if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1098 { requestFish(tile.tileX, tile.tileY); }
1099 else if (isAnvilTile(view, tile.tileX, tile.tileY))
1100 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
1101 else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1102 { requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }
1103 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1104 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
1105 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1106 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
1107 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1108 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
1109 else if (isLoomTile(view, tile.tileX, tile.tileY))
1110 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
1111 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1112 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
1113 else if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1114 { requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY); }
1115 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1116 { requestMine(tile.tileX, tile.tileY); }
1117 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1118 { requestChop(tile.tileX, tile.tileY); }
1119 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1120 { requestPick(tile.tileX, tile.tileY); }
1121 else
1122 {
1123 clearAllPendingActions();
1124 sendPlayerMoveTo(tile.tileX, tile.tileY);
1125 }
1126}
1127
1128function handleRightClick (event, mouseX, mouseY)
1129{
1130 event.preventDefault();
1131 if (spells?.isTargeting?.())
1132 {
1133 spells.cancelTargeting();
1134 view?.clearSpellTargetHighlight();
1135 return;
1136 }
1137 const tile = view.screenToTile(mouseX, mouseY);
1138 const items = [];
1139 const walkTileX = tile.tileX;
1140 const walkTileY = tile.tileY;
1141
1142 items.push({
1143 label: "Walk here",
1144 onSelect: () =>
1145 {
1146 clearAllPendingActions();
1147 sendPlayerMoveTo(walkTileX, walkTileY);
1148 }
1149 });
1150
1151 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY))
1152 {
1153 if (entity.entityId === view.localEntityId)
1154 { continue; }
1155 const targetName = entityLabel(entity);
1156 items.push({
1157 label: `Follow ${targetName}`,
1158 onSelect: () =>
1159 {
1160 clearAllPendingActions();
1161 sendPlayerFollow(entity.entityId);
1162 }
1163 });
1164 if (entity.untargetable)
1165 { continue; }
1166 if (entity.hasShop)
1167 {
1168 items.push({
1169 label: `Shop ${targetName}`,
1170 onSelect: () => requestTalk(entity.entityId, "shop")
1171 });
1172 }
1173 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
1174 {
1175 items.push({
1176 label: `Talk to ${targetName}`,
1177 onSelect: () => requestTalk(entity.entityId, "talk")
1178 });
1179 }
1180 if (entityCanShear(entity))
1181 {
1182 items.push({
1183 label: `Shear ${targetName}`,
1184 onSelect: () => requestShear(entity.entityId)
1185 });
1186 }
1187 if (entity.characterId)
1188 {
1189 items.push({
1190 label: `${targetName} info`,
1191 onSelect: () =>
1192 {
1193 clearAllPendingActions();
1194 social.inspect(entity);
1195 }
1196 });
1197 }
1198 items.push({
1199 label: `Attack ${targetName}`,
1200 onSelect: () => requestAttack(entity.entityId)
1201 });
1202 }
1203
1204 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1205 {
1206 const name = groundLabel(ground);
1207 items.push({
1208 label: `Pick up ${name}`,
1209 onSelect: () => requestPickup(ground)
1210 });
1211 if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
1212 {
1213 items.push({
1214 label: `Start Fire`,
1215 onSelect: () => requestStartFire(ground)
1216 });
1217 }
1218 }
1219
1220 if (isBankTile(view, tile.tileX, tile.tileY))
1221 {
1222 items.push({
1223 label: "Bank",
1224 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
1225 });
1226 items.push({
1227 label: "Get Blank Cheques",
1228 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
1229 });
1230 }
1231
1232 if (isDoorwayTile(view, tile.tileX, tile.tileY))
1233 {
1234 items.push({
1235 label: "Enter",
1236 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
1237 });
1238 }
1239
1240 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1241 {
1242 items.push({
1243 label: "Central Exchange",
1244 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
1245 });
1246 }
1247
1248 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1249 {
1250 items.push({
1251 label: "Bounty Office",
1252 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
1253 });
1254 }
1255
1256 if (isBarberTile(view, tile.tileX, tile.tileY))
1257 {
1258 items.push({
1259 label: "Barber",
1260 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
1261 });
1262 }
1263
1264 if (isCauldronTile(view, tile.tileX, tile.tileY))
1265 {
1266 items.push({
1267 label: "Alchemy",
1268 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
1269 });
1270 }
1271
1272 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1273 {
1274 items.push({
1275 label: "Smelt",
1276 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
1277 });
1278 }
1279
1280 if (isOvenTile(view, tile.tileX, tile.tileY))
1281 {
1282 items.push({
1283 label: "Cook",
1284 onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
1285 });
1286 }
1287
1288 if (isCampfireTile(view, tile.tileX, tile.tileY))
1289 {
1290 items.push({
1291 label: "Cook",
1292 onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
1293 });
1294 }
1295
1296 if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1297 {
1298 items.push({
1299 label: "Fish",
1300 onSelect: () => requestFish(tile.tileX, tile.tileY)
1301 });
1302 }
1303
1304 if (isAnvilTile(view, tile.tileX, tile.tileY))
1305 {
1306 items.push({
1307 label: "Smith",
1308 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
1309 });
1310 }
1311
1312 if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1313 {
1314 items.push({
1315 label: "Jewel",
1316 onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1317 });
1318 }
1319
1320 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1321 {
1322 items.push({
1323 label: "Woodwork",
1324 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
1325 });
1326 }
1327
1328 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1329 {
1330 items.push({
1331 label: "Craft",
1332 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
1333 });
1334 }
1335
1336 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1337 {
1338 items.push({
1339 label: "Spin",
1340 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
1341 });
1342 }
1343
1344 if (isLoomTile(view, tile.tileX, tile.tileY))
1345 {
1346 items.push({
1347 label: "Weave",
1348 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
1349 });
1350 }
1351
1352 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1353 {
1354 items.push({
1355 label: "Tailor",
1356 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
1357 });
1358 }
1359
1360 if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1361 {
1362 items.push({
1363 label: "Leatherwork",
1364 onSelect: () => requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY)
1365 });
1366 }
1367
1368 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1369 {
1370 items.push({
1371 label: "Mine",
1372 onSelect: () => requestMine(tile.tileX, tile.tileY)
1373 });
1374 }
1375
1376 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1377 {
1378 items.push({
1379 label: "Chop",
1380 onSelect: () => requestChop(tile.tileX, tile.tileY)
1381 });
1382 }
1383
1384 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1385 {
1386 items.push({
1387 label: "Pick",
1388 onSelect: () => requestPick(tile.tileX, tile.tileY)
1389 });
1390 }
1391
1392 contextMenu.show(event.clientX, event.clientY, items);
1393}
1394
1395function entityLabel (entity)
1396{
1397 const first = (entity?.firstName ?? "").trim();
1398 const last = (entity?.lastName ?? "").trim();
1399 const name = first && last ? `${first} ${last}` : (first || "target");
1400 const level = entity?.level | 0;
1401 if (entity?.mobTypeId && level > 0)
1402 { return `Lv.${level} ${name}`; }
1403 return name;
1404}
1405
1406function groundLabel (ground)
1407{
1408 const name = (ground?.displayName ?? "").trim() || "item";
1409 const qty = ground?.quantity ?? 1;
1410 if (qty <= 1)
1411 { return name; }
1412 return `${name} (${formatQuantity(qty)})`;
1413}
1414
1415function startPlay (payload)
1416{
1417 playing = true;
1418 overlay.hidden = true;
1419 hud.hidden = false;
1420 const settingsToggle = document.getElementById("settings-toggle");
1421 if (settingsToggle)
1422 { settingsToggle.hidden = false; }
1423 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
1424 gait = payload.gait ?? GAIT.walk;
1425 document.getElementById("gait").textContent = gait;
1426 staminaUi?.show();
1427 healthUi?.show();
1428 statusEffectsUi?.show();
1429 if (payload.stamina != null)
1430 { staminaUi?.apply(payload.stamina); }
1431 if (payload.health != null || payload.maxHealth != null)
1432 {
1433 healthUi?.apply({
1434 current: payload.health ?? healthUi.getCurrent?.(),
1435 max: payload.maxHealth ?? healthUi.getMax?.()
1436 });
1437 }
1438 if (!scene)
1439 {
1440 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1441 game.loadScene(scene);
1442 useNearestNeighbour(scene, game.images);
1443 }
1444 if (!view)
1445 {
1446 view = new WorldView(game, scene, catalog);
1447 graphicsSettingsUi?.apply();
1448 const ticker = new GameObject(0, 0, null, 10);
1449 ticker.update = (dt) =>
1450 {
1451 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
1452 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
1453 if (!leftPressed && !leftHeld)
1454 { leftClickConsumed = false; }
1455 else if (!leftClickConsumed && playing && !uiBlocked())
1456 {
1457 leftClickConsumed = true;
1458 const canvas = scene.canvas;
1459 const rect = canvas.getBoundingClientRect();
1460 const mouseX = GameInput.mousePosition.x - rect.left;
1461 const mouseY = GameInput.mousePosition.y - rect.top;
1462 handleLeftClick(mouseX, mouseY);
1463 }
1464 if (GameInput.isPressed(82) && !uiBlocked())
1465 {
1466 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
1467 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
1468 { return; }
1469 socket.send({ type: MessageType.setGait, gait: next });
1470 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
1471 if (next === GAIT.walk)
1472 {
1473 gait = next;
1474 document.getElementById("gait").textContent = gait;
1475 }
1476 }
1477 if (playing && !death?.isBlocking())
1478 {
1479 flushPendingPickup();
1480 flushPendingInteract();
1481 syncAutorun();
1482 social?.updateNametag(view, scene, view.localEntityId);
1483 chat?.update(view, scene);
1484 updateSpellTargetHighlight();
1485 updateWorldTooltip();
1486 }
1487 else
1488 {
1489 hideWorldTooltip();
1490 view?.clearSpellTargetHighlight();
1491 }
1492 view.update(dt);
1493 };
1494 scene.addObject(ticker);
1495 window.addEventListener("resize", () =>
1496 {
1497 scene.size.x = window.innerWidth;
1498 scene.size.y = window.innerHeight;
1499 scene.g_fixSize();
1500 useNearestNeighbour(scene, game.images);
1501 });
1502 window.addEventListener("wheel", (event) =>
1503 {
1504 if (!playing || uiBlocked())
1505 { return; }
1506 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
1507 if (playZoomRaf)
1508 { return; }
1509 playZoomRaf = requestAnimationFrame(() =>
1510 {
1511 playZoomRaf = 0;
1512 if (!view || !playZoomDelta)
1513 { return; }
1514 view.setZoom(view.zoom + playZoomDelta);
1515 playZoomDelta = 0;
1516 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
1517 });
1518 }, { passive: true });
1519 scene.canvas.addEventListener("contextmenu", (event) =>
1520 {
1521 if (!playing || uiBlocked())
1522 { return; }
1523 const rect = scene.canvas.getBoundingClientRect();
1524 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
1525 });
1526 }
1527 view.setSettings(payload.settings ?? view.settings);
1528 chat?.syncSettings();
1529 view.worldHour = payload.worldTime?.hour ?? 12;
1530 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
1531 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
1532 view.setWorldSeason(payload.worldTime?.season);
1533 view.setLocalEntity(
1534 payload.entityId,
1535 payload.tileX,
1536 payload.tileY,
1537 payload.gait,
1538 payload.sex,
1539 payload.firstName,
1540 payload.lastName,
1541 payload.characterId,
1542 payload.layers,
1543 payload.health,
1544 payload.maxHealth,
1545 payload.skullValue
1546 );
1547 social?.setLocalIdentity?.({
1548 accountId: payload.accountId,
1549 characterId: payload.characterId
1550 });
1551 graphicsSettingsUi?.apply();
1552}
1553
1554async function main ()
1555{
1556 const authStatus = await fetchAuthStatus();
1557 updateAuthUi(authStatus);
1558 if (!authStatus.authenticated)
1559 {
1560 statusEl.textContent = "Sign in to play Questward.";
1561 showError("");
1562 return;
1563 }
1564
1565 setAssetLoading(true, { phase: "Loading catalog…" });
1566 catalog = await loadSpriteCatalog();
1567 const assetTotal = playImagesFromCatalog(catalog).length;
1568 setAssetLoading(true, { loaded: 0, total: assetTotal, phase: "Loading assets…" });
1569 await preloadCatalogImages(game, catalog, {
1570 onProgress ({ loaded, total })
1571 {
1572 setAssetLoading(true, { loaded, total });
1573 }
1574 });
1575 applySpriteSheets(game.images, catalog);
1576 if (!scene)
1577 {
1578 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1579 game.loadScene(scene);
1580 }
1581 setAssetLoading(false);
1582 statusEl.textContent = "Connecting…";
1583 createHairControls = bindHairControls({
1584 root: document.getElementById("create-hair"),
1585 resolveSpriteUrl (name)
1586 {
1587 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1588 },
1589 getSex: () => document.getElementById("sex")?.value ?? "male",
1590 getBag: () => null,
1591 hideHeadgear: true,
1592 onChange ()
1593 {
1594 if (createActiveTab === "clothing")
1595 { void refreshCreateClothingPreview(); }
1596 }
1597 });
1598 createClothingControls = bindCreateClothingControls({
1599 root: document.getElementById("create-clothing"),
1600 onChange ()
1601 {
1602 if (createActiveTab === "clothing")
1603 { void refreshCreateClothingPreview(); }
1604 }
1605 });
1606 initCreateTabs();
1607 document.getElementById("sex")?.addEventListener("change", () =>
1608 {
1609 createHairControls?.fillStyles();
1610 void createHairControls?.refreshPreview();
1611 if (createActiveTab === "clothing")
1612 { void refreshCreateClothingPreview(); }
1613 });
1614 void createHairControls?.refreshPreview();
1615 void refreshCreateClothingPreview();
1616 graphicsSettingsUi = initGraphicsSettings({
1617 onChange: applyGraphicsSettings,
1618 onSuppressWorldClick: consumeWorldClick
1619 });
1620 social = initSocial({
1621 socket: { send (payload) { socket.send(payload); } },
1622 MessageType,
1623 resolveSpriteUrl (name)
1624 {
1625 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1626 },
1627 resolveImage (name)
1628 {
1629 return game?.images?.[name] ?? null;
1630 }
1631 });
1632 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1633 const tipArrows = initTipArrows({
1634 socket: { send (payload) { socket.send(payload); } },
1635 MessageType,
1636 getInventoryBag ()
1637 {
1638 return inventory?.getBag?.() ?? null;
1639 }
1640 });
1641 inventory = initInventory({
1642 socket: { send (payload) { socket.send(payload); } },
1643 MessageType,
1644 contextMenu,
1645 tipArrows,
1646 resolveSpriteUrl (name)
1647 {
1648 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1649 },
1650 resolveImage (name)
1651 {
1652 return game?.images?.[name] ?? null;
1653 },
1654 getFriends ()
1655 {
1656 return social?.getFriends?.() ?? [];
1657 },
1658 getLocalName ()
1659 {
1660 const you = document.getElementById("you")?.textContent ?? "";
1661 return you.split("(")[0].trim() || "Unknown";
1662 },
1663 getSoftClaims ()
1664 {
1665 return alchemy?.listSoftClaims?.() ?? [];
1666 },
1667 knowsSpell (spellId)
1668 {
1669 return !!spells?.knowsSpell?.(spellId);
1670 }
1671 });
1672 skills = initSkills({
1673 getEquipmentSlots ()
1674 {
1675 return inventory?.getEquipment?.() ?? {};
1676 },
1677 getSettings ()
1678 {
1679 return view?.settings ?? null;
1680 }
1681 });
1682 spells = initSpells({
1683 socket: { send (payload) { socket.send(payload); } },
1684 MessageType,
1685 getSkillLevel (skillId)
1686 {
1687 return skills?.skillLevel?.(skillId) ?? 1;
1688 }
1689 });
1690 crafting = initCrafting({
1691 socket: { send (payload) { socket.send(payload); } },
1692 MessageType,
1693 getInventorySlots ()
1694 {
1695 return inventory?.getInventorySlots?.() ?? [];
1696 },
1697 getSkillLevel (skillId)
1698 {
1699 return skills?.skillLevel?.(skillId) ?? 1;
1700 }
1701 });
1702 alchemy = initAlchemy({
1703 socket: { send (payload) { socket.send(payload); } },
1704 MessageType,
1705 getInventorySlots ()
1706 {
1707 return inventory?.getInventorySlots?.() ?? [];
1708 }
1709 });
1710 alchemy?.setOnSoftClaimsChanged?.(() => inventory?.refreshBagDisplay?.());
1711 staminaUi = initStamina();
1712 healthUi = initHealth();
1713 statusEffectsUi = initStatusEffects();
1714 toasts = initToasts();
1715 questsUi = initQuests({
1716 socket: { send (payload) { socket.send(payload); } },
1717 MessageType,
1718 toasts
1719 });
1720 dialogueUi = initDialogue({
1721 socket: { send (payload) { socket.send(payload); } },
1722 MessageType,
1723 getEntity (id)
1724 {
1725 if (id === "local")
1726 { return view?.entities.get(view.localEntityId) ?? null; }
1727 return view?.entities.get(id) ?? null;
1728 },
1729 captureSpeakerIcon (entityId, size = 64)
1730 {
1731 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1732 }
1733 });
1734 shop = initShop({
1735 socket: { send (payload) { socket.send(payload); } },
1736 MessageType,
1737 onSuppressWorldClick: consumeWorldClick,
1738 getCoinCount ()
1739 {
1740 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1741 },
1742 getInventorySlots ()
1743 {
1744 return inventory?.getInventorySlots?.() ?? [];
1745 }
1746 });
1747 market = initMarket({
1748 socket: { send (payload) { socket.send(payload); } },
1749 MessageType,
1750 onSuppressWorldClick: consumeWorldClick,
1751 getCoinCount ()
1752 {
1753 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1754 },
1755 getInventorySlots ()
1756 {
1757 return inventory?.getInventorySlots?.() ?? [];
1758 },
1759 getLocalCharacterId ()
1760 {
1761 return inventory?.getLocalCharacterId?.() ?? null;
1762 }
1763 });
1764 bounty = initBounty({
1765 socket: { send (payload) { socket.send(payload); } },
1766 MessageType,
1767 onSuppressWorldClick: consumeWorldClick,
1768 resolveSpriteUrl (name)
1769 {
1770 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1771 },
1772 resolveImage (name)
1773 {
1774 return game?.images?.[name] ?? null;
1775 }
1776 });
1777 barber = initBarber({
1778 socket: { send (payload) { socket.send(payload); } },
1779 MessageType,
1780 onSuppressWorldClick: consumeWorldClick,
1781 resolveSpriteUrl (name)
1782 {
1783 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1784 },
1785 getInventoryBag ()
1786 {
1787 return {
1788 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1789 inventory: inventory?.getInventorySlots?.() ?? []
1790 };
1791 }
1792 });
1793 chat = initChat({
1794 socket: { send (payload) { socket.send(payload); } },
1795 MessageType,
1796 getSettings: () => view?.settings
1797 });
1798 death = initDeath({
1799 socket: { send (payload) { socket.send(payload); } },
1800 MessageType
1801 });
1802 game.startGame();
1803 useNearestNeighbour(scene, game.images);
1804
1805 socket = new GameSocket(defaultSocketUrl(), (message) =>
1806 {
1807 switch (message.type)
1808 {
1809 case MessageType.session:
1810 session = message;
1811 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1812 renderCharacters(message.characters);
1813 break;
1814 case MessageType.characterList:
1815 renderCharacters(message.characters);
1816 if (!playing)
1817 { overlay.hidden = false; }
1818 break;
1819 case MessageType.enterWorld:
1820 closeCreateModal();
1821 startPlay(message);
1822 inventory?.setLocalCharacterId(message.characterId);
1823 toasts?.applyRestartStatus?.(message.restartStatus);
1824 socket.send({ type: MessageType.requestQuests });
1825 break;
1826 case MessageType.chunkSnapshot:
1827 view?.applySnapshot(message);
1828 break;
1829 case MessageType.dimensionChanged:
1830 if (view)
1831 {
1832 view.setDimensionId(message.dimensionId);
1833 view.setDimensionModes(message.lightingMode, message.seasonMode);
1834 view.clearAllChunks();
1835 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1836 {
1837 view.moveEntity({
1838 entityId: view.localEntityId,
1839 tileX: message.tileX,
1840 tileY: message.tileY
1841 });
1842 }
1843 }
1844 closeOpenUiIfTooFar();
1845 break;
1846 case MessageType.chunkDelta:
1847 for (const tile of message.tiles ?? [])
1848 {
1849 view?.updateAuthoredTile(
1850 message.chunkX,
1851 message.chunkY,
1852 tile.localX,
1853 tile.localY,
1854 { ground: tile.ground, block: tile.block, light: tile.light }
1855 );
1856 }
1857 break;
1858 case MessageType.unsubscribeChunk:
1859 view?.removeChunk(message.chunkX, message.chunkY);
1860 break;
1861 case MessageType.entitySpawn:
1862 view?.spawnEntity(message);
1863 break;
1864 case MessageType.entityMove:
1865 view?.moveEntity(message);
1866 if (message.entityId === view?.localEntityId)
1867 {
1868 if (message.gait)
1869 {
1870 gait = message.gait;
1871 document.getElementById("gait").textContent = gait;
1872 }
1873 closeOpenUiIfTooFar();
1874 }
1875 else if (
1876 uiFocus?.entityId != null
1877 && message.entityId === uiFocus.entityId
1878 )
1879 { closeOpenUiIfTooFar(); }
1880 break;
1881 case MessageType.entityDespawn:
1882 if (message.entityId === autorunFocusEntityId)
1883 { clearAutorunFocus(); }
1884 view?.despawnEntity(message.entityId);
1885 break;
1886 case MessageType.entityAppearance:
1887 view?.setAppearance(message);
1888 break;
1889 case MessageType.entitySkull:
1890 view?.updateEntitySkull(message.entityId, message.skullValue);
1891 break;
1892 case MessageType.groundItemAppear:
1893 view?.upsertGroundItem(message);
1894 break;
1895 case MessageType.groundItemDespawn:
1896 view?.despawnGroundItem(message.groundItemId);
1897 break;
1898 case MessageType.inventory:
1899 inventory?.handleInventory(message);
1900 skills?.refresh?.();
1901 crafting?.refresh();
1902 alchemy?.refresh();
1903 shop?.refresh();
1904 market?.refresh();
1905 break;
1906 case MessageType.skills:
1907 skills?.render(message.skills);
1908 crafting?.refresh();
1909 spells?.refreshCastGates?.();
1910 break;
1911 case MessageType.spells:
1912 case MessageType.spellsUpdated:
1913 spells?.render(message);
1914 break;
1915 case MessageType.spellArmed:
1916 spells?.handleSpellArmed(message);
1917 break;
1918 case MessageType.spellDisarmed:
1919 spells?.handleSpellDisarmed();
1920 break;
1921 case MessageType.spellProjectile:
1922 view?.spawnSpellProjectileFx(message);
1923 if (message.casterId === view?.localEntityId)
1924 { clearAutorunFocus(); }
1925 break;
1926 case MessageType.spellFizzle:
1927 view?.spawnSpellFizzleFx(message);
1928 if (message.casterId === view?.localEntityId)
1929 {
1930 clearAutorunFocus();
1931 toasts?.show("Failed to cast spell");
1932 }
1933 break;
1934 case MessageType.spellCastFlash:
1935 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
1936 if (message.casterId === view?.localEntityId)
1937 { clearAutorunFocus(); }
1938 break;
1939 case MessageType.spellLightAppear:
1940 case MessageType.spellLightUpdate:
1941 view?.setSpellLight(message);
1942 break;
1943 case MessageType.spellLightRemove:
1944 view?.removeSpellLight(message);
1945 break;
1946 case MessageType.spellDarkAppear:
1947 case MessageType.spellDarkUpdate:
1948 view?.setSpellDark(message);
1949 break;
1950 case MessageType.spellDarkRemove:
1951 view?.removeSpellDark(message);
1952 break;
1953 case MessageType.stamina:
1954 staminaUi?.apply(message);
1955 if (message.gait)
1956 {
1957 gait = message.gait;
1958 document.getElementById("gait").textContent = gait;
1959 if (gait === GAIT.walk && (staminaUi?.getCurrent?.() ?? 0) <= 0)
1960 { autorunWaitingStamina = true; }
1961 }
1962 syncAutorun();
1963 break;
1964 case MessageType.statusEffects:
1965 view?.setLocalBlind(!!message.blind);
1966 statusEffectsUi?.apply(message);
1967 break;
1968 case MessageType.bankSnapshot:
1969 inventory?.handleBank(message);
1970 break;
1971 case MessageType.cauldronSnapshot:
1972 if (message.open === false && uiFocus?.kind === "cauldron")
1973 { clearUiFocus(); }
1974 alchemy?.handleSnapshot(message);
1975 break;
1976 case MessageType.pigeonDispatched:
1977 inventory?.handlePigeonDispatched(message);
1978 break;
1979 case MessageType.pigeonDelivered:
1980 inventory?.handlePigeonDelivered(message);
1981 break;
1982 case MessageType.characterSearchResult:
1983 inventory?.handleCharacterSearch(message);
1984 break;
1985 case MessageType.craftResult:
1986 crafting?.handleCraftResult(message);
1987 break;
1988 case MessageType.worldStatus:
1989 if (view)
1990 {
1991 view.setSettings(message.settings ?? view.settings);
1992 view.worldHour = message.worldTime?.hour ?? view.worldHour;
1993 view.setWorldSeason(message.worldTime?.season);
1994 chat?.syncSettings();
1995 }
1996 skills?.refresh?.();
1997 toasts?.applyRestartStatus?.(message.restartStatus);
1998 break;
1999 case MessageType.restartStatus:
2000 toasts?.applyRestartStatus?.(message.restartStatus);
2001 break;
2002 case MessageType.chatBubble:
2003 chat?.showBubble(message);
2004 break;
2005 case MessageType.friends:
2006 social?.handleFriends(message);
2007 break;
2008 case MessageType.combatSwing:
2009 view?.spawnCombatSwing(message);
2010 break;
2011 case MessageType.combatProjectile:
2012 view?.spawnPhysicalProjectileFx({
2013 ...message,
2014 sprite: "fx:projectile:arrow"
2015 });
2016 break;
2017 case MessageType.combatNoArrows:
2018 toasts?.show("Out of arrows!");
2019 break;
2020 case MessageType.gatherSwing:
2021 case MessageType.tileShove:
2022 view?.spawnGatherSwing(message);
2023 break;
2024 case MessageType.stationOpen:
2025 if (message.stationId)
2026 { crafting?.openStation(message.stationId); }
2027 break;
2028 case MessageType.shopOpen:
2029 if (message.npcEntityId != null)
2030 { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); }
2031 shop?.handleShopOpen(message);
2032 break;
2033 case MessageType.shopClosed:
2034 if (uiFocus?.kind === "shop")
2035 { clearUiFocus(); }
2036 shop?.handleShopClosed(message);
2037 break;
2038 case MessageType.marketOpen:
2039 market?.handleOpen(message);
2040 break;
2041 case MessageType.marketClosed:
2042 if (uiFocus?.kind === "market")
2043 { clearUiFocus(); }
2044 market?.handleClosed(message);
2045 break;
2046 case MessageType.marketTrade:
2047 market?.handleTrade(message);
2048 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
2049 break;
2050 case MessageType.bountySnapshot:
2051 bounty?.handleSnapshot(message);
2052 break;
2053 case MessageType.closeBounty:
2054 if (uiFocus?.kind === "bounty")
2055 { clearUiFocus(); }
2056 bounty?.handleClosed(message);
2057 break;
2058 case MessageType.characterBounty:
2059 bounty?.handleCharacterBounty(message);
2060 social?.handleCharacterBounty(message);
2061 break;
2062 case MessageType.barberSnapshot:
2063 barber?.handleSnapshot(message);
2064 break;
2065 case MessageType.closeBarber:
2066 if (uiFocus?.kind === "barber")
2067 { clearUiFocus(); }
2068 barber?.handleClosed(message);
2069 break;
2070 case MessageType.itemBubble:
2071 chat?.showItemBubble(message);
2072 break;
2073 case MessageType.gatherComplete:
2074 crafting?.refresh();
2075 break;
2076 case MessageType.combatHit:
2077 {
2078 const applyHit = () =>
2079 {
2080 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
2081 view?.flashDamage(message.targetId);
2082 view?.spawnCombatKnockback?.(message);
2083 view?.spawnDamageNumber(message.targetId, message.damage);
2084 if (message.targetId === view?.localEntityId)
2085 {
2086 healthUi?.apply({
2087 current: message.health,
2088 max: message.maxHealth
2089 });
2090 }
2091 };
2092 if (!view?.deferCombatHit?.(message, applyHit))
2093 { applyHit(); }
2094 break;
2095 }
2096 case MessageType.combatMiss:
2097 view?.spawnCombatDodge?.(message);
2098 view?.markProjectileMiss?.(message);
2099 break;
2100 case MessageType.combatBlock:
2101 {
2102 const applyBlock = () =>
2103 {
2104 view?.flashBlock?.(message.targetId);
2105 if (message.health != null)
2106 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
2107 };
2108 if (!view?.deferCombatHit?.(message, applyBlock))
2109 { applyBlock(); }
2110 break;
2111 }
2112 case MessageType.entityHealth:
2113 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2114 if (message.entityId === view?.localEntityId)
2115 {
2116 healthUi?.apply({
2117 current: message.health,
2118 max: message.maxHealth
2119 });
2120 }
2121 break;
2122 case MessageType.skillLevelUp:
2123 view?.spawnSkillLevelUp(message.entityId, message);
2124 if (message.entityId === view?.localEntityId)
2125 {
2126 const level = message.level | 0;
2127 const previousLevel = message.previousLevel == null
2128 ? Math.max(0, level - 1)
2129 : message.previousLevel | 0;
2130 const unlockCount = skillUnlockMessages(message.skillId, previousLevel, level).length;
2131 toasts?.show(skillLevelUpToastText(message.skillId, level, previousLevel), {
2132 durationMs: 3500 + unlockCount * 1600
2133 });
2134 }
2135 break;
2136 case MessageType.playerDied:
2137 clearAllPendingActions();
2138 clearAutorunFocus();
2139 contextMenu?.hide();
2140 spells?.handleSpellDisarmed?.();
2141 closeCloseablePlayUi();
2142 death?.show();
2143 if (message.entityId === view?.localEntityId)
2144 {
2145 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
2146 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
2147 }
2148 break;
2149 case MessageType.playerRespawned:
2150 death?.hide();
2151 // Drop deferred killing-blow health=0 that may still be queued on a projectile.
2152 view?.cancelDeferredCombatHits?.(message.entityId);
2153 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2154 if (message.skullValue != null)
2155 { view?.updateEntitySkull(message.entityId, message.skullValue); }
2156 if (message.entityId === view?.localEntityId)
2157 {
2158 healthUi?.apply({
2159 current: message.health,
2160 max: message.maxHealth
2161 });
2162 }
2163 if (message.stamina != null || message.maxStamina != null)
2164 {
2165 staminaUi?.apply({
2166 current: message.stamina ?? staminaUi.getCurrent?.(),
2167 max: message.maxStamina ?? staminaUi.getMax?.()
2168 });
2169 }
2170 break;
2171 case MessageType.error:
2172 if (playing)
2173 { toasts?.show(message.message); }
2174 else
2175 {
2176 const createPanel = document.getElementById("create-panel");
2177 const createError = document.getElementById("create-error");
2178 if (createPanel && !createPanel.hidden && createError)
2179 { createError.textContent = message.message ?? ""; }
2180 else
2181 { showError(message.message); }
2182 }
2183 social?.showError(message.message);
2184 break;
2185 case MessageType.toast:
2186 if (playing)
2187 { toasts?.show(message.message); }
2188 break;
2189 case MessageType.questsSnapshot:
2190 questsUi?.applySnapshot(message);
2191 break;
2192 case MessageType.questStepComplete:
2193 questsUi?.handleStepComplete(message);
2194 break;
2195 case MessageType.dialogueStep:
2196 if (message.npcEntityId != null)
2197 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2198 dialogueUi?.handleStep(message);
2199 break;
2200 case MessageType.dialogueChoices:
2201 if (message.npcEntityId != null)
2202 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2203 dialogueUi?.handleChoices(message);
2204 break;
2205 case MessageType.dialogueClose:
2206 if (uiFocus?.kind === "dialogue")
2207 { clearUiFocus(); }
2208 dialogueUi?.handleClose(message);
2209 break;
2210 case MessageType.forceLogout:
2211 returnToMenu(message.reason);
2212 break;
2213 }
2214 }, {
2215 onClose (event)
2216 {
2217 if (playing)
2218 { returnToMenu(event.reason || "Disconnected from server."); }
2219 }
2220 });
2221 await socket.connect();
2222 if (typeof window !== "undefined")
2223 {
2224 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
2225 {
2226 crafting?.openStation(stationId);
2227 };
2228 }
2229}
2230
2231function returnToMenu (reason = "")
2232{
2233 playing = false;
2234 followTargetId = null;
2235 moveDest = null;
2236 clearAutorunFocus();
2237 autorunWaitingStamina = false;
2238 clearAllPendingActions();
2239 clearUiFocus();
2240 social?.reset();
2241 chat?.reset();
2242 inventory?.reset();
2243 crafting?.reset();
2244 alchemy?.reset();
2245 staminaUi?.hide();
2246 healthUi?.hide();
2247 statusEffectsUi?.hide();
2248 skills?.hide();
2249 spells?.hide();
2250 contextMenu?.hide();
2251 death?.reset();
2252 shop?.close({ notifyServer: false });
2253 bounty?.close();
2254 barber?.close();
2255 questsUi?.reset();
2256 dialogueUi?.reset();
2257 hideWorldTooltip();
2258 if (view)
2259 { view.clearPlaySession(); }
2260 overlay.hidden = false;
2261 hud.hidden = true;
2262 const settingsToggle = document.getElementById("settings-toggle");
2263 if (settingsToggle)
2264 { settingsToggle.hidden = true; }
2265 graphicsSettingsUi?.close();
2266 if (reason)
2267 { statusEl.textContent = reason; }
2268}
2269
2270document.getElementById("create-character-open")?.addEventListener("click", () =>
2271{
2272 showError("");
2273 const createError = document.getElementById("create-error");
2274 if (createError)
2275 { createError.textContent = ""; }
2276 document.getElementById("create-backdrop").hidden = false;
2277 document.getElementById("create-panel").hidden = false;
2278 setCreateTab("appearance");
2279 void createHairControls?.refreshPreview();
2280});
2281
2282function closeCreateModal ()
2283{
2284 document.getElementById("create-backdrop").hidden = true;
2285 document.getElementById("create-panel").hidden = true;
2286}
2287
2288document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
2289document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
2290
2291document.getElementById("create-form").addEventListener("submit", (event) =>
2292{
2293 event.preventDefault();
2294 showError("");
2295 const createError = document.getElementById("create-error");
2296 if (createError)
2297 { createError.textContent = ""; }
2298 socket.send({
2299 type: MessageType.createCharacter,
2300 firstName: document.getElementById("first-name").value,
2301 lastName: document.getElementById("last-name").value,
2302 sex: document.getElementById("sex").value,
2303 hair: createHairControls?.currentHair?.() ?? null,
2304 clothing: createClothingControls?.currentClothing?.() ?? null
2305 });
2306});
2307
2308function initCreateTabs ()
2309{
2310 const tabs = document.querySelectorAll(".create-tab");
2311 for (const tab of tabs)
2312 {
2313 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
2314 }
2315 setCreateTab("appearance");
2316}
2317
2318function setCreateTab (name)
2319{
2320 createActiveTab = name === "clothing" ? "clothing" : "appearance";
2321 for (const tab of document.querySelectorAll(".create-tab"))
2322 {
2323 const on = tab.dataset.createTab === createActiveTab;
2324 tab.classList.toggle("active", on);
2325 tab.setAttribute("aria-selected", on ? "true" : "false");
2326 }
2327 for (const pane of document.querySelectorAll("[data-create-pane]"))
2328 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
2329 if (createActiveTab === "clothing")
2330 { void refreshCreateClothingPreview(); }
2331 else
2332 { void createHairControls?.refreshPreview(); }
2333}
2334
2335async function refreshCreateClothingPreview ()
2336{
2337 const canvas = document.getElementById("create-clothing-preview");
2338 if (!canvas || !createClothingControls)
2339 { return; }
2340 try
2341 {
2342 await paintCharacterPreview(canvas, {
2343 sex: document.getElementById("sex")?.value ?? "male",
2344 bag: createClothingControls.previewBag(),
2345 hair: createHairControls?.currentHair?.() ?? null,
2346 hideHeadgear: true,
2347 resolveSpriteUrl (name)
2348 {
2349 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2350 },
2351 scale: 4
2352 });
2353 }
2354 catch (error)
2355 { console.warn(error); }
2356}
2357
2358document.getElementById("leave").addEventListener("click", () =>
2359{
2360 socket.send({ type: MessageType.leaveWorld });
2361 returnToMenu();
2362});
2363
2364main().catch((error) =>
2365{
2366 showError(error.message);
2367 console.error(error);
2368});
2369
2370function isBankTile (view, tileX, tileY)
2371{
2372 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
2373}
2374
2375function isDoorwayTile (view, tileX, tileY)
2376{
2377 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
2378}
2379
2380function isMarketplaceTile (view, tileX, tileY)
2381{
2382 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
2383}
2384
2385function isBountyOfficeTile (view, tileX, tileY)
2386{
2387 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
2388}
2389
2390function isBarberTile (view, tileX, tileY)
2391{
2392 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
2393}
2394
2395function isCauldronTile (view, tileX, tileY)
2396{
2397 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2398}
2399
2400function isFurnaceTile (view, tileX, tileY)
2401{
2402 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2403}
2404
2405function isOvenTile (view, tileX, tileY)
2406{
2407 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2408}
2409
2410function isCampfireTile (view, tileX, tileY)
2411{
2412 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2413}
2414
2415function isFishingSpotTile (view, tileX, tileY)
2416{
2417 const block = blockAt(view, tileX, tileY);
2418 if (!block || block.typeId !== BlockType.fishingSpot)
2419 { return false; }
2420 return block.state !== "exhausted";
2421}
2422
2423function isAnvilTile (view, tileX, tileY)
2424{
2425 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2426}
2427
2428function isJeweleringStationTile (view, tileX, tileY)
2429{
2430 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2431}
2432
2433function isGroundWoodLog (ground)
2434{
2435 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2436 return def?.familyId === ItemFamilyId.log;
2437}
2438
2439function playerHasUsableTinderbox ()
2440{
2441 const slots = inventory?.getInventorySlots?.() ?? [];
2442 for (const slot of slots)
2443 {
2444 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2445 { continue; }
2446 const charges = slot.instance?.kind === "tinderbox"
2447 ? (slot.instance.charges | 0)
2448 : TINDERBOX_MAX_CHARGES;
2449 if (charges > 0)
2450 { return true; }
2451 }
2452 return false;
2453}
2454
2455function isWoodworkingBenchTile (view, tileX, tileY)
2456{
2457 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2458}
2459
2460function isCraftingBenchTile (view, tileX, tileY)
2461{
2462 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
2463}
2464
2465function isSpinningWheelTile (view, tileX, tileY)
2466{
2467 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
2468}
2469
2470function isLoomTile (view, tileX, tileY)
2471{
2472 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
2473}
2474
2475function isTailorBenchTile (view, tileX, tileY)
2476{
2477 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
2478}
2479
2480function isLeatherworkingTableTile (view, tileX, tileY)
2481{
2482 return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable;
2483}
2484
2485function isOreBoulderTile (view, tileX, tileY)
2486{
2487 const block = blockAt(view, tileX, tileY);
2488 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
2489}
2490
2491function isChopableTreeTile (view, tileX, tileY)
2492{
2493 return isChopableTreeBlock(blockAt(view, tileX, tileY));
2494}
2495
2496function isPickablePlantTile (view, tileX, tileY)
2497{
2498 return isPickablePlantBlock(blockAt(view, tileX, tileY));
2499}
2500
2501const SPELL_ENTITY_SNAP_TILES = 2;
2502
2503function updateSpellTargetHighlight ()
2504{
2505 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
2506 {
2507 view?.clearSpellTargetHighlight();
2508 return;
2509 }
2510 const canvas = scene?.canvas;
2511 if (!canvas)
2512 { return; }
2513 const rect = canvas.getBoundingClientRect();
2514 const mouseX = GameInput.mousePosition.x - rect.left;
2515 const mouseY = GameInput.mousePosition.y - rect.top;
2516 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2517 {
2518 view.clearSpellTargetHighlight();
2519 return;
2520 }
2521 const armed = spells.getArmedSpell?.();
2522 const local = view.entities.get(view.localEntityId);
2523 if (armed?.target === "entity")
2524 {
2525 const target = nearestSpellEntityAtCursor(mouseX, mouseY);
2526 if (!target)
2527 {
2528 view.clearSpellTargetHighlight();
2529 return;
2530 }
2531 const inRange = !local
2532 || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) <= COMBAT_RANGE_TILES;
2533 view.setSpellEntityTargetHighlight(target.entityId, inRange);
2534 return;
2535 }
2536 const tile = view.screenToTile(mouseX, mouseY);
2537 const inRange = !local
2538 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
2539 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
2540}
2541
2542/**
2543 * Nearest spell-targetable entity within {@link SPELL_ENTITY_SNAP_TILES} of the
2544 * cursor tile (uses both authoritative and visual tile for moving mobs).
2545 */
2546function nearestSpellEntityAtCursor (mouseX, mouseY)
2547{
2548 if (!view)
2549 { return null; }
2550 const cursor = view.screenToTile(mouseX, mouseY);
2551 const tileSize = view.tileSize();
2552 let best = null;
2553 let bestDist = Infinity;
2554 let bestScreen = Infinity;
2555 for (const entity of view.entities.values())
2556 {
2557 if (!isSpellEntityTarget(entity))
2558 { continue; }
2559 const visualTileX = Math.floor((entity.visualX + (entity.stackOffsetX ?? 0)) / tileSize);
2560 const visualTileY = Math.floor((entity.visualY + (entity.stackOffsetY ?? 0)) / tileSize);
2561 const dist = Math.min(
2562 chebyshev(cursor.tileX, cursor.tileY, entity.tileX, entity.tileY),
2563 chebyshev(cursor.tileX, cursor.tileY, visualTileX, visualTileY)
2564 );
2565 if (dist > SPELL_ENTITY_SNAP_TILES)
2566 { continue; }
2567 const box = view.nametagAnchor?.(entity);
2568 const screenDist = box
2569 ? Math.hypot(box.x - mouseX, box.y - mouseY)
2570 : dist;
2571 if (dist < bestDist || (dist === bestDist && screenDist < bestScreen))
2572 {
2573 best = entity;
2574 bestDist = dist;
2575 bestScreen = screenDist;
2576 }
2577 }
2578 return best;
2579}
2580
2581function isSpellEntityTarget (entity)
2582{
2583 if (!entity || entity.entityId === view?.localEntityId)
2584 { return false; }
2585 if (entity.untargetable || entity.freeFlight)
2586 { return false; }
2587 return isAttackableEntity(entity);
2588}
2589
2590function hideWorldTooltip ()
2591{
2592 if (worldTooltip)
2593 {
2594 worldTooltip.hidden = true;
2595 worldTooltip.classList.remove("friend-name");
2596 worldTooltip.style.color = "";
2597 }
2598}
2599
2600/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
2601function updateWorldTooltip ()
2602{
2603 if (!worldTooltip || !view || !scene || uiBlocked())
2604 {
2605 hideWorldTooltip();
2606 return;
2607 }
2608 const canvas = scene.canvas;
2609 const rect = canvas.getBoundingClientRect();
2610 const mouseX = GameInput.mousePosition.x - rect.left;
2611 const mouseY = GameInput.mousePosition.y - rect.top;
2612 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2613 {
2614 hideWorldTooltip();
2615 return;
2616 }
2617 const entity = view.entityAtScreen(mouseX, mouseY);
2618 if (entity && entity.entityId !== view.localEntityId)
2619 {
2620 const label = entityLabel(entity);
2621 worldTooltip.hidden = false;
2622 worldTooltip.textContent = label;
2623 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2624 worldTooltip.classList.toggle("friend-name", !!friend);
2625 worldTooltip.style.color = friend ? "#e8c84a" : "";
2626 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2627 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2628 return;
2629 }
2630 const tile = view.screenToTile(mouseX, mouseY);
2631 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
2632 if (!label)
2633 {
2634 hideWorldTooltip();
2635 return;
2636 }
2637 worldTooltip.hidden = false;
2638 worldTooltip.textContent = label;
2639 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2640 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2641}
2642
2643function blockTypeAt (view, tileX, tileY)
2644{
2645 return blockAt(view, tileX, tileY)?.typeId ?? null;
2646}
2647
2648function blockAt (view, tileX, tileY)
2649{
2650 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2651 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2652 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2653 if (!snapshot)
2654 { return null; }
2655 const localX = tileX - chunkX * CHUNK_SIZE;
2656 const localY = tileY - chunkY * CHUNK_SIZE;
2657 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
2658}
2659
2660function groundTypeAt (view, tileX, tileY)
2661{
2662 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2663 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2664 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2665 if (!snapshot)
2666 { return null; }
2667 const localX = tileX - chunkX * CHUNK_SIZE;
2668 const localY = tileY - chunkY * CHUNK_SIZE;
2669 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
2670}
2671
2672/** Best-effort client filter for approach destinations (server still authorizes paths). */
2673function isClientApproachable (tileX, tileY)
2674{
2675 if (!view)
2676 { return true; }
2677 const groundId = groundTypeAt(view, tileX, tileY);
2678 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
2679 if (groundDef && !groundDef.passable)
2680 { return false; }
2681 const block = blockAt(view, tileX, tileY);
2682 if (block?.typeId != null)
2683 {
2684 const blockDef = BLOCK_DEFINITIONS[block.typeId];
2685 if (blockDef && !blockDef.passable)
2686 { return false; }
2687 }
2688 for (const entity of view.entitiesAtTile(tileX, tileY))
2689 {
2690 if (entity.entityId === view.localEntityId)
2691 { continue; }
2692 if (entity.untargetable || entity.freeFlight)
2693 { continue; }
2694 return false;
2695 }
2696 return true;
2697}
2698
2699function chebyshev (ax, ay, bx, by)
2700{
2701 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
2702}
2703
2704function updateAuthUi (authStatus)
2705{
2706 const signIn = document.getElementById("auth-sign-in");
2707 const signOut = document.getElementById("auth-sign-out");
2708 const exportLink = document.getElementById("auth-export");
2709 if (signIn)
2710 {
2711 signIn.hidden = !!authStatus?.authenticated;
2712 signIn.href = loginUrl("/");
2713 }
2714 if (signOut)
2715 {
2716 signOut.hidden = !authStatus?.authenticated;
2717 signOut.href = logoutUrl("/");
2718 }
2719 if (exportLink)
2720 { exportLink.hidden = !authStatus?.authenticated; }
2721 if (authStatus?.authenticated && !session)
2722 {
2723 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
2724 }
2725}