BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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