BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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