BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 48.3 KiB Download Raw
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
3import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
4import { OVERWORLD_ID } from "/shared/world/dimensions.js";
5import { GameSocket, defaultSocketUrl } from "../net/socket.js";
6import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
7import { WorldView } from "../render/worldView.js";
8import { initSocial } from "./social.js";
9import { initChat } from "./chat.js";
10import { initInventory } from "./inventory.js";
11import { initSkills } from "./skills.js";
12import { initSpells } from "./spells.js";
13import { initCrafting } from "./crafting.js";
14import { initAlchemy } from "./alchemy.js";
15import { initStamina } from "./stamina.js";
16import { initHealth } from "./health.js";
17import { initStatusEffects } from "./statusEffects.js";
18import { initContextMenu } from "./contextMenu.js";
19import { initDeath } from "./death.js";
20import { initToasts } from "./toasts.js";
21import { initQuests } from "./quests.js";
22import { initDialogue } from "./dialogue.js";
23import { initShop } from "./shop.js";
24import { initMarket } from "./market.js";
25import { initBounty } from "./bounty.js";
26import { initBarber } from "./barber.js";
27import { bindHairControls } from "./hairControls.js";
28import { initGraphicsSettings } from "./graphicsSettings.js";
29import { CraftingStationId } from "/shared/definitions/craftingStations.js";
30import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
31import { formatQuantity } from "/shared/items/formatQuantity.js";
32import { ItemId } from "/shared/definitions/items.js";
33import { countCoinsInSlots } from "/shared/items/inventory.js";
34
35const game = new Game();
36const hud = document.getElementById("hud");
37const overlay = document.getElementById("overlay");
38const statusEl = document.getElementById("status");
39const characterList = document.getElementById("character-list");
40const errorEl = document.getElementById("error");
41const worldTooltip = document.getElementById("world-tooltip");
42
43let socket;
44let session = null;
45let playing = false;
46let view = null;
47let graphicsSettingsUi = null;
48let scene = null;
49let gait = GAIT.walk;
50let catalog = { grounds: {}, blocks: {} };
51let social;
52let chat;
53let inventory;
54let skills;
55let spells;
56let crafting;
57let alchemy;
58let staminaUi;
59let healthUi;
60let statusEffectsUi;
61let contextMenu;
62let death;
63let toasts;
64let questsUi;
65let dialogueUi;
66let shop;
67let market;
68let bounty;
69let barber;
70let createHairControls;
71let pendingPickup = null;
72/** @type {{ kind: "bank" | "doorway" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
73let pendingInteract = null;
74/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
75let approachMove = null;
76/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
77let leftClickConsumed = false;
78
79function consumeWorldClick ()
80{
81 leftClickConsumed = true;
82}
83
84function showError (message)
85{
86 errorEl.textContent = message ?? "";
87}
88
89function renderCharacters (characters)
90{
91 characterList.innerHTML = "";
92 for (const character of characters)
93 {
94 const row = document.createElement("div");
95 row.className = "character-row";
96 const pending = character.deletionScheduledAt
97 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
98 : "";
99 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
100 const play = document.createElement("button");
101 play.textContent = "Play";
102 play.disabled = !!character.deletionScheduledAt;
103 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
104 const del = document.createElement("button");
105 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
106 del.addEventListener("click", () =>
107 {
108 socket.send({
109 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
110 characterId: character.characterId
111 });
112 });
113 row.append(play, del);
114 characterList.append(row);
115 }
116}
117
118function uiBlocked ()
119{
120 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
121 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
122 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
123 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
124 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
125 || pointerOverSpellUi());
126}
127
128function pointerOverSpellUi ()
129{
130 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
131 if (!el)
132 { return false; }
133 return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
134}
135
136function applyGraphicsSettings (settings)
137{
138 view?.setGraphicsPrefs(settings);
139 if (socket && playing)
140 {
141 socket.send({
142 type: MessageType.setGraphicsSettings,
143 viewDistance: settings.viewDistance
144 });
145 }
146}
147
148function clearPendingPickup ()
149{
150 pendingPickup = null;
151}
152
153function clearPendingInteract ()
154{
155 pendingInteract = null;
156 approachMove = null;
157}
158
159function clearAllPendingActions ()
160{
161 clearPendingPickup();
162 clearPendingInteract();
163}
164
165function approachAdjacentTile (tileX, tileY)
166{
167 const local = view.entities.get(view.localEntityId);
168 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
169 {
170 approachMove = null;
171 return true;
172 }
173 let bestWalkable = null;
174 let bestWalkableDist = Infinity;
175 let bestAny = null;
176 let bestAnyDist = Infinity;
177 for (let dy = -1; dy <= 1; dy++)
178 {
179 for (let dx = -1; dx <= 1; dx++)
180 {
181 if (dx === 0 && dy === 0)
182 { continue; }
183 const destX = tileX + dx;
184 const destY = tileY + dy;
185 const dist = local
186 ? chebyshev(local.tileX, local.tileY, destX, destY)
187 : 0;
188 if (dist < bestAnyDist)
189 {
190 bestAnyDist = dist;
191 bestAny = { tileX: destX, tileY: destY };
192 }
193 if (isClientApproachable(destX, destY) && dist < bestWalkableDist)
194 {
195 bestWalkableDist = dist;
196 bestWalkable = { tileX: destX, tileY: destY };
197 }
198 }
199 }
200 const best = bestWalkable ?? bestAny;
201 if (!best)
202 { return false; }
203 if (
204 approachMove
205 && approachMove.focusX === tileX
206 && approachMove.focusY === tileY
207 && approachMove.destX === best.tileX
208 && approachMove.destY === best.tileY
209 )
210 { return false; }
211 approachMove = {
212 focusX: tileX,
213 focusY: tileY,
214 destX: best.tileX,
215 destY: best.tileY
216 };
217 socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY });
218 return false;
219}
220
221function requestOpenBank (tileX, tileY, { getCheques = false } = {})
222{
223 clearAllPendingActions();
224 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
225 const local = view?.entities.get(view.localEntityId);
226 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
227 { flushPendingInteract(); }
228 else
229 { approachAdjacentTile(tileX, tileY); }
230}
231
232function requestEnterDoorway (tileX, tileY)
233{
234 clearAllPendingActions();
235 pendingInteract = { kind: "doorway", tileX, tileY };
236 const local = view?.entities.get(view.localEntityId);
237 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
238 { flushPendingInteract(); }
239 else
240 { approachAdjacentTile(tileX, tileY); }
241}
242
243function requestOpenMarket (tileX, tileY)
244{
245 clearAllPendingActions();
246 pendingInteract = { kind: "market", tileX, tileY };
247 const local = view?.entities.get(view.localEntityId);
248 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
249 { flushPendingInteract(); }
250 else
251 { approachAdjacentTile(tileX, tileY); }
252}
253
254function requestOpenBounty (tileX, tileY)
255{
256 clearAllPendingActions();
257 pendingInteract = { kind: "bounty", tileX, tileY };
258 const local = view?.entities.get(view.localEntityId);
259 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
260 { flushPendingInteract(); }
261 else
262 { approachAdjacentTile(tileX, tileY); }
263}
264
265function requestOpenBarber (tileX, tileY)
266{
267 clearAllPendingActions();
268 pendingInteract = { kind: "barber", tileX, tileY };
269 const local = view?.entities.get(view.localEntityId);
270 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
271 { flushPendingInteract(); }
272 else
273 { approachAdjacentTile(tileX, tileY); }
274}
275
276function requestOpenCauldron (tileX, tileY)
277{
278 clearAllPendingActions();
279 pendingInteract = { kind: "cauldron", tileX, tileY };
280 const local = view?.entities.get(view.localEntityId);
281 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
282 { flushPendingInteract(); }
283 else
284 { approachAdjacentTile(tileX, tileY); }
285}
286
287function requestOpenFurnace (tileX, tileY)
288{
289 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
290}
291
292function requestOpenCraftStation (stationId, tileX, tileY)
293{
294 clearAllPendingActions();
295 pendingInteract = { kind: "station", stationId, tileX, tileY };
296 const local = view?.entities.get(view.localEntityId);
297 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
298 { flushPendingInteract(); }
299 else
300 { approachAdjacentTile(tileX, tileY); }
301}
302
303function requestMine (tileX, tileY)
304{
305 clearAllPendingActions();
306 pendingInteract = { kind: "mine", tileX, tileY };
307 const local = view?.entities.get(view.localEntityId);
308 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
309 { flushPendingInteract(); }
310 else
311 { approachAdjacentTile(tileX, tileY); }
312}
313
314function requestChop (tileX, tileY)
315{
316 clearAllPendingActions();
317 pendingInteract = { kind: "chop", tileX, tileY };
318 const local = view?.entities.get(view.localEntityId);
319 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
320 { flushPendingInteract(); }
321 else
322 { approachAdjacentTile(tileX, tileY); }
323}
324
325function requestPick (tileX, tileY)
326{
327 clearAllPendingActions();
328 pendingInteract = { kind: "pick", tileX, tileY };
329 const local = view?.entities.get(view.localEntityId);
330 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
331 { flushPendingInteract(); }
332 else
333 { approachAdjacentTile(tileX, tileY); }
334}
335
336function requestTalk (targetEntityId, purpose = null)
337{
338 clearAllPendingActions();
339 pendingInteract = { kind: "talk", targetEntityId, purpose };
340 const target = view?.entities.get(targetEntityId);
341 if (!target)
342 {
343 clearPendingInteract();
344 return;
345 }
346 if (approachAdjacentTile(target.tileX, target.tileY))
347 { flushPendingInteract(); }
348}
349
350function flushPendingInteract ()
351{
352 if (!pendingInteract || !view)
353 { return; }
354 const local = view.entities.get(view.localEntityId);
355 if (!local)
356 { return; }
357
358 if (pendingInteract.kind === "bank")
359 {
360 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
361 { return; }
362 const getCheques = !!pendingInteract.getCheques;
363 socket.send({ type: MessageType.openBank });
364 if (getCheques)
365 { inventory?.getBlankCheques(); }
366 clearPendingInteract();
367 return;
368 }
369
370 if (pendingInteract.kind === "doorway")
371 {
372 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
373 { return; }
374 socket.send({
375 type: MessageType.enterDoorway,
376 tileX: pendingInteract.tileX,
377 tileY: pendingInteract.tileY
378 });
379 clearPendingInteract();
380 return;
381 }
382
383 if (pendingInteract.kind === "market")
384 {
385 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
386 { return; }
387 socket.send({ type: MessageType.openMarket });
388 clearPendingInteract();
389 return;
390 }
391
392 if (pendingInteract.kind === "bounty")
393 {
394 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
395 { return; }
396 socket.send({ type: MessageType.openBounty });
397 clearPendingInteract();
398 return;
399 }
400
401 if (pendingInteract.kind === "barber")
402 {
403 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
404 { return; }
405 socket.send({ type: MessageType.openBarber });
406 clearPendingInteract();
407 return;
408 }
409
410 if (pendingInteract.kind === "cauldron")
411 {
412 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
413 { return; }
414 socket.send({ type: MessageType.openCauldron });
415 clearPendingInteract();
416 return;
417 }
418
419 if (pendingInteract.kind === "station")
420 {
421 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
422 { return; }
423 socket.send({
424 type: MessageType.openStation,
425 stationId: pendingInteract.stationId
426 });
427 clearPendingInteract();
428 return;
429 }
430
431 if (pendingInteract.kind === "mine")
432 {
433 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
434 { return; }
435 socket.send({
436 type: MessageType.mine,
437 tileX: pendingInteract.tileX,
438 tileY: pendingInteract.tileY
439 });
440 clearPendingInteract();
441 return;
442 }
443
444 if (pendingInteract.kind === "chop")
445 {
446 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
447 { return; }
448 socket.send({
449 type: MessageType.chop,
450 tileX: pendingInteract.tileX,
451 tileY: pendingInteract.tileY
452 });
453 clearPendingInteract();
454 return;
455 }
456
457 if (pendingInteract.kind === "pick")
458 {
459 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
460 { return; }
461 socket.send({
462 type: MessageType.pick,
463 tileX: pendingInteract.tileX,
464 tileY: pendingInteract.tileY
465 });
466 clearPendingInteract();
467 return;
468 }
469
470 if (pendingInteract.kind === "talk")
471 {
472 const target = view.entities.get(pendingInteract.targetEntityId);
473 if (!target)
474 {
475 clearPendingInteract();
476 return;
477 }
478 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
479 {
480 // Target may have moved — keep chasing.
481 approachAdjacentTile(target.tileX, target.tileY);
482 return;
483 }
484 socket.send({
485 type: MessageType.interact,
486 targetEntityId: pendingInteract.targetEntityId,
487 purpose: pendingInteract.purpose || undefined
488 });
489 clearPendingInteract();
490 }
491}
492
493function requestPickup (ground)
494{
495 if (!ground)
496 { return; }
497 clearPendingInteract();
498 pendingPickup = {
499 groundItemId: ground.groundItemId,
500 tileX: ground.tileX,
501 tileY: ground.tileY
502 };
503 const local = view.entities.get(view.localEntityId);
504 if (local && local.tileX === ground.tileX && local.tileY === ground.tileY)
505 {
506 flushPendingPickup();
507 return;
508 }
509 socket.send({ type: MessageType.moveTo, tileX: ground.tileX, tileY: ground.tileY });
510}
511
512function flushPendingPickup ()
513{
514 if (!pendingPickup || !view)
515 { return; }
516 const item = view.groundItems.get(pendingPickup.groundItemId);
517 if (!item)
518 {
519 clearPendingPickup();
520 return;
521 }
522 const local = view.entities.get(view.localEntityId);
523 if (!local)
524 { return; }
525 if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY)
526 { return; }
527 socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId });
528 clearPendingPickup();
529}
530
531function requestAttack (targetEntityId)
532{
533 clearAllPendingActions();
534 socket.send({ type: MessageType.attack, targetEntityId });
535}
536
537function isAttackableEntity (entity)
538{
539 if (!entity || entity.untargetable)
540 { return false; }
541 if (entity.canFight)
542 { return true; }
543 // Snapshots can omit canFight; mobs are still attackable via LMB.
544 return !!entity.mobTypeId && !entity.talkable;
545}
546
547function canTalkToEntity (entity)
548{
549 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
550}
551
552function handleLeftClick (mouseX, mouseY)
553{
554 const tile = view.screenToTile(mouseX, mouseY);
555 const armed = spells?.getArmedSpell?.();
556 if (armed?.target === "tile" && armed.canCast && spells.tryCastAtTile(tile.tileX, tile.tileY))
557 { return; }
558
559 const entity = view.entityAtScreen(mouseX, mouseY);
560 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
561 {
562 clearPendingPickup();
563 if (entity.characterId)
564 {
565 clearPendingInteract();
566 social.inspect(entity);
567 return;
568 }
569 // Dialogue (or shop/talkable) wins over attack as the default click.
570 if (canTalkToEntity(entity))
571 {
572 // Same intent as context-menu Talk / Shop so dialogue pin matches.
573 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
574 ? "talk"
575 : (entity.hasShop ? "shop" : "talk");
576 requestTalk(entity.entityId, purpose);
577 return;
578 }
579 if (isAttackableEntity(entity))
580 {
581 if (spells?.tryCastAtEntity?.(entity.entityId))
582 { return; }
583 requestAttack(entity.entityId);
584 return;
585 }
586 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
587 return;
588 }
589
590 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
591 if (ground)
592 { requestPickup(ground); }
593 else if (isBankTile(view, tile.tileX, tile.tileY))
594 { requestOpenBank(tile.tileX, tile.tileY); }
595 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
596 { requestEnterDoorway(tile.tileX, tile.tileY); }
597 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
598 { requestOpenMarket(tile.tileX, tile.tileY); }
599 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
600 { requestOpenBounty(tile.tileX, tile.tileY); }
601 else if (isBarberTile(view, tile.tileX, tile.tileY))
602 { requestOpenBarber(tile.tileX, tile.tileY); }
603 else if (isCauldronTile(view, tile.tileX, tile.tileY))
604 { requestOpenCauldron(tile.tileX, tile.tileY); }
605 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
606 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
607 else if (isAnvilTile(view, tile.tileX, tile.tileY))
608 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
609 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
610 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
611 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
612 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
613 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
614 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
615 else if (isLoomTile(view, tile.tileX, tile.tileY))
616 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
617 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
618 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
619 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
620 { requestMine(tile.tileX, tile.tileY); }
621 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
622 { requestChop(tile.tileX, tile.tileY); }
623 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
624 { requestPick(tile.tileX, tile.tileY); }
625 else
626 {
627 clearAllPendingActions();
628 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
629 }
630}
631
632function handleRightClick (event, mouseX, mouseY)
633{
634 event.preventDefault();
635 if (spells?.isTargeting?.())
636 {
637 spells.cancelTargeting();
638 view?.clearSpellTargetHighlight();
639 return;
640 }
641 const tile = view.screenToTile(mouseX, mouseY);
642 const items = [];
643 const walkTileX = tile.tileX;
644 const walkTileY = tile.tileY;
645
646 items.push({
647 label: "Walk here",
648 onSelect: () =>
649 {
650 clearAllPendingActions();
651 socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY });
652 }
653 });
654
655 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY))
656 {
657 if (entity.entityId === view.localEntityId)
658 { continue; }
659 const targetName = entityLabel(entity);
660 items.push({
661 label: `Follow ${targetName}`,
662 onSelect: () =>
663 {
664 clearAllPendingActions();
665 socket.send({ type: MessageType.follow, targetEntityId: entity.entityId });
666 }
667 });
668 if (entity.untargetable)
669 { continue; }
670 if (entity.hasShop)
671 {
672 items.push({
673 label: `Shop ${targetName}`,
674 onSelect: () => requestTalk(entity.entityId, "shop")
675 });
676 }
677 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
678 {
679 items.push({
680 label: `Talk to ${targetName}`,
681 onSelect: () => requestTalk(entity.entityId, "talk")
682 });
683 }
684 if (entity.characterId)
685 {
686 items.push({
687 label: `${targetName} info`,
688 onSelect: () =>
689 {
690 clearAllPendingActions();
691 social.inspect(entity);
692 }
693 });
694 }
695 items.push({
696 label: `Attack ${targetName}`,
697 onSelect: () => requestAttack(entity.entityId)
698 });
699 }
700
701 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
702 {
703 const name = groundLabel(ground);
704 items.push({
705 label: `Pick up ${name}`,
706 onSelect: () => requestPickup(ground)
707 });
708 }
709
710 if (isBankTile(view, tile.tileX, tile.tileY))
711 {
712 items.push({
713 label: "Bank",
714 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
715 });
716 items.push({
717 label: "Get Blank Cheques",
718 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
719 });
720 }
721
722 if (isDoorwayTile(view, tile.tileX, tile.tileY))
723 {
724 items.push({
725 label: "Enter",
726 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
727 });
728 }
729
730 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
731 {
732 items.push({
733 label: "Central Exchange",
734 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
735 });
736 }
737
738 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
739 {
740 items.push({
741 label: "Bounty Office",
742 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
743 });
744 }
745
746 if (isBarberTile(view, tile.tileX, tile.tileY))
747 {
748 items.push({
749 label: "Barber",
750 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
751 });
752 }
753
754 if (isCauldronTile(view, tile.tileX, tile.tileY))
755 {
756 items.push({
757 label: "Alchemy",
758 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
759 });
760 }
761
762 if (isFurnaceTile(view, tile.tileX, tile.tileY))
763 {
764 items.push({
765 label: "Smelt",
766 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
767 });
768 }
769
770 if (isAnvilTile(view, tile.tileX, tile.tileY))
771 {
772 items.push({
773 label: "Smith",
774 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
775 });
776 }
777
778 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
779 {
780 items.push({
781 label: "Woodwork",
782 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
783 });
784 }
785
786 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
787 {
788 items.push({
789 label: "Craft",
790 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
791 });
792 }
793
794 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
795 {
796 items.push({
797 label: "Spin",
798 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
799 });
800 }
801
802 if (isLoomTile(view, tile.tileX, tile.tileY))
803 {
804 items.push({
805 label: "Weave",
806 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
807 });
808 }
809
810 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
811 {
812 items.push({
813 label: "Tailor",
814 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
815 });
816 }
817
818 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
819 {
820 items.push({
821 label: "Mine",
822 onSelect: () => requestMine(tile.tileX, tile.tileY)
823 });
824 }
825
826 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
827 {
828 items.push({
829 label: "Chop",
830 onSelect: () => requestChop(tile.tileX, tile.tileY)
831 });
832 }
833
834 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
835 {
836 items.push({
837 label: "Pick",
838 onSelect: () => requestPick(tile.tileX, tile.tileY)
839 });
840 }
841
842 contextMenu.show(event.clientX, event.clientY, items);
843}
844
845function entityLabel (entity)
846{
847 const first = (entity?.firstName ?? "").trim();
848 const last = (entity?.lastName ?? "").trim();
849 const name = first && last ? `${first} ${last}` : (first || "target");
850 const level = entity?.level | 0;
851 if (entity?.mobTypeId && level > 0)
852 { return `Lv.${level} ${name}`; }
853 return name;
854}
855
856function groundLabel (ground)
857{
858 const name = (ground?.displayName ?? "").trim() || "item";
859 const qty = ground?.quantity ?? 1;
860 if (qty <= 1)
861 { return name; }
862 return `${name} (${formatQuantity(qty)})`;
863}
864
865function startPlay (payload)
866{
867 playing = true;
868 overlay.hidden = true;
869 hud.hidden = false;
870 const settingsToggle = document.getElementById("settings-toggle");
871 if (settingsToggle)
872 { settingsToggle.hidden = false; }
873 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
874 gait = payload.gait ?? GAIT.walk;
875 document.getElementById("gait").textContent = gait;
876 staminaUi?.show();
877 healthUi?.show();
878 statusEffectsUi?.show();
879 if (payload.stamina != null)
880 { staminaUi?.apply(payload.stamina); }
881 if (payload.health != null || payload.maxHealth != null)
882 {
883 healthUi?.apply({
884 current: payload.health ?? healthUi.getCurrent?.(),
885 max: payload.maxHealth ?? healthUi.getMax?.()
886 });
887 }
888 if (!scene)
889 {
890 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
891 game.loadScene(scene);
892 useNearestNeighbour(scene, game.images);
893 view = new WorldView(game, scene, catalog);
894 graphicsSettingsUi?.apply();
895 const ticker = new GameObject(0, 0, null, 10);
896 ticker.update = (dt) =>
897 {
898 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
899 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
900 if (!leftPressed && !leftHeld)
901 { leftClickConsumed = false; }
902 else if (!leftClickConsumed && playing && !uiBlocked())
903 {
904 leftClickConsumed = true;
905 const canvas = scene.canvas;
906 const rect = canvas.getBoundingClientRect();
907 const mouseX = GameInput.mousePosition.x - rect.left;
908 const mouseY = GameInput.mousePosition.y - rect.top;
909 handleLeftClick(mouseX, mouseY);
910 }
911 if (GameInput.isPressed(82) && !uiBlocked())
912 {
913 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
914 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
915 { return; }
916 socket.send({ type: MessageType.setGait, gait: next });
917 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
918 if (next === GAIT.walk)
919 {
920 gait = next;
921 document.getElementById("gait").textContent = gait;
922 }
923 }
924 if (playing && !death?.isBlocking())
925 {
926 flushPendingPickup();
927 flushPendingInteract();
928 social?.updateNametag(view, scene, view.localEntityId);
929 chat?.update(view, scene);
930 updateSpellTargetHighlight();
931 updateWorldTooltip();
932 }
933 else
934 {
935 hideWorldTooltip();
936 view?.clearSpellTargetHighlight();
937 }
938 view.update(dt);
939 };
940 scene.addObject(ticker);
941 window.addEventListener("resize", () =>
942 {
943 scene.size.x = window.innerWidth;
944 scene.size.y = window.innerHeight;
945 scene.g_fixSize();
946 useNearestNeighbour(scene, game.images);
947 });
948 window.addEventListener("wheel", (event) =>
949 {
950 if (!playing || uiBlocked())
951 { return; }
952 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
953 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
954 }, { passive: true });
955 scene.canvas.addEventListener("contextmenu", (event) =>
956 {
957 if (!playing || uiBlocked())
958 { return; }
959 const rect = scene.canvas.getBoundingClientRect();
960 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
961 });
962 }
963 view.setSettings(payload.settings ?? view.settings);
964 chat?.syncSettings();
965 view.worldHour = payload.worldTime?.hour ?? 12;
966 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
967 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
968 view.setWorldSeason(payload.worldTime?.season);
969 view.setLocalEntity(
970 payload.entityId,
971 payload.tileX,
972 payload.tileY,
973 payload.gait,
974 payload.sex,
975 payload.firstName,
976 payload.lastName,
977 payload.characterId,
978 payload.layers,
979 payload.health,
980 payload.maxHealth
981 );
982 graphicsSettingsUi?.apply();
983}
984
985async function main ()
986{
987 catalog = await loadSpriteCatalog();
988 await preloadCatalogImages(game, catalog);
989 applySpriteSheets(game.images, catalog);
990 createHairControls = bindHairControls({
991 root: document.getElementById("create-hair"),
992 resolveSpriteUrl (name)
993 {
994 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
995 },
996 getSex: () => document.getElementById("sex")?.value ?? "male",
997 hideHeadgear: true
998 });
999 document.getElementById("sex")?.addEventListener("change", () =>
1000 {
1001 createHairControls?.fillStyles();
1002 void createHairControls?.refreshPreview();
1003 });
1004 void createHairControls?.refreshPreview();
1005 graphicsSettingsUi = initGraphicsSettings({
1006 onChange: applyGraphicsSettings
1007 });
1008 social = initSocial({
1009 socket: { send (payload) { socket.send(payload); } },
1010 MessageType
1011 });
1012 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1013 inventory = initInventory({
1014 socket: { send (payload) { socket.send(payload); } },
1015 MessageType,
1016 contextMenu,
1017 resolveSpriteUrl (name)
1018 {
1019 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1020 },
1021 getFriends ()
1022 {
1023 return social?.getFriends?.() ?? [];
1024 },
1025 getLocalName ()
1026 {
1027 const you = document.getElementById("you")?.textContent ?? "";
1028 return you.split("(")[0].trim() || "Unknown";
1029 }
1030 });
1031 skills = initSkills();
1032 spells = initSpells({
1033 socket: { send (payload) { socket.send(payload); } },
1034 MessageType
1035 });
1036 crafting = initCrafting({
1037 socket: { send (payload) { socket.send(payload); } },
1038 MessageType,
1039 getInventorySlots ()
1040 {
1041 return inventory?.getInventorySlots?.() ?? [];
1042 },
1043 getSkillLevel (skillId)
1044 {
1045 return skills?.skillLevel?.(skillId) ?? 1;
1046 }
1047 });
1048 alchemy = initAlchemy({
1049 socket: { send (payload) { socket.send(payload); } },
1050 MessageType,
1051 getInventorySlots ()
1052 {
1053 return inventory?.getInventorySlots?.() ?? [];
1054 }
1055 });
1056 staminaUi = initStamina();
1057 healthUi = initHealth();
1058 statusEffectsUi = initStatusEffects();
1059 toasts = initToasts();
1060 questsUi = initQuests({
1061 socket: { send (payload) { socket.send(payload); } },
1062 MessageType,
1063 toasts
1064 });
1065 dialogueUi = initDialogue({
1066 socket: { send (payload) { socket.send(payload); } },
1067 MessageType,
1068 getEntity (id)
1069 {
1070 if (id === "local")
1071 { return view?.entities.get(view.localEntityId) ?? null; }
1072 return view?.entities.get(id) ?? null;
1073 },
1074 captureSpeakerIcon (entityId, size = 64)
1075 {
1076 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1077 }
1078 });
1079 shop = initShop({
1080 socket: { send (payload) { socket.send(payload); } },
1081 MessageType,
1082 onSuppressWorldClick: consumeWorldClick,
1083 getCoinCount ()
1084 {
1085 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1086 },
1087 getInventorySlots ()
1088 {
1089 return inventory?.getInventorySlots?.() ?? [];
1090 }
1091 });
1092 market = initMarket({
1093 socket: { send (payload) { socket.send(payload); } },
1094 MessageType,
1095 onSuppressWorldClick: consumeWorldClick,
1096 getCoinCount ()
1097 {
1098 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1099 },
1100 getInventorySlots ()
1101 {
1102 return inventory?.getInventorySlots?.() ?? [];
1103 }
1104 });
1105 bounty = initBounty({
1106 socket: { send (payload) { socket.send(payload); } },
1107 MessageType,
1108 onSuppressWorldClick: consumeWorldClick,
1109 resolveSpriteUrl (name)
1110 {
1111 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1112 }
1113 });
1114 barber = initBarber({
1115 socket: { send (payload) { socket.send(payload); } },
1116 MessageType,
1117 onSuppressWorldClick: consumeWorldClick,
1118 resolveSpriteUrl (name)
1119 {
1120 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1121 },
1122 getInventoryBag ()
1123 {
1124 return {
1125 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1126 inventory: inventory?.getInventorySlots?.() ?? []
1127 };
1128 }
1129 });
1130 chat = initChat({
1131 socket: { send (payload) { socket.send(payload); } },
1132 MessageType,
1133 getSettings: () => view?.settings
1134 });
1135 death = initDeath({
1136 socket: { send (payload) { socket.send(payload); } },
1137 MessageType
1138 });
1139 game.startGame();
1140
1141 socket = new GameSocket(defaultSocketUrl(), (message) =>
1142 {
1143 switch (message.type)
1144 {
1145 case MessageType.session:
1146 session = message;
1147 statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`;
1148 renderCharacters(message.characters);
1149 break;
1150 case MessageType.characterList:
1151 renderCharacters(message.characters);
1152 if (!playing)
1153 { overlay.hidden = false; }
1154 break;
1155 case MessageType.enterWorld:
1156 closeCreateModal();
1157 startPlay(message);
1158 inventory?.setLocalCharacterId(message.characterId);
1159 socket.send({ type: MessageType.requestQuests });
1160 break;
1161 case MessageType.chunkSnapshot:
1162 view?.applySnapshot(message);
1163 break;
1164 case MessageType.dimensionChanged:
1165 if (view)
1166 {
1167 view.setDimensionId(message.dimensionId);
1168 view.setDimensionModes(message.lightingMode, message.seasonMode);
1169 view.clearAllChunks();
1170 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1171 {
1172 view.moveEntity({
1173 entityId: view.localEntityId,
1174 tileX: message.tileX,
1175 tileY: message.tileY
1176 });
1177 }
1178 }
1179 break;
1180 case MessageType.chunkDelta:
1181 for (const tile of message.tiles ?? [])
1182 {
1183 view?.updateAuthoredTile(
1184 message.chunkX,
1185 message.chunkY,
1186 tile.localX,
1187 tile.localY,
1188 { ground: tile.ground, block: tile.block, light: tile.light }
1189 );
1190 }
1191 break;
1192 case MessageType.unsubscribeChunk:
1193 view?.removeChunk(message.chunkX, message.chunkY);
1194 break;
1195 case MessageType.entitySpawn:
1196 view?.spawnEntity(message);
1197 break;
1198 case MessageType.entityMove:
1199 view?.moveEntity(message);
1200 if (message.entityId === view?.localEntityId && message.gait)
1201 {
1202 gait = message.gait;
1203 document.getElementById("gait").textContent = gait;
1204 }
1205 break;
1206 case MessageType.entityDespawn:
1207 view?.despawnEntity(message.entityId);
1208 break;
1209 case MessageType.entityAppearance:
1210 view?.setAppearance(message);
1211 break;
1212 case MessageType.groundItemAppear:
1213 view?.upsertGroundItem(message);
1214 break;
1215 case MessageType.groundItemDespawn:
1216 view?.despawnGroundItem(message.groundItemId);
1217 break;
1218 case MessageType.inventory:
1219 inventory?.handleInventory(message);
1220 crafting?.refresh();
1221 alchemy?.refresh();
1222 shop?.refresh();
1223 market?.refresh();
1224 break;
1225 case MessageType.skills:
1226 skills?.render(message.skills);
1227 crafting?.refresh();
1228 break;
1229 case MessageType.spells:
1230 case MessageType.spellsUpdated:
1231 spells?.render(message);
1232 break;
1233 case MessageType.spellArmed:
1234 spells?.handleSpellArmed(message);
1235 break;
1236 case MessageType.spellDisarmed:
1237 spells?.handleSpellDisarmed();
1238 break;
1239 case MessageType.spellProjectile:
1240 view?.spawnSpellProjectileFx(message);
1241 break;
1242 case MessageType.spellFizzle:
1243 view?.spawnSpellFizzleFx(message);
1244 if (message.casterId === view?.localEntityId)
1245 { toasts?.show("Failed to cast spell"); }
1246 break;
1247 case MessageType.spellCastFlash:
1248 view?.spawnSpellCastFlash(message);
1249 break;
1250 case MessageType.spellLightAppear:
1251 case MessageType.spellLightUpdate:
1252 view?.setSpellLight(message);
1253 break;
1254 case MessageType.spellLightRemove:
1255 view?.removeSpellLight(message);
1256 break;
1257 case MessageType.stamina:
1258 staminaUi?.apply(message);
1259 if (message.gait)
1260 {
1261 gait = message.gait;
1262 document.getElementById("gait").textContent = gait;
1263 }
1264 break;
1265 case MessageType.statusEffects:
1266 view?.setLocalBlind(!!message.blind);
1267 statusEffectsUi?.apply(message);
1268 break;
1269 case MessageType.bankSnapshot:
1270 inventory?.handleBank(message);
1271 break;
1272 case MessageType.cauldronSnapshot:
1273 alchemy?.handleSnapshot(message);
1274 break;
1275 case MessageType.pigeonDispatched:
1276 inventory?.handlePigeonDispatched(message);
1277 break;
1278 case MessageType.pigeonDelivered:
1279 inventory?.handlePigeonDelivered(message);
1280 break;
1281 case MessageType.characterSearchResult:
1282 inventory?.handleCharacterSearch(message);
1283 break;
1284 case MessageType.craftResult:
1285 crafting?.handleCraftResult(message);
1286 break;
1287 case MessageType.worldStatus:
1288 if (view)
1289 {
1290 view.setSettings(message.settings ?? view.settings);
1291 view.worldHour = message.worldTime?.hour ?? view.worldHour;
1292 view.setWorldSeason(message.worldTime?.season);
1293 chat?.syncSettings();
1294 }
1295 break;
1296 case MessageType.chatBubble:
1297 chat?.showBubble(message);
1298 break;
1299 case MessageType.friends:
1300 social?.handleFriends(message);
1301 break;
1302 case MessageType.combatSwing:
1303 view?.spawnCombatSwing(message);
1304 break;
1305 case MessageType.combatProjectile:
1306 view?.spawnPhysicalProjectileFx({
1307 ...message,
1308 sprite: "fx:projectile:arrow"
1309 });
1310 break;
1311 case MessageType.combatNoArrows:
1312 toasts?.show("Out of arrows!");
1313 break;
1314 case MessageType.gatherSwing:
1315 case MessageType.tileShove:
1316 view?.spawnGatherSwing(message);
1317 break;
1318 case MessageType.stationOpen:
1319 if (message.stationId)
1320 { crafting?.openStation(message.stationId); }
1321 break;
1322 case MessageType.shopOpen:
1323 shop?.handleShopOpen(message);
1324 break;
1325 case MessageType.shopClosed:
1326 shop?.handleShopClosed(message);
1327 break;
1328 case MessageType.marketOpen:
1329 market?.handleOpen(message);
1330 break;
1331 case MessageType.marketClosed:
1332 market?.handleClosed(message);
1333 break;
1334 case MessageType.marketTrade:
1335 market?.handleTrade(message);
1336 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
1337 break;
1338 case MessageType.bountySnapshot:
1339 bounty?.handleSnapshot(message);
1340 break;
1341 case MessageType.closeBounty:
1342 bounty?.handleClosed(message);
1343 break;
1344 case MessageType.characterBounty:
1345 bounty?.handleCharacterBounty(message);
1346 social?.handleCharacterBounty(message);
1347 break;
1348 case MessageType.barberSnapshot:
1349 barber?.handleSnapshot(message);
1350 break;
1351 case MessageType.closeBarber:
1352 barber?.handleClosed(message);
1353 break;
1354 case MessageType.itemBubble:
1355 chat?.showItemBubble(message);
1356 break;
1357 case MessageType.gatherComplete:
1358 crafting?.refresh();
1359 break;
1360 case MessageType.combatHit:
1361 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1362 view?.flashDamage(message.targetId);
1363 view?.spawnDamageNumber(message.targetId, message.damage);
1364 if (message.targetId === view?.localEntityId)
1365 {
1366 healthUi?.apply({
1367 current: message.health,
1368 max: message.maxHealth
1369 });
1370 }
1371 break;
1372 case MessageType.entityHealth:
1373 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1374 if (message.entityId === view?.localEntityId)
1375 {
1376 healthUi?.apply({
1377 current: message.health,
1378 max: message.maxHealth
1379 });
1380 }
1381 break;
1382 case MessageType.skillLevelUp:
1383 view?.spawnSkillLevelUp(message.entityId, message);
1384 if (message.entityId === view?.localEntityId)
1385 {
1386 const name = message.displayName ?? message.skillId ?? "Skill";
1387 toasts?.show(`${name} level ${message.level}!`);
1388 }
1389 break;
1390 case MessageType.playerDied:
1391 clearAllPendingActions();
1392 contextMenu?.hide();
1393 death?.show();
1394 if (message.entityId === view?.localEntityId)
1395 {
1396 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
1397 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
1398 }
1399 break;
1400 case MessageType.playerRespawned:
1401 death?.hide();
1402 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1403 if (message.entityId === view?.localEntityId)
1404 {
1405 healthUi?.apply({
1406 current: message.health,
1407 max: message.maxHealth
1408 });
1409 }
1410 if (message.stamina != null || message.maxStamina != null)
1411 {
1412 staminaUi?.apply({
1413 current: message.stamina ?? staminaUi.getCurrent?.(),
1414 max: message.maxStamina ?? staminaUi.getMax?.()
1415 });
1416 }
1417 break;
1418 case MessageType.error:
1419 if (playing)
1420 { toasts?.show(message.message); }
1421 else
1422 {
1423 const createPanel = document.getElementById("create-panel");
1424 const createError = document.getElementById("create-error");
1425 if (createPanel && !createPanel.hidden && createError)
1426 { createError.textContent = message.message ?? ""; }
1427 else
1428 { showError(message.message); }
1429 }
1430 social?.showError(message.message);
1431 break;
1432 case MessageType.toast:
1433 if (playing)
1434 { toasts?.show(message.message); }
1435 break;
1436 case MessageType.questsSnapshot:
1437 questsUi?.applySnapshot(message);
1438 break;
1439 case MessageType.questStepComplete:
1440 questsUi?.handleStepComplete(message);
1441 break;
1442 case MessageType.dialogueStep:
1443 dialogueUi?.handleStep(message);
1444 break;
1445 case MessageType.dialogueChoices:
1446 dialogueUi?.handleChoices(message);
1447 break;
1448 case MessageType.dialogueClose:
1449 dialogueUi?.handleClose(message);
1450 break;
1451 case MessageType.forceLogout:
1452 returnToMenu(message.reason);
1453 break;
1454 }
1455 }, {
1456 onClose (event)
1457 {
1458 if (playing)
1459 { returnToMenu(event.reason || "Disconnected from server."); }
1460 }
1461 });
1462 await socket.connect();
1463 if (typeof window !== "undefined")
1464 {
1465 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
1466 {
1467 crafting?.openStation(stationId);
1468 };
1469 }
1470}
1471
1472function returnToMenu (reason = "")
1473{
1474 playing = false;
1475 clearAllPendingActions();
1476 social?.reset();
1477 chat?.reset();
1478 inventory?.reset();
1479 crafting?.reset();
1480 alchemy?.reset();
1481 staminaUi?.hide();
1482 healthUi?.hide();
1483 statusEffectsUi?.hide();
1484 skills?.hide();
1485 spells?.hide();
1486 contextMenu?.hide();
1487 death?.reset();
1488 shop?.close({ notifyServer: false });
1489 bounty?.close();
1490 barber?.close();
1491 questsUi?.reset();
1492 dialogueUi?.reset();
1493 hideWorldTooltip();
1494 if (view)
1495 {
1496 for (const key of [...(view.chunks?.keys?.() ?? [])])
1497 {
1498 const [chunkX, chunkY] = key.split(",").map(Number);
1499 view.removeChunk(chunkX, chunkY);
1500 }
1501 }
1502 overlay.hidden = false;
1503 hud.hidden = true;
1504 const settingsToggle = document.getElementById("settings-toggle");
1505 if (settingsToggle)
1506 { settingsToggle.hidden = true; }
1507 graphicsSettingsUi?.close();
1508 if (reason)
1509 { statusEl.textContent = reason; }
1510}
1511
1512document.getElementById("create-character-open")?.addEventListener("click", () =>
1513{
1514 showError("");
1515 const createError = document.getElementById("create-error");
1516 if (createError)
1517 { createError.textContent = ""; }
1518 document.getElementById("create-backdrop").hidden = false;
1519 document.getElementById("create-panel").hidden = false;
1520 void createHairControls?.refreshPreview();
1521});
1522
1523function closeCreateModal ()
1524{
1525 document.getElementById("create-backdrop").hidden = true;
1526 document.getElementById("create-panel").hidden = true;
1527}
1528
1529document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
1530document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
1531
1532document.getElementById("create-form").addEventListener("submit", (event) =>
1533{
1534 event.preventDefault();
1535 showError("");
1536 const createError = document.getElementById("create-error");
1537 if (createError)
1538 { createError.textContent = ""; }
1539 socket.send({
1540 type: MessageType.createCharacter,
1541 firstName: document.getElementById("first-name").value,
1542 lastName: document.getElementById("last-name").value,
1543 sex: document.getElementById("sex").value,
1544 hair: createHairControls?.currentHair?.() ?? null
1545 });
1546});
1547
1548document.getElementById("leave").addEventListener("click", () =>
1549{
1550 socket.send({ type: MessageType.leaveWorld });
1551 returnToMenu();
1552});
1553
1554main().catch((error) =>
1555{
1556 showError(error.message);
1557 console.error(error);
1558});
1559
1560function isBankTile (view, tileX, tileY)
1561{
1562 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
1563}
1564
1565function isDoorwayTile (view, tileX, tileY)
1566{
1567 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
1568}
1569
1570function isMarketplaceTile (view, tileX, tileY)
1571{
1572 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1573}
1574
1575function isBountyOfficeTile (view, tileX, tileY)
1576{
1577 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
1578}
1579
1580function isBarberTile (view, tileX, tileY)
1581{
1582 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
1583}
1584
1585function isCauldronTile (view, tileX, tileY)
1586{
1587 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
1588}
1589
1590function isFurnaceTile (view, tileX, tileY)
1591{
1592 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
1593}
1594
1595function isAnvilTile (view, tileX, tileY)
1596{
1597 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
1598}
1599
1600function isWoodworkingBenchTile (view, tileX, tileY)
1601{
1602 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
1603}
1604
1605function isCraftingBenchTile (view, tileX, tileY)
1606{
1607 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1608}
1609
1610function isSpinningWheelTile (view, tileX, tileY)
1611{
1612 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
1613}
1614
1615function isLoomTile (view, tileX, tileY)
1616{
1617 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
1618}
1619
1620function isTailorBenchTile (view, tileX, tileY)
1621{
1622 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
1623}
1624
1625function isOreBoulderTile (view, tileX, tileY)
1626{
1627 const block = blockAt(view, tileX, tileY);
1628 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
1629}
1630
1631function isChopableTreeTile (view, tileX, tileY)
1632{
1633 return isChopableTreeBlock(blockAt(view, tileX, tileY));
1634}
1635
1636function isPickablePlantTile (view, tileX, tileY)
1637{
1638 return isPickablePlantBlock(blockAt(view, tileX, tileY));
1639}
1640
1641function updateSpellTargetHighlight ()
1642{
1643 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
1644 {
1645 view?.clearSpellTargetHighlight();
1646 return;
1647 }
1648 const canvas = scene?.canvas;
1649 if (!canvas)
1650 { return; }
1651 const rect = canvas.getBoundingClientRect();
1652 const mouseX = GameInput.mousePosition.x - rect.left;
1653 const mouseY = GameInput.mousePosition.y - rect.top;
1654 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1655 {
1656 view.clearSpellTargetHighlight();
1657 return;
1658 }
1659 const tile = view.screenToTile(mouseX, mouseY);
1660 const local = view.entities.get(view.localEntityId);
1661 const inRange = !local
1662 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
1663 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
1664}
1665
1666function hideWorldTooltip ()
1667{
1668 if (worldTooltip)
1669 { worldTooltip.hidden = true; }
1670}
1671
1672/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
1673function updateWorldTooltip ()
1674{
1675 if (!worldTooltip || !view || !scene || uiBlocked())
1676 {
1677 hideWorldTooltip();
1678 return;
1679 }
1680 const canvas = scene.canvas;
1681 const rect = canvas.getBoundingClientRect();
1682 const mouseX = GameInput.mousePosition.x - rect.left;
1683 const mouseY = GameInput.mousePosition.y - rect.top;
1684 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1685 {
1686 hideWorldTooltip();
1687 return;
1688 }
1689 const entity = view.entityAtScreen(mouseX, mouseY);
1690 if (entity && entity.entityId !== view.localEntityId)
1691 {
1692 const label = entityLabel(entity);
1693 worldTooltip.hidden = false;
1694 worldTooltip.textContent = label;
1695 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
1696 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
1697 return;
1698 }
1699 const tile = view.screenToTile(mouseX, mouseY);
1700 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
1701 if (!label)
1702 {
1703 hideWorldTooltip();
1704 return;
1705 }
1706 worldTooltip.hidden = false;
1707 worldTooltip.textContent = label;
1708 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
1709 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
1710}
1711
1712function blockTypeAt (view, tileX, tileY)
1713{
1714 return blockAt(view, tileX, tileY)?.typeId ?? null;
1715}
1716
1717function blockAt (view, tileX, tileY)
1718{
1719 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1720 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1721 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1722 if (!snapshot)
1723 { return null; }
1724 const localX = tileX - chunkX * CHUNK_SIZE;
1725 const localY = tileY - chunkY * CHUNK_SIZE;
1726 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
1727}
1728
1729function groundTypeAt (view, tileX, tileY)
1730{
1731 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1732 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1733 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1734 if (!snapshot)
1735 { return null; }
1736 const localX = tileX - chunkX * CHUNK_SIZE;
1737 const localY = tileY - chunkY * CHUNK_SIZE;
1738 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
1739}
1740
1741/** Best-effort client filter for approach destinations (server still authorizes paths). */
1742function isClientApproachable (tileX, tileY)
1743{
1744 if (!view)
1745 { return true; }
1746 const groundId = groundTypeAt(view, tileX, tileY);
1747 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
1748 if (groundDef && !groundDef.passable)
1749 { return false; }
1750 const block = blockAt(view, tileX, tileY);
1751 if (block?.typeId != null)
1752 {
1753 const blockDef = BLOCK_DEFINITIONS[block.typeId];
1754 if (blockDef && !blockDef.passable)
1755 { return false; }
1756 }
1757 for (const entity of view.entitiesAtTile(tileX, tileY))
1758 {
1759 if (entity.entityId === view.localEntityId)
1760 { continue; }
1761 if (entity.untargetable || entity.freeFlight)
1762 { continue; }
1763 return false;
1764 }
1765 return true;
1766}
1767
1768function chebyshev (ax, ay, bx, by)
1769{
1770 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
1771}