BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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