BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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