BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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