BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 83.0 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 } from "/shared/definitions/tiles.js";
6import { OVERWORLD_ID } from "/shared/world/dimensions.js";
7import { findPathToNearestGoal } from "/shared/navigation/bfs.js";
8import { isAdjacentTile } from "/shared/navigation/adjacency.js";
9import { GameSocket, defaultSocketUrl } from "../net/socket.js";
10import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
11import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
12import { WorldView } from "../render/worldView.js";
13import { initSocial } from "./social.js";
14import { initChat } from "./chat.js";
15import { initInventory } from "./inventory.js";
16import { initSkills } from "./skills.js";
17import { initSpells } from "./spells.js";
18import { initCrafting } from "./crafting.js";
19import { initAlchemy } from "./alchemy.js";
20import { initTipArrows } from "./tipArrows.js";
21import { initStamina } from "./stamina.js";
22import { initHealth } from "./health.js";
23import { initStatusEffects } from "./statusEffects.js";
24import { initContextMenu } from "./contextMenu.js";
25import { initDeath } from "./death.js";
26import { initToasts } from "./toasts.js";
27import { initTrade } from "./trade.js";
28import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
29import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";
30import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";
31import { initQuests } from "./quests.js";
32import { initDialogue } from "./dialogue.js";
33import { initShop } from "./shop.js";
34import { initMarket } from "./market.js";
35import { initBounty } from "./bounty.js";
36import { initBarber } from "./barber.js";
37import { bindHairControls } from "./hairControls.js";
38import { bindCreateClothingControls } from "./createClothingControls.js";
39import { paintCharacterPreview } from "./characterPreview.js";
40import { initGraphicsSettings } from "./graphicsSettings.js";
41import { CraftingStationId } from "/shared/definitions/craftingStations.js";
42import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
43import { formatQuantity } from "/shared/items/formatQuantity.js";
44import { ItemId, itemDefinition } from "/shared/definitions/items.js";
45import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
46import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
47import { isLogDebarked } from "/shared/definitions/woodItems.js";
48import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
49import { countCoinsInSlots } from "/shared/items/inventory.js";
50
51const game = new Game();
52const hud = document.getElementById("hud");
53const overlay = document.getElementById("overlay");
54const statusEl = document.getElementById("status");
55const characterList = document.getElementById("character-list");
56const errorEl = document.getElementById("error");
57const assetLoadEl = document.getElementById("asset-load");
58const assetLoadBar = document.getElementById("asset-load-bar");
59const assetLoadLabel = document.getElementById("asset-load-label");
60const createCharacterOpen = document.getElementById("create-character-open");
61const worldTooltip = document.getElementById("world-tooltip");
62
63let socket;
64let session = null;
65let playing = false;
66let view = null;
67let graphicsSettingsUi = null;
68let scene = null;
69let gait = GAIT.walk;
70let catalog = { grounds: {}, blocks: {} };
71let social;
72let chat;
73let inventory;
74let skills;
75let spells;
76let crafting;
77let alchemy;
78let staminaUi;
79let healthUi;
80let statusEffectsUi;
81let contextMenu;
82let death;
83let toasts;
84let trade;
85let questsUi;
86let dialogueUi;
87let shop;
88let playZoomRaf = 0;
89let playZoomDelta = 0;
90let market;
91let bounty;
92let barber;
93let createHairControls;
94let createClothingControls;
95let createActiveTab = "appearance";
96let pendingPickup = null;
97/** @type {{ kind: "bank" | "doorway" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | { kind: "market" | "bounty" | "barber", tileX: number, tileY: number } | null } */
98let pendingInteract = null;
99/**
100 * Block/NPC the player currently has a station UI open for.
101 * Closed automatically when Chebyshev distance exceeds 1.
102 * @type {null | { kind: "bank" | "station" | "cauldron" | "market" | "bounty" | "barber", tileX: number, tileY: number } | { kind: "shop" | "dialogue", entityId: number }}
103 */
104let uiFocus = null;
105/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
106let approachMove = null;
107/** Client-tracked follow target; server follow owns gait while this is set. */
108let followTargetId = null;
109/** Destination of the active click/approach moveTo for autorun distance checks. */
110let moveDest = null;
111/** Entity / tile focus for server-driven approach (attack, cast) — no client moveTo. */
112let autorunFocusEntityId = null;
113let autorunFocusTile = null;
114/** After stamina hits 0 while autorunning, wait until ≥50% before running again. */
115let autorunWaitingStamina = false;
116/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
117let leftClickConsumed = false;
118/** Mob/NPC entity ids recently trading blows with the local player (LMB prefers Attack). */
119const combatWithLocalIds = new Set();
120
121const AUTORUN_DISTANCE_TILES = 3;
122const AUTORUN_STAMINA_RESUME_RATIO = 0.5;
123
124function noteCombatWithLocal (attackerId, targetId)
125{
126 const localId = view?.localEntityId;
127 if (localId == null)
128 { return; }
129 const a = attackerId | 0;
130 const t = targetId | 0;
131 if (a === localId && t)
132 { combatWithLocalIds.add(t); }
133 else if (t === localId && a)
134 { combatWithLocalIds.add(a); }
135}
136
137function clearCombatWithLocal (entityId = null)
138{
139 if (entityId == null)
140 {
141 combatWithLocalIds.clear();
142 return;
143 }
144 combatWithLocalIds.delete(entityId | 0);
145}
146
147function leftClickContextFor (entity)
148{
149 const local = view?.entities.get(view.localEntityId);
150 const entityId = entity?.entityId | 0;
151 return {
152 localSkullValue: local?.skullValue | 0,
153 skullSettings: view?.settings ?? null,
154 inCombatWithLocal: combatWithLocalIds.has(entityId)
155 || (autorunFocusEntityId | 0) === entityId
156 };
157}
158
159function sendPlayerMoveTo (tileX, tileY)
160{
161 followTargetId = null;
162 clearAutorunFocus();
163 moveDest = { tileX: tileX | 0, tileY: tileY | 0 };
164 socket.send({ type: MessageType.moveTo, tileX: moveDest.tileX, tileY: moveDest.tileY });
165 syncAutorun();
166}
167
168function sendPlayerFollow (targetEntityId)
169{
170 followTargetId = targetEntityId | 0;
171 moveDest = null;
172 clearAutorunFocus();
173 autorunWaitingStamina = false;
174 socket.send({ type: MessageType.follow, targetEntityId: followTargetId });
175}
176
177function clearAutorunFocus ()
178{
179 autorunFocusEntityId = null;
180 autorunFocusTile = null;
181}
182
183function setAutorunFocusEntity (entityId)
184{
185 moveDest = null;
186 autorunFocusTile = null;
187 autorunFocusEntityId = entityId | 0;
188 syncAutorun();
189}
190
191function setAutorunFocusTile (tileX, tileY)
192{
193 moveDest = null;
194 autorunFocusEntityId = null;
195 autorunFocusTile = { tileX: tileX | 0, tileY: tileY | 0 };
196 syncAutorun();
197}
198
199function resolveAutorunDest ()
200{
201 if (moveDest)
202 { return moveDest; }
203 if (autorunFocusEntityId != null)
204 {
205 const target = view?.entities?.get(autorunFocusEntityId);
206 if (!target)
207 { return null; }
208 return { tileX: target.tileX | 0, tileY: target.tileY | 0 };
209 }
210 return autorunFocusTile;
211}
212
213function localEntityIsMoving (local)
214{
215 if (!local)
216 { return false; }
217 if (local.lerpStarted != null)
218 { return true; }
219 const dx = (local.visualX ?? 0) - (local.targetX ?? local.visualX ?? 0);
220 const dy = (local.visualY ?? 0) - (local.targetY ?? local.visualY ?? 0);
221 return (dx * dx + dy * dy) > 0.25;
222}
223
224function requestGaitIfNeeded (next)
225{
226 if (next !== GAIT.walk && next !== GAIT.run)
227 { return; }
228 if (next === gait)
229 { return; }
230 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 0) <= 0)
231 { return; }
232 socket.send({ type: MessageType.setGait, gait: next });
233 if (next === GAIT.walk)
234 {
235 gait = next;
236 const el = document.getElementById("gait");
237 if (el)
238 { el.textContent = gait; }
239 }
240}
241
242function syncAutorun ()
243{
244 if (!playing || followTargetId != null)
245 { return; }
246 const settings = graphicsSettingsUi?.getSettings?.() ?? {};
247 if (settings.autorun !== "on")
248 { return; }
249 const local = view?.entities?.get(view.localEntityId);
250 const dest = resolveAutorunDest();
251 if (!local || !dest)
252 { return; }
253 if (moveDest && local.tileX === moveDest.tileX && local.tileY === moveDest.tileY)
254 {
255 moveDest = null;
256 autorunWaitingStamina = false;
257 requestGaitIfNeeded(GAIT.walk);
258 return;
259 }
260 // Attack / cast approach is server-pathed — only run while tiles are changing.
261 if (!moveDest && !localEntityIsMoving(local))
262 {
263 requestGaitIfNeeded(GAIT.walk);
264 return;
265 }
266 const dist = chebyshev(local.tileX, local.tileY, dest.tileX, dest.tileY);
267 const wantRun = dist > AUTORUN_DISTANCE_TILES;
268 const current = staminaUi?.getCurrent?.() ?? 0;
269 const max = Math.max(1, staminaUi?.getMax?.() ?? 1);
270 if (gait === GAIT.run && current <= 0)
271 { autorunWaitingStamina = true; }
272 if (autorunWaitingStamina)
273 {
274 if (wantRun && current / max >= AUTORUN_STAMINA_RESUME_RATIO)
275 {
276 autorunWaitingStamina = false;
277 requestGaitIfNeeded(GAIT.run);
278 }
279 else
280 { requestGaitIfNeeded(GAIT.walk); }
281 return;
282 }
283 if (wantRun)
284 {
285 if (current <= 0)
286 {
287 autorunWaitingStamina = true;
288 requestGaitIfNeeded(GAIT.walk);
289 }
290 else
291 { requestGaitIfNeeded(GAIT.run); }
292 }
293 else
294 { requestGaitIfNeeded(GAIT.walk); }
295}
296
297function consumeWorldClick ()
298{
299 leftClickConsumed = true;
300}
301
302function showError (message)
303{
304 errorEl.textContent = message ?? "";
305}
306
307function setAssetLoading (active, { loaded = 0, total = 0, phase = "" } = {})
308{
309 if (assetLoadEl)
310 { assetLoadEl.hidden = !active; }
311 if (characterList)
312 { characterList.hidden = active; }
313 if (createCharacterOpen)
314 { createCharacterOpen.hidden = active; }
315 if (!active)
316 { return; }
317 if (assetLoadBar && total > 0)
318 { assetLoadBar.value = Math.round((loaded / total) * 100); }
319 if (assetLoadLabel)
320 {
321 assetLoadLabel.textContent = phase
322 || (total > 0 ? `Loading assets… ${loaded}/${total}` : "Loading assets…");
323 }
324}
325
326function renderCharacters (characters)
327{
328 characterList.innerHTML = "";
329 for (const character of characters)
330 {
331 const row = document.createElement("div");
332 row.className = "character-row";
333 const pending = character.deletionScheduledAt
334 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
335 : "";
336 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
337 const play = document.createElement("button");
338 play.textContent = "Play";
339 play.disabled = !!character.deletionScheduledAt;
340 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
341 const del = document.createElement("button");
342 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
343 del.addEventListener("click", () =>
344 {
345 socket.send({
346 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
347 characterId: character.characterId
348 });
349 });
350 row.append(play, del);
351 characterList.append(row);
352 }
353}
354
355function uiBlocked ()
356{
357 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
358 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
359 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
360 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
361 || trade?.isBlocking()
362 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
363 || graphicsSettingsUi?.isBlocking?.()
364 || pointerOverSpellUi()
365 || pointerOverToastUi());
366}
367
368function pointerOverSpellUi ()
369{
370 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
371 if (!el)
372 { return false; }
373 return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
374}
375
376function pointerOverToastUi ()
377{
378 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
379 if (!el)
380 { return false; }
381 return !!el.closest("#toast-stack .toast");
382}
383
384function applyGraphicsSettings (settings)
385{
386 view?.setGraphicsPrefs(settings);
387 if (socket && playing)
388 {
389 socket.send({
390 type: MessageType.setGraphicsSettings,
391 viewDistance: settings.viewDistance
392 });
393 }
394 syncAutorun();
395}
396
397function clearPendingPickup ()
398{
399 pendingPickup = null;
400}
401
402function clearPendingInteract ()
403{
404 pendingInteract = null;
405 approachMove = null;
406}
407
408function clearAllPendingActions ()
409{
410 clearPendingPickup();
411 clearPendingInteract();
412}
413
414function approachAdjacentTile (tileX, tileY)
415{
416 const local = view.entities.get(view.localEntityId);
417 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
418 {
419 approachMove = null;
420 return true;
421 }
422 if (!local)
423 { return false; }
424
425 const radius = Math.max(1, STATIC_CHUNK_RADIUS | 0) * CHUNK_SIZE;
426 const path = findPathToNearestGoal(
427 local.tileX,
428 local.tileY,
429 (x, y) => chebyshev(x, y, tileX, tileY) === 1 && isClientApproachable(x, y),
430 (x, y) => isClientApproachable(x, y),
431 local.tileX - radius,
432 local.tileY - radius,
433 local.tileX + radius,
434 local.tileY + radius
435 );
436 let best = path.length ? path[path.length - 1] : null;
437 if (!best)
438 {
439 // Fallback if BFS finds nothing (incomplete client map): nearest adjacent guess.
440 let bestAny = null;
441 let bestAnyDist = Infinity;
442 for (let dy = -1; dy <= 1; dy++)
443 {
444 for (let dx = -1; dx <= 1; dx++)
445 {
446 if (dx === 0 && dy === 0)
447 { continue; }
448 const destX = tileX + dx;
449 const destY = tileY + dy;
450 const dist = chebyshev(local.tileX, local.tileY, destX, destY);
451 if (dist < bestAnyDist)
452 {
453 bestAnyDist = dist;
454 bestAny = { tileX: destX, tileY: destY };
455 }
456 }
457 }
458 best = bestAny ? { x: bestAny.tileX, y: bestAny.tileY } : null;
459 }
460 if (!best)
461 { return false; }
462 const destX = best.x ?? best.tileX;
463 const destY = best.y ?? best.tileY;
464 if (
465 approachMove
466 && approachMove.focusX === tileX
467 && approachMove.focusY === tileY
468 && approachMove.destX === destX
469 && approachMove.destY === destY
470 )
471 { return false; }
472 approachMove = {
473 focusX: tileX,
474 focusY: tileY,
475 destX,
476 destY
477 };
478 sendPlayerMoveTo(destX, destY);
479 return false;
480}
481
482function requestOpenBank (tileX, tileY, { getCheques = false } = {})
483{
484 clearAllPendingActions();
485 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
486 const local = view?.entities.get(view.localEntityId);
487 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
488 { flushPendingInteract(); }
489 else
490 { approachAdjacentTile(tileX, tileY); }
491}
492
493function requestEnterDoorway (tileX, tileY)
494{
495 clearAllPendingActions();
496 pendingInteract = { kind: "doorway", tileX, tileY };
497 const local = view?.entities.get(view.localEntityId);
498 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
499 { flushPendingInteract(); }
500 else
501 { approachAdjacentTile(tileX, tileY); }
502}
503
504function requestOpenMarket (tileX, tileY)
505{
506 clearAllPendingActions();
507 pendingInteract = { kind: "market", tileX, tileY };
508 const local = view?.entities.get(view.localEntityId);
509 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
510 { flushPendingInteract(); }
511 else
512 { approachAdjacentTile(tileX, tileY); }
513}
514
515function requestOpenBounty (tileX, tileY)
516{
517 clearAllPendingActions();
518 pendingInteract = { kind: "bounty", tileX, tileY };
519 const local = view?.entities.get(view.localEntityId);
520 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
521 { flushPendingInteract(); }
522 else
523 { approachAdjacentTile(tileX, tileY); }
524}
525
526function requestOpenBarber (tileX, tileY)
527{
528 clearAllPendingActions();
529 pendingInteract = { kind: "barber", tileX, tileY };
530 const local = view?.entities.get(view.localEntityId);
531 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
532 { flushPendingInteract(); }
533 else
534 { approachAdjacentTile(tileX, tileY); }
535}
536
537function requestOpenCauldron (tileX, tileY)
538{
539 clearAllPendingActions();
540 pendingInteract = { kind: "cauldron", tileX, tileY };
541 const local = view?.entities.get(view.localEntityId);
542 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
543 { flushPendingInteract(); }
544 else
545 { approachAdjacentTile(tileX, tileY); }
546}
547
548function requestOpenFurnace (tileX, tileY)
549{
550 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
551}
552
553function requestOpenCraftStation (stationId, tileX, tileY)
554{
555 clearAllPendingActions();
556 pendingInteract = { kind: "station", stationId, tileX, tileY };
557 const local = view?.entities.get(view.localEntityId);
558 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
559 { flushPendingInteract(); }
560 else
561 { approachAdjacentTile(tileX, tileY); }
562}
563
564function requestStartFire (ground)
565{
566 if (!ground)
567 { return; }
568 clearAllPendingActions();
569 pendingInteract = {
570 kind: "start-fire",
571 groundItemId: ground.groundItemId,
572 tileX: ground.tileX,
573 tileY: ground.tileY
574 };
575 const local = view?.entities.get(view.localEntityId);
576 if (local && isAdjacentTile(local.tileX, local.tileY, ground.tileX, ground.tileY))
577 { flushPendingInteract(); }
578 else
579 { approachAdjacentTile(ground.tileX, ground.tileY); }
580}
581
582function requestDebarkLog (ground)
583{
584 if (!ground)
585 { return; }
586 clearAllPendingActions();
587 pendingInteract = {
588 kind: "debark-log",
589 groundItemId: ground.groundItemId,
590 tileX: ground.tileX,
591 tileY: ground.tileY
592 };
593 const local = view?.entities.get(view.localEntityId);
594 if (local && isAdjacentTile(local.tileX, local.tileY, ground.tileX, ground.tileY))
595 { flushPendingInteract(); }
596 else
597 { approachAdjacentTile(ground.tileX, ground.tileY); }
598}
599
600function requestFish (tileX, tileY)
601{
602 clearAllPendingActions();
603 pendingInteract = { kind: "fish", tileX, tileY };
604 const local = view?.entities.get(view.localEntityId);
605 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
606 { flushPendingInteract(); }
607 else
608 { approachAdjacentTile(tileX, tileY); }
609}
610
611function requestMine (tileX, tileY)
612{
613 clearAllPendingActions();
614 pendingInteract = { kind: "mine", tileX, tileY };
615 const local = view?.entities.get(view.localEntityId);
616 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
617 { flushPendingInteract(); }
618 else
619 { approachAdjacentTile(tileX, tileY); }
620}
621
622function requestChop (tileX, tileY)
623{
624 clearAllPendingActions();
625 pendingInteract = { kind: "chop", tileX, tileY };
626 const local = view?.entities.get(view.localEntityId);
627 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
628 { flushPendingInteract(); }
629 else
630 { approachAdjacentTile(tileX, tileY); }
631}
632
633function requestPick (tileX, tileY)
634{
635 clearAllPendingActions();
636 pendingInteract = { kind: "pick", tileX, tileY };
637 const local = view?.entities.get(view.localEntityId);
638 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
639 { flushPendingInteract(); }
640 else
641 { approachAdjacentTile(tileX, tileY); }
642}
643
644function requestTalk (targetEntityId, purpose = null)
645{
646 clearAllPendingActions();
647 pendingInteract = { kind: "talk", targetEntityId, purpose };
648 const target = view?.entities.get(targetEntityId);
649 if (!target)
650 {
651 clearPendingInteract();
652 return;
653 }
654 if (approachAdjacentTile(target.tileX, target.tileY))
655 { flushPendingInteract(); }
656}
657
658function playerHasShears ()
659{
660 const slots = inventory?.getInventorySlots?.() ?? [];
661 const equipment = inventory?.getEquipment?.() ?? {};
662 for (const stack of [...slots, equipment.weapon])
663 {
664 if (!stack?.itemId)
665 { continue; }
666 if (itemDefinition(stack.itemId)?.equipment?.kind === EquipmentKind.shears)
667 { return true; }
668 }
669 return false;
670}
671
672function entityCanShear (entity)
673{
674 if (!entity?.mobTypeId)
675 { return false; }
676 const def = mobDefinition(entity.mobTypeId);
677 const shearable = def?.shearable;
678 if (!shearable)
679 { return false; }
680 const sprite = entity.layers?.[0]?.sprite ?? entity.sprite ?? "";
681 if (String(sprite).endsWith(`:${shearable.shornState}`))
682 { return false; }
683 return playerHasShears();
684}
685
686function requestShear (targetEntityId)
687{
688 clearAllPendingActions();
689 pendingInteract = { kind: "shear", targetEntityId };
690 const target = view?.entities.get(targetEntityId);
691 if (!target)
692 {
693 clearPendingInteract();
694 return;
695 }
696 if (approachAdjacentTile(target.tileX, target.tileY))
697 { flushPendingInteract(); }
698}
699
700function setUiFocus (focus)
701{
702 uiFocus = focus;
703}
704
705function clearUiFocus ()
706{
707 uiFocus = null;
708}
709
710/** Close stations, bank, dialogue, and other overlays when the local player dies. */
711function closeCloseablePlayUi ()
712{
713 clearUiFocus();
714 inventory?.closeBank?.();
715 inventory?.closeOverlays?.();
716 if (crafting?.isOpen?.())
717 { crafting.close(); }
718 if (alchemy?.isOpen?.())
719 { alchemy.close(); }
720 if (market?.isOpen?.())
721 { market.close(); }
722 if (bounty?.isOpen?.())
723 { bounty.close(); }
724 if (barber?.isOpen?.())
725 { barber.close(); }
726 if (shop?.isOpen?.())
727 { shop.close(); }
728 if (dialogueUi?.isOpen?.())
729 { dialogueUi.close(); }
730 questsUi?.hide?.();
731 chat?.close?.();
732 social?.closeOverlays?.();
733 contextMenu?.hide();
734 spells?.handleSpellDisarmed?.();
735 graphicsSettingsUi?.close?.();
736}
737
738/** Close bank / station / NPC UIs when the player walks out of adjacency. */
739function closeOpenUiIfTooFar ()
740{
741 if (!uiFocus || !view)
742 { return; }
743 const local = view.entities.get(view.localEntityId);
744 if (!local)
745 { return; }
746
747 let tooFar = false;
748 if (uiFocus.entityId != null)
749 {
750 const target = view.entities.get(uiFocus.entityId);
751 tooFar = !target
752 || !isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY);
753 }
754 else if (uiFocus.tileX != null && uiFocus.tileY != null)
755 {
756 tooFar = !isAdjacentTile(local.tileX, local.tileY, uiFocus.tileX, uiFocus.tileY);
757 }
758 if (!tooFar)
759 { return; }
760
761 const kind = uiFocus.kind;
762 clearUiFocus();
763 switch (kind)
764 {
765 case "bank":
766 if (inventory?.isBankOpen?.())
767 { inventory.closeBank(); }
768 break;
769 case "station":
770 if (crafting?.isOpen?.())
771 { crafting.close(); }
772 break;
773 case "cauldron":
774 if (alchemy?.isOpen?.())
775 { alchemy.close(); }
776 break;
777 case "market":
778 if (market?.isOpen?.())
779 { market.close(); }
780 break;
781 case "bounty":
782 if (bounty?.isOpen?.())
783 { bounty.close(); }
784 break;
785 case "barber":
786 if (barber?.isOpen?.())
787 { barber.close(); }
788 break;
789 case "shop":
790 if (shop?.isOpen?.())
791 { shop.close(); }
792 break;
793 case "dialogue":
794 if (dialogueUi?.isOpen?.())
795 { dialogueUi.close(); }
796 break;
797 default:
798 break;
799 }
800}
801
802function flushPendingInteract ()
803{
804 if (!pendingInteract || !view)
805 { return; }
806 const local = view.entities.get(view.localEntityId);
807 if (!local)
808 { return; }
809
810 if (pendingInteract.kind === "bank")
811 {
812 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
813 { return; }
814 setUiFocus({
815 kind: "bank",
816 tileX: pendingInteract.tileX,
817 tileY: pendingInteract.tileY
818 });
819 const getCheques = !!pendingInteract.getCheques;
820 socket.send({ type: MessageType.openBank });
821 if (getCheques)
822 { inventory?.getBlankCheques(); }
823 clearPendingInteract();
824 return;
825 }
826
827 if (pendingInteract.kind === "doorway")
828 {
829 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
830 { return; }
831 socket.send({
832 type: MessageType.enterDoorway,
833 tileX: pendingInteract.tileX,
834 tileY: pendingInteract.tileY
835 });
836 clearPendingInteract();
837 return;
838 }
839
840 if (pendingInteract.kind === "market")
841 {
842 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
843 { return; }
844 setUiFocus({
845 kind: "market",
846 tileX: pendingInteract.tileX,
847 tileY: pendingInteract.tileY
848 });
849 socket.send({ type: MessageType.openMarket });
850 clearPendingInteract();
851 return;
852 }
853
854 if (pendingInteract.kind === "bounty")
855 {
856 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
857 { return; }
858 setUiFocus({
859 kind: "bounty",
860 tileX: pendingInteract.tileX,
861 tileY: pendingInteract.tileY
862 });
863 socket.send({ type: MessageType.openBounty });
864 clearPendingInteract();
865 return;
866 }
867
868 if (pendingInteract.kind === "barber")
869 {
870 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
871 { return; }
872 setUiFocus({
873 kind: "barber",
874 tileX: pendingInteract.tileX,
875 tileY: pendingInteract.tileY
876 });
877 socket.send({ type: MessageType.openBarber });
878 clearPendingInteract();
879 return;
880 }
881
882 if (pendingInteract.kind === "cauldron")
883 {
884 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
885 { return; }
886 setUiFocus({
887 kind: "cauldron",
888 tileX: pendingInteract.tileX,
889 tileY: pendingInteract.tileY
890 });
891 socket.send({ type: MessageType.openCauldron });
892 clearPendingInteract();
893 return;
894 }
895
896 if (pendingInteract.kind === "station")
897 {
898 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
899 { return; }
900 setUiFocus({
901 kind: "station",
902 tileX: pendingInteract.tileX,
903 tileY: pendingInteract.tileY
904 });
905 socket.send({
906 type: MessageType.openStation,
907 stationId: pendingInteract.stationId
908 });
909 clearPendingInteract();
910 return;
911 }
912
913 if (pendingInteract.kind === "mine")
914 {
915 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
916 { return; }
917 socket.send({
918 type: MessageType.mine,
919 tileX: pendingInteract.tileX,
920 tileY: pendingInteract.tileY
921 });
922 clearPendingInteract();
923 return;
924 }
925
926 if (pendingInteract.kind === "start-fire")
927 {
928 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
929 { return; }
930 socket.send({
931 type: MessageType.startFire,
932 groundItemId: pendingInteract.groundItemId
933 });
934 clearPendingInteract();
935 return;
936 }
937
938 if (pendingInteract.kind === "debark-log")
939 {
940 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY)
941 && !(local.tileX === pendingInteract.tileX && local.tileY === pendingInteract.tileY))
942 { return; }
943 socket.send({
944 type: MessageType.debarkLog,
945 groundItemId: pendingInteract.groundItemId
946 });
947 clearPendingInteract();
948 return;
949 }
950
951 if (pendingInteract.kind === "fish")
952 {
953 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
954 { return; }
955 socket.send({
956 type: MessageType.startFish,
957 tileX: pendingInteract.tileX,
958 tileY: pendingInteract.tileY
959 });
960 clearPendingInteract();
961 return;
962 }
963
964 if (pendingInteract.kind === "chop")
965 {
966 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
967 { return; }
968 socket.send({
969 type: MessageType.chop,
970 tileX: pendingInteract.tileX,
971 tileY: pendingInteract.tileY
972 });
973 clearPendingInteract();
974 return;
975 }
976
977 if (pendingInteract.kind === "pick")
978 {
979 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
980 { return; }
981 socket.send({
982 type: MessageType.pick,
983 tileX: pendingInteract.tileX,
984 tileY: pendingInteract.tileY
985 });
986 clearPendingInteract();
987 return;
988 }
989
990 if (pendingInteract.kind === "talk")
991 {
992 const target = view.entities.get(pendingInteract.targetEntityId);
993 if (!target)
994 {
995 clearPendingInteract();
996 return;
997 }
998 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY))
999 {
1000 // Target may have moved — keep chasing.
1001 approachAdjacentTile(target.tileX, target.tileY);
1002 return;
1003 }
1004 socket.send({
1005 type: MessageType.interact,
1006 targetEntityId: pendingInteract.targetEntityId,
1007 purpose: pendingInteract.purpose || undefined
1008 });
1009 // Shop vs dialogue is decided server-side; both use NPC adjacency.
1010 setUiFocus({
1011 kind: pendingInteract.purpose === "shop" ? "shop" : "dialogue",
1012 entityId: pendingInteract.targetEntityId
1013 });
1014 clearPendingInteract();
1015 return;
1016 }
1017
1018 if (pendingInteract.kind === "trade-request")
1019 {
1020 const target = view.entities.get(pendingInteract.targetEntityId);
1021 if (!target)
1022 {
1023 clearPendingInteract();
1024 return;
1025 }
1026 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY)
1027 && !(local.tileX === target.tileX && local.tileY === target.tileY))
1028 {
1029 approachAdjacentTile(target.tileX, target.tileY);
1030 return;
1031 }
1032 const targetEntityId = pendingInteract.targetEntityId;
1033 clearPendingInteract();
1034 trade?.flushPendingRequest?.(targetEntityId);
1035 return;
1036 }
1037
1038 if (pendingInteract.kind === "trade-accept")
1039 {
1040 const target = view.entities.get(pendingInteract.fromEntityId);
1041 if (!target)
1042 {
1043 clearPendingInteract();
1044 return;
1045 }
1046 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY)
1047 && !(local.tileX === target.tileX && local.tileY === target.tileY))
1048 {
1049 approachAdjacentTile(target.tileX, target.tileY);
1050 return;
1051 }
1052 const invite = pendingInteract.invite;
1053 clearPendingInteract();
1054 trade?.flushPendingAccept?.(invite);
1055 return;
1056 }
1057 if (pendingInteract.kind === "shear")
1058 {
1059 const target = view.entities.get(pendingInteract.targetEntityId);
1060 if (!target)
1061 {
1062 clearPendingInteract();
1063 return;
1064 }
1065 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY))
1066 {
1067 approachAdjacentTile(target.tileX, target.tileY);
1068 return;
1069 }
1070 socket.send({
1071 type: MessageType.shear,
1072 targetEntityId: pendingInteract.targetEntityId
1073 });
1074 clearPendingInteract();
1075 }
1076}
1077
1078function requestPickup (ground)
1079{
1080 if (!ground)
1081 { return; }
1082 clearPendingInteract();
1083 pendingPickup = {
1084 groundItemId: ground.groundItemId,
1085 tileX: ground.tileX,
1086 tileY: ground.tileY
1087 };
1088 const local = view.entities.get(view.localEntityId);
1089 if (local && local.tileX === ground.tileX && local.tileY === ground.tileY)
1090 {
1091 flushPendingPickup();
1092 return;
1093 }
1094 sendPlayerMoveTo(ground.tileX, ground.tileY);
1095}
1096
1097function flushPendingPickup ()
1098{
1099 if (!pendingPickup || !view)
1100 { return; }
1101 const item = view.groundItems.get(pendingPickup.groundItemId);
1102 if (!item)
1103 {
1104 clearPendingPickup();
1105 return;
1106 }
1107 const local = view.entities.get(view.localEntityId);
1108 if (!local)
1109 { return; }
1110 if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY)
1111 { return; }
1112 socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId });
1113 clearPendingPickup();
1114}
1115
1116function requestApproachEntity (targetEntityId)
1117{
1118 clearAllPendingActions();
1119 const target = view?.entities.get(targetEntityId);
1120 if (!target)
1121 { return; }
1122 approachAdjacentTile(target.tileX, target.tileY);
1123}
1124
1125function requestAttack (targetEntityId)
1126{
1127 clearAllPendingActions();
1128 setAutorunFocusEntity(targetEntityId);
1129 combatWithLocalIds.add(targetEntityId | 0);
1130 socket.send({ type: MessageType.attack, targetEntityId });
1131}
1132
1133function isAttackableEntity (entity)
1134{
1135 if (!entity || entity.untargetable)
1136 { return false; }
1137 if (entity.canFight)
1138 { return true; }
1139 // Snapshots can omit canFight; mobs are still attackable via LMB.
1140 return !!entity.mobTypeId && !entity.talkable;
1141}
1142
1143function canTalkToEntity (entity)
1144{
1145 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
1146}
1147
1148function isApproachingCombatOrCast ()
1149{
1150 return autorunFocusEntityId != null || autorunFocusTile != null;
1151}
1152
1153function handleLeftClick (mouseX, mouseY)
1154{
1155 const tile = view.screenToTile(mouseX, mouseY);
1156 const armed = spells?.getArmedSpell?.();
1157 const approaching = isApproachingCombatOrCast();
1158
1159 // Entity-armed: cast only when a valid target is under the cursor. Empty ground
1160 // must fall through so walk cancels cast/attack approach (server moveTo clears it).
1161 if (armed?.target === "entity" && armed.canCast)
1162 {
1163 const snap = nearestSpellEntityAtCursor(mouseX, mouseY);
1164 if (snap && spells.tryCastAtEntity(snap.entityId))
1165 {
1166 setAutorunFocusEntity(snap.entityId);
1167 return;
1168 }
1169 }
1170 // Tile-armed while approaching: prefer walk-cancel over re-targeting the cast.
1171 else if (
1172 !approaching
1173 && armed?.target === "tile"
1174 && armed.canCast
1175 && spells.tryCastAtTile(tile.tileX, tile.tileY)
1176 )
1177 {
1178 setAutorunFocusTile(tile.tileX, tile.tileY);
1179 return;
1180 }
1181
1182 const entity = view.entityAtScreen(mouseX, mouseY);
1183 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
1184 {
1185 clearPendingPickup();
1186 const clickAction = defaultLeftClickEntityAction(entity, leftClickContextFor(entity));
1187 if (clickAction === "inspect")
1188 {
1189 clearPendingInteract();
1190 social.inspect(entity);
1191 return;
1192 }
1193 if (clickAction === "attack")
1194 {
1195 requestAttack(entity.entityId);
1196 return;
1197 }
1198 if (clickAction === "talk")
1199 {
1200 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
1201 ? "talk"
1202 : (entity.hasShop ? "shop" : "talk");
1203 requestTalk(entity.entityId, purpose);
1204 return;
1205 }
1206 if (clickAction === "approach")
1207 {
1208 requestApproachEntity(entity.entityId);
1209 return;
1210 }
1211 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
1212 return;
1213 }
1214
1215 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
1216 if (ground)
1217 { requestPickup(ground); }
1218 else if (isBankTile(view, tile.tileX, tile.tileY))
1219 { requestOpenBank(tile.tileX, tile.tileY); }
1220 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
1221 { requestEnterDoorway(tile.tileX, tile.tileY); }
1222 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1223 { requestOpenMarket(tile.tileX, tile.tileY); }
1224 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1225 { requestOpenBounty(tile.tileX, tile.tileY); }
1226 else if (isBarberTile(view, tile.tileX, tile.tileY))
1227 { requestOpenBarber(tile.tileX, tile.tileY); }
1228 else if (isCauldronTile(view, tile.tileX, tile.tileY))
1229 { requestOpenCauldron(tile.tileX, tile.tileY); }
1230 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
1231 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
1232 else if (isOvenTile(view, tile.tileX, tile.tileY))
1233 { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); }
1234 else if (isCampfireTile(view, tile.tileX, tile.tileY))
1235 { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); }
1236 else if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1237 { requestFish(tile.tileX, tile.tileY); }
1238 else if (isAnvilTile(view, tile.tileX, tile.tileY))
1239 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
1240 else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1241 { requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }
1242 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1243 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
1244 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1245 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
1246 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1247 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
1248 else if (isLoomTile(view, tile.tileX, tile.tileY))
1249 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
1250 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1251 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
1252 else if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1253 { requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY); }
1254 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1255 { requestMine(tile.tileX, tile.tileY); }
1256 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1257 { requestChop(tile.tileX, tile.tileY); }
1258 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1259 { requestPick(tile.tileX, tile.tileY); }
1260 else
1261 {
1262 clearAllPendingActions();
1263 sendPlayerMoveTo(tile.tileX, tile.tileY);
1264 }
1265}
1266
1267function handleRightClick (event, mouseX, mouseY)
1268{
1269 event.preventDefault();
1270 if (spells?.isTargeting?.())
1271 {
1272 spells.cancelTargeting();
1273 view?.clearSpellTargetHighlight();
1274 return;
1275 }
1276 const tile = view.screenToTile(mouseX, mouseY);
1277 const items = [];
1278 const walkTileX = tile.tileX;
1279 const walkTileY = tile.tileY;
1280
1281 items.push({
1282 label: "Walk here",
1283 onSelect: () =>
1284 {
1285 clearAllPendingActions();
1286 sendPlayerMoveTo(walkTileX, walkTileY);
1287 }
1288 });
1289
1290 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY, { includePrevious: true }))
1291 {
1292 if (entity.entityId === view.localEntityId)
1293 {
1294 const equipment = { slots: inventory?.getEquipment?.() ?? {} };
1295 if (canTeleportToChurch(equipment))
1296 {
1297 items.push({
1298 label: "Teleport to Church",
1299 onSelect: () =>
1300 {
1301 clearAllPendingActions();
1302 socket.send({
1303 type: MessageType.jewelryTeleport,
1304 destination: "church"
1305 });
1306 }
1307 });
1308 }
1309 if (canTeleportToBank(equipment))
1310 {
1311 items.push({
1312 label: "Teleport to bank",
1313 onSelect: () =>
1314 {
1315 clearAllPendingActions();
1316 socket.send({
1317 type: MessageType.jewelryTeleport,
1318 destination: "bank"
1319 });
1320 }
1321 });
1322 }
1323 continue;
1324 }
1325 const targetName = entityLabel(entity);
1326 items.push({
1327 label: `Follow ${targetName}`,
1328 onSelect: () =>
1329 {
1330 clearAllPendingActions();
1331 sendPlayerFollow(entity.entityId);
1332 }
1333 });
1334 if (entity.untargetable)
1335 { continue; }
1336 const clickCtx = leftClickContextFor(entity);
1337 const attackFirst = preferAttackInContextMenu(entity, clickCtx);
1338 const pushAttack = () =>
1339 {
1340 if (!isAttackableEntity(entity))
1341 { return; }
1342 items.push({
1343 label: `Attack ${targetName}`,
1344 onSelect: () => requestAttack(entity.entityId)
1345 });
1346 };
1347 // Prefer Attack first when that matches LMB (aggressive / combat / hostile guards).
1348 if (attackFirst)
1349 { pushAttack(); }
1350 if (entity.hasShop)
1351 {
1352 items.push({
1353 label: `Shop ${targetName}`,
1354 onSelect: () => requestTalk(entity.entityId, "shop")
1355 });
1356 }
1357 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
1358 {
1359 items.push({
1360 label: `Talk to ${targetName}`,
1361 onSelect: () => requestTalk(entity.entityId, "talk")
1362 });
1363 }
1364 if (entityCanShear(entity))
1365 {
1366 items.push({
1367 label: `Shear ${targetName}`,
1368 onSelect: () => requestShear(entity.entityId)
1369 });
1370 }
1371 if (entity.characterId)
1372 {
1373 items.push({
1374 label: "Trade",
1375 onSelect: () =>
1376 {
1377 clearAllPendingActions();
1378 trade?.requestTrade?.(entity.entityId);
1379 }
1380 });
1381 items.push({
1382 label: `${targetName} info`,
1383 onSelect: () =>
1384 {
1385 clearAllPendingActions();
1386 social.inspect(entity);
1387 }
1388 });
1389 }
1390 if (!attackFirst)
1391 { pushAttack(); }
1392 }
1393
1394 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1395 {
1396 const name = groundLabel(ground);
1397 items.push({
1398 label: `Pick up ${name}`,
1399 onSelect: () => requestPickup(ground)
1400 });
1401 if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
1402 {
1403 items.push({
1404 label: `Start Fire`,
1405 onSelect: () => requestStartFire(ground)
1406 });
1407 }
1408 if (isGroundWoodLog(ground) && !isLogDebarked(ground))
1409 {
1410 items.push({
1411 label: "Debark",
1412 onSelect: () => requestDebarkLog(ground)
1413 });
1414 }
1415 }
1416
1417 if (isBankTile(view, tile.tileX, tile.tileY))
1418 {
1419 items.push({
1420 label: "Bank",
1421 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
1422 });
1423 items.push({
1424 label: "Get Blank Cheques",
1425 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
1426 });
1427 }
1428
1429 if (isDoorwayTile(view, tile.tileX, tile.tileY))
1430 {
1431 items.push({
1432 label: "Enter",
1433 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
1434 });
1435 }
1436
1437 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1438 {
1439 items.push({
1440 label: "Central Exchange",
1441 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
1442 });
1443 }
1444
1445 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1446 {
1447 items.push({
1448 label: "Bounty Office",
1449 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
1450 });
1451 }
1452
1453 if (isBarberTile(view, tile.tileX, tile.tileY))
1454 {
1455 items.push({
1456 label: "Barber",
1457 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
1458 });
1459 }
1460
1461 if (isCauldronTile(view, tile.tileX, tile.tileY))
1462 {
1463 items.push({
1464 label: "Alchemy",
1465 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
1466 });
1467 }
1468
1469 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1470 {
1471 items.push({
1472 label: "Smelt",
1473 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
1474 });
1475 }
1476
1477 if (isOvenTile(view, tile.tileX, tile.tileY))
1478 {
1479 items.push({
1480 label: "Cook",
1481 onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
1482 });
1483 }
1484
1485 if (isCampfireTile(view, tile.tileX, tile.tileY))
1486 {
1487 items.push({
1488 label: "Cook",
1489 onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
1490 });
1491 }
1492
1493 if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1494 {
1495 items.push({
1496 label: "Fish",
1497 onSelect: () => requestFish(tile.tileX, tile.tileY)
1498 });
1499 }
1500
1501 if (isAnvilTile(view, tile.tileX, tile.tileY))
1502 {
1503 items.push({
1504 label: "Smith",
1505 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
1506 });
1507 }
1508
1509 if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1510 {
1511 items.push({
1512 label: "Jewel",
1513 onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1514 });
1515 }
1516
1517 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1518 {
1519 items.push({
1520 label: "Woodwork",
1521 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
1522 });
1523 }
1524
1525 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1526 {
1527 items.push({
1528 label: "Craft",
1529 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
1530 });
1531 }
1532
1533 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1534 {
1535 items.push({
1536 label: "Spin",
1537 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
1538 });
1539 }
1540
1541 if (isLoomTile(view, tile.tileX, tile.tileY))
1542 {
1543 items.push({
1544 label: "Weave",
1545 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
1546 });
1547 }
1548
1549 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1550 {
1551 items.push({
1552 label: "Tailor",
1553 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
1554 });
1555 }
1556
1557 if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1558 {
1559 items.push({
1560 label: "Leatherwork",
1561 onSelect: () => requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY)
1562 });
1563 }
1564
1565 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1566 {
1567 items.push({
1568 label: "Mine",
1569 onSelect: () => requestMine(tile.tileX, tile.tileY)
1570 });
1571 }
1572
1573 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1574 {
1575 items.push({
1576 label: "Chop",
1577 onSelect: () => requestChop(tile.tileX, tile.tileY)
1578 });
1579 }
1580
1581 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1582 {
1583 items.push({
1584 label: "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}