BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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