BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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