BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 44.7 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 if (first && last)
796 { return `${first} ${last}`; }
797 return first || "target";
798}
799
800function groundLabel (ground)
801{
802 const name = (ground?.displayName ?? "").trim() || "item";
803 const qty = ground?.quantity ?? 1;
804 if (qty <= 1)
805 { return name; }
806 return `${name} (${formatQuantity(qty)})`;
807}
808
809function startPlay (payload)
810{
811 playing = true;
812 overlay.hidden = true;
813 hud.hidden = false;
814 const settingsToggle = document.getElementById("settings-toggle");
815 if (settingsToggle)
816 { settingsToggle.hidden = false; }
817 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
818 gait = payload.gait ?? GAIT.walk;
819 document.getElementById("gait").textContent = gait;
820 staminaUi?.show();
821 healthUi?.show();
822 statusEffectsUi?.show();
823 if (payload.stamina != null)
824 { staminaUi?.apply(payload.stamina); }
825 if (payload.health != null || payload.maxHealth != null)
826 {
827 healthUi?.apply({
828 current: payload.health ?? healthUi.getCurrent?.(),
829 max: payload.maxHealth ?? healthUi.getMax?.()
830 });
831 }
832 if (!scene)
833 {
834 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
835 game.loadScene(scene);
836 useNearestNeighbour(scene, game.images);
837 view = new WorldView(game, scene, catalog);
838 graphicsSettingsUi?.apply();
839 const ticker = new GameObject(0, 0, null, 10);
840 ticker.update = (dt) =>
841 {
842 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
843 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
844 if (!leftPressed && !leftHeld)
845 { leftClickConsumed = false; }
846 else if (!leftClickConsumed && playing && !uiBlocked())
847 {
848 leftClickConsumed = true;
849 const canvas = scene.canvas;
850 const rect = canvas.getBoundingClientRect();
851 const mouseX = GameInput.mousePosition.x - rect.left;
852 const mouseY = GameInput.mousePosition.y - rect.top;
853 handleLeftClick(mouseX, mouseY);
854 }
855 if (GameInput.isPressed(82) && !uiBlocked())
856 {
857 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
858 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
859 { return; }
860 socket.send({ type: MessageType.setGait, gait: next });
861 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
862 if (next === GAIT.walk)
863 {
864 gait = next;
865 document.getElementById("gait").textContent = gait;
866 }
867 }
868 if (playing && !death?.isBlocking())
869 {
870 flushPendingPickup();
871 flushPendingInteract();
872 social?.updateNametag(view, scene, view.localEntityId);
873 chat?.update(view, scene);
874 updateSpellTargetHighlight();
875 updateWorldTooltip();
876 }
877 else
878 {
879 hideWorldTooltip();
880 view?.clearSpellTargetHighlight();
881 }
882 view.update(dt);
883 };
884 scene.addObject(ticker);
885 window.addEventListener("resize", () =>
886 {
887 scene.size.x = window.innerWidth;
888 scene.size.y = window.innerHeight;
889 scene.g_fixSize();
890 useNearestNeighbour(scene, game.images);
891 });
892 window.addEventListener("wheel", (event) =>
893 {
894 if (!playing || uiBlocked())
895 { return; }
896 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
897 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
898 }, { passive: true });
899 scene.canvas.addEventListener("contextmenu", (event) =>
900 {
901 if (!playing || uiBlocked())
902 { return; }
903 const rect = scene.canvas.getBoundingClientRect();
904 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
905 });
906 }
907 view.setSettings(payload.settings ?? view.settings);
908 chat?.syncSettings();
909 view.worldHour = payload.worldTime?.hour ?? 12;
910 view.setWorldSeason(payload.worldTime?.season);
911 view.setLocalEntity(
912 payload.entityId,
913 payload.tileX,
914 payload.tileY,
915 payload.gait,
916 payload.sex,
917 payload.firstName,
918 payload.lastName,
919 payload.characterId,
920 payload.layers,
921 payload.health,
922 payload.maxHealth
923 );
924 graphicsSettingsUi?.apply();
925}
926
927async function main ()
928{
929 catalog = await loadSpriteCatalog();
930 await preloadCatalogImages(game, catalog);
931 applySpriteSheets(game.images, catalog);
932 createHairControls = bindHairControls({
933 root: document.getElementById("create-hair"),
934 resolveSpriteUrl (name)
935 {
936 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
937 },
938 getSex: () => document.getElementById("sex")?.value ?? "male",
939 hideHeadgear: true
940 });
941 document.getElementById("sex")?.addEventListener("change", () =>
942 {
943 createHairControls?.fillStyles();
944 void createHairControls?.refreshPreview();
945 });
946 void createHairControls?.refreshPreview();
947 graphicsSettingsUi = initGraphicsSettings({
948 onChange: applyGraphicsSettings
949 });
950 social = initSocial({
951 socket: { send (payload) { socket.send(payload); } },
952 MessageType
953 });
954 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
955 inventory = initInventory({
956 socket: { send (payload) { socket.send(payload); } },
957 MessageType,
958 contextMenu,
959 resolveSpriteUrl (name)
960 {
961 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
962 },
963 getFriends ()
964 {
965 return social?.getFriends?.() ?? [];
966 },
967 getLocalName ()
968 {
969 const you = document.getElementById("you")?.textContent ?? "";
970 return you.split("(")[0].trim() || "Unknown";
971 }
972 });
973 skills = initSkills();
974 spells = initSpells({
975 socket: { send (payload) { socket.send(payload); } },
976 MessageType
977 });
978 crafting = initCrafting({
979 socket: { send (payload) { socket.send(payload); } },
980 MessageType,
981 getInventorySlots ()
982 {
983 return inventory?.getInventorySlots?.() ?? [];
984 },
985 getSkillLevel (skillId)
986 {
987 return skills?.skillLevel?.(skillId) ?? 1;
988 }
989 });
990 alchemy = initAlchemy({
991 socket: { send (payload) { socket.send(payload); } },
992 MessageType,
993 getInventorySlots ()
994 {
995 return inventory?.getInventorySlots?.() ?? [];
996 }
997 });
998 staminaUi = initStamina();
999 healthUi = initHealth();
1000 statusEffectsUi = initStatusEffects();
1001 toasts = initToasts();
1002 shop = initShop({
1003 socket: { send (payload) { socket.send(payload); } },
1004 MessageType,
1005 onSuppressWorldClick: consumeWorldClick,
1006 getCoinCount ()
1007 {
1008 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1009 },
1010 getInventorySlots ()
1011 {
1012 return inventory?.getInventorySlots?.() ?? [];
1013 }
1014 });
1015 market = initMarket({
1016 socket: { send (payload) { socket.send(payload); } },
1017 MessageType,
1018 onSuppressWorldClick: consumeWorldClick,
1019 getCoinCount ()
1020 {
1021 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1022 },
1023 getInventorySlots ()
1024 {
1025 return inventory?.getInventorySlots?.() ?? [];
1026 }
1027 });
1028 bounty = initBounty({
1029 socket: { send (payload) { socket.send(payload); } },
1030 MessageType,
1031 onSuppressWorldClick: consumeWorldClick,
1032 resolveSpriteUrl (name)
1033 {
1034 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1035 }
1036 });
1037 barber = initBarber({
1038 socket: { send (payload) { socket.send(payload); } },
1039 MessageType,
1040 onSuppressWorldClick: consumeWorldClick,
1041 resolveSpriteUrl (name)
1042 {
1043 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1044 },
1045 getInventoryBag ()
1046 {
1047 return {
1048 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1049 inventory: inventory?.getInventorySlots?.() ?? []
1050 };
1051 }
1052 });
1053 chat = initChat({
1054 socket: { send (payload) { socket.send(payload); } },
1055 MessageType,
1056 getSettings: () => view?.settings
1057 });
1058 death = initDeath({
1059 socket: { send (payload) { socket.send(payload); } },
1060 MessageType
1061 });
1062 game.startGame();
1063
1064 socket = new GameSocket(defaultSocketUrl(), (message) =>
1065 {
1066 switch (message.type)
1067 {
1068 case MessageType.session:
1069 session = message;
1070 statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`;
1071 renderCharacters(message.characters);
1072 break;
1073 case MessageType.characterList:
1074 renderCharacters(message.characters);
1075 if (!playing)
1076 { overlay.hidden = false; }
1077 break;
1078 case MessageType.enterWorld:
1079 closeCreateModal();
1080 startPlay(message);
1081 inventory?.setLocalCharacterId(message.characterId);
1082 break;
1083 case MessageType.chunkSnapshot:
1084 view?.applySnapshot(message);
1085 break;
1086 case MessageType.chunkDelta:
1087 for (const tile of message.tiles ?? [])
1088 {
1089 view?.updateAuthoredTile(
1090 message.chunkX,
1091 message.chunkY,
1092 tile.localX,
1093 tile.localY,
1094 { ground: tile.ground, block: tile.block, light: tile.light }
1095 );
1096 }
1097 break;
1098 case MessageType.unsubscribeChunk:
1099 view?.removeChunk(message.chunkX, message.chunkY);
1100 break;
1101 case MessageType.entitySpawn:
1102 view?.spawnEntity(message);
1103 break;
1104 case MessageType.entityMove:
1105 view?.moveEntity(message);
1106 if (message.entityId === view?.localEntityId && message.gait)
1107 {
1108 gait = message.gait;
1109 document.getElementById("gait").textContent = gait;
1110 }
1111 break;
1112 case MessageType.entityDespawn:
1113 view?.despawnEntity(message.entityId);
1114 break;
1115 case MessageType.entityAppearance:
1116 view?.setAppearance(message);
1117 break;
1118 case MessageType.groundItemAppear:
1119 view?.upsertGroundItem(message);
1120 break;
1121 case MessageType.groundItemDespawn:
1122 view?.despawnGroundItem(message.groundItemId);
1123 break;
1124 case MessageType.inventory:
1125 inventory?.handleInventory(message);
1126 crafting?.refresh();
1127 alchemy?.refresh();
1128 shop?.refresh();
1129 market?.refresh();
1130 break;
1131 case MessageType.skills:
1132 skills?.render(message.skills);
1133 crafting?.refresh();
1134 break;
1135 case MessageType.spells:
1136 case MessageType.spellsUpdated:
1137 spells?.render(message);
1138 break;
1139 case MessageType.spellArmed:
1140 spells?.handleSpellArmed(message);
1141 break;
1142 case MessageType.spellDisarmed:
1143 spells?.handleSpellDisarmed();
1144 break;
1145 case MessageType.spellProjectile:
1146 view?.spawnSpellProjectileFx(message);
1147 break;
1148 case MessageType.spellFizzle:
1149 view?.spawnSpellFizzleFx(message);
1150 if (message.casterId === view?.localEntityId)
1151 { toasts?.show("Failed to cast spell"); }
1152 break;
1153 case MessageType.spellCastFlash:
1154 view?.spawnSpellCastFlash(message);
1155 break;
1156 case MessageType.spellLightAppear:
1157 case MessageType.spellLightUpdate:
1158 view?.setSpellLight(message);
1159 break;
1160 case MessageType.spellLightRemove:
1161 view?.removeSpellLight(message);
1162 break;
1163 case MessageType.stamina:
1164 staminaUi?.apply(message);
1165 if (message.gait)
1166 {
1167 gait = message.gait;
1168 document.getElementById("gait").textContent = gait;
1169 }
1170 break;
1171 case MessageType.statusEffects:
1172 view?.setLocalBlind(!!message.blind);
1173 statusEffectsUi?.apply(message);
1174 break;
1175 case MessageType.bankSnapshot:
1176 inventory?.handleBank(message);
1177 break;
1178 case MessageType.cauldronSnapshot:
1179 alchemy?.handleSnapshot(message);
1180 break;
1181 case MessageType.pigeonDispatched:
1182 inventory?.handlePigeonDispatched(message);
1183 break;
1184 case MessageType.pigeonDelivered:
1185 inventory?.handlePigeonDelivered(message);
1186 break;
1187 case MessageType.characterSearchResult:
1188 inventory?.handleCharacterSearch(message);
1189 break;
1190 case MessageType.craftResult:
1191 crafting?.handleCraftResult(message);
1192 break;
1193 case MessageType.worldStatus:
1194 if (view)
1195 {
1196 view.setSettings(message.settings ?? view.settings);
1197 view.worldHour = message.worldTime?.hour ?? view.worldHour;
1198 view.setWorldSeason(message.worldTime?.season);
1199 chat?.syncSettings();
1200 }
1201 break;
1202 case MessageType.chatBubble:
1203 chat?.showBubble(message);
1204 break;
1205 case MessageType.friends:
1206 social?.handleFriends(message);
1207 break;
1208 case MessageType.combatSwing:
1209 view?.spawnCombatSwing(message);
1210 break;
1211 case MessageType.combatProjectile:
1212 view?.spawnPhysicalProjectileFx({
1213 ...message,
1214 sprite: "fx:projectile:arrow"
1215 });
1216 break;
1217 case MessageType.combatNoArrows:
1218 toasts?.show("Out of arrows!");
1219 break;
1220 case MessageType.gatherSwing:
1221 case MessageType.tileShove:
1222 view?.spawnGatherSwing(message);
1223 break;
1224 case MessageType.stationOpen:
1225 if (message.stationId)
1226 { crafting?.openStation(message.stationId); }
1227 break;
1228 case MessageType.shopOpen:
1229 shop?.handleShopOpen(message);
1230 break;
1231 case MessageType.shopClosed:
1232 shop?.handleShopClosed(message);
1233 break;
1234 case MessageType.marketOpen:
1235 market?.handleOpen(message);
1236 break;
1237 case MessageType.marketClosed:
1238 market?.handleClosed(message);
1239 break;
1240 case MessageType.marketTrade:
1241 market?.handleTrade(message);
1242 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
1243 break;
1244 case MessageType.bountySnapshot:
1245 bounty?.handleSnapshot(message);
1246 break;
1247 case MessageType.closeBounty:
1248 bounty?.handleClosed(message);
1249 break;
1250 case MessageType.characterBounty:
1251 bounty?.handleCharacterBounty(message);
1252 social?.handleCharacterBounty(message);
1253 break;
1254 case MessageType.barberSnapshot:
1255 barber?.handleSnapshot(message);
1256 break;
1257 case MessageType.closeBarber:
1258 barber?.handleClosed(message);
1259 break;
1260 case MessageType.itemBubble:
1261 chat?.showItemBubble(message);
1262 break;
1263 case MessageType.gatherComplete:
1264 crafting?.refresh();
1265 break;
1266 case MessageType.combatHit:
1267 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
1268 view?.flashDamage(message.targetId);
1269 view?.spawnDamageNumber(message.targetId, message.damage);
1270 if (message.targetId === view?.localEntityId)
1271 {
1272 healthUi?.apply({
1273 current: message.health,
1274 max: message.maxHealth
1275 });
1276 }
1277 break;
1278 case MessageType.entityHealth:
1279 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1280 if (message.entityId === view?.localEntityId)
1281 {
1282 healthUi?.apply({
1283 current: message.health,
1284 max: message.maxHealth
1285 });
1286 }
1287 break;
1288 case MessageType.skillLevelUp:
1289 view?.spawnSkillLevelUp(message.entityId, message);
1290 if (message.entityId === view?.localEntityId)
1291 {
1292 const name = message.displayName ?? message.skillId ?? "Skill";
1293 toasts?.show(`${name} level ${message.level}!`);
1294 }
1295 break;
1296 case MessageType.playerDied:
1297 clearAllPendingActions();
1298 contextMenu?.hide();
1299 death?.show();
1300 if (message.entityId === view?.localEntityId)
1301 {
1302 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
1303 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
1304 }
1305 break;
1306 case MessageType.playerRespawned:
1307 death?.hide();
1308 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
1309 if (message.entityId === view?.localEntityId)
1310 {
1311 healthUi?.apply({
1312 current: message.health,
1313 max: message.maxHealth
1314 });
1315 }
1316 if (message.stamina != null || message.maxStamina != null)
1317 {
1318 staminaUi?.apply({
1319 current: message.stamina ?? staminaUi.getCurrent?.(),
1320 max: message.maxStamina ?? staminaUi.getMax?.()
1321 });
1322 }
1323 break;
1324 case MessageType.error:
1325 if (playing)
1326 { toasts?.show(message.message); }
1327 else
1328 {
1329 const createPanel = document.getElementById("create-panel");
1330 const createError = document.getElementById("create-error");
1331 if (createPanel && !createPanel.hidden && createError)
1332 { createError.textContent = message.message ?? ""; }
1333 else
1334 { showError(message.message); }
1335 }
1336 social?.showError(message.message);
1337 break;
1338 case MessageType.toast:
1339 if (playing)
1340 { toasts?.show(message.message); }
1341 break;
1342 case MessageType.forceLogout:
1343 returnToMenu(message.reason);
1344 break;
1345 }
1346 }, {
1347 onClose (event)
1348 {
1349 if (playing)
1350 { returnToMenu(event.reason || "Disconnected from server."); }
1351 }
1352 });
1353 await socket.connect();
1354 if (typeof window !== "undefined")
1355 {
1356 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
1357 {
1358 crafting?.openStation(stationId);
1359 };
1360 }
1361}
1362
1363function returnToMenu (reason = "")
1364{
1365 playing = false;
1366 clearAllPendingActions();
1367 social?.reset();
1368 chat?.reset();
1369 inventory?.reset();
1370 crafting?.reset();
1371 alchemy?.reset();
1372 staminaUi?.hide();
1373 healthUi?.hide();
1374 statusEffectsUi?.hide();
1375 skills?.hide();
1376 spells?.hide();
1377 contextMenu?.hide();
1378 death?.reset();
1379 shop?.close({ notifyServer: false });
1380 bounty?.close();
1381 barber?.close();
1382 hideWorldTooltip();
1383 if (view)
1384 {
1385 for (const key of [...(view.chunks?.keys?.() ?? [])])
1386 {
1387 const [chunkX, chunkY] = key.split(",").map(Number);
1388 view.removeChunk(chunkX, chunkY);
1389 }
1390 }
1391 overlay.hidden = false;
1392 hud.hidden = true;
1393 const settingsToggle = document.getElementById("settings-toggle");
1394 if (settingsToggle)
1395 { settingsToggle.hidden = true; }
1396 graphicsSettingsUi?.close();
1397 if (reason)
1398 { statusEl.textContent = reason; }
1399}
1400
1401document.getElementById("create-character-open")?.addEventListener("click", () =>
1402{
1403 showError("");
1404 const createError = document.getElementById("create-error");
1405 if (createError)
1406 { createError.textContent = ""; }
1407 document.getElementById("create-backdrop").hidden = false;
1408 document.getElementById("create-panel").hidden = false;
1409 void createHairControls?.refreshPreview();
1410});
1411
1412function closeCreateModal ()
1413{
1414 document.getElementById("create-backdrop").hidden = true;
1415 document.getElementById("create-panel").hidden = true;
1416}
1417
1418document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
1419document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
1420
1421document.getElementById("create-form").addEventListener("submit", (event) =>
1422{
1423 event.preventDefault();
1424 showError("");
1425 const createError = document.getElementById("create-error");
1426 if (createError)
1427 { createError.textContent = ""; }
1428 socket.send({
1429 type: MessageType.createCharacter,
1430 firstName: document.getElementById("first-name").value,
1431 lastName: document.getElementById("last-name").value,
1432 sex: document.getElementById("sex").value,
1433 hair: createHairControls?.currentHair?.() ?? null
1434 });
1435});
1436
1437document.getElementById("leave").addEventListener("click", () =>
1438{
1439 socket.send({ type: MessageType.leaveWorld });
1440 returnToMenu();
1441});
1442
1443main().catch((error) =>
1444{
1445 showError(error.message);
1446 console.error(error);
1447});
1448
1449function isBankTile (view, tileX, tileY)
1450{
1451 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
1452}
1453
1454function isMarketplaceTile (view, tileX, tileY)
1455{
1456 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1457}
1458
1459function isBountyOfficeTile (view, tileX, tileY)
1460{
1461 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
1462}
1463
1464function isBarberTile (view, tileX, tileY)
1465{
1466 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
1467}
1468
1469function isCauldronTile (view, tileX, tileY)
1470{
1471 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
1472}
1473
1474function isFurnaceTile (view, tileX, tileY)
1475{
1476 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
1477}
1478
1479function isAnvilTile (view, tileX, tileY)
1480{
1481 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
1482}
1483
1484function isWoodworkingBenchTile (view, tileX, tileY)
1485{
1486 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
1487}
1488
1489function isCraftingBenchTile (view, tileX, tileY)
1490{
1491 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1492}
1493
1494function isSpinningWheelTile (view, tileX, tileY)
1495{
1496 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
1497}
1498
1499function isLoomTile (view, tileX, tileY)
1500{
1501 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
1502}
1503
1504function isTailorBenchTile (view, tileX, tileY)
1505{
1506 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
1507}
1508
1509function isOreBoulderTile (view, tileX, tileY)
1510{
1511 const block = blockAt(view, tileX, tileY);
1512 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
1513}
1514
1515function isChopableTreeTile (view, tileX, tileY)
1516{
1517 return isChopableTreeBlock(blockAt(view, tileX, tileY));
1518}
1519
1520function isPickablePlantTile (view, tileX, tileY)
1521{
1522 return isPickablePlantBlock(blockAt(view, tileX, tileY));
1523}
1524
1525function updateSpellTargetHighlight ()
1526{
1527 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
1528 {
1529 view?.clearSpellTargetHighlight();
1530 return;
1531 }
1532 const canvas = scene?.canvas;
1533 if (!canvas)
1534 { return; }
1535 const rect = canvas.getBoundingClientRect();
1536 const mouseX = GameInput.mousePosition.x - rect.left;
1537 const mouseY = GameInput.mousePosition.y - rect.top;
1538 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1539 {
1540 view.clearSpellTargetHighlight();
1541 return;
1542 }
1543 const tile = view.screenToTile(mouseX, mouseY);
1544 const local = view.entities.get(view.localEntityId);
1545 const inRange = !local
1546 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
1547 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
1548}
1549
1550function hideWorldTooltip ()
1551{
1552 if (worldTooltip)
1553 { worldTooltip.hidden = true; }
1554}
1555
1556/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
1557function updateWorldTooltip ()
1558{
1559 if (!worldTooltip || !view || !scene || uiBlocked())
1560 {
1561 hideWorldTooltip();
1562 return;
1563 }
1564 const canvas = scene.canvas;
1565 const rect = canvas.getBoundingClientRect();
1566 const mouseX = GameInput.mousePosition.x - rect.left;
1567 const mouseY = GameInput.mousePosition.y - rect.top;
1568 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
1569 {
1570 hideWorldTooltip();
1571 return;
1572 }
1573 const entity = view.entityAtScreen(mouseX, mouseY);
1574 if (entity && entity.entityId !== view.localEntityId)
1575 {
1576 hideWorldTooltip();
1577 return;
1578 }
1579 const tile = view.screenToTile(mouseX, mouseY);
1580 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
1581 if (!label)
1582 {
1583 hideWorldTooltip();
1584 return;
1585 }
1586 worldTooltip.hidden = false;
1587 worldTooltip.textContent = label;
1588 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
1589 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
1590}
1591
1592function blockTypeAt (view, tileX, tileY)
1593{
1594 return blockAt(view, tileX, tileY)?.typeId ?? null;
1595}
1596
1597function blockAt (view, tileX, tileY)
1598{
1599 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1600 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1601 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1602 if (!snapshot)
1603 { return null; }
1604 const localX = tileX - chunkX * CHUNK_SIZE;
1605 const localY = tileY - chunkY * CHUNK_SIZE;
1606 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
1607}
1608
1609function groundTypeAt (view, tileX, tileY)
1610{
1611 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1612 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1613 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
1614 if (!snapshot)
1615 { return null; }
1616 const localX = tileX - chunkX * CHUNK_SIZE;
1617 const localY = tileY - chunkY * CHUNK_SIZE;
1618 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
1619}
1620
1621/** Best-effort client filter for approach destinations (server still authorizes paths). */
1622function isClientApproachable (tileX, tileY)
1623{
1624 if (!view)
1625 { return true; }
1626 const groundId = groundTypeAt(view, tileX, tileY);
1627 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
1628 if (groundDef && !groundDef.passable)
1629 { return false; }
1630 const block = blockAt(view, tileX, tileY);
1631 if (block?.typeId != null)
1632 {
1633 const blockDef = BLOCK_DEFINITIONS[block.typeId];
1634 if (blockDef && !blockDef.passable)
1635 { return false; }
1636 }
1637 for (const entity of view.entitiesAtTile(tileX, tileY))
1638 {
1639 if (entity.entityId === view.localEntityId)
1640 { continue; }
1641 if (entity.untargetable || entity.freeFlight)
1642 { continue; }
1643 return false;
1644 }
1645 return true;
1646}
1647
1648function chebyshev (ax, ay, bx, by)
1649{
1650 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
1651}