BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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