BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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