import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js"; import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js"; import { GameSocket, defaultSocketUrl } from "../net/socket.js"; import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } 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 { initCrafting } from "./crafting.js"; import { initAlchemy } from "./alchemy.js"; import { initStamina } from "./stamina.js"; import { initHealth } from "./health.js"; import { initStatusEffects } from "./statusEffects.js"; import { initContextMenu } from "./contextMenu.js"; import { initDeath } from "./death.js"; import { initToasts } from "./toasts.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 { 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 } from "/shared/definitions/items.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 worldTooltip = document.getElementById("world-tooltip"); let socket; let session = null; let playing = false; let view = null; let graphicsSettingsUi = null; let scene = null; let gait = GAIT.walk; let catalog = { grounds: {}, blocks: {} }; let social; let chat; let inventory; let skills; let crafting; let alchemy; let staminaUi; let healthUi; let statusEffectsUi; let contextMenu; let death; let toasts; let shop; let market; let bounty; let barber; let createHairControls; let pendingPickup = null; /** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */ let pendingInteract = null; /** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */ let approachMove = null; /** Framework can report mousePressed for two frames; latch so one physical click is one command. */ let leftClickConsumed = false; function consumeWorldClick () { leftClickConsumed = true; } function showError (message) { errorEl.textContent = message ?? ""; } 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() || contextMenu?.isOpen() || death?.isBlocking()); } function applyGraphicsSettings (settings) { view?.setGraphicsPrefs(settings); if (socket && playing) { socket.send({ type: MessageType.setGraphicsSettings, viewDistance: settings.viewDistance }); } } 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 && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { approachMove = null; return true; } let bestWalkable = null; let bestWalkableDist = Infinity; 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 = local ? chebyshev(local.tileX, local.tileY, destX, destY) : 0; if (dist < bestAnyDist) { bestAnyDist = dist; bestAny = { tileX: destX, tileY: destY }; } if (isClientApproachable(destX, destY) && dist < bestWalkableDist) { bestWalkableDist = dist; bestWalkable = { tileX: destX, tileY: destY }; } } } const best = bestWalkable ?? bestAny; if (!best) { return false; } if ( approachMove && approachMove.focusX === tileX && approachMove.focusY === tileY && approachMove.destX === best.tileX && approachMove.destY === best.tileY ) { return false; } approachMove = { focusX: tileX, focusY: tileY, destX: best.tileX, destY: best.tileY }; socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); 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 && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenMarket (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "market", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenBounty (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "bounty", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenBarber (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "barber", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestOpenCauldron (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "cauldron", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { 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 && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestMine (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "mine", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestChop (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "chop", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestPick (tileX, tileY) { clearAllPendingActions(); pendingInteract = { kind: "pick", tileX, tileY }; const local = view?.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingInteract(); } else { approachAdjacentTile(tileX, tileY); } } function requestTalk (targetEntityId) { clearAllPendingActions(); pendingInteract = { kind: "talk", targetEntityId }; const target = view?.entities.get(targetEntityId); if (!target) { clearPendingInteract(); return; } if (approachAdjacentTile(target.tileX, target.tileY)) { flushPendingInteract(); } } function flushPendingInteract () { if (!pendingInteract || !view) { return; } const local = view.entities.get(view.localEntityId); if (!local) { return; } if (pendingInteract.kind === "bank") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } const getCheques = !!pendingInteract.getCheques; socket.send({ type: MessageType.openBank }); if (getCheques) { inventory?.getBlankCheques(); } clearPendingInteract(); return; } if (pendingInteract.kind === "market") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.openMarket }); clearPendingInteract(); return; } if (pendingInteract.kind === "bounty") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.openBounty }); clearPendingInteract(); return; } if (pendingInteract.kind === "barber") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.openBarber }); clearPendingInteract(); return; } if (pendingInteract.kind === "cauldron") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.openCauldron }); clearPendingInteract(); return; } if (pendingInteract.kind === "station") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.openStation, stationId: pendingInteract.stationId }); clearPendingInteract(); return; } if (pendingInteract.kind === "mine") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.mine, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "chop") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { return; } socket.send({ type: MessageType.chop, tileX: pendingInteract.tileX, tileY: pendingInteract.tileY }); clearPendingInteract(); return; } if (pendingInteract.kind === "pick") { if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) { 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 (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1) { // Target may have moved — keep chasing. approachAdjacentTile(target.tileX, target.tileY); return; } socket.send({ type: MessageType.interact, 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; } socket.send({ type: MessageType.moveTo, tileX: ground.tileX, tileY: 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 requestAttack (targetEntityId) { clearAllPendingActions(); 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 handleLeftClick (mouseX, mouseY) { const entity = view.entityAtScreen(mouseX, mouseY); if (entity && entity.entityId !== view.localEntityId && !entity.untargetable) { clearPendingPickup(); if (entity.characterId) { clearPendingInteract(); social.inspect(entity); return; } if (entity.talkable) { requestTalk(entity.entityId); return; } if (isAttackableEntity(entity)) { requestAttack(entity.entityId); return; } // Clicked an entity we don't act on — do not fall through to walk (that cancels combat). return; } const tile = view.screenToTile(mouseX, mouseY); 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 (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 (isFurnaceTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); } else if (isAnvilTile(view, tile.tileX, tile.tileY)) { requestOpenCraftStation(CraftingStationId.anvil, 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 (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(); socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); } } function handleRightClick (event, mouseX, mouseY) { event.preventDefault(); const tile = view.screenToTile(mouseX, mouseY); const items = []; const walkTileX = tile.tileX; const walkTileY = tile.tileY; items.push({ label: "Walk here", onSelect: () => { clearAllPendingActions(); socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY }); } }); for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY)) { if (entity.entityId === view.localEntityId) { continue; } const targetName = entityLabel(entity); items.push({ label: `Follow ${targetName}`, onSelect: () => { clearAllPendingActions(); socket.send({ type: MessageType.follow, targetEntityId: entity.entityId }); } }); if (entity.untargetable) { continue; } if (entity.hasShop) { items.push({ label: `Shop ${targetName}`, onSelect: () => requestTalk(entity.entityId) }); } else if (entity.talkable) { items.push({ label: `Talk to ${targetName}`, onSelect: () => requestTalk(entity.entityId) }); } if (entity.characterId) { items.push({ label: `${targetName} info`, onSelect: () => { clearAllPendingActions(); social.inspect(entity); } }); } items.push({ label: `Attack ${targetName}`, onSelect: () => requestAttack(entity.entityId) }); } for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY)) { const name = groundLabel(ground); items.push({ label: `Pick up ${name}`, onSelect: () => requestPickup(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 (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 (isFurnaceTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Smelt", onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY) }); } if (isAnvilTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Smith", onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, 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 (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)) { items.push({ label: "Pick", onSelect: () => requestPick(tile.tileX, tile.tileY) }); } contextMenu.show(event.clientX, event.clientY, items); } function entityLabel (entity) { const first = (entity?.firstName ?? "").trim(); const last = (entity?.lastName ?? "").trim(); if (first && last) { return `${first} ${last}`; } return 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); game.loadScene(scene); useNearestNeighbour(scene, game.images); view = new WorldView(game, scene, catalog); 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 (!leftClickConsumed && playing && !uiBlocked()) { 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(); social?.updateNametag(view, scene, view.localEntityId); chat?.update(view, scene); updateWorldTooltip(); } else { hideWorldTooltip(); } 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; } view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25)); 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.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 ); graphicsSettingsUi?.apply(); } async function main () { catalog = await loadSpriteCatalog(); await preloadCatalogImages(game, catalog); applySpriteSheets(game.images, catalog); 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", hideHeadgear: true }); document.getElementById("sex")?.addEventListener("change", () => { createHairControls?.fillStyles(); void createHairControls?.refreshPreview(); }); void createHairControls?.refreshPreview(); graphicsSettingsUi = initGraphicsSettings({ onChange: applyGraphicsSettings }); social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType }); contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick }); inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, contextMenu, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; }, getFriends () { return social?.getFriends?.() ?? []; }, getLocalName () { const you = document.getElementById("you")?.textContent ?? ""; return you.split("(")[0].trim() || "Unknown"; } }); skills = initSkills(); crafting = initCrafting({ socket: { send (payload) { socket.send(payload); } }, MessageType, getInventorySlots () { return inventory?.getInventorySlots?.() ?? []; }, getSkillLevel (skillId) { return skills?.skillLevel?.(skillId) ?? 1; } }); alchemy = initAlchemy({ socket: { send (payload) { socket.send(payload); } }, MessageType, getInventorySlots () { return inventory?.getInventorySlots?.() ?? []; } }); staminaUi = initStamina(); healthUi = initHealth(); statusEffectsUi = initStatusEffects(); toasts = initToasts(); 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?.() ?? []; } }); bounty = initBounty({ socket: { send (payload) { socket.send(payload); } }, MessageType, onSuppressWorldClick: consumeWorldClick, resolveSpriteUrl (name) { return catalog?.images?.find((entry) => entry.name === name)?.url ?? 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(); socket = new GameSocket(defaultSocketUrl(), (message) => { switch (message.type) { case MessageType.session: session = message; statusEl.textContent = `Signed in as ${message.authSubject} (stub 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); break; case MessageType.chunkSnapshot: view?.applySnapshot(message); break; case MessageType.chunkDelta: 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 && message.gait) { gait = message.gait; document.getElementById("gait").textContent = gait; } break; case MessageType.entityDespawn: view?.despawnEntity(message.entityId); break; case MessageType.entityAppearance: view?.setAppearance(message); break; case MessageType.groundItemAppear: view?.upsertGroundItem(message); break; case MessageType.groundItemDespawn: view?.despawnGroundItem(message.groundItemId); break; case MessageType.inventory: inventory?.handleInventory(message); crafting?.refresh(); alchemy?.refresh(); shop?.refresh(); market?.refresh(); break; case MessageType.skills: skills?.render(message.skills); crafting?.refresh(); break; case MessageType.stamina: staminaUi?.apply(message); if (message.gait) { gait = message.gait; document.getElementById("gait").textContent = gait; } break; case MessageType.statusEffects: view?.setLocalBlind(!!message.blind); statusEffectsUi?.apply(message); break; case MessageType.bankSnapshot: inventory?.handleBank(message); break; case MessageType.cauldronSnapshot: 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(); } break; case MessageType.chatBubble: chat?.showBubble(message); break; case MessageType.friends: social?.handleFriends(message); break; case MessageType.combatSwing: view?.spawnCombatSwing(message); break; case MessageType.gatherSwing: case MessageType.tileShove: view?.spawnGatherSwing(message); break; case MessageType.stationOpen: if (message.stationId) { crafting?.openStation(message.stationId); } break; case MessageType.shopOpen: shop?.handleShopOpen(message); break; case MessageType.shopClosed: shop?.handleShopClosed(message); break; case MessageType.marketOpen: market?.handleOpen(message); break; case MessageType.marketClosed: 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: bounty?.handleClosed(message); break; case MessageType.characterBounty: bounty?.handleCharacterBounty(message); social?.handleCharacterBounty(message); break; case MessageType.barberSnapshot: barber?.handleSnapshot(message); break; case MessageType.closeBarber: barber?.handleClosed(message); break; case MessageType.itemBubble: chat?.showItemBubble(message); break; case MessageType.gatherComplete: crafting?.refresh(); break; case MessageType.combatHit: view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); view?.flashDamage(message.targetId); view?.spawnDamageNumber(message.targetId, message.damage); if (message.targetId === view?.localEntityId) { healthUi?.apply({ current: message.health, max: message.maxHealth }); } 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 name = message.displayName ?? message.skillId ?? "Skill"; toasts?.show(`${name} level ${message.level}!`); } break; case MessageType.playerDied: clearAllPendingActions(); contextMenu?.hide(); death?.show(); if (message.entityId === view?.localEntityId) { healthUi?.apply({ current: 0, max: healthUi.getMax?.() }); view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.()); } break; case MessageType.playerRespawned: death?.hide(); view?.updateEntityHealth(message.entityId, message.health, message.maxHealth); 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.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; clearAllPendingActions(); social?.reset(); chat?.reset(); inventory?.reset(); crafting?.reset(); alchemy?.reset(); staminaUi?.hide(); healthUi?.hide(); statusEffectsUi?.hide(); skills?.hide(); contextMenu?.hide(); death?.reset(); shop?.close({ notifyServer: false }); bounty?.close(); barber?.close(); hideWorldTooltip(); if (view) { for (const key of [...(view.chunks?.keys?.() ?? [])]) { const [chunkX, chunkY] = key.split(",").map(Number); view.removeChunk(chunkX, chunkY); } } 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; 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 = ""; } socket.send({ type: MessageType.createCharacter, firstName: document.getElementById("first-name").value, lastName: document.getElementById("last-name").value, sex: document.getElementById("sex").value, hair: createHairControls?.currentHair?.() ?? null }); }); 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 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 isFurnaceTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.furnace; } function isAnvilTile (view, tileX, tileY) { return blockTypeAt(view, tileX, tileY) === BlockType.anvil; } 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 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)); } function hideWorldTooltip () { if (worldTooltip) { worldTooltip.hidden = true; } } /** 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) { hideWorldTooltip(); 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)); }