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