BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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