BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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