BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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