BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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