BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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