BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

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