BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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