BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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