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 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))
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 const first = (entity?.firstName ?? "").trim();
1399 const last = (entity?.lastName ?? "").trim();
1400 const name = first && last ? `${first} ${last}` : (first || "target");
1401 const level = entity?.level | 0;
1402 if (entity?.mobTypeId && level > 0)
1403 { return `Lv.${level} ${name}`; }
1404 return name;
1405}
1406
1407function groundLabel (ground)
1408{
1409 const name = (ground?.displayName ?? "").trim() || "item";
1410 const qty = ground?.quantity ?? 1;
1411 if (qty <= 1)
1412 { return name; }
1413 return `${name} (${formatQuantity(qty)})`;
1414}
1415
1416function startPlay (payload)
1417{
1418 playing = true;
1419 overlay.hidden = true;
1420 hud.hidden = false;
1421 const settingsToggle = document.getElementById("settings-toggle");
1422 if (settingsToggle)
1423 { settingsToggle.hidden = false; }
1424 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
1425 gait = payload.gait ?? GAIT.walk;
1426 document.getElementById("gait").textContent = gait;
1427 staminaUi?.show();
1428 healthUi?.show();
1429 statusEffectsUi?.show();
1430 if (payload.stamina != null)
1431 { staminaUi?.apply(payload.stamina); }
1432 if (payload.health != null || payload.maxHealth != null)
1433 {
1434 healthUi?.apply({
1435 current: payload.health ?? healthUi.getCurrent?.(),
1436 max: payload.maxHealth ?? healthUi.getMax?.()
1437 });
1438 }
1439 if (!scene)
1440 {
1441 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1442 game.loadScene(scene);
1443 useNearestNeighbour(scene, game.images);
1444 }
1445 if (!view)
1446 {
1447 view = new WorldView(game, scene, catalog);
1448 graphicsSettingsUi?.apply();
1449 const ticker = new GameObject(0, 0, null, 10);
1450 ticker.update = (dt) =>
1451 {
1452 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
1453 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
1454 if (!leftPressed && !leftHeld)
1455 { leftClickConsumed = false; }
1456 else if (!leftClickConsumed && playing && !uiBlocked())
1457 {
1458 leftClickConsumed = true;
1459 const canvas = scene.canvas;
1460 const rect = canvas.getBoundingClientRect();
1461 const mouseX = GameInput.mousePosition.x - rect.left;
1462 const mouseY = GameInput.mousePosition.y - rect.top;
1463 handleLeftClick(mouseX, mouseY);
1464 }
1465 if (GameInput.isPressed(82) && !uiBlocked())
1466 {
1467 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
1468 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
1469 { return; }
1470 socket.send({ type: MessageType.setGait, gait: next });
1471 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
1472 if (next === GAIT.walk)
1473 {
1474 gait = next;
1475 document.getElementById("gait").textContent = gait;
1476 }
1477 }
1478 if (playing && !death?.isBlocking())
1479 {
1480 flushPendingPickup();
1481 flushPendingInteract();
1482 syncAutorun();
1483 social?.updateNametag(view, scene, view.localEntityId);
1484 chat?.update(view, scene);
1485 updateSpellTargetHighlight();
1486 updateWorldTooltip();
1487 }
1488 else
1489 {
1490 hideWorldTooltip();
1491 view?.clearSpellTargetHighlight();
1492 }
1493 view.update(dt);
1494 };
1495 scene.addObject(ticker);
1496 window.addEventListener("resize", () =>
1497 {
1498 scene.size.x = window.innerWidth;
1499 scene.size.y = window.innerHeight;
1500 scene.g_fixSize();
1501 useNearestNeighbour(scene, game.images);
1502 });
1503 window.addEventListener("wheel", (event) =>
1504 {
1505 if (!playing || uiBlocked())
1506 { return; }
1507 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
1508 if (playZoomRaf)
1509 { return; }
1510 playZoomRaf = requestAnimationFrame(() =>
1511 {
1512 playZoomRaf = 0;
1513 if (!view || !playZoomDelta)
1514 { return; }
1515 view.setZoom(view.zoom + playZoomDelta);
1516 playZoomDelta = 0;
1517 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
1518 });
1519 }, { passive: true });
1520 scene.canvas.addEventListener("contextmenu", (event) =>
1521 {
1522 if (!playing || uiBlocked())
1523 { return; }
1524 const rect = scene.canvas.getBoundingClientRect();
1525 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
1526 });
1527 }
1528 view.setSettings(payload.settings ?? view.settings);
1529 chat?.syncSettings();
1530 view.worldHour = payload.worldTime?.hour ?? 12;
1531 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
1532 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
1533 view.setWorldSeason(payload.worldTime?.season);
1534 view.setLocalEntity(
1535 payload.entityId,
1536 payload.tileX,
1537 payload.tileY,
1538 payload.gait,
1539 payload.sex,
1540 payload.firstName,
1541 payload.lastName,
1542 payload.characterId,
1543 payload.layers,
1544 payload.health,
1545 payload.maxHealth,
1546 payload.skullValue
1547 );
1548 social?.setLocalIdentity?.({
1549 accountId: payload.accountId,
1550 characterId: payload.characterId
1551 });
1552 graphicsSettingsUi?.apply();
1553}
1554
1555async function main ()
1556{
1557 const authStatus = await fetchAuthStatus();
1558 updateAuthUi(authStatus);
1559 if (!authStatus.authenticated)
1560 {
1561 statusEl.textContent = "Sign in to play Questward.";
1562 showError("");
1563 return;
1564 }
1565
1566 setAssetLoading(true, { phase: "Loading catalog…" });
1567 catalog = await loadSpriteCatalog();
1568 const assetTotal = playImagesFromCatalog(catalog).length;
1569 setAssetLoading(true, { loaded: 0, total: assetTotal, phase: "Loading assets…" });
1570 await preloadCatalogImages(game, catalog, {
1571 onProgress ({ loaded, total })
1572 {
1573 setAssetLoading(true, { loaded, total });
1574 }
1575 });
1576 applySpriteSheets(game.images, catalog);
1577 if (!scene)
1578 {
1579 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1580 game.loadScene(scene);
1581 }
1582 setAssetLoading(false);
1583 statusEl.textContent = "Connecting…";
1584 createHairControls = bindHairControls({
1585 root: document.getElementById("create-hair"),
1586 resolveSpriteUrl (name)
1587 {
1588 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1589 },
1590 getSex: () => document.getElementById("sex")?.value ?? "male",
1591 getBag: () => null,
1592 hideHeadgear: true,
1593 onChange ()
1594 {
1595 if (createActiveTab === "clothing")
1596 { void refreshCreateClothingPreview(); }
1597 }
1598 });
1599 createClothingControls = bindCreateClothingControls({
1600 root: document.getElementById("create-clothing"),
1601 onChange ()
1602 {
1603 if (createActiveTab === "clothing")
1604 { void refreshCreateClothingPreview(); }
1605 }
1606 });
1607 initCreateTabs();
1608 document.getElementById("sex")?.addEventListener("change", () =>
1609 {
1610 createHairControls?.fillStyles();
1611 void createHairControls?.refreshPreview();
1612 if (createActiveTab === "clothing")
1613 { void refreshCreateClothingPreview(); }
1614 });
1615 void createHairControls?.refreshPreview();
1616 void refreshCreateClothingPreview();
1617 graphicsSettingsUi = initGraphicsSettings({
1618 onChange: applyGraphicsSettings,
1619 onSuppressWorldClick: consumeWorldClick
1620 });
1621 social = initSocial({
1622 socket: { send (payload) { socket.send(payload); } },
1623 MessageType,
1624 resolveSpriteUrl (name)
1625 {
1626 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1627 },
1628 resolveImage (name)
1629 {
1630 return game?.images?.[name] ?? null;
1631 }
1632 });
1633 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1634 const tipArrows = initTipArrows({
1635 socket: { send (payload) { socket.send(payload); } },
1636 MessageType,
1637 getInventoryBag ()
1638 {
1639 return inventory?.getBag?.() ?? null;
1640 }
1641 });
1642 inventory = initInventory({
1643 socket: { send (payload) { socket.send(payload); } },
1644 MessageType,
1645 contextMenu,
1646 tipArrows,
1647 resolveSpriteUrl (name)
1648 {
1649 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1650 },
1651 resolveImage (name)
1652 {
1653 return game?.images?.[name] ?? null;
1654 },
1655 getFriends ()
1656 {
1657 return social?.getFriends?.() ?? [];
1658 },
1659 getLocalName ()
1660 {
1661 const you = document.getElementById("you")?.textContent ?? "";
1662 return you.split("(")[0].trim() || "Unknown";
1663 },
1664 getSoftClaims ()
1665 {
1666 return alchemy?.listSoftClaims?.() ?? [];
1667 },
1668 knowsSpell (spellId)
1669 {
1670 return !!spells?.knowsSpell?.(spellId);
1671 }
1672 });
1673 skills = initSkills({
1674 getEquipmentSlots ()
1675 {
1676 return inventory?.getEquipment?.() ?? {};
1677 },
1678 getSettings ()
1679 {
1680 return view?.settings ?? null;
1681 }
1682 });
1683 spells = initSpells({
1684 socket: { send (payload) { socket.send(payload); } },
1685 MessageType,
1686 getSkillLevel (skillId)
1687 {
1688 return skills?.skillLevel?.(skillId) ?? 1;
1689 }
1690 });
1691 crafting = initCrafting({
1692 socket: { send (payload) { socket.send(payload); } },
1693 MessageType,
1694 getInventorySlots ()
1695 {
1696 return inventory?.getInventorySlots?.() ?? [];
1697 },
1698 getSkillLevel (skillId)
1699 {
1700 return skills?.skillLevel?.(skillId) ?? 1;
1701 }
1702 });
1703 alchemy = initAlchemy({
1704 socket: { send (payload) { socket.send(payload); } },
1705 MessageType,
1706 getInventorySlots ()
1707 {
1708 return inventory?.getInventorySlots?.() ?? [];
1709 }
1710 });
1711 alchemy?.setOnSoftClaimsChanged?.(() => inventory?.refreshBagDisplay?.());
1712 staminaUi = initStamina();
1713 healthUi = initHealth();
1714 statusEffectsUi = initStatusEffects();
1715 toasts = initToasts();
1716 questsUi = initQuests({
1717 socket: { send (payload) { socket.send(payload); } },
1718 MessageType,
1719 toasts
1720 });
1721 dialogueUi = initDialogue({
1722 socket: { send (payload) { socket.send(payload); } },
1723 MessageType,
1724 getEntity (id)
1725 {
1726 if (id === "local")
1727 { return view?.entities.get(view.localEntityId) ?? null; }
1728 return view?.entities.get(id) ?? null;
1729 },
1730 captureSpeakerIcon (entityId, size = 64)
1731 {
1732 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1733 }
1734 });
1735 shop = initShop({
1736 socket: { send (payload) { socket.send(payload); } },
1737 MessageType,
1738 onSuppressWorldClick: consumeWorldClick,
1739 getCoinCount ()
1740 {
1741 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1742 },
1743 getInventorySlots ()
1744 {
1745 return inventory?.getInventorySlots?.() ?? [];
1746 }
1747 });
1748 market = initMarket({
1749 socket: { send (payload) { socket.send(payload); } },
1750 MessageType,
1751 onSuppressWorldClick: consumeWorldClick,
1752 getCoinCount ()
1753 {
1754 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1755 },
1756 getInventorySlots ()
1757 {
1758 return inventory?.getInventorySlots?.() ?? [];
1759 },
1760 getLocalCharacterId ()
1761 {
1762 return inventory?.getLocalCharacterId?.() ?? null;
1763 }
1764 });
1765 bounty = initBounty({
1766 socket: { send (payload) { socket.send(payload); } },
1767 MessageType,
1768 onSuppressWorldClick: consumeWorldClick,
1769 resolveSpriteUrl (name)
1770 {
1771 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1772 },
1773 resolveImage (name)
1774 {
1775 return game?.images?.[name] ?? null;
1776 }
1777 });
1778 barber = initBarber({
1779 socket: { send (payload) { socket.send(payload); } },
1780 MessageType,
1781 onSuppressWorldClick: consumeWorldClick,
1782 resolveSpriteUrl (name)
1783 {
1784 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1785 },
1786 getInventoryBag ()
1787 {
1788 return {
1789 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1790 inventory: inventory?.getInventorySlots?.() ?? []
1791 };
1792 }
1793 });
1794 chat = initChat({
1795 socket: { send (payload) { socket.send(payload); } },
1796 MessageType,
1797 getSettings: () => view?.settings
1798 });
1799 death = initDeath({
1800 socket: { send (payload) { socket.send(payload); } },
1801 MessageType
1802 });
1803 game.startGame();
1804 useNearestNeighbour(scene, game.images);
1805
1806 socket = new GameSocket(defaultSocketUrl(), (message) =>
1807 {
1808 switch (message.type)
1809 {
1810 case MessageType.session:
1811 session = message;
1812 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1813 renderCharacters(message.characters);
1814 break;
1815 case MessageType.characterList:
1816 renderCharacters(message.characters);
1817 if (!playing)
1818 { overlay.hidden = false; }
1819 break;
1820 case MessageType.enterWorld:
1821 closeCreateModal();
1822 startPlay(message);
1823 inventory?.setLocalCharacterId(message.characterId);
1824 toasts?.applyRestartStatus?.(message.restartStatus);
1825 socket.send({ type: MessageType.requestQuests });
1826 break;
1827 case MessageType.chunkSnapshot:
1828 view?.applySnapshot(message);
1829 break;
1830 case MessageType.dimensionChanged:
1831 if (view)
1832 {
1833 view.setDimensionId(message.dimensionId);
1834 view.setDimensionModes(message.lightingMode, message.seasonMode);
1835 view.clearAllChunks();
1836 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1837 {
1838 view.moveEntity({
1839 entityId: view.localEntityId,
1840 tileX: message.tileX,
1841 tileY: message.tileY
1842 });
1843 }
1844 }
1845 closeOpenUiIfTooFar();
1846 break;
1847 case MessageType.chunkDelta:
1848 for (const tile of message.tiles ?? [])
1849 {
1850 view?.updateAuthoredTile(
1851 message.chunkX,
1852 message.chunkY,
1853 tile.localX,
1854 tile.localY,
1855 { ground: tile.ground, block: tile.block, light: tile.light }
1856 );
1857 }
1858 break;
1859 case MessageType.unsubscribeChunk:
1860 view?.removeChunk(message.chunkX, message.chunkY);
1861 break;
1862 case MessageType.entitySpawn:
1863 view?.spawnEntity(message);
1864 break;
1865 case MessageType.entityMove:
1866 view?.moveEntity(message);
1867 if (message.entityId === view?.localEntityId)
1868 {
1869 if (message.gait)
1870 {
1871 gait = message.gait;
1872 document.getElementById("gait").textContent = gait;
1873 }
1874 closeOpenUiIfTooFar();
1875 }
1876 else if (
1877 uiFocus?.entityId != null
1878 && message.entityId === uiFocus.entityId
1879 )
1880 { closeOpenUiIfTooFar(); }
1881 break;
1882 case MessageType.entityDespawn:
1883 if (message.entityId === autorunFocusEntityId)
1884 { clearAutorunFocus(); }
1885 view?.despawnEntity(message.entityId);
1886 break;
1887 case MessageType.entityAppearance:
1888 view?.setAppearance(message);
1889 break;
1890 case MessageType.entitySkull:
1891 view?.updateEntitySkull(message.entityId, message.skullValue);
1892 break;
1893 case MessageType.groundItemAppear:
1894 view?.upsertGroundItem(message);
1895 break;
1896 case MessageType.groundItemDespawn:
1897 view?.despawnGroundItem(message.groundItemId);
1898 break;
1899 case MessageType.inventory:
1900 inventory?.handleInventory(message);
1901 skills?.refresh?.();
1902 crafting?.refresh();
1903 alchemy?.refresh();
1904 shop?.refresh();
1905 market?.refresh();
1906 break;
1907 case MessageType.skills:
1908 skills?.render(message.skills);
1909 crafting?.refresh();
1910 spells?.refreshCastGates?.();
1911 break;
1912 case MessageType.spells:
1913 case MessageType.spellsUpdated:
1914 spells?.render(message);
1915 break;
1916 case MessageType.spellArmed:
1917 spells?.handleSpellArmed(message);
1918 break;
1919 case MessageType.spellDisarmed:
1920 spells?.handleSpellDisarmed();
1921 break;
1922 case MessageType.spellProjectile:
1923 view?.spawnSpellProjectileFx(message);
1924 if (message.casterId === view?.localEntityId)
1925 { clearAutorunFocus(); }
1926 break;
1927 case MessageType.spellFizzle:
1928 view?.spawnSpellFizzleFx(message);
1929 if (message.casterId === view?.localEntityId)
1930 {
1931 clearAutorunFocus();
1932 toasts?.show("Failed to cast spell");
1933 }
1934 break;
1935 case MessageType.spellCastFlash:
1936 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
1937 if (message.casterId === view?.localEntityId)
1938 { clearAutorunFocus(); }
1939 break;
1940 case MessageType.spellLightAppear:
1941 case MessageType.spellLightUpdate:
1942 view?.setSpellLight(message);
1943 break;
1944 case MessageType.spellLightRemove:
1945 view?.removeSpellLight(message);
1946 break;
1947 case MessageType.spellDarkAppear:
1948 case MessageType.spellDarkUpdate:
1949 view?.setSpellDark(message);
1950 break;
1951 case MessageType.spellDarkRemove:
1952 view?.removeSpellDark(message);
1953 break;
1954 case MessageType.stamina:
1955 staminaUi?.apply(message);
1956 if (message.gait)
1957 {
1958 gait = message.gait;
1959 document.getElementById("gait").textContent = gait;
1960 if (gait === GAIT.walk && (staminaUi?.getCurrent?.() ?? 0) <= 0)
1961 { autorunWaitingStamina = true; }
1962 }
1963 syncAutorun();
1964 break;
1965 case MessageType.statusEffects:
1966 view?.setLocalBlind(!!message.blind);
1967 statusEffectsUi?.apply(message);
1968 break;
1969 case MessageType.bankSnapshot:
1970 inventory?.handleBank(message);
1971 break;
1972 case MessageType.cauldronSnapshot:
1973 if (message.open === false && uiFocus?.kind === "cauldron")
1974 { clearUiFocus(); }
1975 alchemy?.handleSnapshot(message);
1976 break;
1977 case MessageType.pigeonDispatched:
1978 inventory?.handlePigeonDispatched(message);
1979 break;
1980 case MessageType.pigeonDelivered:
1981 inventory?.handlePigeonDelivered(message);
1982 break;
1983 case MessageType.characterSearchResult:
1984 inventory?.handleCharacterSearch(message);
1985 break;
1986 case MessageType.craftResult:
1987 crafting?.handleCraftResult(message);
1988 break;
1989 case MessageType.worldStatus:
1990 if (view)
1991 {
1992 view.setSettings(message.settings ?? view.settings);
1993 view.worldHour = message.worldTime?.hour ?? view.worldHour;
1994 view.setWorldSeason(message.worldTime?.season);
1995 chat?.syncSettings();
1996 }
1997 skills?.refresh?.();
1998 toasts?.applyRestartStatus?.(message.restartStatus);
1999 break;
2000 case MessageType.restartStatus:
2001 toasts?.applyRestartStatus?.(message.restartStatus);
2002 break;
2003 case MessageType.chatBubble:
2004 chat?.showBubble(message);
2005 break;
2006 case MessageType.friends:
2007 social?.handleFriends(message);
2008 break;
2009 case MessageType.combatSwing:
2010 view?.spawnCombatSwing(message);
2011 break;
2012 case MessageType.combatProjectile:
2013 view?.spawnPhysicalProjectileFx({
2014 ...message,
2015 sprite: "fx:projectile:arrow"
2016 });
2017 break;
2018 case MessageType.combatNoArrows:
2019 toasts?.show("Out of arrows!");
2020 break;
2021 case MessageType.gatherSwing:
2022 case MessageType.tileShove:
2023 view?.spawnGatherSwing(message);
2024 break;
2025 case MessageType.stationOpen:
2026 if (message.stationId)
2027 { crafting?.openStation(message.stationId); }
2028 break;
2029 case MessageType.shopOpen:
2030 if (message.npcEntityId != null)
2031 { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); }
2032 shop?.handleShopOpen(message);
2033 break;
2034 case MessageType.shopClosed:
2035 if (uiFocus?.kind === "shop")
2036 { clearUiFocus(); }
2037 shop?.handleShopClosed(message);
2038 break;
2039 case MessageType.marketOpen:
2040 market?.handleOpen(message);
2041 break;
2042 case MessageType.marketClosed:
2043 if (uiFocus?.kind === "market")
2044 { clearUiFocus(); }
2045 market?.handleClosed(message);
2046 break;
2047 case MessageType.marketTrade:
2048 market?.handleTrade(message);
2049 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
2050 break;
2051 case MessageType.bountySnapshot:
2052 bounty?.handleSnapshot(message);
2053 break;
2054 case MessageType.closeBounty:
2055 if (uiFocus?.kind === "bounty")
2056 { clearUiFocus(); }
2057 bounty?.handleClosed(message);
2058 break;
2059 case MessageType.characterBounty:
2060 bounty?.handleCharacterBounty(message);
2061 social?.handleCharacterBounty(message);
2062 break;
2063 case MessageType.barberSnapshot:
2064 barber?.handleSnapshot(message);
2065 break;
2066 case MessageType.closeBarber:
2067 if (uiFocus?.kind === "barber")
2068 { clearUiFocus(); }
2069 barber?.handleClosed(message);
2070 break;
2071 case MessageType.itemBubble:
2072 chat?.showItemBubble(message);
2073 break;
2074 case MessageType.gatherComplete:
2075 crafting?.refresh();
2076 break;
2077 case MessageType.combatHit:
2078 {
2079 const applyHit = () =>
2080 {
2081 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
2082 view?.flashDamage(message.targetId);
2083 view?.spawnCombatKnockback?.(message);
2084 view?.spawnDamageNumber(message.targetId, message.damage);
2085 if (message.targetId === view?.localEntityId)
2086 {
2087 healthUi?.apply({
2088 current: message.health,
2089 max: message.maxHealth
2090 });
2091 }
2092 };
2093 if (!view?.deferCombatHit?.(message, applyHit))
2094 { applyHit(); }
2095 break;
2096 }
2097 case MessageType.combatMiss:
2098 view?.spawnCombatDodge?.(message);
2099 view?.markProjectileMiss?.(message);
2100 break;
2101 case MessageType.combatBlock:
2102 {
2103 const applyBlock = () =>
2104 {
2105 view?.flashBlock?.(message.targetId);
2106 if (message.health != null)
2107 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
2108 };
2109 if (!view?.deferCombatHit?.(message, applyBlock))
2110 { applyBlock(); }
2111 break;
2112 }
2113 case MessageType.entityHealth:
2114 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2115 if (message.entityId === view?.localEntityId)
2116 {
2117 healthUi?.apply({
2118 current: message.health,
2119 max: message.maxHealth
2120 });
2121 }
2122 break;
2123 case MessageType.skillLevelUp:
2124 view?.spawnSkillLevelUp(message.entityId, message);
2125 if (message.entityId === view?.localEntityId)
2126 {
2127 const level = message.level | 0;
2128 const previousLevel = message.previousLevel == null
2129 ? Math.max(0, level - 1)
2130 : message.previousLevel | 0;
2131 const unlockCount = skillUnlockMessages(message.skillId, previousLevel, level).length;
2132 toasts?.show(skillLevelUpToastText(message.skillId, level, previousLevel), {
2133 durationMs: 3500 + unlockCount * 1600
2134 });
2135 }
2136 break;
2137 case MessageType.playerDied:
2138 clearAllPendingActions();
2139 clearAutorunFocus();
2140 contextMenu?.hide();
2141 spells?.handleSpellDisarmed?.();
2142 closeCloseablePlayUi();
2143 death?.show();
2144 if (message.entityId === view?.localEntityId)
2145 {
2146 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
2147 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
2148 }
2149 break;
2150 case MessageType.playerRespawned:
2151 death?.hide();
2152 // Drop deferred killing-blow health=0 that may still be queued on a projectile.
2153 view?.cancelDeferredCombatHits?.(message.entityId);
2154 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2155 if (message.skullValue != null)
2156 { view?.updateEntitySkull(message.entityId, message.skullValue); }
2157 if (message.entityId === view?.localEntityId)
2158 {
2159 healthUi?.apply({
2160 current: message.health,
2161 max: message.maxHealth
2162 });
2163 }
2164 if (message.stamina != null || message.maxStamina != null)
2165 {
2166 staminaUi?.apply({
2167 current: message.stamina ?? staminaUi.getCurrent?.(),
2168 max: message.maxStamina ?? staminaUi.getMax?.()
2169 });
2170 }
2171 break;
2172 case MessageType.error:
2173 if (playing)
2174 { toasts?.show(message.message); }
2175 else
2176 {
2177 const createPanel = document.getElementById("create-panel");
2178 const createError = document.getElementById("create-error");
2179 if (createPanel && !createPanel.hidden && createError)
2180 { createError.textContent = message.message ?? ""; }
2181 else
2182 { showError(message.message); }
2183 }
2184 social?.showError(message.message);
2185 break;
2186 case MessageType.toast:
2187 if (playing)
2188 { toasts?.show(message.message); }
2189 break;
2190 case MessageType.questsSnapshot:
2191 questsUi?.applySnapshot(message);
2192 break;
2193 case MessageType.questStepComplete:
2194 questsUi?.handleStepComplete(message);
2195 break;
2196 case MessageType.dialogueStep:
2197 if (message.npcEntityId != null)
2198 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2199 dialogueUi?.handleStep(message);
2200 break;
2201 case MessageType.dialogueChoices:
2202 if (message.npcEntityId != null)
2203 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2204 dialogueUi?.handleChoices(message);
2205 break;
2206 case MessageType.dialogueClose:
2207 if (uiFocus?.kind === "dialogue")
2208 { clearUiFocus(); }
2209 dialogueUi?.handleClose(message);
2210 break;
2211 case MessageType.forceLogout:
2212 returnToMenu(message.reason);
2213 break;
2214 }
2215 }, {
2216 onClose (event)
2217 {
2218 if (playing)
2219 { returnToMenu(event.reason || "Disconnected from server."); }
2220 }
2221 });
2222 await socket.connect();
2223 if (typeof window !== "undefined")
2224 {
2225 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
2226 {
2227 crafting?.openStation(stationId);
2228 };
2229 }
2230}
2231
2232function returnToMenu (reason = "")
2233{
2234 playing = false;
2235 followTargetId = null;
2236 moveDest = null;
2237 clearAutorunFocus();
2238 autorunWaitingStamina = false;
2239 clearAllPendingActions();
2240 clearUiFocus();
2241 social?.reset();
2242 chat?.reset();
2243 inventory?.reset();
2244 crafting?.reset();
2245 alchemy?.reset();
2246 staminaUi?.hide();
2247 healthUi?.hide();
2248 statusEffectsUi?.hide();
2249 skills?.hide();
2250 spells?.hide();
2251 contextMenu?.hide();
2252 death?.reset();
2253 shop?.close({ notifyServer: false });
2254 bounty?.close();
2255 barber?.close();
2256 questsUi?.reset();
2257 dialogueUi?.reset();
2258 hideWorldTooltip();
2259 if (view)
2260 { view.clearPlaySession(); }
2261 overlay.hidden = false;
2262 hud.hidden = true;
2263 const settingsToggle = document.getElementById("settings-toggle");
2264 if (settingsToggle)
2265 { settingsToggle.hidden = true; }
2266 graphicsSettingsUi?.close();
2267 if (reason)
2268 { statusEl.textContent = reason; }
2269}
2270
2271document.getElementById("create-character-open")?.addEventListener("click", () =>
2272{
2273 showError("");
2274 const createError = document.getElementById("create-error");
2275 if (createError)
2276 { createError.textContent = ""; }
2277 document.getElementById("create-backdrop").hidden = false;
2278 document.getElementById("create-panel").hidden = false;
2279 setCreateTab("appearance");
2280 void createHairControls?.refreshPreview();
2281});
2282
2283function closeCreateModal ()
2284{
2285 document.getElementById("create-backdrop").hidden = true;
2286 document.getElementById("create-panel").hidden = true;
2287}
2288
2289document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
2290document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
2291
2292document.getElementById("create-form").addEventListener("submit", (event) =>
2293{
2294 event.preventDefault();
2295 showError("");
2296 const createError = document.getElementById("create-error");
2297 if (createError)
2298 { createError.textContent = ""; }
2299 socket.send({
2300 type: MessageType.createCharacter,
2301 firstName: document.getElementById("first-name").value,
2302 lastName: document.getElementById("last-name").value,
2303 sex: document.getElementById("sex").value,
2304 hair: createHairControls?.currentHair?.() ?? null,
2305 clothing: createClothingControls?.currentClothing?.() ?? null
2306 });
2307});
2308
2309function initCreateTabs ()
2310{
2311 const tabs = document.querySelectorAll(".create-tab");
2312 for (const tab of tabs)
2313 {
2314 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
2315 }
2316 setCreateTab("appearance");
2317}
2318
2319function setCreateTab (name)
2320{
2321 createActiveTab = name === "clothing" ? "clothing" : "appearance";
2322 for (const tab of document.querySelectorAll(".create-tab"))
2323 {
2324 const on = tab.dataset.createTab === createActiveTab;
2325 tab.classList.toggle("active", on);
2326 tab.setAttribute("aria-selected", on ? "true" : "false");
2327 }
2328 for (const pane of document.querySelectorAll("[data-create-pane]"))
2329 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
2330 if (createActiveTab === "clothing")
2331 { void refreshCreateClothingPreview(); }
2332 else
2333 { void createHairControls?.refreshPreview(); }
2334}
2335
2336async function refreshCreateClothingPreview ()
2337{
2338 const canvas = document.getElementById("create-clothing-preview");
2339 if (!canvas || !createClothingControls)
2340 { return; }
2341 try
2342 {
2343 await paintCharacterPreview(canvas, {
2344 sex: document.getElementById("sex")?.value ?? "male",
2345 bag: createClothingControls.previewBag(),
2346 hair: createHairControls?.currentHair?.() ?? null,
2347 hideHeadgear: true,
2348 resolveSpriteUrl (name)
2349 {
2350 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2351 },
2352 scale: 4
2353 });
2354 }
2355 catch (error)
2356 { console.warn(error); }
2357}
2358
2359document.getElementById("leave").addEventListener("click", () =>
2360{
2361 socket.send({ type: MessageType.leaveWorld });
2362 returnToMenu();
2363});
2364
2365main().catch((error) =>
2366{
2367 showError(error.message);
2368 console.error(error);
2369});
2370
2371function isBankTile (view, tileX, tileY)
2372{
2373 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
2374}
2375
2376function isDoorwayTile (view, tileX, tileY)
2377{
2378 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
2379}
2380
2381function isMarketplaceTile (view, tileX, tileY)
2382{
2383 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
2384}
2385
2386function isBountyOfficeTile (view, tileX, tileY)
2387{
2388 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
2389}
2390
2391function isBarberTile (view, tileX, tileY)
2392{
2393 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
2394}
2395
2396function isCauldronTile (view, tileX, tileY)
2397{
2398 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2399}
2400
2401function isFurnaceTile (view, tileX, tileY)
2402{
2403 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2404}
2405
2406function isOvenTile (view, tileX, tileY)
2407{
2408 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2409}
2410
2411function isCampfireTile (view, tileX, tileY)
2412{
2413 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2414}
2415
2416function isFishingSpotTile (view, tileX, tileY)
2417{
2418 const block = blockAt(view, tileX, tileY);
2419 if (!block || block.typeId !== BlockType.fishingSpot)
2420 { return false; }
2421 return block.state !== "exhausted";
2422}
2423
2424function isAnvilTile (view, tileX, tileY)
2425{
2426 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2427}
2428
2429function isJeweleringStationTile (view, tileX, tileY)
2430{
2431 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2432}
2433
2434function isGroundWoodLog (ground)
2435{
2436 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2437 return def?.familyId === ItemFamilyId.log;
2438}
2439
2440function playerHasUsableTinderbox ()
2441{
2442 const slots = inventory?.getInventorySlots?.() ?? [];
2443 for (const slot of slots)
2444 {
2445 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2446 { continue; }
2447 const charges = slot.instance?.kind === "tinderbox"
2448 ? (slot.instance.charges | 0)
2449 : TINDERBOX_MAX_CHARGES;
2450 if (charges > 0)
2451 { return true; }
2452 }
2453 return false;
2454}
2455
2456function isWoodworkingBenchTile (view, tileX, tileY)
2457{
2458 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2459}
2460
2461function isCraftingBenchTile (view, tileX, tileY)
2462{
2463 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
2464}
2465
2466function isSpinningWheelTile (view, tileX, tileY)
2467{
2468 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
2469}
2470
2471function isLoomTile (view, tileX, tileY)
2472{
2473 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
2474}
2475
2476function isTailorBenchTile (view, tileX, tileY)
2477{
2478 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
2479}
2480
2481function isLeatherworkingTableTile (view, tileX, tileY)
2482{
2483 return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable;
2484}
2485
2486function isOreBoulderTile (view, tileX, tileY)
2487{
2488 const block = blockAt(view, tileX, tileY);
2489 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
2490}
2491
2492function isChopableTreeTile (view, tileX, tileY)
2493{
2494 return isChopableTreeBlock(blockAt(view, tileX, tileY));
2495}
2496
2497function isPickablePlantTile (view, tileX, tileY)
2498{
2499 return isPickablePlantBlock(blockAt(view, tileX, tileY));
2500}
2501
2502const SPELL_ENTITY_SNAP_TILES = 2;
2503
2504function updateSpellTargetHighlight ()
2505{
2506 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
2507 {
2508 view?.clearSpellTargetHighlight();
2509 return;
2510 }
2511 const canvas = scene?.canvas;
2512 if (!canvas)
2513 { return; }
2514 const rect = canvas.getBoundingClientRect();
2515 const mouseX = GameInput.mousePosition.x - rect.left;
2516 const mouseY = GameInput.mousePosition.y - rect.top;
2517 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2518 {
2519 view.clearSpellTargetHighlight();
2520 return;
2521 }
2522 const armed = spells.getArmedSpell?.();
2523 const local = view.entities.get(view.localEntityId);
2524 if (armed?.target === "entity")
2525 {
2526 const target = nearestSpellEntityAtCursor(mouseX, mouseY);
2527 if (!target)
2528 {
2529 view.clearSpellTargetHighlight();
2530 return;
2531 }
2532 const inRange = !local
2533 || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) <= COMBAT_RANGE_TILES;
2534 view.setSpellEntityTargetHighlight(target.entityId, inRange);
2535 return;
2536 }
2537 const tile = view.screenToTile(mouseX, mouseY);
2538 const inRange = !local
2539 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
2540 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
2541}
2542
2543/**
2544 * Nearest spell-targetable entity within {@link SPELL_ENTITY_SNAP_TILES} of the
2545 * cursor tile (uses both authoritative and visual tile for moving mobs).
2546 */
2547function nearestSpellEntityAtCursor (mouseX, mouseY)
2548{
2549 if (!view)
2550 { return null; }
2551 const cursor = view.screenToTile(mouseX, mouseY);
2552 const tileSize = view.tileSize();
2553 let best = null;
2554 let bestDist = Infinity;
2555 let bestScreen = Infinity;
2556 for (const entity of view.entities.values())
2557 {
2558 if (!isSpellEntityTarget(entity))
2559 { continue; }
2560 const visualTileX = Math.floor((entity.visualX + (entity.stackOffsetX ?? 0)) / tileSize);
2561 const visualTileY = Math.floor((entity.visualY + (entity.stackOffsetY ?? 0)) / tileSize);
2562 const dist = Math.min(
2563 chebyshev(cursor.tileX, cursor.tileY, entity.tileX, entity.tileY),
2564 chebyshev(cursor.tileX, cursor.tileY, visualTileX, visualTileY)
2565 );
2566 if (dist > SPELL_ENTITY_SNAP_TILES)
2567 { continue; }
2568 const box = view.nametagAnchor?.(entity);
2569 const screenDist = box
2570 ? Math.hypot(box.x - mouseX, box.y - mouseY)
2571 : dist;
2572 if (dist < bestDist || (dist === bestDist && screenDist < bestScreen))
2573 {
2574 best = entity;
2575 bestDist = dist;
2576 bestScreen = screenDist;
2577 }
2578 }
2579 return best;
2580}
2581
2582function isSpellEntityTarget (entity)
2583{
2584 if (!entity || entity.entityId === view?.localEntityId)
2585 { return false; }
2586 if (entity.untargetable || entity.freeFlight)
2587 { return false; }
2588 return isAttackableEntity(entity);
2589}
2590
2591function hideWorldTooltip ()
2592{
2593 if (worldTooltip)
2594 {
2595 worldTooltip.hidden = true;
2596 worldTooltip.classList.remove("friend-name");
2597 worldTooltip.style.color = "";
2598 }
2599}
2600
2601/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
2602function updateWorldTooltip ()
2603{
2604 if (!worldTooltip || !view || !scene || uiBlocked())
2605 {
2606 hideWorldTooltip();
2607 return;
2608 }
2609 const canvas = scene.canvas;
2610 const rect = canvas.getBoundingClientRect();
2611 const mouseX = GameInput.mousePosition.x - rect.left;
2612 const mouseY = GameInput.mousePosition.y - rect.top;
2613 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2614 {
2615 hideWorldTooltip();
2616 return;
2617 }
2618 const entity = view.entityAtScreen(mouseX, mouseY);
2619 if (entity && entity.entityId !== view.localEntityId)
2620 {
2621 const label = entityLabel(entity);
2622 worldTooltip.hidden = false;
2623 worldTooltip.textContent = label;
2624 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2625 worldTooltip.classList.toggle("friend-name", !!friend);
2626 worldTooltip.style.color = friend ? "#e8c84a" : "";
2627 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2628 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2629 return;
2630 }
2631 const tile = view.screenToTile(mouseX, mouseY);
2632 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
2633 if (!label)
2634 {
2635 hideWorldTooltip();
2636 return;
2637 }
2638 worldTooltip.hidden = false;
2639 worldTooltip.textContent = label;
2640 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2641 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2642}
2643
2644function blockTypeAt (view, tileX, tileY)
2645{
2646 return blockAt(view, tileX, tileY)?.typeId ?? null;
2647}
2648
2649function blockAt (view, tileX, tileY)
2650{
2651 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2652 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2653 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2654 if (!snapshot)
2655 { return null; }
2656 const localX = tileX - chunkX * CHUNK_SIZE;
2657 const localY = tileY - chunkY * CHUNK_SIZE;
2658 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
2659}
2660
2661function groundTypeAt (view, tileX, tileY)
2662{
2663 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2664 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2665 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2666 if (!snapshot)
2667 { return null; }
2668 const localX = tileX - chunkX * CHUNK_SIZE;
2669 const localY = tileY - chunkY * CHUNK_SIZE;
2670 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
2671}
2672
2673/** Best-effort client filter for approach destinations (server still authorizes paths). */
2674function isClientApproachable (tileX, tileY)
2675{
2676 if (!view)
2677 { return true; }
2678 const groundId = groundTypeAt(view, tileX, tileY);
2679 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
2680 if (groundDef && !groundDef.passable)
2681 { return false; }
2682 const block = blockAt(view, tileX, tileY);
2683 if (block?.typeId != null)
2684 {
2685 const blockDef = BLOCK_DEFINITIONS[block.typeId];
2686 if (blockDef && !blockDef.passable)
2687 { return false; }
2688 }
2689 for (const entity of view.entitiesAtTile(tileX, tileY))
2690 {
2691 if (entity.entityId === view.localEntityId)
2692 { continue; }
2693 if (entity.untargetable || entity.freeFlight)
2694 { continue; }
2695 return false;
2696 }
2697 return true;
2698}
2699
2700function chebyshev (ax, ay, bx, by)
2701{
2702 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
2703}
2704
2705function updateAuthUi (authStatus)
2706{
2707 const signIn = document.getElementById("auth-sign-in");
2708 const signOut = document.getElementById("auth-sign-out");
2709 const exportLink = document.getElementById("auth-export");
2710 if (signIn)
2711 {
2712 signIn.hidden = !!authStatus?.authenticated;
2713 signIn.href = loginUrl("/");
2714 }
2715 if (signOut)
2716 {
2717 signOut.hidden = !authStatus?.authenticated;
2718 signOut.href = logoutUrl("/");
2719 }
2720 if (exportLink)
2721 { exportLink.hidden = !authStatus?.authenticated; }
2722 if (authStatus?.authenticated && !session)
2723 {
2724 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
2725 }
2726}