BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

crafting.js 19.7 KiB Download Raw
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity,
6 ItemId
7} from "/shared/definitions/items.js";
8import { craftingStationDefinition, CraftingStationId } from "/shared/definitions/craftingStations.js";
9import {
10 CRAFT_DURATION_MS,
11 canStartCraft,
12 countItemInSlots,
13 hasRecipeInputs,
14 recipesForStation
15} from "/shared/crafting/recipes.js";
16import { resolveTailorCraft } from "/shared/crafting/tailor.js";
17import {
18 CLOTH_TIER_ORDER,
19 CLOTH_DISPLAY_NAME,
20 ClothTier,
21 MATERIAL_TIER_ORDER,
22 MATERIAL_DISPLAY_NAME,
23 WOOD_TIER_ORDER,
24 WoodTier,
25 MaterialTier,
26 woodTierForMetal
27} from "/shared/definitions/materialTiers.js";
28import { craftDurationMs } from "/shared/definitions/gathering.js";
29import { applyItemIcon } from "../render/potionIcon.js";
30
31export function initCrafting ({
32 socket,
33 MessageType,
34 getInventorySlots,
35 getSkillLevel
36})
37{
38 const backdrop = document.getElementById("craft-backdrop");
39 const panel = document.getElementById("craft-panel");
40 const stationName = document.getElementById("craft-station-name");
41 const recipeGrid = document.getElementById("craft-recipe-grid");
42 const detailEmpty = document.getElementById("craft-detail-empty");
43 const detailBody = document.getElementById("craft-detail-body");
44 const materialControls = document.getElementById("craft-material-controls");
45 const materialTierSelect = document.getElementById("craft-material-tier");
46 const dyeControls = document.getElementById("craft-dye-controls");
47 const dyePickBtn = document.getElementById("craft-dye-pick");
48 const dyeClearBtn = document.getElementById("craft-dye-clear");
49 const dyePreview = document.getElementById("craft-dye-preview");
50 const outputImg = document.getElementById("craft-output-img");
51 const outputName = document.getElementById("craft-output-name");
52 const inputsList = document.getElementById("craft-inputs");
53 const statusEl = document.getElementById("craft-status");
54 const progressWrap = document.getElementById("craft-progress");
55 const progressFill = document.getElementById("craft-progress-fill");
56 const craftButton = document.getElementById("craft-button");
57 const craftBatchButton = document.getElementById("craft-batch-button");
58 const craftBatchAllButton = document.getElementById("craft-batch-all-button");
59 const dyeBackdrop = document.getElementById("dye-picker-backdrop");
60 const dyePanel = document.getElementById("dye-picker-panel");
61 const dyeGrid = document.getElementById("dye-picker-grid");
62
63 let open = false;
64 let stationId = null;
65 let recipes = [];
66 let selectedRecipeId = null;
67 let selectedCraftGroup = null;
68 let selectedMaterial = ClothTier.cotton;
69 let dyeSlotIndex = null;
70 let crafting = false;
71 let craftTimer = null;
72 let craftAnimFrame = null;
73 let craftStartedAt = 0;
74
75 document.getElementById("craft-close").addEventListener("click", () => close());
76 backdrop.addEventListener("click", () => close());
77 craftButton.addEventListener("click", () => startCraft());
78 craftBatchButton?.addEventListener("click", () => startBatchCraft());
79 craftBatchAllButton?.addEventListener("click", () => startCraft({ batchAll: true }));
80 materialTierSelect?.addEventListener("change", () =>
81 {
82 selectedMaterial = materialTierSelect.value || selectedMaterial;
83 if (usesCraftGroups())
84 {
85 const rows = groupedDisplayRecipes();
86 if (!rows.some((row) => row.group === selectedCraftGroup))
87 { selectedCraftGroup = rows[0]?.group ?? null; }
88 syncSelectedRecipeFromMaterial();
89 }
90 renderRecipeGrid();
91 renderDetail();
92 });
93 dyePickBtn?.addEventListener("click", () =>
94 {
95 if (!isTailorStation())
96 { return; }
97 openDyePicker();
98 });
99 dyeClearBtn?.addEventListener("click", () =>
100 {
101 dyeSlotIndex = null;
102 renderDetail();
103 });
104 document.getElementById("dye-picker-close")?.addEventListener("click", () => closeDyePicker());
105 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
106
107 function isTailorStation ()
108 {
109 return stationId === CraftingStationId.tailorBench;
110 }
111
112 function isAnvilStation ()
113 {
114 return stationId === CraftingStationId.anvil;
115 }
116
117 function isWoodworkingStation ()
118 {
119 return stationId === CraftingStationId.woodworkingBench;
120 }
121
122 function isCraftingBenchStation ()
123 {
124 return stationId === CraftingStationId.craftingBench;
125 }
126
127 function isSpinningWheelStation ()
128 {
129 return stationId === CraftingStationId.spinningWheel;
130 }
131
132 function isLoomStation ()
133 {
134 return stationId === CraftingStationId.loom;
135 }
136
137 function usesMaterialDropdown ()
138 {
139 return isTailorStation()
140 || isAnvilStation()
141 || isWoodworkingStation()
142 || isCraftingBenchStation()
143 || isSpinningWheelStation()
144 || isLoomStation();
145 }
146
147 /** One grid cell per craft group; material dropdown picks the tier variant. */
148 function usesCraftGroups ()
149 {
150 return isAnvilStation()
151 || isWoodworkingStation()
152 || isCraftingBenchStation()
153 || isSpinningWheelStation()
154 || isLoomStation();
155 }
156
157 function craftGroupKey (recipe)
158 {
159 return recipe.craftGroup ?? recipe.recipeId;
160 }
161
162 /** Map UI material selection to a recipe's xpMaterial tier. */
163 function recipeXpMaterialForSelection (recipe, material = selectedMaterial)
164 {
165 if (isCraftingBenchStation() && recipe.craftGroup === "bow")
166 { return woodTierForMetal(material); }
167 return material;
168 }
169
170 function recipeMatchesMaterial (recipe, material = selectedMaterial)
171 {
172 if (!recipe?.xpMaterial)
173 { return true; }
174 return recipe.xpMaterial === recipeXpMaterialForSelection(recipe, material);
175 }
176
177 function selectedRecipe ()
178 {
179 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
180 }
181
182 function stationSkillLevel ()
183 {
184 const def = craftingStationDefinition(stationId);
185 return getSkillLevel?.(def?.skillId) ?? 1;
186 }
187
188 function activeRecipe ()
189 {
190 const base = selectedRecipe();
191 if (!base)
192 { return null; }
193 if (!base.tailorTemplate)
194 { return base; }
195 const slots = getInventorySlots?.() ?? [];
196 const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
197 const resolved = resolveTailorCraft({
198 templateId: base.tailorTemplate,
199 clothTier: selectedMaterial,
200 dyeStack
201 });
202 return resolved.ok ? resolved.recipe : base;
203 }
204
205 function refresh ()
206 {
207 if (!open)
208 { return; }
209 renderRecipeGrid();
210 renderDetail();
211 }
212
213 function materialOptionsForStation ()
214 {
215 if (isTailorStation() || isSpinningWheelStation() || isLoomStation())
216 {
217 return {
218 order: CLOTH_TIER_ORDER,
219 names: CLOTH_DISPLAY_NAME,
220 fallback: ClothTier.cotton
221 };
222 }
223 if (isWoodworkingStation())
224 {
225 return {
226 order: WOOD_TIER_ORDER,
227 names: MATERIAL_DISPLAY_NAME,
228 fallback: WoodTier.pine
229 };
230 }
231 return {
232 order: MATERIAL_TIER_ORDER,
233 names: MATERIAL_DISPLAY_NAME,
234 fallback: MaterialTier.bronze
235 };
236 }
237
238 function fillMaterialTiers ()
239 {
240 if (!materialTierSelect)
241 { return; }
242 const { order, names, fallback } = materialOptionsForStation();
243 if (!order.includes(selectedMaterial))
244 { selectedMaterial = fallback; }
245 materialTierSelect.replaceChildren();
246 for (const tier of order)
247 {
248 const option = document.createElement("option");
249 option.value = tier;
250 option.textContent = names[tier] ?? tier;
251 materialTierSelect.append(option);
252 }
253 materialTierSelect.value = selectedMaterial;
254 }
255
256 function groupedDisplayRecipes ()
257 {
258 if (!usesCraftGroups())
259 {
260 return recipes.map((recipe) => ({
261 group: craftGroupKey(recipe),
262 recipe
263 }));
264 }
265 const byGroup = new Map();
266 for (const recipe of recipes)
267 {
268 const group = craftGroupKey(recipe);
269 if (!byGroup.has(group))
270 { byGroup.set(group, []); }
271 byGroup.get(group).push(recipe);
272 }
273 const rows = [];
274 for (const [group, variants] of byGroup)
275 {
276 if (!variants.some((entry) => recipeMatchesMaterial(entry)))
277 { continue; }
278 const recipe = variants.find((entry) => recipeMatchesMaterial(entry))
279 ?? variants[0];
280 rows.push({ group, recipe, variants });
281 }
282 return rows;
283 }
284
285 function syncSelectedRecipeFromMaterial ()
286 {
287 if (!usesCraftGroups() || !selectedCraftGroup)
288 { return; }
289 const variants = recipes.filter((recipe) => craftGroupKey(recipe) === selectedCraftGroup);
290 if (!variants.length)
291 { return; }
292 let match = variants.find((entry) => recipeMatchesMaterial(entry));
293 if (!match)
294 {
295 match = variants[0];
296 if (match?.xpMaterial && !(isCraftingBenchStation() && match.craftGroup === "bow"))
297 {
298 selectedMaterial = match.xpMaterial;
299 if (materialTierSelect)
300 { materialTierSelect.value = selectedMaterial; }
301 }
302 }
303 selectedRecipeId = match.recipeId;
304 }
305
306 function renderRecipeGrid ()
307 {
308 recipeGrid.replaceChildren();
309 for (const row of groupedDisplayRecipes())
310 {
311 recipeGrid.append(renderRecipeCell(row));
312 }
313 }
314
315 function renderRecipeCell ({ group, recipe })
316 {
317 const def = itemDefinition(recipe.output.itemId);
318 const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
319 const cell = document.createElement("button");
320 cell.type = "button";
321 cell.className = "craft-recipe-cell";
322 const selected = usesCraftGroups()
323 ? group === selectedCraftGroup
324 : recipe.recipeId === selectedRecipeId;
325 if (selected)
326 { cell.classList.add("selected"); }
327
328 const img = document.createElement("img");
329 img.alt = def?.displayName ?? "Item";
330 applyItemIcon(img, stack, itemAssetPathForStack(stack));
331
332 const label = document.createElement("span");
333 label.className = "craft-recipe-name";
334 if (recipe.tailorTemplate)
335 { label.textContent = def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment"; }
336 else if (recipe.craftGroupLabel)
337 { label.textContent = recipe.craftGroupLabel; }
338 else
339 { label.textContent = def?.displayName ?? "Item"; }
340
341 cell.append(img, label);
342 cell.addEventListener("click", () =>
343 {
344 if (crafting)
345 { return; }
346 selectedCraftGroup = group;
347 if (usesCraftGroups())
348 { syncSelectedRecipeFromMaterial(); }
349 else
350 { selectedRecipeId = recipe.recipeId; }
351 renderRecipeGrid();
352 renderDetail();
353 });
354 return cell;
355 }
356
357 function renderDetail ()
358 {
359 if (materialControls)
360 { materialControls.hidden = !usesMaterialDropdown(); }
361 if (!isTailorStation())
362 { dyeSlotIndex = null; }
363 if (dyeControls)
364 { dyeControls.hidden = !isTailorStation(); }
365
366 const recipe = activeRecipe();
367 if (!recipe)
368 {
369 detailEmpty.hidden = false;
370 detailBody.hidden = true;
371 return;
372 }
373 detailEmpty.hidden = true;
374 detailBody.hidden = false;
375
376 const outputStack = {
377 itemId: recipe.output.itemId,
378 quantity: Math.max(1, recipe.output.quantity | 0 || 1),
379 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
380 };
381 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
382 outputImg.alt = itemDisplayName(outputStack);
383 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
384 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
385
386 inputsList.replaceChildren();
387 const slots = getInventorySlots?.() ?? [];
388 for (const input of recipe.inputs ?? [])
389 {
390 inputsList.append(renderInputRow(input, slots));
391 }
392 if (recipe.consumeDye)
393 {
394 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
395 const row = document.createElement("li");
396 row.className = "craft-input-row";
397 row.textContent = dye
398 ? `Dye — 1 use (${dye.instance?.fillLevel ?? "?"}/5)`
399 : "Dye — none selected";
400 inputsList.append(row);
401 }
402
403 if (dyePreview && dyeClearBtn)
404 {
405 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
406 if (dye?.itemId === ItemId.dye)
407 {
408 dyePreview.hidden = false;
409 dyeClearBtn.hidden = false;
410 applyItemIcon(dyePreview, dye, itemAssetPathForStack(dye));
411 }
412 else
413 {
414 dyePreview.hidden = true;
415 dyeClearBtn.hidden = true;
416 }
417 }
418
419 updateCraftState(slots, recipe);
420 }
421
422 function renderInputRow (input, slots)
423 {
424 const need = input.quantity | 0;
425 const have = countItemInSlots(slots, input.itemId);
426 const stack = { itemId: input.itemId, quantity: need };
427 const row = document.createElement("li");
428 row.className = "craft-input-row";
429 if (have < need)
430 { row.classList.add("short"); }
431
432 const img = document.createElement("img");
433 img.alt = itemDisplayName(stack);
434 applyItemIcon(img, stack, itemAssetPathForStack(stack));
435
436 const text = document.createElement("span");
437 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
438 row.append(img, text);
439 return row;
440 }
441
442 function updateCraftState (slots, recipe)
443 {
444 const batchVisible = isCraftingBenchStation();
445 if (craftBatchButton)
446 { craftBatchButton.hidden = !batchVisible; }
447 if (craftBatchAllButton)
448 { craftBatchAllButton.hidden = !batchVisible; }
449
450 if (crafting)
451 {
452 craftButton.disabled = true;
453 if (craftBatchButton)
454 { craftBatchButton.disabled = true; }
455 if (craftBatchAllButton)
456 { craftBatchAllButton.disabled = true; }
457 return;
458 }
459 const skill = stationSkillLevel();
460 const minLevel = recipe.minSkillLevel | 0 || 1;
461 if (skill < minLevel)
462 {
463 statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`;
464 craftButton.disabled = true;
465 if (craftBatchButton)
466 { craftBatchButton.disabled = true; }
467 if (craftBatchAllButton)
468 { craftBatchAllButton.disabled = true; }
469 return;
470 }
471 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
472 const craftOpts = { dyeSlotIndex };
473 if (canStartCraft(slotsSnapshot, recipe, skill, craftOpts))
474 {
475 statusEl.textContent = "";
476 craftButton.disabled = false;
477 if (craftBatchButton)
478 { craftBatchButton.disabled = !batchVisible; }
479 if (craftBatchAllButton)
480 { craftBatchAllButton.disabled = !batchVisible; }
481 return;
482 }
483 if (!hasRecipeInputs(slotsSnapshot, recipe))
484 {
485 statusEl.textContent = "Missing materials.";
486 }
487 else if (recipe.consumeDye && dyeSlotIndex != null)
488 {
489 statusEl.textContent = "Not enough bag space (need room for the result or a partially used dye).";
490 }
491 else
492 {
493 statusEl.textContent = "Not enough bag space for the result.";
494 }
495 craftButton.disabled = true;
496 if (craftBatchButton)
497 { craftBatchButton.disabled = true; }
498 if (craftBatchAllButton)
499 { craftBatchAllButton.disabled = true; }
500 }
501
502 function openDyePicker ()
503 {
504 if (!isTailorStation())
505 { return; }
506 const slots = getInventorySlots?.() ?? [];
507 dyeGrid.replaceChildren();
508 let found = false;
509 slots.forEach((stack, index) =>
510 {
511 if (!stack || stack.itemId !== ItemId.dye)
512 { return; }
513 found = true;
514 const cell = document.createElement("button");
515 cell.type = "button";
516 cell.className = "craft-recipe-cell craft-dye-cell";
517 cell.title = "Dye";
518 const img = document.createElement("img");
519 applyItemIcon(img, stack, itemAssetPathForStack(stack));
520 img.alt = "Dye";
521 cell.append(img);
522 cell.addEventListener("click", () =>
523 {
524 dyeSlotIndex = index;
525 closeDyePicker();
526 renderDetail();
527 });
528 dyeGrid.append(cell);
529 });
530 if (!found)
531 {
532 const empty = document.createElement("p");
533 empty.className = "hint";
534 empty.textContent = "No dyes in your inventory.";
535 dyeGrid.append(empty);
536 }
537 dyePanel.hidden = false;
538 dyeBackdrop.hidden = false;
539 }
540
541 function closeDyePicker ()
542 {
543 dyePanel.hidden = true;
544 dyeBackdrop.hidden = true;
545 }
546
547 function startBatchCraft ()
548 {
549 const raw = window.prompt("How many?", "1");
550 if (raw == null)
551 { return; }
552 const count = Number.parseInt(raw, 10);
553 if (!Number.isFinite(count) || count < 1)
554 { return; }
555 startCraft({ batchCount: count });
556 }
557
558 function startCraft (options = {})
559 {
560 const recipe = activeRecipe();
561 if (!recipe || crafting)
562 { return; }
563 const slots = getInventorySlots?.() ?? [];
564 if (!canStartCraft(slots, recipe, stationSkillLevel(), { dyeSlotIndex }))
565 {
566 renderDetail();
567 return;
568 }
569 crafting = true;
570 craftButton.disabled = true;
571 if (craftBatchButton)
572 { craftBatchButton.disabled = true; }
573 if (craftBatchAllButton)
574 { craftBatchAllButton.disabled = true; }
575 progressWrap.hidden = false;
576 progressFill.style.width = "0%";
577 statusEl.textContent = options.batchAll
578 ? "Crafting all…"
579 : options.batchCount > 1
580 ? `Crafting ${options.batchCount}…`
581 : "Crafting…";
582 craftStartedAt = performance.now();
583 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
584 const payload = {
585 type: MessageType.startCraft,
586 stationId,
587 recipeId: selectedRecipeId
588 };
589 if (options.batchCount != null)
590 { payload.batchCount = options.batchCount | 0; }
591 if (options.batchAll)
592 { payload.batchAll = true; }
593 if (isTailorStation())
594 {
595 payload.clothTier = selectedMaterial;
596 payload.dyeSlotIndex = dyeSlotIndex;
597 }
598 socket.send(payload);
599 animateProgress(durationMs);
600 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
601 }
602
603 function animateProgress (durationMs)
604 {
605 const tick = (now) =>
606 {
607 if (!crafting)
608 { return; }
609 const elapsed = now - craftStartedAt;
610 const pct = Math.min(100, (elapsed / durationMs) * 100);
611 progressFill.style.width = `${pct}%`;
612 if (pct < 100)
613 { craftAnimFrame = requestAnimationFrame(tick); }
614 };
615 craftAnimFrame = requestAnimationFrame(tick);
616 }
617
618 function stopCraftAnimation ()
619 {
620 if (craftTimer != null)
621 {
622 clearTimeout(craftTimer);
623 craftTimer = null;
624 }
625 if (craftAnimFrame != null)
626 {
627 cancelAnimationFrame(craftAnimFrame);
628 craftAnimFrame = null;
629 }
630 crafting = false;
631 progressWrap.hidden = true;
632 progressFill.style.width = "0%";
633 }
634
635 function finishCraft (timedOut)
636 {
637 stopCraftAnimation();
638 if (timedOut)
639 {
640 statusEl.textContent = "Waiting for server…";
641 }
642 renderDetail();
643 }
644
645 function openStation (nextStationId)
646 {
647 const def = craftingStationDefinition(nextStationId);
648 if (!def)
649 { return; }
650 stationId = nextStationId;
651 recipes = recipesForStation(nextStationId);
652 const { fallback } = materialOptionsForStation();
653 selectedMaterial = fallback;
654 dyeSlotIndex = null;
655 fillMaterialTiers();
656 const first = groupedDisplayRecipes()[0];
657 selectedCraftGroup = first?.group ?? null;
658 if (usesCraftGroups())
659 { syncSelectedRecipeFromMaterial(); }
660 else
661 { selectedRecipeId = first?.recipe?.recipeId ?? recipes[0]?.recipeId ?? null; }
662 stationName.textContent = def.displayName;
663 open = true;
664 panel.hidden = false;
665 backdrop.hidden = false;
666 statusEl.textContent = recipes.length
667 ? "Select a recipe."
668 : "No recipes defined for this station yet.";
669 renderRecipeGrid();
670 renderDetail();
671 }
672
673 function close ()
674 {
675 if (crafting)
676 {
677 socket.send({ type: MessageType.cancelCraft });
678 stopCraftAnimation();
679 }
680 closeDyePicker();
681 open = false;
682 stationId = null;
683 recipes = [];
684 selectedRecipeId = null;
685 selectedCraftGroup = null;
686 dyeSlotIndex = null;
687 panel.hidden = true;
688 backdrop.hidden = true;
689 detailEmpty.hidden = false;
690 detailBody.hidden = true;
691 statusEl.textContent = "";
692 }
693
694 function handleCraftResult (message)
695 {
696 if (!open || message.recipeId !== selectedRecipeId)
697 { return; }
698 if (message.ok && message.continuing)
699 {
700 const recipe = activeRecipe();
701 if (!recipe)
702 {
703 stopCraftAnimation();
704 renderDetail();
705 return;
706 }
707 statusEl.textContent = "Crafting…";
708 craftStartedAt = performance.now();
709 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
710 if (craftTimer != null)
711 { clearTimeout(craftTimer); }
712 animateProgress(durationMs);
713 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
714 renderDetail();
715 return;
716 }
717 stopCraftAnimation();
718 if (message.ok)
719 {
720 statusEl.textContent = message.burned
721 ? "The food burned."
722 : "Craft complete.";
723 }
724 else
725 {
726 statusEl.textContent = message.error ?? "Could not craft.";
727 }
728 renderDetail();
729 }
730
731 return {
732 openStation,
733 close,
734 refresh,
735 handleCraftResult,
736 isOpen ()
737 {
738 return open;
739 },
740 isBlocking ()
741 {
742 if (!open)
743 { return false; }
744 if (backdrop && !backdrop.hidden)
745 { return true; }
746 const x = GameInput.mousePosition.x;
747 const y = GameInput.mousePosition.y;
748 const box = panel.getBoundingClientRect();
749 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
750 },
751 reset ()
752 {
753 close();
754 }
755 };
756}