BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 63.3 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 spells = initSpells({
1380 socket: { send (payload) { socket.send(payload); } },
1381 MessageType
1382 });
1383 crafting = initCrafting({
1384 socket: { send (payload) { socket.send(payload); } },
1385 MessageType,
1386 getInventorySlots ()
1387 {
1388 return inventory?.getInventorySlots?.() ?? [];
1389 },
1390 getSkillLevel (skillId)
1391 {
1392 return skills?.skillLevel?.(skillId) ?? 1;
1393 }
1394 });
1395 alchemy = initAlchemy({
1396 socket: { send (payload) { socket.send(payload); } },
1397 MessageType,
1398 getInventorySlots ()
1399 {
1400 return inventory?.getInventorySlots?.() ?? [];
1401 }
1402 });
1403 staminaUi = initStamina();
1404 healthUi = initHealth();
1405 statusEffectsUi = initStatusEffects();
1406 toasts = initToasts();
1407 questsUi = initQuests({
1408 socket: { send (payload) { socket.send(payload); } },
1409 MessageType,
1410 toasts
1411 });
1412 dialogueUi = initDialogue({
1413 socket: { send (payload) { socket.send(payload); } },
1414 MessageType,
1415 getEntity (id)
1416 {
1417 if (id === "local")
1418 { return view?.entities.get(view.localEntityId) ?? null; }
1419 return view?.entities.get(id) ?? null;
1420 },
1421 captureSpeakerIcon (entityId, size = 64)
1422 {
1423 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1424 }
1425 });
1426 shop = initShop({
1427 socket: { send (payload) { socket.send(payload); } },
1428 MessageType,
1429 onSuppressWorldClick: consumeWorldClick,
1430 getCoinCount ()
1431 {
1432 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1433 },
1434 getInventorySlots ()
1435 {
1436 return inventory?.getInventorySlots?.() ?? [];
1437 }
1438 });
1439 market = initMarket({
1440 socket: { send (payload) { socket.send(payload); } },
1441 MessageType,
1442 onSuppressWorldClick: consumeWorldClick,
1443 getCoinCount ()
1444 {
1445 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1446 },
1447 getInventorySlots ()
1448 {
1449 return inventory?.getInventorySlots?.() ?? [];
1450 },
1451 getLocalCharacterId ()
1452 {
1453 return inventory?.getLocalCharacterId?.() ?? null;
1454 }
1455 });
1456 bounty = initBounty({
1457 socket: { send (payload) { socket.send(payload); } },
1458 MessageType,
1459 onSuppressWorldClick: consumeWorldClick,
1460 resolveSpriteUrl (name)
1461 {
1462 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1463 }
1464 });
1465 barber = initBarber({
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 getInventoryBag ()
1474 {
1475 return {
1476 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1477 inventory: inventory?.getInventorySlots?.() ?? []
1478 };
1479 }
1480 });
1481 chat = initChat({
1482 socket: { send (payload) { socket.send(payload); } },
1483 MessageType,
1484 getSettings: () => view?.settings
1485 });
1486 death = initDeath({
1487 socket: { send (payload) { socket.send(payload); } },
1488 MessageType
1489 });
1490 game.startGame();
1491 useNearestNeighbour(scene, game.images);
1492
1493 socket = new GameSocket(defaultSocketUrl(), (message) =>
1494 {
1495 switch (message.type)
1496 {
1497 case MessageType.session:
1498 session = message;
1499 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1500 renderCharacters(message.characters);
1501 break;
1502 case MessageType.characterList:
1503 renderCharacters(message.characters);
1504 if (!playing)
1505 { overlay.hidden = false; }
1506 break;
1507 case MessageType.enterWorld:
1508 closeCreateModal();
1509 startPlay(message);
1510 inventory?.setLocalCharacterId(message.characterId);
1511 toasts?.applyRestartStatus?.(message.restartStatus);
1512 socket.send({ type: MessageType.requestQuests });
1513 break;
1514 case MessageType.chunkSnapshot:
1515 view?.applySnapshot(message);
1516 break;
1517 case MessageType.dimensionChanged:
1518 if (view)
1519 {
1520 view.setDimensionId(message.dimensionId);
1521 view.setDimensionModes(message.lightingMode, message.seasonMode);
1522 view.clearAllChunks();
1523 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1524 {
1525 view.moveEntity({
1526 entityId: view.localEntityId,
1527 tileX: message.tileX,
1528 tileY: message.tileY
1529 });
1530 }
1531 }
1532 closeOpenUiIfTooFar();
1533 break;
1534 case MessageType.chunkDelta:
1535 for (const tile of message.tiles ?? [])
1536 {
1537 view?.updateAuthoredTile(
1538 message.chunkX,
1539 message.chunkY,
1540 tile.localX,
1541 tile.localY,
1542 { ground: tile.ground, block: tile.block, light: tile.light }
1543 );
1544 }
1545 break;
1546 case MessageType.unsubscribeChunk:
1547 view?.removeChunk(message.chunkX, message.chunkY);
1548 break;
1549 case MessageType.entitySpawn:
1550 view?.spawnEntity(message);
1551 break;
1552 case MessageType.entityMove:
1553 view?.moveEntity(message);
1554 if (message.entityId === view?.localEntityId)
1555 {
1556 if (message.gait)
1557 {
1558 gait = message.gait;
1559 document.getElementById("gait").textContent = gait;
1560 }
1561 closeOpenUiIfTooFar();
1562 }
1563 else if (
1564 uiFocus?.entityId != null
1565 && message.entityId === uiFocus.entityId
1566 )
1567 { closeOpenUiIfTooFar(); }
1568 break;
1569 case MessageType.entityDespawn:
1570 view?.despawnEntity(message.entityId);
1571 break;
1572 case MessageType.entityAppearance:
1573 view?.setAppearance(message);
1574 break;
1575 case MessageType.entitySkull:
1576 view?.updateEntitySkull(message.entityId, message.skullValue);
1577 break;
1578 case MessageType.groundItemAppear:
1579 view?.upsertGroundItem(message);
1580 break;
1581 case MessageType.groundItemDespawn:
1582 view?.despawnGroundItem(message.groundItemId);
1583 break;
1584 case MessageType.inventory:
1585 inventory?.handleInventory(message);
1586 crafting?.refresh();
1587 alchemy?.refresh();
1588 shop?.refresh();
1589 market?.refresh();
1590 break;
1591 case MessageType.skills:
1592 skills?.render(message.skills);
1593 crafting?.refresh();
1594 break;
1595 case MessageType.spells:
1596 case MessageType.spellsUpdated:
1597 spells?.render(message);
1598 break;
1599 case MessageType.spellArmed:
1600 spells?.handleSpellArmed(message);
1601 break;
1602 case MessageType.spellDisarmed:
1603 spells?.handleSpellDisarmed();
1604 break;
1605 case MessageType.spellProjectile:
1606 view?.spawnSpellProjectileFx(message);
1607 break;
1608 case MessageType.spellFizzle:
1609 view?.spawnSpellFizzleFx(message);
1610 if (message.casterId === view?.localEntityId)
1611 { toasts?.show("Failed to cast spell"); }
1612 break;
1613 case MessageType.spellCastFlash:
1614 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
1615 break;
1616 case MessageType.spellLightAppear:
1617 case MessageType.spellLightUpdate:
1618 view?.setSpellLight(message);
1619 break;
1620 case MessageType.spellLightRemove:
1621 view?.removeSpellLight(message);
1622 break;
1623 case MessageType.spellDarkAppear:
1624 case MessageType.spellDarkUpdate:
1625 view?.setSpellDark(message);
1626 break;
1627 case MessageType.spellDarkRemove:
1628 view?.removeSpellDark(message);
1629 break;
1630 case MessageType.stamina:
1631 staminaUi?.apply(message);
1632 if (message.gait)
1633 {
1634 gait = message.gait;
1635 document.getElementById("gait").textContent = gait;
1636 }
1637 break;
1638 case MessageType.statusEffects:
1639 view?.setLocalBlind(!!message.blind);
1640 statusEffectsUi?.apply(message);
1641 break;
1642 case MessageType.bankSnapshot:
1643 inventory?.handleBank(message);
1644 break;
1645 case MessageType.cauldronSnapshot:
1646 if (message.open === false && uiFocus?.kind === "cauldron")
1647 { clearUiFocus(); }
1648 alchemy?.handleSnapshot(message);
1649 break;
1650 case MessageType.pigeonDispatched:
1651 inventory?.handlePigeonDispatched(message);
1652 break;
1653 case MessageType.pigeonDelivered:
1654 inventory?.handlePigeonDelivered(message);
1655 break;
1656 case MessageType.characterSearchResult:
1657 inventory?.handleCharacterSearch(message);
1658 break;
1659 case MessageType.craftResult:
1660 crafting?.handleCraftResult(message);
1661 break;
1662 case MessageType.worldStatus:
1663 if (view)
1664 {
1665 view.setSettings(message.settings ?? view.settings);
1666 view.worldHour = message.worldTime?.hour ?? view.worldHour;
1667 view.setWorldSeason(message.worldTime?.season);
1668 chat?.syncSettings();
1669 }
1670 toasts?.applyRestartStatus?.(message.restartStatus);
1671 break;
1672 case MessageType.restartStatus:
1673 toasts?.applyRestartStatus?.(message.restartStatus);
1674 break;
1675 case MessageType.chatBubble:
1676 chat?.showBubble(message);
1677 break;
1678 case MessageType.friends:
1679 social?.handleFriends(message);
1680 break;
1681 case MessageType.combatSwing:
1682 view?.spawnCombatSwing(message);
1683 break;
1684 case MessageType.combatProjectile:
1685 view?.spawnPhysicalProjectileFx({
1686 ...message,
1687 sprite: "fx:projectile:arrow"
1688 });
1689 break;
1690 case MessageType.combatNoArrows:
1691 toasts?.show("Out of arrows!");
1692 break;
1693 case MessageType.gatherSwing:
1694 case MessageType.tileShove:
1695 view?.spawnGatherSwing(message);
1696 break;
1697 case MessageType.stationOpen:
1698 if (message.stationId)
1699 { crafting?.openStation(message.stationId); }
1700 break;
1701 case MessageType.shopOpen:
1702 if (message.npcEntityId != null)
1703 { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); }
1704 shop?.handleShopOpen(message);
1705 break;
1706 case MessageType.shopClosed:
1707 if (uiFocus?.kind === "shop")
1708 { clearUiFocus(); }
1709 shop?.handleShopClosed(message);
1710 break;
1711 case MessageType.marketOpen:
1712 market?.handleOpen(message);
1713 break;
1714 case MessageType.marketClosed:
1715 if (uiFocus?.kind === "market")
1716 { clearUiFocus(); }
1717 market?.handleClosed(message);
1718 break;
1719 case MessageType.marketTrade:
1720 market?.handleTrade(message);
1721 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
1722 break;
1723 case MessageType.bountySnapshot:
1724 bounty?.handleSnapshot(message);
1725 break;
1726 case MessageType.closeBounty:
1727 if (uiFocus?.kind === "bounty")
1728 { clearUiFocus(); }
1729 bounty?.handleClosed(message);
1730 break;
1731 case MessageType.characterBounty:
1732 bounty?.handleCharacterBounty(message);
1733 social?.handleCharacterBounty(message);
1734 break;
1735 case MessageType.barberSnapshot:
1736 barber?.handleSnapshot(message);
1737 break;
1738 case MessageType.closeBarber:
1739 if (uiFocus?.kind === "barber")
1740 { clearUiFocus(); }
1741 barber?.handleClosed(message);
1742 break;
1743 case MessageType.itemBubble:
1744 chat?.showItemBubble(message);
1745 break;
1746 case MessageType.gatherComplete:
1747 crafting?.refresh();
1748 break;
1749 case MessageType.combatHit:
1750 {
1751 const applyHit = () =>
1752 {
1753 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1754 view?.flashDamage(message.targetId);
1755 view?.spawnDamageNumber(message.targetId, message.damage);
1756 if (message.targetId === view?.localEntityId)
1757 {
1758 healthUi?.apply({
1759 current: message.health,
1760 max: message.maxHealth
1761 });
1762 }
1763 };
1764 if (!view?.deferCombatHit?.(message, applyHit))
1765 { applyHit(); }
1766 break;
1767 }
1768 case MessageType.combatMiss:
1769 view?.markProjectileMiss?.(message);
1770 break;
1771 case MessageType.combatBlock:
1772 {
1773 const applyBlock = () =>
1774 {
1775 view?.flashDamage(message.targetId);
1776 if (message.health != null)
1777 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
1778 };
1779 if (!view?.deferCombatHit?.(message, applyBlock))
1780 { applyBlock(); }
1781 break;
1782 }
1783 case MessageType.entityHealth:
1784 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1785 if (message.entityId === view?.localEntityId)
1786 {
1787 healthUi?.apply({
1788 current: message.health,
1789 max: message.maxHealth
1790 });
1791 }
1792 break;
1793 case MessageType.skillLevelUp:
1794 view?.spawnSkillLevelUp(message.entityId, message);
1795 if (message.entityId === view?.localEntityId)
1796 {
1797 const name = message.displayName ?? message.skillId ?? "Skill";
1798 toasts?.show(`${name} level ${message.level}!`);
1799 }
1800 break;
1801 case MessageType.playerDied:
1802 clearAllPendingActions();
1803 contextMenu?.hide();
1804 death?.show();
1805 if (message.entityId === view?.localEntityId)
1806 {
1807 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
1808 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
1809 }
1810 break;
1811 case MessageType.playerRespawned:
1812 death?.hide();
1813 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1814 if (message.entityId === view?.localEntityId)
1815 {
1816 healthUi?.apply({
1817 current: message.health,
1818 max: message.maxHealth
1819 });
1820 }
1821 if (message.stamina != null || message.maxStamina != null)
1822 {
1823 staminaUi?.apply({
1824 current: message.stamina ?? staminaUi.getCurrent?.(),
1825 max: message.maxStamina ?? staminaUi.getMax?.()
1826 });
1827 }
1828 break;
1829 case MessageType.error:
1830 if (playing)
1831 { toasts?.show(message.message); }
1832 else
1833 {
1834 const createPanel = document.getElementById("create-panel");
1835 const createError = document.getElementById("create-error");
1836 if (createPanel && !createPanel.hidden && createError)
1837 { createError.textContent = message.message ?? ""; }
1838 else
1839 { showError(message.message); }
1840 }
1841 social?.showError(message.message);
1842 break;
1843 case MessageType.toast:
1844 if (playing)
1845 { toasts?.show(message.message); }
1846 break;
1847 case MessageType.questsSnapshot:
1848 questsUi?.applySnapshot(message);
1849 break;
1850 case MessageType.questStepComplete:
1851 questsUi?.handleStepComplete(message);
1852 break;
1853 case MessageType.dialogueStep:
1854 if (message.npcEntityId != null)
1855 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
1856 dialogueUi?.handleStep(message);
1857 break;
1858 case MessageType.dialogueChoices:
1859 if (message.npcEntityId != null)
1860 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
1861 dialogueUi?.handleChoices(message);
1862 break;
1863 case MessageType.dialogueClose:
1864 if (uiFocus?.kind === "dialogue")
1865 { clearUiFocus(); }
1866 dialogueUi?.handleClose(message);
1867 break;
1868 case MessageType.forceLogout:
1869 returnToMenu(message.reason);
1870 break;
1871 }
1872 }, {
1873 onClose (event)
1874 {
1875 if (playing)
1876 { returnToMenu(event.reason || "Disconnected from server."); }
1877 }
1878 });
1879 await socket.connect();
1880 if (typeof window !== "undefined")
1881 {
1882 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
1883 {
1884 crafting?.openStation(stationId);
1885 };
1886 }
1887}
1888
1889function returnToMenu (reason = "")
1890{
1891 playing = false;
1892 clearAllPendingActions();
1893 clearUiFocus();
1894 social?.reset();
1895 chat?.reset();
1896 inventory?.reset();
1897 crafting?.reset();
1898 alchemy?.reset();
1899 staminaUi?.hide();
1900 healthUi?.hide();
1901 statusEffectsUi?.hide();
1902 skills?.hide();
1903 spells?.hide();
1904 contextMenu?.hide();
1905 death?.reset();
1906 shop?.close({ notifyServer: false });
1907 bounty?.close();
1908 barber?.close();
1909 questsUi?.reset();
1910 dialogueUi?.reset();
1911 hideWorldTooltip();
1912 if (view)
1913 { view.clearPlaySession(); }
1914 overlay.hidden = false;
1915 hud.hidden = true;
1916 const settingsToggle = document.getElementById("settings-toggle");
1917 if (settingsToggle)
1918 { settingsToggle.hidden = true; }
1919 graphicsSettingsUi?.close();
1920 if (reason)
1921 { statusEl.textContent = reason; }
1922}
1923
1924document.getElementById("create-character-open")?.addEventListener("click", () =>
1925{
1926 showError("");
1927 const createError = document.getElementById("create-error");
1928 if (createError)
1929 { createError.textContent = ""; }
1930 document.getElementById("create-backdrop").hidden = false;
1931 document.getElementById("create-panel").hidden = false;
1932 setCreateTab("appearance");
1933 void createHairControls?.refreshPreview();
1934});
1935
1936function closeCreateModal ()
1937{
1938 document.getElementById("create-backdrop").hidden = true;
1939 document.getElementById("create-panel").hidden = true;
1940}
1941
1942document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
1943document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
1944
1945document.getElementById("create-form").addEventListener("submit", (event) =>
1946{
1947 event.preventDefault();
1948 showError("");
1949 const createError = document.getElementById("create-error");
1950 if (createError)
1951 { createError.textContent = ""; }
1952 socket.send({
1953 type: MessageType.createCharacter,
1954 firstName: document.getElementById("first-name").value,
1955 lastName: document.getElementById("last-name").value,
1956 sex: document.getElementById("sex").value,
1957 hair: createHairControls?.currentHair?.() ?? null,
1958 clothing: createClothingControls?.currentClothing?.() ?? null
1959 });
1960});
1961
1962function initCreateTabs ()
1963{
1964 const tabs = document.querySelectorAll(".create-tab");
1965 for (const tab of tabs)
1966 {
1967 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
1968 }
1969 setCreateTab("appearance");
1970}
1971
1972function setCreateTab (name)
1973{
1974 createActiveTab = name === "clothing" ? "clothing" : "appearance";
1975 for (const tab of document.querySelectorAll(".create-tab"))
1976 {
1977 const on = tab.dataset.createTab === createActiveTab;
1978 tab.classList.toggle("active", on);
1979 tab.setAttribute("aria-selected", on ? "true" : "false");
1980 }
1981 for (const pane of document.querySelectorAll("[data-create-pane]"))
1982 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
1983 if (createActiveTab === "clothing")
1984 { void refreshCreateClothingPreview(); }
1985 else
1986 { void createHairControls?.refreshPreview(); }
1987}
1988
1989async function refreshCreateClothingPreview ()
1990{
1991 const canvas = document.getElementById("create-clothing-preview");
1992 if (!canvas || !createClothingControls)
1993 { return; }
1994 try
1995 {
1996 await paintCharacterPreview(canvas, {
1997 sex: document.getElementById("sex")?.value ?? "male",
1998 bag: createClothingControls.previewBag(),
1999 hair: createHairControls?.currentHair?.() ?? null,
2000 hideHeadgear: true,
2001 resolveSpriteUrl (name)
2002 {
2003 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2004 },
2005 scale: 4
2006 });
2007 }
2008 catch (error)
2009 { console.warn(error); }
2010}
2011
2012document.getElementById("leave").addEventListener("click", () =>
2013{
2014 socket.send({ type: MessageType.leaveWorld });
2015 returnToMenu();
2016});
2017
2018main().catch((error) =>
2019{
2020 showError(error.message);
2021 console.error(error);
2022});
2023
2024function isBankTile (view, tileX, tileY)
2025{
2026 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
2027}
2028
2029function isDoorwayTile (view, tileX, tileY)
2030{
2031 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
2032}
2033
2034function isMarketplaceTile (view, tileX, tileY)
2035{
2036 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
2037}
2038
2039function isBountyOfficeTile (view, tileX, tileY)
2040{
2041 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
2042}
2043
2044function isBarberTile (view, tileX, tileY)
2045{
2046 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
2047}
2048
2049function isCauldronTile (view, tileX, tileY)
2050{
2051 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2052}
2053
2054function isFurnaceTile (view, tileX, tileY)
2055{
2056 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2057}
2058
2059function isOvenTile (view, tileX, tileY)
2060{
2061 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2062}
2063
2064function isCampfireTile (view, tileX, tileY)
2065{
2066 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2067}
2068
2069function isFishingSpotTile (view, tileX, tileY)
2070{
2071 const block = blockAt(view, tileX, tileY);
2072 if (!block || block.typeId !== BlockType.fishingSpot)
2073 { return false; }
2074 return block.state !== "exhausted";
2075}
2076
2077function isAnvilTile (view, tileX, tileY)
2078{
2079 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2080}
2081
2082function isJeweleringStationTile (view, tileX, tileY)
2083{
2084 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2085}
2086
2087function isGroundWoodLog (ground)
2088{
2089 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2090 return def?.familyId === ItemFamilyId.log;
2091}
2092
2093function playerHasUsableTinderbox ()
2094{
2095 const slots = inventory?.getInventorySlots?.() ?? [];
2096 for (const slot of slots)
2097 {
2098 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2099 { continue; }
2100 const charges = slot.instance?.kind === "tinderbox"
2101 ? (slot.instance.charges | 0)
2102 : TINDERBOX_MAX_CHARGES;
2103 if (charges > 0)
2104 { return true; }
2105 }
2106 return false;
2107}
2108
2109function isWoodworkingBenchTile (view, tileX, tileY)
2110{
2111 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2112}
2113
2114function isCraftingBenchTile (view, tileX, tileY)
2115{
2116 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
2117}
2118
2119function isSpinningWheelTile (view, tileX, tileY)
2120{
2121 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
2122}
2123
2124function isLoomTile (view, tileX, tileY)
2125{
2126 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
2127}
2128
2129function isTailorBenchTile (view, tileX, tileY)
2130{
2131 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
2132}
2133
2134function isLeatherworkingTableTile (view, tileX, tileY)
2135{
2136 return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable;
2137}
2138
2139function isOreBoulderTile (view, tileX, tileY)
2140{
2141 const block = blockAt(view, tileX, tileY);
2142 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
2143}
2144
2145function isChopableTreeTile (view, tileX, tileY)
2146{
2147 return isChopableTreeBlock(blockAt(view, tileX, tileY));
2148}
2149
2150function isPickablePlantTile (view, tileX, tileY)
2151{
2152 return isPickablePlantBlock(blockAt(view, tileX, tileY));
2153}
2154
2155function updateSpellTargetHighlight ()
2156{
2157 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
2158 {
2159 view?.clearSpellTargetHighlight();
2160 return;
2161 }
2162 const canvas = scene?.canvas;
2163 if (!canvas)
2164 { return; }
2165 const rect = canvas.getBoundingClientRect();
2166 const mouseX = GameInput.mousePosition.x - rect.left;
2167 const mouseY = GameInput.mousePosition.y - rect.top;
2168 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2169 {
2170 view.clearSpellTargetHighlight();
2171 return;
2172 }
2173 const tile = view.screenToTile(mouseX, mouseY);
2174 const local = view.entities.get(view.localEntityId);
2175 const inRange = !local
2176 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
2177 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
2178}
2179
2180function hideWorldTooltip ()
2181{
2182 if (worldTooltip)
2183 {
2184 worldTooltip.hidden = true;
2185 worldTooltip.classList.remove("friend-name");
2186 worldTooltip.style.color = "";
2187 }
2188}
2189
2190/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
2191function updateWorldTooltip ()
2192{
2193 if (!worldTooltip || !view || !scene || uiBlocked())
2194 {
2195 hideWorldTooltip();
2196 return;
2197 }
2198 const canvas = scene.canvas;
2199 const rect = canvas.getBoundingClientRect();
2200 const mouseX = GameInput.mousePosition.x - rect.left;
2201 const mouseY = GameInput.mousePosition.y - rect.top;
2202 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2203 {
2204 hideWorldTooltip();
2205 return;
2206 }
2207 const entity = view.entityAtScreen(mouseX, mouseY);
2208 if (entity && entity.entityId !== view.localEntityId)
2209 {
2210 const label = entityLabel(entity);
2211 worldTooltip.hidden = false;
2212 worldTooltip.textContent = label;
2213 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2214 worldTooltip.classList.toggle("friend-name", !!friend);
2215 worldTooltip.style.color = friend ? "#e8c84a" : "";
2216 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2217 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2218 return;
2219 }
2220 const tile = view.screenToTile(mouseX, mouseY);
2221 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
2222 if (!label)
2223 {
2224 hideWorldTooltip();
2225 return;
2226 }
2227 worldTooltip.hidden = false;
2228 worldTooltip.textContent = label;
2229 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2230 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2231}
2232
2233function blockTypeAt (view, tileX, tileY)
2234{
2235 return blockAt(view, tileX, tileY)?.typeId ?? null;
2236}
2237
2238function blockAt (view, tileX, tileY)
2239{
2240 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2241 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2242 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2243 if (!snapshot)
2244 { return null; }
2245 const localX = tileX - chunkX * CHUNK_SIZE;
2246 const localY = tileY - chunkY * CHUNK_SIZE;
2247 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
2248}
2249
2250function groundTypeAt (view, tileX, tileY)
2251{
2252 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2253 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2254 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2255 if (!snapshot)
2256 { return null; }
2257 const localX = tileX - chunkX * CHUNK_SIZE;
2258 const localY = tileY - chunkY * CHUNK_SIZE;
2259 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
2260}
2261
2262/** Best-effort client filter for approach destinations (server still authorizes paths). */
2263function isClientApproachable (tileX, tileY)
2264{
2265 if (!view)
2266 { return true; }
2267 const groundId = groundTypeAt(view, tileX, tileY);
2268 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
2269 if (groundDef && !groundDef.passable)
2270 { return false; }
2271 const block = blockAt(view, tileX, tileY);
2272 if (block?.typeId != null)
2273 {
2274 const blockDef = BLOCK_DEFINITIONS[block.typeId];
2275 if (blockDef && !blockDef.passable)
2276 { return false; }
2277 }
2278 for (const entity of view.entitiesAtTile(tileX, tileY))
2279 {
2280 if (entity.entityId === view.localEntityId)
2281 { continue; }
2282 if (entity.untargetable || entity.freeFlight)
2283 { continue; }
2284 return false;
2285 }
2286 return true;
2287}
2288
2289function chebyshev (ax, ay, bx, by)
2290{
2291 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
2292}
2293
2294function updateAuthUi (authStatus)
2295{
2296 const signIn = document.getElementById("auth-sign-in");
2297 const signOut = document.getElementById("auth-sign-out");
2298 const exportLink = document.getElementById("auth-export");
2299 if (signIn)
2300 {
2301 signIn.hidden = !!authStatus?.authenticated;
2302 signIn.href = loginUrl("/");
2303 }
2304 if (signOut)
2305 {
2306 signOut.hidden = !authStatus?.authenticated;
2307 signOut.href = logoutUrl("/");
2308 }
2309 if (exportLink)
2310 { exportLink.hidden = !authStatus?.authenticated; }
2311 if (authStatus?.authenticated && !session)
2312 {
2313 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
2314 }
2315}