BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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