BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 74.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, { includePrevious: true }))
1153 {
1154 if (entity.entityId === view.localEntityId)
1155 { continue; }
1156 const targetName = entityLabel(entity);
1157 items.push({
1158 label: `Follow ${targetName}`,
1159 onSelect: () =>
1160 {
1161 clearAllPendingActions();
1162 sendPlayerFollow(entity.entityId);
1163 }
1164 });
1165 if (entity.untargetable)
1166 { continue; }
1167 if (entity.hasShop)
1168 {
1169 items.push({
1170 label: `Shop ${targetName}`,
1171 onSelect: () => requestTalk(entity.entityId, "shop")
1172 });
1173 }
1174 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
1175 {
1176 items.push({
1177 label: `Talk to ${targetName}`,
1178 onSelect: () => requestTalk(entity.entityId, "talk")
1179 });
1180 }
1181 if (entityCanShear(entity))
1182 {
1183 items.push({
1184 label: `Shear ${targetName}`,
1185 onSelect: () => requestShear(entity.entityId)
1186 });
1187 }
1188 if (entity.characterId)
1189 {
1190 items.push({
1191 label: `${targetName} info`,
1192 onSelect: () =>
1193 {
1194 clearAllPendingActions();
1195 social.inspect(entity);
1196 }
1197 });
1198 }
1199 items.push({
1200 label: `Attack ${targetName}`,
1201 onSelect: () => requestAttack(entity.entityId)
1202 });
1203 }
1204
1205 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1206 {
1207 const name = groundLabel(ground);
1208 items.push({
1209 label: `Pick up ${name}`,
1210 onSelect: () => requestPickup(ground)
1211 });
1212 if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
1213 {
1214 items.push({
1215 label: `Start Fire`,
1216 onSelect: () => requestStartFire(ground)
1217 });
1218 }
1219 }
1220
1221 if (isBankTile(view, tile.tileX, tile.tileY))
1222 {
1223 items.push({
1224 label: "Bank",
1225 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
1226 });
1227 items.push({
1228 label: "Get Blank Cheques",
1229 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
1230 });
1231 }
1232
1233 if (isDoorwayTile(view, tile.tileX, tile.tileY))
1234 {
1235 items.push({
1236 label: "Enter",
1237 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
1238 });
1239 }
1240
1241 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1242 {
1243 items.push({
1244 label: "Central Exchange",
1245 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
1246 });
1247 }
1248
1249 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1250 {
1251 items.push({
1252 label: "Bounty Office",
1253 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
1254 });
1255 }
1256
1257 if (isBarberTile(view, tile.tileX, tile.tileY))
1258 {
1259 items.push({
1260 label: "Barber",
1261 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
1262 });
1263 }
1264
1265 if (isCauldronTile(view, tile.tileX, tile.tileY))
1266 {
1267 items.push({
1268 label: "Alchemy",
1269 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
1270 });
1271 }
1272
1273 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1274 {
1275 items.push({
1276 label: "Smelt",
1277 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
1278 });
1279 }
1280
1281 if (isOvenTile(view, tile.tileX, tile.tileY))
1282 {
1283 items.push({
1284 label: "Cook",
1285 onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
1286 });
1287 }
1288
1289 if (isCampfireTile(view, tile.tileX, tile.tileY))
1290 {
1291 items.push({
1292 label: "Cook",
1293 onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
1294 });
1295 }
1296
1297 if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1298 {
1299 items.push({
1300 label: "Fish",
1301 onSelect: () => requestFish(tile.tileX, tile.tileY)
1302 });
1303 }
1304
1305 if (isAnvilTile(view, tile.tileX, tile.tileY))
1306 {
1307 items.push({
1308 label: "Smith",
1309 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
1310 });
1311 }
1312
1313 if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1314 {
1315 items.push({
1316 label: "Jewel",
1317 onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1318 });
1319 }
1320
1321 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1322 {
1323 items.push({
1324 label: "Woodwork",
1325 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
1326 });
1327 }
1328
1329 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1330 {
1331 items.push({
1332 label: "Craft",
1333 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
1334 });
1335 }
1336
1337 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1338 {
1339 items.push({
1340 label: "Spin",
1341 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
1342 });
1343 }
1344
1345 if (isLoomTile(view, tile.tileX, tile.tileY))
1346 {
1347 items.push({
1348 label: "Weave",
1349 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
1350 });
1351 }
1352
1353 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1354 {
1355 items.push({
1356 label: "Tailor",
1357 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
1358 });
1359 }
1360
1361 if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1362 {
1363 items.push({
1364 label: "Leatherwork",
1365 onSelect: () => requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY)
1366 });
1367 }
1368
1369 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1370 {
1371 items.push({
1372 label: "Mine",
1373 onSelect: () => requestMine(tile.tileX, tile.tileY)
1374 });
1375 }
1376
1377 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1378 {
1379 items.push({
1380 label: "Chop",
1381 onSelect: () => requestChop(tile.tileX, tile.tileY)
1382 });
1383 }
1384
1385 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1386 {
1387 items.push({
1388 label: "Pick",
1389 onSelect: () => requestPick(tile.tileX, tile.tileY)
1390 });
1391 }
1392
1393 contextMenu.show(event.clientX, event.clientY, items);
1394}
1395
1396function entityLabel (entity)
1397{
1398 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 getSkillLevels ()
1673 {
1674 return skills?.getSkillLevels?.() ?? {};
1675 },
1676 getSettings ()
1677 {
1678 return view?.settings ?? null;
1679 },
1680 getKnownSpellIds ()
1681 {
1682 return spells?.getKnownSpellIds?.() ?? [];
1683 },
1684 onBagChanged ()
1685 {
1686 spells?.refreshMaxHitDisplay?.();
1687 }
1688 });
1689 skills = initSkills({
1690 getEquipmentSlots ()
1691 {
1692 return inventory?.getEquipment?.() ?? {};
1693 },
1694 getSettings ()
1695 {
1696 return view?.settings ?? null;
1697 }
1698 });
1699 spells = initSpells({
1700 socket: { send (payload) { socket.send(payload); } },
1701 MessageType,
1702 getSkillLevel (skillId)
1703 {
1704 return skills?.skillLevel?.(skillId) ?? 1;
1705 },
1706 getSkillLevels ()
1707 {
1708 return skills?.getSkillLevels?.() ?? {};
1709 },
1710 getEquipmentSlots ()
1711 {
1712 return inventory?.getEquipment?.() ?? {};
1713 },
1714 getSettings ()
1715 {
1716 return view?.settings ?? null;
1717 }
1718 });
1719 crafting = initCrafting({
1720 socket: { send (payload) { socket.send(payload); } },
1721 MessageType,
1722 getInventorySlots ()
1723 {
1724 return inventory?.getInventorySlots?.() ?? [];
1725 },
1726 getSkillLevel (skillId)
1727 {
1728 return skills?.skillLevel?.(skillId) ?? 1;
1729 }
1730 });
1731 alchemy = initAlchemy({
1732 socket: { send (payload) { socket.send(payload); } },
1733 MessageType,
1734 getInventorySlots ()
1735 {
1736 return inventory?.getInventorySlots?.() ?? [];
1737 }
1738 });
1739 alchemy?.setOnSoftClaimsChanged?.(() => inventory?.refreshBagDisplay?.());
1740 staminaUi = initStamina();
1741 healthUi = initHealth();
1742 statusEffectsUi = initStatusEffects();
1743 toasts = initToasts();
1744 questsUi = initQuests({
1745 socket: { send (payload) { socket.send(payload); } },
1746 MessageType,
1747 toasts
1748 });
1749 dialogueUi = initDialogue({
1750 socket: { send (payload) { socket.send(payload); } },
1751 MessageType,
1752 getEntity (id)
1753 {
1754 if (id === "local")
1755 { return view?.entities.get(view.localEntityId) ?? null; }
1756 return view?.entities.get(id) ?? null;
1757 },
1758 captureSpeakerIcon (entityId, size = 64)
1759 {
1760 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1761 }
1762 });
1763 shop = initShop({
1764 socket: { send (payload) { socket.send(payload); } },
1765 MessageType,
1766 onSuppressWorldClick: consumeWorldClick,
1767 getCoinCount ()
1768 {
1769 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1770 },
1771 getInventorySlots ()
1772 {
1773 return inventory?.getInventorySlots?.() ?? [];
1774 }
1775 });
1776 market = initMarket({
1777 socket: { send (payload) { socket.send(payload); } },
1778 MessageType,
1779 onSuppressWorldClick: consumeWorldClick,
1780 getCoinCount ()
1781 {
1782 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1783 },
1784 getInventorySlots ()
1785 {
1786 return inventory?.getInventorySlots?.() ?? [];
1787 },
1788 getLocalCharacterId ()
1789 {
1790 return inventory?.getLocalCharacterId?.() ?? null;
1791 }
1792 });
1793 bounty = initBounty({
1794 socket: { send (payload) { socket.send(payload); } },
1795 MessageType,
1796 onSuppressWorldClick: consumeWorldClick,
1797 resolveSpriteUrl (name)
1798 {
1799 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1800 },
1801 resolveImage (name)
1802 {
1803 return game?.images?.[name] ?? null;
1804 }
1805 });
1806 barber = initBarber({
1807 socket: { send (payload) { socket.send(payload); } },
1808 MessageType,
1809 onSuppressWorldClick: consumeWorldClick,
1810 resolveSpriteUrl (name)
1811 {
1812 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1813 },
1814 getInventoryBag ()
1815 {
1816 return {
1817 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1818 inventory: inventory?.getInventorySlots?.() ?? []
1819 };
1820 }
1821 });
1822 chat = initChat({
1823 socket: { send (payload) { socket.send(payload); } },
1824 MessageType,
1825 getSettings: () => view?.settings
1826 });
1827 death = initDeath({
1828 socket: { send (payload) { socket.send(payload); } },
1829 MessageType
1830 });
1831 game.startGame();
1832 useNearestNeighbour(scene, game.images);
1833
1834 socket = new GameSocket(defaultSocketUrl(), (message) =>
1835 {
1836 switch (message.type)
1837 {
1838 case MessageType.session:
1839 session = message;
1840 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1841 renderCharacters(message.characters);
1842 break;
1843 case MessageType.characterList:
1844 renderCharacters(message.characters);
1845 if (!playing)
1846 { overlay.hidden = false; }
1847 break;
1848 case MessageType.enterWorld:
1849 closeCreateModal();
1850 startPlay(message);
1851 inventory?.setLocalCharacterId(message.characterId);
1852 toasts?.applyRestartStatus?.(message.restartStatus);
1853 socket.send({ type: MessageType.requestQuests });
1854 break;
1855 case MessageType.chunkSnapshot:
1856 view?.applySnapshot(message);
1857 break;
1858 case MessageType.dimensionChanged:
1859 if (view)
1860 {
1861 view.setDimensionId(message.dimensionId);
1862 view.setDimensionModes(message.lightingMode, message.seasonMode);
1863 view.clearAllChunks();
1864 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1865 {
1866 view.moveEntity({
1867 entityId: view.localEntityId,
1868 tileX: message.tileX,
1869 tileY: message.tileY
1870 });
1871 }
1872 }
1873 closeOpenUiIfTooFar();
1874 break;
1875 case MessageType.chunkDelta:
1876 for (const tile of message.tiles ?? [])
1877 {
1878 view?.updateAuthoredTile(
1879 message.chunkX,
1880 message.chunkY,
1881 tile.localX,
1882 tile.localY,
1883 { ground: tile.ground, block: tile.block, light: tile.light }
1884 );
1885 }
1886 break;
1887 case MessageType.unsubscribeChunk:
1888 view?.removeChunk(message.chunkX, message.chunkY);
1889 break;
1890 case MessageType.entitySpawn:
1891 view?.spawnEntity(message);
1892 break;
1893 case MessageType.entityMove:
1894 view?.moveEntity(message);
1895 if (message.entityId === view?.localEntityId)
1896 {
1897 if (message.gait)
1898 {
1899 gait = message.gait;
1900 document.getElementById("gait").textContent = gait;
1901 }
1902 closeOpenUiIfTooFar();
1903 }
1904 else if (
1905 uiFocus?.entityId != null
1906 && message.entityId === uiFocus.entityId
1907 )
1908 { closeOpenUiIfTooFar(); }
1909 break;
1910 case MessageType.entityDespawn:
1911 if (message.entityId === autorunFocusEntityId)
1912 { clearAutorunFocus(); }
1913 view?.despawnEntity(message.entityId);
1914 break;
1915 case MessageType.entityAppearance:
1916 view?.setAppearance(message);
1917 break;
1918 case MessageType.entitySkull:
1919 view?.updateEntitySkull(message.entityId, message.skullValue);
1920 break;
1921 case MessageType.groundItemAppear:
1922 view?.upsertGroundItem(message);
1923 break;
1924 case MessageType.groundItemDespawn:
1925 view?.despawnGroundItem(message.groundItemId);
1926 break;
1927 case MessageType.inventory:
1928 inventory?.handleInventory(message);
1929 skills?.refresh?.();
1930 crafting?.refresh();
1931 alchemy?.refresh();
1932 shop?.refresh();
1933 market?.refresh();
1934 break;
1935 case MessageType.skills:
1936 skills?.render(message.skills, message.combatLevel);
1937 inventory?.refreshMaxHit?.();
1938 spells?.refreshMaxHitDisplay?.();
1939 crafting?.refresh();
1940 spells?.refreshCastGates?.();
1941 break;
1942 case MessageType.spells:
1943 case MessageType.spellsUpdated:
1944 spells?.render(message);
1945 inventory?.refreshMaxHit?.();
1946 break;
1947 case MessageType.spellArmed:
1948 spells?.handleSpellArmed(message);
1949 break;
1950 case MessageType.spellDisarmed:
1951 spells?.handleSpellDisarmed();
1952 break;
1953 case MessageType.spellProjectile:
1954 view?.spawnSpellProjectileFx(message);
1955 if (message.casterId === view?.localEntityId)
1956 { clearAutorunFocus(); }
1957 break;
1958 case MessageType.spellFizzle:
1959 view?.spawnSpellFizzleFx(message);
1960 if (message.casterId === view?.localEntityId)
1961 {
1962 clearAutorunFocus();
1963 toasts?.show("Failed to cast spell");
1964 }
1965 break;
1966 case MessageType.spellCastFlash:
1967 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
1968 if (message.casterId === view?.localEntityId)
1969 { clearAutorunFocus(); }
1970 break;
1971 case MessageType.spellLightAppear:
1972 case MessageType.spellLightUpdate:
1973 view?.setSpellLight(message);
1974 break;
1975 case MessageType.spellLightRemove:
1976 view?.removeSpellLight(message);
1977 break;
1978 case MessageType.spellDarkAppear:
1979 case MessageType.spellDarkUpdate:
1980 view?.setSpellDark(message);
1981 break;
1982 case MessageType.spellDarkRemove:
1983 view?.removeSpellDark(message);
1984 break;
1985 case MessageType.stamina:
1986 staminaUi?.apply(message);
1987 if (message.gait)
1988 {
1989 gait = message.gait;
1990 document.getElementById("gait").textContent = gait;
1991 if (gait === GAIT.walk && (staminaUi?.getCurrent?.() ?? 0) <= 0)
1992 { autorunWaitingStamina = true; }
1993 }
1994 syncAutorun();
1995 break;
1996 case MessageType.statusEffects:
1997 view?.setLocalBlind(!!message.blind);
1998 statusEffectsUi?.apply(message);
1999 break;
2000 case MessageType.bankSnapshot:
2001 inventory?.handleBank(message);
2002 break;
2003 case MessageType.cauldronSnapshot:
2004 if (message.open === false && uiFocus?.kind === "cauldron")
2005 { clearUiFocus(); }
2006 alchemy?.handleSnapshot(message);
2007 break;
2008 case MessageType.pigeonDispatched:
2009 inventory?.handlePigeonDispatched(message);
2010 break;
2011 case MessageType.pigeonDelivered:
2012 inventory?.handlePigeonDelivered(message);
2013 break;
2014 case MessageType.characterSearchResult:
2015 inventory?.handleCharacterSearch(message);
2016 break;
2017 case MessageType.craftResult:
2018 crafting?.handleCraftResult(message);
2019 break;
2020 case MessageType.worldStatus:
2021 if (view)
2022 {
2023 view.setSettings(message.settings ?? view.settings);
2024 view.worldHour = message.worldTime?.hour ?? view.worldHour;
2025 view.setWorldSeason(message.worldTime?.season);
2026 chat?.syncSettings();
2027 }
2028 skills?.refresh?.();
2029 toasts?.applyRestartStatus?.(message.restartStatus);
2030 break;
2031 case MessageType.restartStatus:
2032 toasts?.applyRestartStatus?.(message.restartStatus);
2033 break;
2034 case MessageType.chatBubble:
2035 chat?.showBubble(message);
2036 break;
2037 case MessageType.friends:
2038 social?.handleFriends(message);
2039 break;
2040 case MessageType.combatSwing:
2041 view?.spawnCombatSwing(message);
2042 break;
2043 case MessageType.combatProjectile:
2044 view?.spawnPhysicalProjectileFx({
2045 ...message,
2046 sprite: "fx:projectile:arrow"
2047 });
2048 break;
2049 case MessageType.combatNoArrows:
2050 toasts?.show("Out of arrows!");
2051 break;
2052 case MessageType.gatherSwing:
2053 case MessageType.tileShove:
2054 view?.spawnGatherSwing(message);
2055 break;
2056 case MessageType.stationOpen:
2057 if (message.stationId)
2058 { crafting?.openStation(message.stationId); }
2059 break;
2060 case MessageType.shopOpen:
2061 if (message.npcEntityId != null)
2062 { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); }
2063 shop?.handleShopOpen(message);
2064 break;
2065 case MessageType.shopClosed:
2066 if (uiFocus?.kind === "shop")
2067 { clearUiFocus(); }
2068 shop?.handleShopClosed(message);
2069 break;
2070 case MessageType.marketOpen:
2071 market?.handleOpen(message);
2072 break;
2073 case MessageType.marketClosed:
2074 if (uiFocus?.kind === "market")
2075 { clearUiFocus(); }
2076 market?.handleClosed(message);
2077 break;
2078 case MessageType.marketTrade:
2079 market?.handleTrade(message);
2080 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
2081 break;
2082 case MessageType.bountySnapshot:
2083 bounty?.handleSnapshot(message);
2084 break;
2085 case MessageType.closeBounty:
2086 if (uiFocus?.kind === "bounty")
2087 { clearUiFocus(); }
2088 bounty?.handleClosed(message);
2089 break;
2090 case MessageType.characterBounty:
2091 bounty?.handleCharacterBounty(message);
2092 social?.handleCharacterBounty(message);
2093 break;
2094 case MessageType.barberSnapshot:
2095 barber?.handleSnapshot(message);
2096 break;
2097 case MessageType.closeBarber:
2098 if (uiFocus?.kind === "barber")
2099 { clearUiFocus(); }
2100 barber?.handleClosed(message);
2101 break;
2102 case MessageType.itemBubble:
2103 chat?.showItemBubble(message);
2104 break;
2105 case MessageType.gatherComplete:
2106 crafting?.refresh();
2107 break;
2108 case MessageType.combatHit:
2109 {
2110 const applyHit = () =>
2111 {
2112 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
2113 view?.flashDamage(message.targetId);
2114 view?.spawnCombatKnockback?.(message);
2115 view?.spawnDamageNumber(message.targetId, message.damage);
2116 if (message.targetId === view?.localEntityId)
2117 {
2118 healthUi?.apply({
2119 current: message.health,
2120 max: message.maxHealth
2121 });
2122 }
2123 };
2124 if (!view?.deferCombatHit?.(message, applyHit))
2125 { applyHit(); }
2126 break;
2127 }
2128 case MessageType.combatMiss:
2129 view?.spawnCombatDodge?.(message);
2130 view?.markProjectileMiss?.(message);
2131 break;
2132 case MessageType.combatBlock:
2133 {
2134 const applyBlock = () =>
2135 {
2136 view?.flashBlock?.(message.targetId);
2137 if (message.health != null)
2138 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
2139 };
2140 if (!view?.deferCombatHit?.(message, applyBlock))
2141 { applyBlock(); }
2142 break;
2143 }
2144 case MessageType.entityHealth:
2145 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2146 if (message.entityId === view?.localEntityId)
2147 {
2148 healthUi?.apply({
2149 current: message.health,
2150 max: message.maxHealth
2151 });
2152 }
2153 break;
2154 case MessageType.skillLevelUp:
2155 view?.spawnSkillLevelUp(message.entityId, message);
2156 if (message.entityId === view?.localEntityId)
2157 {
2158 const level = message.level | 0;
2159 const previousLevel = message.previousLevel == null
2160 ? Math.max(0, level - 1)
2161 : message.previousLevel | 0;
2162 const unlockCount = skillUnlockMessages(message.skillId, previousLevel, level).length;
2163 toasts?.show(skillLevelUpToastText(message.skillId, level, previousLevel), {
2164 durationMs: 3500 + unlockCount * 1600
2165 });
2166 }
2167 break;
2168 case MessageType.playerDied:
2169 clearAllPendingActions();
2170 clearAutorunFocus();
2171 contextMenu?.hide();
2172 spells?.handleSpellDisarmed?.();
2173 closeCloseablePlayUi();
2174 death?.show();
2175 if (message.entityId === view?.localEntityId)
2176 {
2177 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
2178 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
2179 }
2180 break;
2181 case MessageType.playerRespawned:
2182 death?.hide();
2183 // Drop deferred killing-blow health=0 that may still be queued on a projectile.
2184 view?.cancelDeferredCombatHits?.(message.entityId);
2185 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2186 if (message.skullValue != null)
2187 { view?.updateEntitySkull(message.entityId, message.skullValue); }
2188 if (message.entityId === view?.localEntityId)
2189 {
2190 healthUi?.apply({
2191 current: message.health,
2192 max: message.maxHealth
2193 });
2194 }
2195 if (message.stamina != null || message.maxStamina != null)
2196 {
2197 staminaUi?.apply({
2198 current: message.stamina ?? staminaUi.getCurrent?.(),
2199 max: message.maxStamina ?? staminaUi.getMax?.()
2200 });
2201 }
2202 break;
2203 case MessageType.error:
2204 if (playing)
2205 { toasts?.show(message.message); }
2206 else
2207 {
2208 const createPanel = document.getElementById("create-panel");
2209 const createError = document.getElementById("create-error");
2210 if (createPanel && !createPanel.hidden && createError)
2211 { createError.textContent = message.message ?? ""; }
2212 else
2213 { showError(message.message); }
2214 }
2215 social?.showError(message.message);
2216 break;
2217 case MessageType.toast:
2218 if (playing)
2219 { toasts?.show(message.message); }
2220 break;
2221 case MessageType.questsSnapshot:
2222 questsUi?.applySnapshot(message);
2223 break;
2224 case MessageType.questStepComplete:
2225 questsUi?.handleStepComplete(message);
2226 break;
2227 case MessageType.dialogueStep:
2228 if (message.npcEntityId != null)
2229 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2230 dialogueUi?.handleStep(message);
2231 break;
2232 case MessageType.dialogueItemRewards:
2233 if (message.npcEntityId != null)
2234 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2235 dialogueUi?.handleItemRewards(message);
2236 break;
2237 case MessageType.dialogueChoices:
2238 if (message.npcEntityId != null)
2239 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2240 dialogueUi?.handleChoices(message);
2241 break;
2242 case MessageType.dialogueClose:
2243 if (uiFocus?.kind === "dialogue")
2244 { clearUiFocus(); }
2245 dialogueUi?.handleClose(message);
2246 break;
2247 case MessageType.forceLogout:
2248 returnToMenu(message.reason);
2249 break;
2250 }
2251 }, {
2252 onClose (event)
2253 {
2254 if (playing)
2255 { returnToMenu(event.reason || "Disconnected from server."); }
2256 }
2257 });
2258 await socket.connect();
2259 if (typeof window !== "undefined")
2260 {
2261 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
2262 {
2263 crafting?.openStation(stationId);
2264 };
2265 }
2266}
2267
2268function returnToMenu (reason = "")
2269{
2270 playing = false;
2271 followTargetId = null;
2272 moveDest = null;
2273 clearAutorunFocus();
2274 autorunWaitingStamina = false;
2275 clearAllPendingActions();
2276 clearUiFocus();
2277 social?.reset();
2278 chat?.reset();
2279 inventory?.reset();
2280 crafting?.reset();
2281 alchemy?.reset();
2282 staminaUi?.hide();
2283 healthUi?.hide();
2284 statusEffectsUi?.hide();
2285 skills?.hide();
2286 spells?.hide();
2287 contextMenu?.hide();
2288 death?.reset();
2289 shop?.close({ notifyServer: false });
2290 bounty?.close();
2291 barber?.close();
2292 questsUi?.reset();
2293 dialogueUi?.reset();
2294 hideWorldTooltip();
2295 if (view)
2296 { view.clearPlaySession(); }
2297 overlay.hidden = false;
2298 hud.hidden = true;
2299 const settingsToggle = document.getElementById("settings-toggle");
2300 if (settingsToggle)
2301 { settingsToggle.hidden = true; }
2302 graphicsSettingsUi?.close();
2303 if (reason)
2304 { statusEl.textContent = reason; }
2305}
2306
2307document.getElementById("create-character-open")?.addEventListener("click", () =>
2308{
2309 showError("");
2310 const createError = document.getElementById("create-error");
2311 if (createError)
2312 { createError.textContent = ""; }
2313 document.getElementById("create-backdrop").hidden = false;
2314 document.getElementById("create-panel").hidden = false;
2315 setCreateTab("appearance");
2316 void createHairControls?.refreshPreview();
2317});
2318
2319function closeCreateModal ()
2320{
2321 document.getElementById("create-backdrop").hidden = true;
2322 document.getElementById("create-panel").hidden = true;
2323}
2324
2325document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
2326document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
2327
2328document.getElementById("create-form").addEventListener("submit", (event) =>
2329{
2330 event.preventDefault();
2331 showError("");
2332 const createError = document.getElementById("create-error");
2333 if (createError)
2334 { createError.textContent = ""; }
2335 socket.send({
2336 type: MessageType.createCharacter,
2337 firstName: document.getElementById("first-name").value,
2338 lastName: document.getElementById("last-name").value,
2339 sex: document.getElementById("sex").value,
2340 hair: createHairControls?.currentHair?.() ?? null,
2341 clothing: createClothingControls?.currentClothing?.() ?? null
2342 });
2343});
2344
2345function initCreateTabs ()
2346{
2347 const tabs = document.querySelectorAll(".create-tab");
2348 for (const tab of tabs)
2349 {
2350 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
2351 }
2352 setCreateTab("appearance");
2353}
2354
2355function setCreateTab (name)
2356{
2357 createActiveTab = name === "clothing" ? "clothing" : "appearance";
2358 for (const tab of document.querySelectorAll(".create-tab"))
2359 {
2360 const on = tab.dataset.createTab === createActiveTab;
2361 tab.classList.toggle("active", on);
2362 tab.setAttribute("aria-selected", on ? "true" : "false");
2363 }
2364 for (const pane of document.querySelectorAll("[data-create-pane]"))
2365 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
2366 if (createActiveTab === "clothing")
2367 { void refreshCreateClothingPreview(); }
2368 else
2369 { void createHairControls?.refreshPreview(); }
2370}
2371
2372async function refreshCreateClothingPreview ()
2373{
2374 const canvas = document.getElementById("create-clothing-preview");
2375 if (!canvas || !createClothingControls)
2376 { return; }
2377 try
2378 {
2379 await paintCharacterPreview(canvas, {
2380 sex: document.getElementById("sex")?.value ?? "male",
2381 bag: createClothingControls.previewBag(),
2382 hair: createHairControls?.currentHair?.() ?? null,
2383 hideHeadgear: true,
2384 resolveSpriteUrl (name)
2385 {
2386 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2387 },
2388 scale: 4
2389 });
2390 }
2391 catch (error)
2392 { console.warn(error); }
2393}
2394
2395document.getElementById("leave").addEventListener("click", () =>
2396{
2397 socket.send({ type: MessageType.leaveWorld });
2398 returnToMenu();
2399});
2400
2401main().catch((error) =>
2402{
2403 showError(error.message);
2404 console.error(error);
2405});
2406
2407function isBankTile (view, tileX, tileY)
2408{
2409 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
2410}
2411
2412function isDoorwayTile (view, tileX, tileY)
2413{
2414 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
2415}
2416
2417function isMarketplaceTile (view, tileX, tileY)
2418{
2419 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
2420}
2421
2422function isBountyOfficeTile (view, tileX, tileY)
2423{
2424 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
2425}
2426
2427function isBarberTile (view, tileX, tileY)
2428{
2429 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
2430}
2431
2432function isCauldronTile (view, tileX, tileY)
2433{
2434 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2435}
2436
2437function isFurnaceTile (view, tileX, tileY)
2438{
2439 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2440}
2441
2442function isOvenTile (view, tileX, tileY)
2443{
2444 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2445}
2446
2447function isCampfireTile (view, tileX, tileY)
2448{
2449 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2450}
2451
2452function isFishingSpotTile (view, tileX, tileY)
2453{
2454 const block = blockAt(view, tileX, tileY);
2455 if (!block || block.typeId !== BlockType.fishingSpot)
2456 { return false; }
2457 return block.state !== "exhausted";
2458}
2459
2460function isAnvilTile (view, tileX, tileY)
2461{
2462 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2463}
2464
2465function isJeweleringStationTile (view, tileX, tileY)
2466{
2467 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2468}
2469
2470function isGroundWoodLog (ground)
2471{
2472 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2473 return def?.familyId === ItemFamilyId.log;
2474}
2475
2476function playerHasUsableTinderbox ()
2477{
2478 const slots = inventory?.getInventorySlots?.() ?? [];
2479 for (const slot of slots)
2480 {
2481 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2482 { continue; }
2483 const charges = slot.instance?.kind === "tinderbox"
2484 ? (slot.instance.charges | 0)
2485 : TINDERBOX_MAX_CHARGES;
2486 if (charges > 0)
2487 { return true; }
2488 }
2489 return false;
2490}
2491
2492function isWoodworkingBenchTile (view, tileX, tileY)
2493{
2494 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2495}
2496
2497function isCraftingBenchTile (view, tileX, tileY)
2498{
2499 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
2500}
2501
2502function isSpinningWheelTile (view, tileX, tileY)
2503{
2504 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
2505}
2506
2507function isLoomTile (view, tileX, tileY)
2508{
2509 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
2510}
2511
2512function isTailorBenchTile (view, tileX, tileY)
2513{
2514 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
2515}
2516
2517function isLeatherworkingTableTile (view, tileX, tileY)
2518{
2519 return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable;
2520}
2521
2522function isOreBoulderTile (view, tileX, tileY)
2523{
2524 const block = blockAt(view, tileX, tileY);
2525 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
2526}
2527
2528function isChopableTreeTile (view, tileX, tileY)
2529{
2530 return isChopableTreeBlock(blockAt(view, tileX, tileY));
2531}
2532
2533function isPickablePlantTile (view, tileX, tileY)
2534{
2535 return isPickablePlantBlock(blockAt(view, tileX, tileY));
2536}
2537
2538const SPELL_ENTITY_SNAP_TILES = 2;
2539
2540function updateSpellTargetHighlight ()
2541{
2542 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
2543 {
2544 view?.clearSpellTargetHighlight();
2545 return;
2546 }
2547 const canvas = scene?.canvas;
2548 if (!canvas)
2549 { return; }
2550 const rect = canvas.getBoundingClientRect();
2551 const mouseX = GameInput.mousePosition.x - rect.left;
2552 const mouseY = GameInput.mousePosition.y - rect.top;
2553 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2554 {
2555 view.clearSpellTargetHighlight();
2556 return;
2557 }
2558 const armed = spells.getArmedSpell?.();
2559 const local = view.entities.get(view.localEntityId);
2560 if (armed?.target === "entity")
2561 {
2562 const target = nearestSpellEntityAtCursor(mouseX, mouseY);
2563 if (!target)
2564 {
2565 view.clearSpellTargetHighlight();
2566 return;
2567 }
2568 const inRange = !local
2569 || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) <= COMBAT_RANGE_TILES;
2570 view.setSpellEntityTargetHighlight(target.entityId, inRange);
2571 return;
2572 }
2573 const tile = view.screenToTile(mouseX, mouseY);
2574 const inRange = !local
2575 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
2576 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
2577}
2578
2579/**
2580 * Nearest spell-targetable entity within {@link SPELL_ENTITY_SNAP_TILES} of the
2581 * cursor tile (uses both authoritative and visual tile for moving mobs).
2582 */
2583function nearestSpellEntityAtCursor (mouseX, mouseY)
2584{
2585 if (!view)
2586 { return null; }
2587 const cursor = view.screenToTile(mouseX, mouseY);
2588 const tileSize = view.tileSize();
2589 let best = null;
2590 let bestDist = Infinity;
2591 let bestScreen = Infinity;
2592 for (const entity of view.entities.values())
2593 {
2594 if (!isSpellEntityTarget(entity))
2595 { continue; }
2596 const visualTileX = Math.floor((entity.visualX + (entity.stackOffsetX ?? 0)) / tileSize);
2597 const visualTileY = Math.floor((entity.visualY + (entity.stackOffsetY ?? 0)) / tileSize);
2598 const dist = Math.min(
2599 chebyshev(cursor.tileX, cursor.tileY, entity.tileX, entity.tileY),
2600 chebyshev(cursor.tileX, cursor.tileY, visualTileX, visualTileY)
2601 );
2602 if (dist > SPELL_ENTITY_SNAP_TILES)
2603 { continue; }
2604 const box = view.nametagAnchor?.(entity);
2605 const screenDist = box
2606 ? Math.hypot(box.x - mouseX, box.y - mouseY)
2607 : dist;
2608 if (dist < bestDist || (dist === bestDist && screenDist < bestScreen))
2609 {
2610 best = entity;
2611 bestDist = dist;
2612 bestScreen = screenDist;
2613 }
2614 }
2615 return best;
2616}
2617
2618function isSpellEntityTarget (entity)
2619{
2620 if (!entity || entity.entityId === view?.localEntityId)
2621 { return false; }
2622 if (entity.untargetable || entity.freeFlight)
2623 { return false; }
2624 return isAttackableEntity(entity);
2625}
2626
2627function hideWorldTooltip ()
2628{
2629 if (worldTooltip)
2630 {
2631 worldTooltip.hidden = true;
2632 worldTooltip.classList.remove("friend-name");
2633 worldTooltip.style.color = "";
2634 }
2635}
2636
2637/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
2638function updateWorldTooltip ()
2639{
2640 if (!worldTooltip || !view || !scene || uiBlocked())
2641 {
2642 hideWorldTooltip();
2643 return;
2644 }
2645 const canvas = scene.canvas;
2646 const rect = canvas.getBoundingClientRect();
2647 const mouseX = GameInput.mousePosition.x - rect.left;
2648 const mouseY = GameInput.mousePosition.y - rect.top;
2649 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2650 {
2651 hideWorldTooltip();
2652 return;
2653 }
2654 const entity = view.entityAtScreen(mouseX, mouseY);
2655 if (entity && entity.entityId !== view.localEntityId)
2656 {
2657 const label = entityLabel(entity);
2658 worldTooltip.hidden = false;
2659 worldTooltip.textContent = label;
2660 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2661 worldTooltip.classList.toggle("friend-name", !!friend);
2662 worldTooltip.style.color = friend ? "#e8c84a" : "";
2663 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2664 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2665 return;
2666 }
2667 const tile = view.screenToTile(mouseX, mouseY);
2668 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
2669 if (!label)
2670 {
2671 hideWorldTooltip();
2672 return;
2673 }
2674 worldTooltip.hidden = false;
2675 worldTooltip.textContent = label;
2676 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2677 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2678}
2679
2680function blockTypeAt (view, tileX, tileY)
2681{
2682 return blockAt(view, tileX, tileY)?.typeId ?? null;
2683}
2684
2685function blockAt (view, tileX, tileY)
2686{
2687 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2688 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2689 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2690 if (!snapshot)
2691 { return null; }
2692 const localX = tileX - chunkX * CHUNK_SIZE;
2693 const localY = tileY - chunkY * CHUNK_SIZE;
2694 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
2695}
2696
2697function groundTypeAt (view, tileX, tileY)
2698{
2699 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2700 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2701 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2702 if (!snapshot)
2703 { return null; }
2704 const localX = tileX - chunkX * CHUNK_SIZE;
2705 const localY = tileY - chunkY * CHUNK_SIZE;
2706 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
2707}
2708
2709/** Best-effort client filter for approach destinations (server still authorizes paths). */
2710function isClientApproachable (tileX, tileY)
2711{
2712 if (!view)
2713 { return true; }
2714 const groundId = groundTypeAt(view, tileX, tileY);
2715 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
2716 if (groundDef && !groundDef.passable)
2717 { return false; }
2718 const block = blockAt(view, tileX, tileY);
2719 if (block?.typeId != null)
2720 {
2721 const blockDef = BLOCK_DEFINITIONS[block.typeId];
2722 if (blockDef && !blockDef.passable)
2723 { return false; }
2724 }
2725 for (const entity of view.entitiesAtTile(tileX, tileY))
2726 {
2727 if (entity.entityId === view.localEntityId)
2728 { continue; }
2729 if (entity.untargetable || entity.freeFlight)
2730 { continue; }
2731 return false;
2732 }
2733 return true;
2734}
2735
2736function chebyshev (ax, ay, bx, by)
2737{
2738 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
2739}
2740
2741function updateAuthUi (authStatus)
2742{
2743 const signIn = document.getElementById("auth-sign-in");
2744 const signOut = document.getElementById("auth-sign-out");
2745 const exportLink = document.getElementById("auth-export");
2746 if (signIn)
2747 {
2748 signIn.hidden = !!authStatus?.authenticated;
2749 signIn.href = loginUrl("/");
2750 }
2751 if (signOut)
2752 {
2753 signOut.hidden = !authStatus?.authenticated;
2754 signOut.href = logoutUrl("/");
2755 }
2756 if (exportLink)
2757 { exportLink.hidden = !authStatus?.authenticated; }
2758 if (createCharacterOpen)
2759 { createCharacterOpen.hidden = !authStatus?.authenticated; }
2760 if (authStatus?.authenticated && !session)
2761 {
2762 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
2763 }
2764}