import { defaultLeftClickEntityAction, preferAttackInContextMenu } from "/shared/combat/entityClick.js"; import { MessageType, GAIT, CHUNK_SIZE, STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js"; import { validateCharacterNames } from "/shared/characters/names.js"; import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js"; import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock, plantGatherForBlock } from "/shared/definitions/tiles.js"; import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js"; import { findPathToNearestGoal } from "/shared/navigation/bfs.js"; import { isAdjacentTile, canTalkOrShopNear } from "/shared/navigation/adjacency.js"; import { GameSocket, defaultSocketUrl } from "../net/socket.js"; import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js"; import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js"; import { WorldView } from "../render/worldView.js"; import { initSocial } from "./social.js"; import { initChat } from "./chat.js"; import { initInventory } from "./inventory.js"; import { initSkills } from "./skills.js"; import { initSpells } from "./spells.js"; import { initCrafting } from "./crafting.js"; import { initAlchemy } from "./alchemy.js"; import { initTipArrows } from "./tipArrows.js"; import { initStamina } from "./stamina.js"; import { initHealth } from "./health.js"; import { initStatusEffects } from "./statusEffects.js"; import { initContextMenu } from "./contextMenu.js"; import { itemSpawnerOpenLabel } from "/shared/definitions/itemSpawners.js"; import { initDeath } from "./death.js"; import { initToasts } from "./toasts.js"; import { initTrade } from "./trade.js"; import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js"; import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js"; import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js"; import { initQuests } from "./quests.js"; import { initDialogue } from "./dialogue.js"; import { initShop } from "./shop.js"; import { initMarket } from "./market.js"; import { initBounty } from "./bounty.js"; import { initBarber } from "./barber.js"; import { bindHairControls } from "./hairControls.js"; import { bindCreateClothingControls } from "./createClothingControls.js"; import { paintCharacterPreview } from "./characterPreview.js"; import { initGraphicsSettings } from "./graphicsSettings.js"; import { CraftingStationId } from "/shared/definitions/craftingStations.js"; import { isOreBoulderState } from "/shared/definitions/materialTiers.js"; import { formatQuantity } from "/shared/items/formatQuantity.js"; import { ItemId, itemDefinition } from "/shared/definitions/items.js"; import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js"; import { ItemFamilyId } from "/shared/definitions/tierFamilies.js"; import { isLogDebarked } from "/shared/definitions/woodItems.js"; import { EquipmentKind } from "/shared/definitions/equipmentKinds.js"; import { countCoinsInSlots } from "/shared/items/inventory.js"; const game = new Game(); const hud = document.getElementById("hud"); const overlay = document.getElementById("overlay"); const statusEl = document.getElementById("status"); const characterList = document.getElementById("character-list"); const errorEl = document.getElementById("error"); const assetLoadEl = document.getElementById("asset-load"); const assetLoadBar = document.getElementById("asset-load-bar"); const assetLoadLabel = document.getElementById("asset-load-label"); const createCharacterOpen = document.getElementById("create-character-open"); const worldTooltip = document.getElementById("world-tooltip"); let socket; let session = null; let playing = false; let view = null; /** True when a server visual event is for another dimension than the local view. */ function isForeignDimensionMessage (message) { if (!view || message?.dimensionId == null) { return false; } return normalizeDimensionId(message.dimensionId) !== normalizeDimensionId(view.dimensionId); } let graphicsSettingsUi = null; let scene = null; let gait = GAIT.walk; let catalog = { grounds: {}, blocks: {} }; let social; let chat; let inventory; let skills; let spells; let crafting; let alchemy; let staminaUi; let healthUi; let statusEffectsUi; let contextMenu; let death; let toasts; let trade; let questsUi; let dialogueUi; let shop; let playZoomRaf = 0; let playZoomDelta = 0; let market; let bounty; let barber; let createHairControls; let createClothingControls; let createActiveTab = "appearance"; let pendingPickup = null; /** @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 } */ let pendingInteract = null; /** * Block/NPC the player currently has a station UI open for. * Closed automatically when Chebyshev distance exceeds 1. * @type {null | { kind: "bank" | "station" | "cauldron" | "market" | "bounty" | "barber", tileX: number, tileY: number } | { kind: "shop" | "dialogue", entityId: number }} */ let uiFocus = null; /** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */ let approachMove = null; /** Client-tracked follow target; server follow owns gait while this is set. */ let followTargetId = null; /** Destination of the active click/approach moveTo for autorun distance checks. */ let moveDest = null; /** Entity / tile focus for server-driven approach (attack, cast) — no client moveTo. */ let autorunFocusEntityId = null; let autorunFocusTile = null; /** After stamina hits 0 while autorunning, wait until ≥50% before running again. */ let autorunWaitingStamina = false; /** Framework can report mousePressed for two frames; latch so one physical click is one command. */ let leftClickConsumed = false; /** Mob/NPC entity ids recently trading blows with the local player (LMB prefers Attack). */ const combatWithLocalIds = new Set(); const AUTORUN_STAMINA_RESUME_RATIO = 0.5; function noteCombatWithLocal (attackerId, targetId) { const localId = view?.localEntityId; if (localId == null) { return; } const a = attackerId | 0; const t = targetId | 0; if (a === localId && t) { combatWithLocalIds.add(t); } else if (t === localId && a) { combatWithLocalIds.add(a); } } function clearCombatWithLocal (entityId = null) { if (entityId == null) { combatWithLocalIds.clear(); return; } combatWithLocalIds.delete(entityId | 0); } function leftClickContextFor (entity) { const local = view?.entities.get(view.localEntityId); const entityId = entity?.entityId | 0; return { localSkullValue: local?.skullValue | 0, skullSettings: view?.settings ?? null, inCombatWithLocal: combatWithLocalIds.has(entityId) || (autorunFocusEntityId | 0) === entityId }; } function sendPlayerMoveTo (tileX, tileY) { followTargetId = null; clearAutorunFocus(); moveDest = { tileX: tileX | 0, tileY: tileY | 0 }; socket.send({ type: MessageType.moveTo, tileX: moveDest.tileX, tileY: moveDest.tileY }); syncAutorun(); } function sendPlayerFollow (targetEntityId) { followTargetId = targetEntityId | 0; moveDest = null; clearAutorunFocus(); autorunWaitingStamina = false; socket.send({ type: MessageType.follow, targetEntityId: followTargetId }); } function clearAutorunFocus () { autorunFocusEntityId = null; autorunFocusTile = null; } function setAutorunFocusEntity (entityId) { moveDest = null; autorunFocusTile = null; autorunFocusEntityId = entityId | 0; syncAutorun(); } function setAutorunFocusTile (tileX, tileY) { moveDest = null; autorunFocusEntityId = null; autorunFocusTile = { tileX: tileX | 0, tileY: tileY | 0 }; syncAutorun(); } function resolveAutorunDest () { if (moveDest) { return moveDest; } if (autorunFocusEntityId != null) { const target = view?.entities?.get(autorunFocusEntityId); if (!target) { return null; } return { tileX: target.tileX | 0, tileY: target.tileY | 0 }; } return autorunFocusTile; } function localEntityIsMoving (local) { if (!local) { return false; } if (local.lerpStarted != null) { return true; } const dx = (local.visualX ?? 0) - (local.targetX ?? local.visualX ?? 0); const dy = (local.visualY ?? 0) - (local.targetY ?? local.visualY ?? 0); return (dx * dx + dy * dy) > 0.25; } function requestGaitIfNeeded (next) { if (next !== GAIT.walk && next !== GAIT.run) { return; } if (next === gait) { return; } if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 0) <= 0) { return; } socket.send({ type: MessageType.setGait, gait: next }); if (next === GAIT.walk) { gait = next; const el = document.getElementById("gait"); if (el) { el.textContent = gait; } } } function syncAutorun () { if (!playing || followTargetId != null) { return; } const settings = graphicsSettingsUi?.getSettings?.() ?? {}; if (settings.autorun !== "on") { return; } const local = view?.entities?.get(view.localEntityId); const dest = resolveAutorunDest(); if (!local || !dest) { return; } if (moveDest && local.tileX === moveDest.tileX && local.tileY === moveDest.tileY) { moveDest = null; autorunWaitingStamina = false; requestGaitIfNeeded(GAIT.walk); return; } // Attack / cast approach is server-pathed — only run while tiles are changing. if (!moveDest && !localEntityIsMoving(local)) { requestGaitIfNeeded(GAIT.walk); return; } const dist = chebyshev(local.tileX, local.tileY, dest.tileX, dest.tileY); const wantRun = dist > 0; const current = staminaUi?.getCurrent?.() ?? 0; const max = Math.max(1, staminaUi?.getMax?.() ?? 1); if (gait === GAIT.run && current <= 0) { autorunWaitingStamina = true; } if (autorunWaitingStamina) { if (wantRun && current / max >= AUTORUN_STAMINA_RESUME_RATIO) { autorunWaitingStamina = false; requestGaitIfNeeded(GAIT.run); } else { requestGaitIfNeeded(GAIT.walk); } return; } if (wantRun) { if (current <= 0) { autorunWaitingStamina = true; requestGaitIfNeeded(GAIT.walk); } else { requestGaitIfNeeded(GAIT.run); } } else { requestGaitIfNeeded(GAIT.walk); } } function consumeWorldClick () { leftClickConsumed = true; } function showError (message) { errorEl.textContent = message ?? ""; } function setAssetLoading (active, { loaded = 0, total = 0, phase = "" } = {}) { if (assetLoadEl) { assetLoadEl.hidden = !active; } if (characterList) { characterList.hidden = active; } if (createCharacterOpen) { createCharacterOpen.hidden = active; } if (!active) { return; } if (assetLoadBar && total > 0) { assetLoadBar.value = Math.round((loaded / total) * 100); } if (assetLoadLabel) { assetLoadLabel.textContent = phase || (total > 0 ? `Loading assets… ${loaded}/${total}` : "Loading assets…"); } } function renderCharacters (characters) { characterList.innerHTML = ""; for (const character of characters) { const row = document.createElement("div"); row.className = "character-row"; const pending = character.deletionScheduledAt ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})` : ""; row.innerHTML = `${character.firstName} ${character.lastName} · ${character.sex}${pending}`; const play = document.createElement("button"); play.textContent = "Play"; play.disabled = !!character.deletionScheduledAt; play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId })); const del = document.createElement("button"); del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete"; del.addEventListener("click", () => { socket.send({ type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter, characterId: character.characterId }); }); row.append(play, del); characterList.append(row); } } function uiBlocked () { return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking() || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking() || questsUi?.isBlocking() || dialogueUi?.isBlocking() || trade?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking() || graphicsSettingsUi?.isBlocking?.() || pointerOverSpellUi() || pointerOverToastUi()); } function pointerOverSpellUi () { const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y); if (!el) { return false; } return !!el.closest("#spells-panel, #spell-favorites-bar, #equipped-ammo-hud, #spells-toggle"); } function pointerOverToastUi () { const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y); if (!el) { return false; } return !!el.closest("#toast-stack .toast"); } function applyGraphicsSettings (settings) { view?.setGraphicsPrefs(settings); if (socket && playing) { socket.send({ type: MessageType.setGraphicsSettings, viewDistance: settings.viewDistance }); } syncAutorun(); } function clearPendingPickup () { pendingPickup = null; } function clearPendingInteract () { pendingInteract = null; approachMove = null; } function clearAllPendingActions () { clearPendingPickup(); clearPendingInteract(); } function approachAdjacentTile (tileX, tileY) { const local = view.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { approachMove = null; return true; } if (!local) { return false; } const radius = Math.max(1, STATIC_CHUNK_RADIUS | 0) * CHUNK_SIZE; const path = findPathToNearestGoal( local.tileX, local.tileY, (x, y) => chebyshev(x, y, tileX, tileY) === 1 && isClientApproachable(x, y), (x, y) => isClientApproachable(x, y), local.tileX - radius, local.tileY - radius, local.tileX + radius, local.tileY + radius ); let best = path.length ? path[path.length - 1] : null; if (!best) { // Fallback if BFS finds nothing (incomplete client map): nearest adjacent guess. let bestAny = null; let bestAnyDist = Infinity; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } const destX = tileX + dx; const destY = tileY + dy; const dist = chebyshev(local.tileX, local.tileY, destX, destY); if (dist < bestAnyDist) { bestAnyDist = dist; bestAny = { tileX: destX, tileY: destY }; } } } best = bestAny ? { x: bestAny.tileX, y: bestAny.tileY } : null; } if (!best) { return false; } const destX = best.x ?? best.tileX; const destY = best.y ?? best.tileY; if ( approachMove && approachMove.focusX === tileX && approachMove.focusY === tileY && approachMove.destX === destX && approachMove.destY === destY ) { return false; } approachMove = { focusX: tileX, focusY: tileY, destX, destY }; sendPlayerMoveTo(destX, destY); return false; } /** Walk to a stance from which talk/shop is allowed (adjacent, or over a table/counter). */ function approachTalkTarget (npcTileX, npcTileY) { const local = view.entities.get(view.localEntityId); if (!local) { return false; } const getBlockType = (x, y) => blockTypeAt(view, x, y); if (canTalkOrShopNear(local.tileX, local.tileY, npcTileX, npcTileY, getBlockType)) { approachMove = null; return true; } const radius = Math.max(1, STATIC_CHUNK_RADIUS | 0) * CHUNK_SIZE; const isStance = (x, y) => canTalkOrShopNear(x, y, npcTileX, npcTileY, getBlockType) && isClientApproachable(x, y); const path = findPathToNearestGoal( local.tileX, local.tileY, isStance, (x, y) => isClientApproachable(x, y), local.tileX - radius, local.tileY - radius, local.tileX + radius, local.tileY + radius ); let best = path.length ? path[path.length - 1] : null; if (!best) { let bestAny = null; let bestAnyDist = Infinity; for (let dy = -2; dy <= 2; dy++) { for (let dx = -2; dx <= 2; dx++) { if (dx === 0 && dy === 0) { continue; } const destX = npcTileX + dx; const destY = npcTileY + dy; if (!isStance(destX, destY)) { continue; } const dist = chebyshev(local.tileX, local.tileY, destX, destY); if (dist < bestAnyDist) { bestAnyDist = dist; bestAny = { tileX: destX, tileY: destY }; } } } best = bestAny ? { x: bestAny.tileX, y: bestAny.tileY } : null; } if (!best) { return false; } const destX = best.x ?? best.tileX; const destY = best.y ?? best.tileY; if ( approachMove && approachMove.focusX === npcTileX && approachMove.focusY === npcTileY && approachMove.destX === destX && approachMove.destY === destY ) { return false; } approachMove = { focusX: npcTileX, focusY: npcTileY, destX, destY }; sendPlayerMoveTo(destX, destY); return false; } function requestOpenBank (tileX, tileY, { getCheques = false } = {}) { clearAllPendingActions(); pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestEnterDoorway (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "doorway", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenMarket (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "market", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenBounty (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "bounty", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenBarber (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "barber", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenCauldron (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "cauldron", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestPrayAtAltar (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "pray-altar", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenFurnace (tileX, tileY) { requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY); } function requestOpenCraftStation (stationId, tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "station", stationId, tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestStartFire (ground) { if (!ground) { return; } clearAllPendingActions(); pendingInteract = { kind: "start-fire", groundItemId: ground.groundItemId, tileX: ground.tileX, tileY: ground.tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, ground.tileX, ground.tileY)) { flushPendingInteract(); } else { approachAdjacentTile(ground.tileX, ground.tileY); } } function requestOpenItemContainer (container) { if (!container) { return; } clearAllPendingActions(); pendingInteract = { kind: "open-item-container", containerId: container.containerId, tileX: container.tileX, tileY: container.tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, container.tileX, container.tileY) && !(local.tileX === container.tileX && local.tileY === container.tileY)) { flushPendingInteract(); } else { approachAdjacentTile(container.tileX, container.tileY); } } function requestDebarkLog (ground) { if (!ground) { return; } clearAllPendingActions(); pendingInteract = { kind: "debark-log", groundItemId: ground.groundItemId, tileX: ground.tileX, tileY: ground.tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, ground.tileX, ground.tileY)) { flushPendingInteract(); } else { approachAdjacentTile(ground.tileX, ground.tileY); } } function requestFish (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "fish", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestMine (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "mine", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestChop (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "chop", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestPick (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "pick", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY)) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestTalk (targetEntityId, purpose = null) { clearAllPendingActions(); pendingInteract = { kind: "talk", targetEntityId, purpose }; const target = view?.entities.get(targetEntityId); if (!target) { clearPendingInteract(); return; } if (approachTalkTarget(target.tileX, target.tileY)) { flushPendingInteract(); } } function playerHasShears () { const slots = inventory?.getInventorySlots?.() ?? []; const equipment = inventory?.getEquipment?.() ?? {}; for (const stack of [...slots, equipment.weapon]) { if (!stack?.itemId) { continue; } if (itemDefinition(stack.itemId)?.equipment?.kind === EquipmentKind.shears) { return true; } } return false; } function entityCanShear (entity) { if (!entity?.mobTypeId) { return false; } const def = mobDefinition(entity.mobTypeId); const shearable = def?.shearable; if (!shearable) { return false; } const sprite = entity.layers?.[0]?.sprite ?? entity.sprite ?? ""; if (String(sprite).endsWith(`:${shearable.shornState}`)) { return false; } return playerHasShears(); } function requestShear (targetEntityId) { clearAllPendingActions(); pendingInteract = { kind: "shear", targetEntityId }; const target = view?.entities.get(targetEntityId); if (!target) { clearPendingInteract(); return; } if (approachAdjacentTile(target.tileX, target.tileY)) { flushPendingInteract(); } } function setUiFocus (focus) { uiFocus = focus; } function clearUiFocus () { uiFocus = null; } /** Close stations, bank, dialogue, and other overlays when the local player dies. */ function closeCloseablePlayUi () { clearUiFocus(); inventory?.closeBank?.(); inventory?.closeOverlays?.(); if (crafting?.isOpen?.()) { crafting.close(); } if (alchemy?.isOpen?.()) { alchemy.close(); } if (market?.isOpen?.()) { market.close(); } if (bounty?.isOpen?.()) { bounty.close(); } if (barber?.isOpen?.()) { barber.close(); } if (shop?.isOpen?.()) { shop.close(); } if (dialogueUi?.isOpen?.()) { dialogueUi.close(); } questsUi?.hide?.(); chat?.close?.(); social?.closeOverlays?.(); contextMenu?.hide(); spells?.handleSpellDisarmed?.(); graphicsSettingsUi?.close?.(); } /** Close bank / station / NPC UIs when the player walks out of adjacency. */ function closeOpenUiIfTooFar () { if (!uiFocus || !view) { return; } const local = view.entities.get(view.localEntityId); if (!local) { return; } let tooFar = false; if (uiFocus.entityId != null) { const target = view.entities.get(uiFocus.entityId); if (!target) { tooFar = true; } else if (uiFocus.kind === "shop" || uiFocus.kind === "dialogue") { tooFar = !canTalkOrShopNear( local.tileX, local.tileY, target.tileX, target.tileY, (x, y) => blockTypeAt(view, x, y) ); } else { tooFar = !isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY); } } else if (uiFocus.tileX != null && uiFocus.tileY != null) { tooFar = !isAdjacentTile(local.tileX, local.tileY, uiFocus.tileX, uiFocus.tileY); } if (!tooFar) { return; } const kind = uiFocus.kind; clearUiFocus(); switch (kind) { case "bank": if (inventory?.isBankOpen?.()) { inventory.closeBank(); } break; case "station": if (crafting?.isOpen?.()) { crafting.close(); } break; case "cauldron": if (alchemy?.isOpen?.()) { alchemy.close(); } break; case "market": if (market?.isOpen?.()) { market.close(); } break; case "bounty": if (bounty?.isOpen?.()) { bounty.close(); } break; case "barber": if (barber?.isOpen?.()) { barber.close(); } break; case "shop": if (shop?.isOpen?.()) { shop.close(); } break; case "dialogue": if (dialogueUi?.isOpen?.()) { dialogueUi.close(); } break; default: break; } } function flushPendingInteract () { if (!pendingInteract || !view) { return; } const local = view.entities.get(view.localEntityId); if (!local) { return; } if (pendingInteract.kind === "bank") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } setUiFocus({ kind: "bank", tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); const getCheques = !!pendingInteract.getCheques; socket.send({ type: MessageType.openBank }); if (getCheques) { inventory?.getBlankCheques(); } clearPendingInteract(); return; } if (pendingInteract.kind === "doorway") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } socket.send({ type: MessageType.enterDoorway, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "market") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } setUiFocus({ kind: "market", tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); socket.send({ type: MessageType.openMarket }); clearPendingInteract(); return; } if (pendingInteract.kind === "bounty") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } setUiFocus({ kind: "bounty", tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); socket.send({ type: MessageType.openBounty }); clearPendingInteract(); return; } if (pendingInteract.kind === "barber") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } setUiFocus({ kind: "barber", tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); socket.send({ type: MessageType.openBarber }); clearPendingInteract(); return; } if (pendingInteract.kind === "cauldron") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } setUiFocus({ kind: "cauldron", tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); socket.send({ type: MessageType.openCauldron }); clearPendingInteract(); return; } if (pendingInteract.kind === "pray-altar") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } socket.send({ type: MessageType.prayAtAltar, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "station") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } setUiFocus({ kind: "station", tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); socket.send({ type: MessageType.openStation, stationId: pendingInteract.stationId }); clearPendingInteract(); return; } if (pendingInteract.kind === "mine") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } socket.send({ type: MessageType.mine, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "start-fire") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } socket.send({ type: MessageType.startFire, groundItemId: pendingInteract.groundItemId }); clearPendingInteract(); return; } if (pendingInteract.kind === "debark-log") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) && !(local.tileX === pendingInteract.tileX && local.tileY === pendingInteract.tileY)) { return; } socket.send({ type: MessageType.debarkLog, groundItemId: pendingInteract.groundItemId }); clearPendingInteract(); return; } if (pendingInteract.kind === "fish") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } socket.send({ type: MessageType.startFish, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "chop") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } socket.send({ type: MessageType.chop, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "pick") { if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { return; } socket.send({ type: MessageType.pick, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "talk") { const target = view.entities.get(pendingInteract.targetEntityId); if (!target) { clearPendingInteract(); return; } if (!canTalkOrShopNear( local.tileX, local.tileY, target.tileX, target.tileY, (x, y) => blockTypeAt(view, x, y) )) { // Target may have moved — keep chasing to a talk stance. approachTalkTarget(target.tileX, target.tileY); return; } socket.send({ type: MessageType.interact, targetEntityId: pendingInteract.targetEntityId, purpose: pendingInteract.purpose || undefined }); // Shop vs dialogue is decided server-side; both use talk/shop reach. setUiFocus({ kind: pendingInteract.purpose === "shop" ? "shop" : "dialogue", entityId: pendingInteract.targetEntityId }); clearPendingInteract(); return; } if (pendingInteract.kind === "trade-request") { const target = view.entities.get(pendingInteract.targetEntityId); if (!target) { clearPendingInteract(); return; } if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY) && !(local.tileX === target.tileX && local.tileY === target.tileY)) { approachAdjacentTile(target.tileX, target.tileY); return; } const targetEntityId = pendingInteract.targetEntityId; clearPendingInteract(); trade?.flushPendingRequest?.(targetEntityId); return; } if (pendingInteract.kind === "trade-accept") { const target = view.entities.get(pendingInteract.fromEntityId); if (!target) { clearPendingInteract(); return; } if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY) && !(local.tileX === target.tileX && local.tileY === target.tileY)) { approachAdjacentTile(target.tileX, target.tileY); return; } const invite = pendingInteract.invite; clearPendingInteract(); trade?.flushPendingAccept?.(invite); return; } if (pendingInteract.kind === "open-item-container") { if (local.tileX === pendingInteract.tileX && local.tileY === pendingInteract.tileY) { approachAdjacentTile(pendingInteract.tileX, pendingInteract.tileY); return; } if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)) { approachAdjacentTile(pendingInteract.tileX, pendingInteract.tileY); return; } socket.send({ type: MessageType.openItemContainer, containerId: pendingInteract.containerId }); clearPendingInteract(); return; } if (pendingInteract.kind === "shear") { const target = view.entities.get(pendingInteract.targetEntityId); if (!target) { clearPendingInteract(); return; } if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY)) { approachAdjacentTile(target.tileX, target.tileY); return; } socket.send({ type: MessageType.shear, targetEntityId: pendingInteract.targetEntityId }); clearPendingInteract(); } } function requestPickup (ground) { if (!ground) { return; } clearPendingInteract(); pendingPickup = { groundItemId: ground.groundItemId, tileX: ground.tileX, tileY: ground.tileY }; const local = view.entities.get(view.localEntityId); if (local && local.tileX === ground.tileX && local.tileY === ground.tileY) { flushPendingPickup(); return; } sendPlayerMoveTo(ground.tileX, ground.tileY); } function flushPendingPickup () { if (!pendingPickup || !view) { return; } const item = view.groundItems.get(pendingPickup.groundItemId); if (!item) { clearPendingPickup(); return; } const local = view.entities.get(view.localEntityId); if (!local) { return; } if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY) { return; } socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId }); clearPendingPickup(); } function requestApproachEntity (targetEntityId) { clearAllPendingActions(); const target = view?.entities.get(targetEntityId); if (!target) { return; } approachAdjacentTile(target.tileX, target.tileY); } function requestAttack (targetEntityId) { clearAllPendingActions(); setAutorunFocusEntity(targetEntityId); combatWithLocalIds.add(targetEntityId | 0); socket.send({ type: MessageType.attack, targetEntityId }); } function isAttackableEntity (entity) { if (!entity || entity.untargetable) { return false; } if (entity.canFight) { return true; } // Snapshots can omit canFight; mobs are still attackable via LMB. return !!entity.mobTypeId && !entity.talkable; } function canTalkToEntity (entity) { return !!(entity && (entity.hasDialogue || entity.hasShop)); } function isApproachingCombatOrCast () { return autorunFocusEntityId != null || autorunFocusTile != null; } function handleLeftClick (mouseX, mouseY) { const tile = view.screenToTile(mouseX, mouseY); const armed = spells?.getArmedSpell?.(); const approaching = isApproachingCombatOrCast(); // Entity-armed: cast only when a valid target is under the cursor. Empty ground // must fall through so walk cancels cast/attack approach (server moveTo clears it). if (armed?.target === "entity" && armed.canCast) { const snap = nearestSpellEntityAtCursor(mouseX, mouseY); if (snap && spells.tryCastAtEntity(snap.entityId)) { setAutorunFocusEntity(snap.entityId); return; } } // Tile-armed while approaching: prefer walk-cancel over re-targeting the cast. else if ( !approaching && armed?.target === "tile" && armed.canCast && spells.tryCastAtTile(tile.tileX, tile.tileY) ) { setAutorunFocusTile(tile.tileX, tile.tileY); return; } const entity = view.entityAtScreen(mouseX, mouseY); if (entity && entity.entityId !== view.localEntityId && !entity.untargetable) { clearPendingPickup(); const clickAction = defaultLeftClickEntityAction(entity, leftClickContextFor(entity)); if (clickAction === "inspect") { clearPendingInteract(); social.inspect(entity); return; } if (clickAction === "attack") { requestAttack(entity.entityId); return; } if (clickAction === "talk") { const purpose = entity.hasDialogue ? "talk" : (entity.hasShop ? "shop" : "talk"); requestTalk(entity.entityId, purpose); return; } if (clickAction === "approach") { requestApproachEntity(entity.entityId); return; } // Clicked an entity we don't act on — do not fall through to walk (that cancels combat). return; } const container = view.itemContainerAtTile?.(tile.tileX, tile.tileY); if (container) { requestOpenItemContainer(container); return; } const ground = view.groundItemAtTile(tile.tileX, tile.tileY); if (ground) { requestPickup(ground); } else if (isBankTile(view, tile.tileX, tile.tileY)) { requestOpenBank(tile.tileX, tile.tileY); } else if (isDoorwayTile(view, tile.tileX, tile.tileY)) { requestEnterDoorway(tile.tileX, tile.tileY); } else if (isMarketplaceTile(view, tile.tileX, tile.tileY)) { requestOpenMarket(tile.tileX, tile.tileY); } else if (isBountyOfficeTile(view, tile.tileX, tile.tileY)) { requestOpenBounty(tile.tileX, tile.tileY); } else if (isBarberTile(view, tile.tileX, tile.tileY)) { requestOpenBarber(tile.tileX, tile.tileY); } else if (isCauldronTile(view, tile.tileX, tile.tileY)) { requestOpenCauldron(tile.tileX, tile.tileY); } else if (isChurchAltarTile(view, tile.tileX, tile.tileY)) { requestPrayAtAltar(tile.tileX, tile.tileY); } else if (isFurnaceTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); } else if (isOvenTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); } else if (isCampfireTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); } else if (isFishingSpotTile(view, tile.tileX, tile.tileY)) { requestFish(tile.tileX, tile.tileY); } else if (isAnvilTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); } else if (isJeweleringStationTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); } else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); } else if (isCraftingBenchTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); } else if (isSpinningWheelTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); } else if (isLoomTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); } else if (isTailorBenchTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); } else if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY); } else if (isOreBoulderTile(view, tile.tileX, tile.tileY)) { requestMine(tile.tileX, tile.tileY); } else if (isChopableTreeTile(view, tile.tileX, tile.tileY)) { requestChop(tile.tileX, tile.tileY); } else if (isPickablePlantTile(view, tile.tileX, tile.tileY)) { requestPick(tile.tileX, tile.tileY); } else { clearAllPendingActions(); sendPlayerMoveTo(tile.tileX, tile.tileY); } } function handleRightClick (event, mouseX, mouseY) { event.preventDefault(); if (spells?.isTargeting?.()) { spells.cancelTargeting(); view?.clearSpellTargetHighlight(); return; } const tile = view.screenToTile(mouseX, mouseY); const items = []; const walkTileX = tile.tileX; const walkTileY = tile.tileY; items.push({ label: "Walk here", onSelect: () => { clearAllPendingActions(); sendPlayerMoveTo(walkTileX, walkTileY); } }); for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY, { includePrevious: true })) { if (entity.entityId === view.localEntityId) { const equipment = { slots: inventory?.getEquipment?.() ?? {} }; if (canTeleportToChurch(equipment)) { items.push({ label: "Teleport to Church", onSelect: () => { clearAllPendingActions(); socket.send({ type: MessageType.jewelryTeleport, destination: "church" }); } }); } if (canTeleportToBank(equipment)) { items.push({ label: "Teleport to bank", onSelect: () => { clearAllPendingActions(); socket.send({ type: MessageType.jewelryTeleport, destination: "bank" }); } }); } continue; } const targetName = entityLabel(entity); items.push({ label: `Follow ${targetName}`, onSelect: () => { clearAllPendingActions(); sendPlayerFollow(entity.entityId); } }); if (entity.untargetable) { continue; } const clickCtx = leftClickContextFor(entity); const attackFirst = preferAttackInContextMenu(entity, clickCtx); const pushAttack = () => { if (!isAttackableEntity(entity)) { return; } items.push({ label: `Attack ${targetName}`, onSelect: () => requestAttack(entity.entityId) }); }; // Prefer Attack first when that matches LMB (aggressive / combat / hostile guards). if (attackFirst) { pushAttack(); } if (entity.hasShop) { items.push({ label: `Shop ${targetName}`, onSelect: () => requestTalk(entity.entityId, "shop") }); } if (entity.hasDialogue) { items.push({ label: `Talk to ${targetName}`, onSelect: () => requestTalk(entity.entityId, "talk") }); } if (entityCanShear(entity)) { items.push({ label: `Shear ${targetName}`, onSelect: () => requestShear(entity.entityId) }); } if (entity.characterId) { items.push({ label: "Trade", onSelect: () => { clearAllPendingActions(); trade?.requestTrade?.(entity.entityId); } }); items.push({ label: `${targetName} info`, onSelect: () => { clearAllPendingActions(); social.inspect(entity); } }); } if (!attackFirst) { pushAttack(); } } const container = view.itemContainerAtTile?.(tile.tileX, tile.tileY); if (container) { items.push({ label: itemSpawnerOpenLabel(container.appearance), onSelect: () => requestOpenItemContainer(container) }); } for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY)) { const name = groundLabel(ground); items.push({ label: `Pick up ${name}`, onSelect: () => requestPickup(ground) }); if (playerHasUsableTinderbox() && isGroundWoodLog(ground)) { items.push({ label: `Start Fire`, onSelect: () => requestStartFire(ground) }); } if (isGroundWoodLog(ground) && !isLogDebarked(ground)) { items.push({ label: "Debark", onSelect: () => requestDebarkLog(ground) }); } } if (isBankTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Bank", onSelect: () => requestOpenBank(tile.tileX, tile.tileY) }); items.push({ label: "Get Blank Cheques", onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true }) }); } if (isDoorwayTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Enter", onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY) }); } if (isMarketplaceTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Central Exchange", onSelect: () => requestOpenMarket(tile.tileX, tile.tileY) }); } if (isBountyOfficeTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Bounty Office", onSelect: () => requestOpenBounty(tile.tileX, tile.tileY) }); } if (isBarberTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Barber", onSelect: () => requestOpenBarber(tile.tileX, tile.tileY) }); } if (isCauldronTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Alchemy", onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY) }); } if (isChurchAltarTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Pray", onSelect: () => requestPrayAtAltar(tile.tileX, tile.tileY) }); } if (isFurnaceTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Smelt", onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY) }); } if (isOvenTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Cook", onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY) }); } if (isCampfireTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Cook", onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY) }); } if (isFishingSpotTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Fish", onSelect: () => requestFish(tile.tileX, tile.tileY) }); } if (isAnvilTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Smith", onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY) }); } if (isJeweleringStationTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Jewel", onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY) }); } if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Woodwork", onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY) }); } if (isCraftingBenchTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Craft", onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY) }); } if (isSpinningWheelTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Spin", onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY) }); } if (isLoomTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Weave", onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY) }); } if (isTailorBenchTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Tailor", onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY) }); } if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Leatherwork", onSelect: () => requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY) }); } if (isOreBoulderTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Mine", onSelect: () => requestMine(tile.tileX, tile.tileY) }); } if (isChopableTreeTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Chop", onSelect: () => requestChop(tile.tileX, tile.tileY) }); } if (isPickablePlantTile(view, tile.tileX, tile.tileY)) { const gather = plantGatherForBlock(blockAt(view, tile.tileX, tile.tileY)); items.push({ label: gather?.requiresClippers ? "Harvest" : "Pick", onSelect: () => requestPick(tile.tileX, tile.tileY) }); } contextMenu.show(event.clientX, event.clientY, items); } function entityLabel (entity) { if (entity?.mobTypeId) { const def = mobDefinition(entity.mobTypeId); const first = (entity?.firstName ?? "").trim(); const last = (entity?.lastName ?? "").trim(); // Fairies keep type name in tooltips ("Lv.n Fairy") even when firstName is "Ada's Fairy". const name = first && last ? `${first} ${last}` : (entity.mobTypeId === MobId.fairy ? (def?.displayName || "Fairy") : (first || def?.displayName || "Creature")); const level = entity?.level ?? def?.attackSkill ?? 1; return mobLevelDisplayName(level, name); } const first = (entity?.firstName ?? "").trim(); const last = (entity?.lastName ?? "").trim(); return first && last ? `${first} ${last}` : (first || "target"); } function groundLabel (ground) { const name = (ground?.displayName ?? "").trim() || "item"; const qty = ground?.quantity ?? 1; if (qty <= 1) { return name; } return `${name} (${formatQuantity(qty)})`; } function startPlay (payload) { playing = true; overlay.hidden = true; hud.hidden = false; const settingsToggle = document.getElementById("settings-toggle"); if (settingsToggle) { settingsToggle.hidden = false; } document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`; gait = payload.gait ?? GAIT.walk; document.getElementById("gait").textContent = gait; staminaUi?.show(); healthUi?.show(); statusEffectsUi?.show(); if (payload.stamina != null) { staminaUi?.apply(payload.stamina); } if (payload.health != null || payload.maxHealth != null) { healthUi?.apply({ current: payload.health ?? healthUi.getCurrent?.(), max: payload.maxHealth ?? healthUi.getMax?.() }); } if (!scene) { scene = new Scene(0, 0, window.innerWidth, window.innerHeight); scene.backgroundColor.r = 0; scene.backgroundColor.g = 0; scene.backgroundColor.b = 0; game.loadScene(scene); useNearestNeighbour(scene, game.images); } if (!view) { view = new WorldView(game, scene, catalog); view.worldBorderWalkableOnly = true; graphicsSettingsUi?.apply(); const ticker = new GameObject(0, 0, null, 10); ticker.update = (dt) => { const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left); const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left); if (!leftPressed && !leftHeld) { leftClickConsumed = false; } else if (uiBlocked()) { // Absorb presses that begin (or continue) over UI so dragging out of a // panel does not issue a world move/order on the same mouse hold. leftClickConsumed = true; } else if (!leftClickConsumed && playing) { leftClickConsumed = true; const canvas = scene.canvas; const rect = canvas.getBoundingClientRect(); const mouseX = GameInput.mousePosition.x - rect.left; const mouseY = GameInput.mousePosition.y - rect.top; handleLeftClick(mouseX, mouseY); } if (GameInput.isPressed(82) && !uiBlocked()) { const next = gait === GAIT.run ? GAIT.walk : GAIT.run; if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0) { return; } socket.send({ type: MessageType.setGait, gait: next }); // Walk always applies; run waits for authoritative STAMINA (may reject if empty). if (next === GAIT.walk) { gait = next; document.getElementById("gait").textContent = gait; } } if (playing && !death?.isBlocking()) { flushPendingPickup(); flushPendingInteract(); syncAutorun(); social?.updateNametag(view, scene, view.localEntityId); chat?.update(view, scene); updateSpellTargetHighlight(); updateWorldTooltip(); } else { hideWorldTooltip(); view?.clearSpellTargetHighlight(); } view.update(dt); }; scene.addObject(ticker); window.addEventListener("resize", () => { scene.size.x = window.innerWidth; scene.size.y = window.innerHeight; scene.g_fixSize(); useNearestNeighbour(scene, game.images); }); window.addEventListener("wheel", (event) => { if (!playing || uiBlocked()) { return; } playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25; if (playZoomRaf) { return; } playZoomRaf = requestAnimationFrame(() => { playZoomRaf = 0; if (!view || !playZoomDelta) { return; } view.setZoom(view.zoom + playZoomDelta); playZoomDelta = 0; document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`; }); }, { passive: true }); scene.canvas.addEventListener("contextmenu", (event) => { if (!playing || uiBlocked()) { return; } const rect = scene.canvas.getBoundingClientRect(); handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top); }); } view.setSettings(payload.settings ?? view.settings); chat?.syncSettings(); view.worldHour = payload.worldTime?.hour ?? 12; view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID); view.setDimensionModes(payload.lightingMode, payload.seasonMode); view.setWorldSeason(payload.worldTime?.season); view.setLocalEntity( payload.entityId, payload.tileX, payload.tileY, payload.gait, payload.sex, payload.firstName, payload.lastName, payload.characterId, payload.layers, payload.health, payload.maxHealth, payload.skullValue ); social?.setLocalIdentity?.({ accountId: payload.accountId, characterId: payload.characterId }); graphicsSettingsUi?.apply(); } async function main () { const authStatus = await fetchAuthStatus(); updateAuthUi(authStatus); if (!authStatus.authenticated) { statusEl.textContent = "Sign in to play Questward."; showError(""); return; } setAssetLoading(true, { phase: "Loading catalog…" }); catalog = await loadSpriteCatalog(); const assetTotal = playImagesFromCatalog(catalog).length; setAssetLoading(true, { loaded: 0, total: assetTotal, phase: "Loading assets…" }); await preloadCatalogImages(game, catalog, { onProgress ({ loaded, total }) { setAssetLoading(true, { loaded, total }); } }); applySpriteSheets(game.images, catalog); if (!scene) { scene = new Scene(0, 0, window.innerWidth, window.innerHeight); scene.backgroundColor.r = 0; scene.backgroundColor.g = 0; scene.backgroundColor.b = 0; game.loadScene(scene); } setAssetLoading(false); statusEl.textContent = "Connecting…"; createHairControls = bindHairControls({ root: document.getElementById("create-hair"), resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, getSex: () => document.getElementById("sex")?.value ?? "male", getBag: () => null, hideHeadgear: true, onChange () { if (createActiveTab === "clothing") { void refreshCreateClothingPreview(); } } }); createClothingControls = bindCreateClothingControls({ root: document.getElementById("create-clothing"), onChange () { if (createActiveTab === "clothing") { void refreshCreateClothingPreview(); } } }); initCreateTabs(); document.getElementById("sex")?.addEventListener("change", () => { createHairControls?.fillStyles(); void createHairControls?.refreshPreview(); if (createActiveTab === "clothing") { void refreshCreateClothingPreview(); } }); void createHairControls?.refreshPreview(); void refreshCreateClothingPreview(); graphicsSettingsUi = initGraphicsSettings({ onChange: applyGraphicsSettings, onSuppressWorldClick: consumeWorldClick }); social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, resolveImage (name) { return game?.images?.[name] ?? null; } }); contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick }); const tipArrows = initTipArrows({ socket: { send (payload) { socket.send(payload); } }, MessageType, getInventoryBag () { return inventory?.getBag?.() ?? null; } }); inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, contextMenu, tipArrows, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, resolveImage (name) { return game?.images?.[name] ?? null; }, getFriends () { return social?.getFriends?.() ?? []; }, getLocalName () { const you = document.getElementById("you")?.textContent ?? ""; return you.split("(")[0].trim() || "Unknown"; }, getSoftClaims () { return [ ...(alchemy?.listSoftClaims?.() ?? []), ...(trade?.listSoftClaims?.() ?? []) ]; }, onBagSlotActivate (slotIndex, slot) { if (!trade?.isOpen?.()) { return false; } const real = inventory?.getInventorySlots?.()?.[slotIndex] ?? slot; return trade.offerBagSlot(slotIndex, real); }, bagClicksLocked () { return !!trade?.inventoryLocked?.(); }, knowsSpell (spellId) { return !!spells?.knowsSpell?.(spellId); }, getSkillLevels () { return skills?.getSkillLevels?.() ?? {}; }, getSettings () { return view?.settings ?? null; }, getKnownSpellIds () { return spells?.getKnownSpellIds?.() ?? []; }, onBagChanged () { spells?.refreshMaxHitDisplay?.(); } }); skills = initSkills({ getEquipmentSlots () { return inventory?.getEquipment?.() ?? {}; }, getSettings () { return view?.settings ?? null; } }); spells = initSpells({ socket: { send (payload) { socket.send(payload); } }, MessageType, getSkillLevel (skillId) { return skills?.skillLevel?.(skillId) ?? 1; }, getSkillLevels () { return skills?.getSkillLevels?.() ?? {}; }, getEquipmentSlots () { return inventory?.getEquipment?.() ?? {}; }, getSettings () { return view?.settings ?? null; } }); crafting = initCrafting({ socket: { send (payload) { socket.send(payload); } }, MessageType, getInventorySlots () { return inventory?.getInventorySlots?.() ?? []; }, getEquipment () { return inventory?.getEquipment?.() ?? {}; }, getSkillLevel (skillId) { return skills?.skillLevel?.(skillId) ?? 1; } }); alchemy = initAlchemy({ socket: { send (payload) { socket.send(payload); } }, MessageType, getInventorySlots () { return inventory?.getInventorySlots?.() ?? []; } }); alchemy?.setOnSoftClaimsChanged?.(() => inventory?.refreshBagDisplay?.()); staminaUi = initStamina(); healthUi = initHealth(); statusEffectsUi = initStatusEffects(); toasts = initToasts({ onSuppressWorldClick: consumeWorldClick }); trade = initTrade({ socket: { send (payload) { socket.send(payload); } }, MessageType, toasts, getLocalEntity () { return view?.entities.get(view.localEntityId) ?? null; }, getEntity (id) { return view?.entities.get(id) ?? null; }, approachAdjacentTile, clearPendingActions: clearAllPendingActions, setPendingTradeRequest (targetEntityId) { pendingInteract = { kind: "trade-request", targetEntityId: targetEntityId | 0 }; }, setPendingTradeAccept (invite) { pendingInteract = { kind: "trade-accept", fromEntityId: invite.fromEntityId | 0, invite }; }, onSuppressWorldClick: consumeWorldClick, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, resolveImage (name) { return game?.images?.[name] ?? null; }, ensureBagOpen () { const bagPanel = document.getElementById("bag-panel"); if (bagPanel?.hidden) { bagPanel.hidden = false; } inventory?.refreshBagDisplay?.(); }, onTradeOpenChanged () { inventory?.refreshBagDisplay?.(); } }); questsUi = initQuests({ socket: { send (payload) { socket.send(payload); } }, MessageType, toasts }); dialogueUi = initDialogue({ socket: { send (payload) { socket.send(payload); } }, MessageType, getEntity (id) { if (id === "local") { return view?.entities.get(view.localEntityId) ?? null; } return view?.entities.get(id) ?? null; }, captureSpeakerIcon (entityId, size = 64) { return view?.captureEntityPortrait?.(entityId, { size }) ?? null; } }); shop = initShop({ socket: { send (payload) { socket.send(payload); } }, MessageType, onSuppressWorldClick: consumeWorldClick, getCoinCount () { return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []); }, getInventorySlots () { return inventory?.getInventorySlots?.() ?? []; } }); market = initMarket({ socket: { send (payload) { socket.send(payload); } }, MessageType, onSuppressWorldClick: consumeWorldClick, getCoinCount () { return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []); }, getInventorySlots () { return inventory?.getInventorySlots?.() ?? []; }, getLocalCharacterId () { return inventory?.getLocalCharacterId?.() ?? null; } }); bounty = initBounty({ socket: { send (payload) { socket.send(payload); } }, MessageType, onSuppressWorldClick: consumeWorldClick, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, resolveImage (name) { return game?.images?.[name] ?? null; } }); barber = initBarber({ socket: { send (payload) { socket.send(payload); } }, MessageType, onSuppressWorldClick: consumeWorldClick, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, getInventoryBag () { return { equipment: { slots: inventory?.getEquipment?.() ?? {} }, inventory: inventory?.getInventorySlots?.() ?? [] }; } }); chat = initChat({ socket: { send (payload) { socket.send(payload); } }, MessageType, getSettings: () => view?.settings }); death = initDeath({ socket: { send (payload) { socket.send(payload); } }, MessageType }); game.startGame(); useNearestNeighbour(scene, game.images); socket = new GameSocket(defaultSocketUrl(), (message) => { switch (message.type) { case MessageType.session: session = message; statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`; renderCharacters(message.characters); break; case MessageType.characterList: renderCharacters(message.characters); if (!playing) { overlay.hidden = false; } break; case MessageType.enterWorld: closeCreateModal(); startPlay(message); inventory?.setLocalCharacterId(message.characterId); questsUi?.setLocalCharacterId?.(message.characterId); toasts?.applyRestartStatus?.(message.restartStatus); socket.send({ type: MessageType.requestQuests }); break; case MessageType.chunkSnapshot: view?.applySnapshot(message); break; case MessageType.dimensionChanged: if (view) { view.setDimensionId(message.dimensionId); view.setDimensionModes(message.lightingMode, message.seasonMode); view.clearAllChunks(); if (message.tileX != null && message.tileY != null && view.localEntityId != null) { view.moveEntity({ entityId: view.localEntityId, tileX: message.tileX, tileY: message.tileY }); } } closeOpenUiIfTooFar(); break; case MessageType.chunkDelta: if (isForeignDimensionMessage(message)) { break; } for (const tile of message.tiles ?? []) { view?.updateAuthoredTile( message.chunkX, message.chunkY, tile.localX, tile.localY, { ground: tile.ground, block: tile.block, light: tile.light } ); } break; case MessageType.unsubscribeChunk: view?.removeChunk(message.chunkX, message.chunkY); break; case MessageType.entitySpawn: view?.spawnEntity(message); break; case MessageType.entityMove: view?.moveEntity(message); if (message.entityId === view?.localEntityId) { if (message.gait) { gait = message.gait; document.getElementById("gait").textContent = gait; } closeOpenUiIfTooFar(); } else if ( uiFocus?.entityId != null && message.entityId === uiFocus.entityId ) { closeOpenUiIfTooFar(); } break; case MessageType.entityDespawn: if (message.entityId === autorunFocusEntityId) { clearAutorunFocus(); } clearCombatWithLocal(message.entityId); view?.despawnEntity(message.entityId, { combatDeath: message.cause === "death" }); break; case MessageType.entityAppearance: view?.setAppearance(message); break; case MessageType.entitySkull: view?.updateEntitySkull(message.entityId, message.skullValue); break; case MessageType.itemContainerAppear: view?.upsertItemContainer(message); break; case MessageType.itemContainerDespawn: view?.despawnItemContainer(message.containerId); break; case MessageType.groundItemAppear: if (isForeignDimensionMessage(message)) { break; } view?.upsertGroundItem(message); break; case MessageType.groundItemDespawn: view?.despawnGroundItem(message.groundItemId); break; case MessageType.inventory: inventory?.handleInventory(message); skills?.refresh?.(); crafting?.refresh(); alchemy?.refresh(); shop?.refresh(); market?.refresh(); break; case MessageType.skills: skills?.render(message.skills, message.combatLevel); inventory?.refreshMaxHit?.(); spells?.refreshMaxHitDisplay?.(); crafting?.refresh(); spells?.refreshCastGates?.(); break; case MessageType.spells: case MessageType.spellsUpdated: spells?.render(message); inventory?.refreshMaxHit?.(); break; case MessageType.spellArmed: spells?.handleSpellArmed(message); break; case MessageType.spellDisarmed: spells?.handleSpellDisarmed(); break; case MessageType.spellProjectile: if (isForeignDimensionMessage(message)) { break; } view?.spawnSpellProjectileFx(message); if (message.casterId === view?.localEntityId) { clearAutorunFocus(); } break; case MessageType.spellFizzle: if (isForeignDimensionMessage(message)) { break; } view?.spawnSpellFizzleFx(message); if (message.casterId === view?.localEntityId) { clearAutorunFocus(); toasts?.show("Failed to cast spell"); } break; case MessageType.spellCastFlash: // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*. if (isForeignDimensionMessage(message)) { break; } if (message.casterId === view?.localEntityId) { clearAutorunFocus(); } break; case MessageType.spellLightAppear: case MessageType.spellLightUpdate: if (isForeignDimensionMessage(message)) { break; } view?.setSpellLight(message); break; case MessageType.spellLightRemove: if (isForeignDimensionMessage(message)) { break; } view?.removeSpellLight(message); break; case MessageType.spellDarkAppear: case MessageType.spellDarkUpdate: if (isForeignDimensionMessage(message)) { break; } view?.setSpellDark(message); break; case MessageType.spellDarkRemove: if (isForeignDimensionMessage(message)) { break; } view?.removeSpellDark(message); break; case MessageType.stamina: staminaUi?.apply(message); if (message.gait) { gait = message.gait; document.getElementById("gait").textContent = gait; if (gait === GAIT.walk && (staminaUi?.getCurrent?.() ?? 0) <= 0) { autorunWaitingStamina = true; } } syncAutorun(); break; case MessageType.statusEffects: view?.setLocalBlind(!!message.blind); statusEffectsUi?.apply(message); break; case MessageType.bankSnapshot: inventory?.handleBank(message); break; case MessageType.cauldronSnapshot: if (message.open === false && uiFocus?.kind === "cauldron") { clearUiFocus(); } alchemy?.handleSnapshot(message); break; case MessageType.pigeonDispatched: inventory?.handlePigeonDispatched(message); break; case MessageType.pigeonDelivered: inventory?.handlePigeonDelivered(message); break; case MessageType.characterSearchResult: inventory?.handleCharacterSearch(message); break; case MessageType.craftResult: crafting?.handleCraftResult(message); break; case MessageType.worldStatus: if (view) { view.setSettings(message.settings ?? view.settings); view.worldHour = message.worldTime?.hour ?? view.worldHour; view.setWorldSeason(message.worldTime?.season); chat?.syncSettings(); } skills?.refresh?.(); toasts?.applyRestartStatus?.(message.restartStatus); break; case MessageType.restartStatus: toasts?.applyRestartStatus?.(message.restartStatus); break; case MessageType.chatBubble: chat?.showBubble(message); break; case MessageType.friends: social?.handleFriends(message); break; case MessageType.combatSwing: if (isForeignDimensionMessage(message)) { break; } noteCombatWithLocal(message.attackerId, message.targetId); view?.spawnCombatSwing(message); break; case MessageType.combatProjectile: if (isForeignDimensionMessage(message)) { break; } noteCombatWithLocal(message.attackerId, message.targetId); view?.spawnPhysicalProjectileFx({ ...message, sprite: "fx:projectile:arrow" }); break; case MessageType.combatNoArrows: toasts?.show("Out of arrows!"); break; case MessageType.gatherSwing: case MessageType.tileShove: if (isForeignDimensionMessage(message)) { break; } view?.spawnGatherSwing(message); break; case MessageType.stationOpen: if (message.stationId) { crafting?.openStation(message.stationId); } break; case MessageType.shopOpen: if (message.npcEntityId != null) { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); } shop?.handleShopOpen(message); break; case MessageType.shopClosed: if (uiFocus?.kind === "shop") { clearUiFocus(); } shop?.handleShopClosed(message); break; case MessageType.marketOpen: market?.handleOpen(message); break; case MessageType.marketClosed: if (uiFocus?.kind === "market") { clearUiFocus(); } market?.handleClosed(message); break; case MessageType.marketTrade: market?.handleTrade(message); toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`); break; case MessageType.bountySnapshot: bounty?.handleSnapshot(message); break; case MessageType.closeBounty: if (uiFocus?.kind === "bounty") { clearUiFocus(); } bounty?.handleClosed(message); break; case MessageType.characterBounty: bounty?.handleCharacterBounty(message); social?.handleCharacterBounty(message); break; case MessageType.barberSnapshot: barber?.handleSnapshot(message); break; case MessageType.closeBarber: if (uiFocus?.kind === "barber") { clearUiFocus(); } barber?.handleClosed(message); break; case MessageType.itemBubble: chat?.showItemBubble(message); break; case MessageType.gatherComplete: crafting?.refresh(); break; case MessageType.combatHit: { if (isForeignDimensionMessage(message)) { break; } noteCombatWithLocal(message.attackerId, message.targetId); const applyHit = () => { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); view?.flashDamage(message.targetId); view?.spawnCombatKnockback?.(message); view?.spawnDamageNumber(message.targetId, message.damage); if (message.targetId === view?.localEntityId) { healthUi?.apply({ current: message.health, max: message.maxHealth }); } }; if (!view?.deferCombatHit?.(message, applyHit)) { applyHit(); } break; } case MessageType.combatMiss: if (isForeignDimensionMessage(message)) { break; } noteCombatWithLocal(message.attackerId, message.targetId); view?.spawnCombatDodge?.(message); view?.markProjectileMiss?.(message); break; case MessageType.combatBlock: { if (isForeignDimensionMessage(message)) { break; } noteCombatWithLocal(message.attackerId, message.targetId); const applyBlock = () => { view?.flashBlock?.(message.targetId); if (message.health != null) { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); } }; if (!view?.deferCombatHit?.(message, applyBlock)) { applyBlock(); } break; } case MessageType.entityHealth: view?.updateEntityHealth(message.entityId, message.health, message.maxHealth); if (message.entityId === view?.localEntityId) { healthUi?.apply({ current: message.health, max: message.maxHealth }); } break; case MessageType.skillLevelUp: view?.spawnSkillLevelUp(message.entityId, message); if (message.entityId === view?.localEntityId) { const level = message.level | 0; const previousLevel = message.previousLevel == null ? Math.max(0, level - 1) : message.previousLevel | 0; const unlockCount = skillUnlockMessages(message.skillId, previousLevel, level).length; toasts?.show(skillLevelUpToastText(message.skillId, level, previousLevel), { durationMs: 3500 + unlockCount * 1600 }); } break; case MessageType.playerDied: clearAllPendingActions(); clearAutorunFocus(); contextMenu?.hide(); spells?.handleSpellDisarmed?.(); closeCloseablePlayUi(); death?.show(); if (message.entityId === view?.localEntityId) { healthUi?.apply({ current: 0, max: healthUi.getMax?.() }); view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.()); } // Red silhouette fade if despawn is delayed or already queued this tick. view?.beginDeathDissolve?.(message.entityId); break; case MessageType.playerRespawned: death?.hide(); // Drop deferred killing-blow health=0 that may still be queued on a projectile. view?.cancelDeferredCombatHits?.(message.entityId); view?.reviveAfterDeath?.(message.entityId, { tileX: message.tileX, tileY: message.tileY, health: message.health, maxHealth: message.maxHealth, skullValue: message.skullValue }); if (message.entityId === view?.localEntityId) { healthUi?.apply({ current: message.health, max: message.maxHealth }); } if (message.stamina != null || message.maxStamina != null) { staminaUi?.apply({ current: message.stamina ?? staminaUi.getCurrent?.(), max: message.maxStamina ?? staminaUi.getMax?.() }); } break; case MessageType.error: if (playing) { toasts?.show(message.message); } else { const createPanel = document.getElementById("create-panel"); const createError = document.getElementById("create-error"); if (createPanel && !createPanel.hidden && createError) { createError.textContent = message.message ?? ""; } else { showError(message.message); } } social?.showError(message.message); break; case MessageType.toast: if (playing) { toasts?.show(message.message); } break; case MessageType.tradeInvite: case MessageType.tradeInviteExpired: case MessageType.tradeOpen: case MessageType.tradeState: case MessageType.tradeClosed: if (playing) { trade?.handleMessage?.(message); } break; case MessageType.questsSnapshot: questsUi?.applySnapshot(message); break; case MessageType.questStepComplete: questsUi?.handleStepComplete(message); break; case MessageType.questObjectiveComplete: questsUi?.handleObjectiveComplete?.(message); break; case MessageType.questComplete: questsUi?.handleComplete?.(message); break; case MessageType.dialogueStep: if (message.npcEntityId != null) { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); } dialogueUi?.handleStep(message); break; case MessageType.dialogueItemRewards: if (message.npcEntityId != null) { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); } dialogueUi?.handleItemRewards(message); break; case MessageType.dialogueChoices: if (message.npcEntityId != null) { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); } dialogueUi?.handleChoices(message); break; case MessageType.dialogueClose: if (uiFocus?.kind === "dialogue") { clearUiFocus(); } dialogueUi?.handleClose(message); break; case MessageType.forceLogout: returnToMenu(message.reason); break; } }, { onClose (event) { if (playing) { returnToMenu(event.reason || "Disconnected from server."); } } }); await socket.connect(); if (typeof window !== "undefined") { window.__craftDev = (stationId = CraftingStationId.craftingBench) => { crafting?.openStation(stationId); }; } } function returnToMenu (reason = "") { playing = false; followTargetId = null; moveDest = null; clearAutorunFocus(); clearCombatWithLocal(); autorunWaitingStamina = false; clearAllPendingActions(); clearUiFocus(); social?.reset(); chat?.reset(); inventory?.reset(); crafting?.reset(); alchemy?.reset(); staminaUi?.hide(); healthUi?.hide(); statusEffectsUi?.hide(); skills?.hide(); spells?.hide(); contextMenu?.hide(); death?.reset(); shop?.close({ notifyServer: false }); bounty?.close(); barber?.close(); questsUi?.reset(); dialogueUi?.reset(); hideWorldTooltip(); if (view) { view.clearPlaySession(); } overlay.hidden = false; hud.hidden = true; const settingsToggle = document.getElementById("settings-toggle"); if (settingsToggle) { settingsToggle.hidden = true; } graphicsSettingsUi?.close(); if (reason) { statusEl.textContent = reason; } } document.getElementById("create-character-open")?.addEventListener("click", () => { showError(""); const createError = document.getElementById("create-error"); if (createError) { createError.textContent = ""; } document.getElementById("create-backdrop").hidden = false; document.getElementById("create-panel").hidden = false; setCreateTab("appearance"); void createHairControls?.refreshPreview(); }); function closeCreateModal () { document.getElementById("create-backdrop").hidden = true; document.getElementById("create-panel").hidden = true; } document.getElementById("create-close")?.addEventListener("click", closeCreateModal); document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal); document.getElementById("create-form").addEventListener("submit", (event) => { event.preventDefault(); showError(""); const createError = document.getElementById("create-error"); if (createError) { createError.textContent = ""; } const names = validateCharacterNames({ firstName: document.getElementById("first-name").value, lastName: document.getElementById("last-name").value, isAdmin: !!session?.isAdmin }); if (!names.ok) { if (createError) { createError.textContent = names.reason; } else { showError(names.reason); } return; } socket.send({ type: MessageType.createCharacter, firstName: names.firstName, lastName: names.lastName, sex: document.getElementById("sex").value, hair: createHairControls?.currentHair?.() ?? null, clothing: createClothingControls?.currentClothing?.() ?? null }); }); function initCreateTabs () { const tabs = document.querySelectorAll(".create-tab"); for (const tab of tabs) { tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab)); } setCreateTab("appearance"); } function setCreateTab (name) { createActiveTab = name === "clothing" ? "clothing" : "appearance"; for (const tab of document.querySelectorAll(".create-tab")) { const on = tab.dataset.createTab === createActiveTab; tab.classList.toggle("active", on); tab.setAttribute("aria-selected", on ? "true" : "false"); } for (const pane of document.querySelectorAll("[data-create-pane]")) { pane.hidden = pane.dataset.createPane !== createActiveTab; } if (createActiveTab === "clothing") { void refreshCreateClothingPreview(); } else { void createHairControls?.refreshPreview(); } } async function refreshCreateClothingPreview () { const canvas = document.getElementById("create-clothing-preview"); if (!canvas || !createClothingControls) { return; } try { await paintCharacterPreview(canvas, { sex: document.getElementById("sex")?.value ?? "male", bag: createClothingControls.previewBag(), hair: createHairControls?.currentHair?.() ?? null, hideHeadgear: true, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, scale: 4 }); } catch (error) { console.warn(error); } } document.getElementById("leave").addEventListener("click", () => { socket.send({ type: MessageType.leaveWorld }); returnToMenu(); }); main().catch((error) => { showError(error.message); console.error(error); }); function isBankTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.bank; } function isDoorwayTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.doorway; } function isMarketplaceTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.marketplace; } function isBountyOfficeTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice; } function isBarberTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.barber; } function isCauldronTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.cauldron; } function isChurchAltarTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.churchAltar; } function isFurnaceTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.furnace; } function isOvenTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.oven; } function isCampfireTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.campfire; } function isFishingSpotTile (view, tileX, tileY) { const block = blockAt(view, tileX, tileY); if (!block || block.typeId !== BlockType.fishingSpot) { return false; } return block.state !== "exhausted"; } function isAnvilTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.anvil; } function isJeweleringStationTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation; } function isGroundWoodLog (ground) { const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId); return def?.familyId === ItemFamilyId.log; } function playerHasUsableTinderbox () { const slots = inventory?.getInventorySlots?.() ?? []; for (const slot of slots) { if (!slot || slot.itemId !== CraftingItemId.tinderbox) { continue; } const charges = slot.instance?.kind === "tinderbox" ? (slot.instance.charges | 0) : TINDERBOX_MAX_CHARGES; if (charges > 0) { return true; } } return false; } function isWoodworkingBenchTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench; } function isCraftingBenchTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench; } function isSpinningWheelTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel; } function isLoomTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.loom; } function isTailorBenchTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench; } function isLeatherworkingTableTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable; } function isOreBoulderTile (view, tileX, tileY) { const block = blockAt(view, tileX, tileY); return block?.typeId === BlockType.boulder && isOreBoulderState(block.state); } function isChopableTreeTile (view, tileX, tileY) { return isChopableTreeBlock(blockAt(view, tileX, tileY)); } function isPickablePlantTile (view, tileX, tileY) { return isPickablePlantBlock(blockAt(view, tileX, tileY)); } const SPELL_ENTITY_SNAP_TILES = 2; function updateSpellTargetHighlight () { if (!view || !playing || uiBlocked() || !spells?.isTargeting?.()) { view?.clearSpellTargetHighlight(); return; } const canvas = scene?.canvas; if (!canvas) { return; } const rect = canvas.getBoundingClientRect(); const mouseX = GameInput.mousePosition.x - rect.left; const mouseY = GameInput.mousePosition.y - rect.top; if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height) { view.clearSpellTargetHighlight(); return; } const armed = spells.getArmedSpell?.(); const local = view.entities.get(view.localEntityId); if (armed?.target === "entity") { const target = nearestSpellEntityAtCursor(mouseX, mouseY); if (!target) { view.clearSpellTargetHighlight(); return; } const inRange = !local || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) <= COMBAT_RANGE_TILES; view.setSpellEntityTargetHighlight(target.entityId, inRange); return; } const tile = view.screenToTile(mouseX, mouseY); const inRange = !local || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES; view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange); } /** * Nearest spell-targetable entity within {@link SPELL_ENTITY_SNAP_TILES} of the * cursor tile (uses both authoritative and visual tile for moving mobs). */ function nearestSpellEntityAtCursor (mouseX, mouseY) { if (!view) { return null; } const cursor = view.screenToTile(mouseX, mouseY); const tileSize = view.tileSize(); let best = null; let bestDist = Infinity; let bestScreen = Infinity; for (const entity of view.entities.values()) { if (!isSpellEntityTarget(entity)) { continue; } const visualTileX = Math.floor((entity.visualX + (entity.stackOffsetX ?? 0)) / tileSize); const visualTileY = Math.floor((entity.visualY + (entity.stackOffsetY ?? 0)) / tileSize); const dist = Math.min( chebyshev(cursor.tileX, cursor.tileY, entity.tileX, entity.tileY), chebyshev(cursor.tileX, cursor.tileY, visualTileX, visualTileY) ); if (dist > SPELL_ENTITY_SNAP_TILES) { continue; } const box = view.nametagAnchor?.(entity); const screenDist = box ? Math.hypot(box.x - mouseX, box.y - mouseY) : dist; if (dist < bestDist || (dist === bestDist && screenDist < bestScreen)) { best = entity; bestDist = dist; bestScreen = screenDist; } } return best; } function isSpellEntityTarget (entity) { if (!entity || entity.entityId === view?.localEntityId) { return false; } if (entity.untargetable || entity.freeFlight) { return false; } return isAttackableEntity(entity); } function hideWorldTooltip () { if (worldTooltip) { worldTooltip.hidden = true; worldTooltip.classList.remove("friend-name"); worldTooltip.style.color = ""; } } /** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */ function updateWorldTooltip () { if (!worldTooltip || !view || !scene || uiBlocked()) { hideWorldTooltip(); return; } const canvas = scene.canvas; const rect = canvas.getBoundingClientRect(); const mouseX = GameInput.mousePosition.x - rect.left; const mouseY = GameInput.mousePosition.y - rect.top; if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height) { hideWorldTooltip(); return; } const entity = view.entityAtScreen(mouseX, mouseY); if (entity && entity.entityId !== view.localEntityId) { const label = entityLabel(entity); worldTooltip.hidden = false; worldTooltip.textContent = label; const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId); worldTooltip.classList.toggle("friend-name", !!friend); worldTooltip.style.color = friend ? "#e8c84a" : ""; worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`; worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`; return; } const tile = view.screenToTile(mouseX, mouseY); const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY)); if (!label) { hideWorldTooltip(); return; } worldTooltip.hidden = false; worldTooltip.textContent = label; worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`; worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`; } function blockTypeAt (view, tileX, tileY) { return blockAt(view, tileX, tileY)?.typeId ?? null; } function blockAt (view, tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = view.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return null; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null; } function groundTypeAt (view, tileX, tileY) { const chunkX = Math.floor(tileX / CHUNK_SIZE); const chunkY = Math.floor(tileY / CHUNK_SIZE); const snapshot = view.chunks.get(`${chunkX},${chunkY}`); if (!snapshot) { return null; } const localX = tileX - chunkX * CHUNK_SIZE; const localY = tileY - chunkY * CHUNK_SIZE; return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId; } /** Best-effort client filter for approach destinations (server still authorizes paths). */ function isClientApproachable (tileX, tileY) { if (!view) { return true; } const groundId = groundTypeAt(view, tileX, tileY); const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null; if (groundDef && !groundDef.passable) { return false; } const block = blockAt(view, tileX, tileY); if (block?.typeId != null) { const blockDef = BLOCK_DEFINITIONS[block.typeId]; if (blockDef && !blockDef.passable) { return false; } } for (const entity of view.entitiesAtTile(tileX, tileY)) { if (entity.entityId === view.localEntityId) { continue; } if (entity.untargetable || entity.freeFlight) { continue; } return false; } return true; } function chebyshev (ax, ay, bx, by) { return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); } function updateAuthUi (authStatus) { const signIn = document.getElementById("auth-sign-in"); const signOut = document.getElementById("auth-sign-out"); const exportLink = document.getElementById("auth-export"); if (signIn) { signIn.hidden = !!authStatus?.authenticated; signIn.href = loginUrl("/"); } if (signOut) { signOut.hidden = !authStatus?.authenticated; signOut.href = logoutUrl("/"); } if (exportLink) { exportLink.hidden = !authStatus?.authenticated; } if (createCharacterOpen) { createCharacterOpen.hidden = !authStatus?.authenticated; } if (authStatus?.authenticated && !session) { statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`; } }