BlueGit

timfa questward

Add cloth tiers, dyes, and tailor crafting loop.

Share armour sprites via material tint, and wire cotton/flower gathering through spinning, weaving, dye mixing, and sweater craft.

timfa Tim Falken · pushed by timfa

Authored 2026-08-26 · 2 months ago

Hash
15d5956a2d4435cd4980d54a0cfe0082bbf213d1
Parent
69bf23af
75 files changed +1735 −85
client/assets/blocks/cotton-plant/cotton-plant.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/loom/loom.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/spinning-wheel/spinning-wheel.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/tailor-bench/tailor-bench.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/adamantium-boots/adamantium-boots.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/adamantium-chestplate/adamantium-chestplate.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/adamantium-full-helm/adamantium-full-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/adamantium-greaves/adamantium-greaves.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/adamantium-helmet/adamantium-helmet.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/adamantium-horned-helm/adamantium-horned-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-boots/bronze-boots.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-chestplate/bronze-chestplate.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-full-helm/bronze-full-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-greaves/bronze-greaves.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-helmet/bronze-helmet.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-horned-helm/bronze-horned-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/dragon-boots/dragon-boots.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/dragon-chestplate/dragon-chestplate.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/dragon-full-helm/dragon-full-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/dragon-greaves/dragon-greaves.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/dragon-helmet/dragon-helmet.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/dragon-horned-helm/dragon-horned-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/flower/flower.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/glass-bottle/glass-bottle.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/iron-boots/iron-boots.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/iron-chestplate/iron-chestplate.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/iron-full-helm/iron-full-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/iron-greaves/iron-greaves.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/iron-helmet/iron-helmet.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/iron-horned-helm/iron-horned-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/mithril-boots/mithril-boots.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/mithril-chestplate/mithril-chestplate.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/mithril-full-helm/mithril-full-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/mithril-greaves/mithril-greaves.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/mithril-helmet/mithril-helmet.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/mithril-horned-helm/mithril-horned-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/orichalcum-boots/orichalcum-boots.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/orichalcum-chestplate/orichalcum-chestplate.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/orichalcum-full-helm/orichalcum-full-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/orichalcum-greaves/orichalcum-greaves.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/orichalcum-helmet/orichalcum-helmet.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/orichalcum-horned-helm/orichalcum-horned-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/steel-boots/steel-boots.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/steel-chestplate/steel-chestplate.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/steel-full-helm/steel-full-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/steel-greaves/steel-greaves.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/steel-helmet/steel-helmet.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/steel-horned-helm/steel-horned-helm.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/index.html +21 −0
@@ -158,6 +158,18 @@
158 158 <div class="craft-detail">
159 159 <p id="craft-detail-empty" class="hint">Select a recipe.</p>
160 160 <div id="craft-detail-body" hidden>
161 <div id="craft-tailor-controls" class="craft-tailor-controls" hidden>
162 <label class="craft-tailor-field">
163 <span>Material</span>
164 <select id="craft-cloth-tier"></select>
165 </label>
166 <div class="craft-tailor-dye">
167 <span>Dye (optional)</span>
168 <button id="craft-dye-pick" type="button">Choose dye…</button>
169 <button id="craft-dye-clear" type="button" hidden>Clear dye</button>
170 <img id="craft-dye-preview" alt="" hidden>
171 </div>
172 </div>
161 173 <div class="craft-output">
162 174 <img id="craft-output-img" alt="">
163 175 <h3 id="craft-output-name"></h3>
@@ -173,6 +185,15 @@
173 185 </div>
174 186 </aside>
175 187
188 <div id="dye-picker-backdrop" class="modal-backdrop" hidden></div>
189 <aside id="dye-picker-panel" hidden>
190 <header>
191 <h2>Choose dye</h2>
192 <button id="dye-picker-close" type="button">Close</button>
193 </header>
194 <div id="dye-picker-grid" class="craft-recipe-grid"></div>
195 </aside>
196
176 197 <div id="shop-backdrop" class="modal-backdrop" hidden></div>
177 198 <aside id="shop-panel" hidden>
178 199 <header>
@@ -158,6 +158,18 @@
158 <div class="craft-detail">
158 <div class="craft-detail">
159 <p id="craft-detail-empty" class="hint">Select a recipe.</p>
159 <p id="craft-detail-empty" class="hint">Select a recipe.</p>
160 <div id="craft-detail-body" hidden>
160 <div id="craft-detail-body" hidden>
161 <div id="craft-tailor-controls" class="craft-tailor-controls" hidden>
162 <label class="craft-tailor-field">
163 <span>Material</span>
164 <select id="craft-cloth-tier"></select>
165 </label>
166 <div class="craft-tailor-dye">
167 <span>Dye (optional)</span>
168 <button id="craft-dye-pick" type="button">Choose dye…</button>
169 <button id="craft-dye-clear" type="button" hidden>Clear dye</button>
170 <img id="craft-dye-preview" alt="" hidden>
171 </div>
172 </div>
161 <div class="craft-output">
173 <div class="craft-output">
162 <img id="craft-output-img" alt="">
174 <img id="craft-output-img" alt="">
163 <h3 id="craft-output-name"></h3>
175 <h3 id="craft-output-name"></h3>
@@ -173,6 +185,15 @@
173 </div>
185 </div>
174 </aside>
186 </aside>
175
187
188 <div id="dye-picker-backdrop" class="modal-backdrop" hidden></div>
189 <aside id="dye-picker-panel" hidden>
190 <header>
191 <h2>Choose dye</h2>
192 <button id="dye-picker-close" type="button">Close</button>
193 </header>
194 <div id="dye-picker-grid" class="craft-recipe-grid"></div>
195 </aside>
196
176 <div id="shop-backdrop" class="modal-backdrop" hidden></div>
197 <div id="shop-backdrop" class="modal-backdrop" hidden></div>
177 <aside id="shop-panel" hidden>
198 <aside id="shop-panel" hidden>
178 <header>
199 <header>
client/src/play/alchemy.js +30 −8
@@ -30,6 +30,7 @@ export function initAlchemy ({
30 30 let state = null;
31 31 let pickSlotIndex = null;
32 32 let pickItemId = null;
33 let pickInstance = null;
33 34
34 35 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
35 36 backdrop?.addEventListener("click", () => close());
@@ -119,6 +120,7 @@ export function initAlchemy ({
119 120 {
120 121 pickSlotIndex = slotIndex;
121 122 pickItemId = null;
123 pickInstance = null;
122 124 pickList.replaceChildren();
123 125 const counts = new Map();
124 126 for (const slot of getInventorySlots?.() ?? [])
@@ -129,24 +131,42 @@ export function initAlchemy ({
129 131 if (!def || def.uniqueInstance || def.equipment
130 132 || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
131 133 { continue; }
132 counts.set(slot.itemId, (counts.get(slot.itemId) ?? 0) + (slot.quantity | 0));
134 const identity = (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye)
135 ? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}`
136 : String(slot.itemId);
137 const prev = counts.get(identity);
138 if (prev)
139 { prev.quantity += slot.quantity | 0; }
140 else
141 {
142 counts.set(identity, {
143 itemId: slot.itemId,
144 quantity: slot.quantity | 0,
145 instance: slot.instance ? structuredClone(slot.instance) : null
146 });
147 }
133 148 }
134 for (const [itemId, quantity] of counts)
149 for (const entry of counts.values())
135 150 {
136 const stack = { itemId, quantity };
151 const stack = {
152 itemId: entry.itemId,
153 quantity: entry.quantity,
154 instance: entry.instance
155 };
137 156 const btn = document.createElement("button");
138 157 btn.type = "button";
139 158 btn.className = "cauldron-pick-item";
140 159 const img = document.createElement("img");
141 160 applyItemIcon(img, stack, itemAssetPathForStack(stack));
142 161 const label = document.createElement("span");
143 label.textContent = `${itemDisplayName(stack)} (${formatQuantity(quantity)})`;
162 label.textContent = `${itemDisplayName(stack)} (${formatQuantity(entry.quantity)})`;
144 163 btn.append(img, label);
145 164 btn.addEventListener("click", () =>
146 165 {
147 pickItemId = itemId;
148 pickQty.max = String(quantity);
149 pickQty.value = String(Math.min(quantity, Number(pickQty.value) || 1));
166 pickItemId = entry.itemId;
167 pickInstance = entry.instance;
168 pickQty.max = String(entry.quantity);
169 pickQty.value = String(Math.min(entry.quantity, Number(pickQty.value) || 1));
150 170 for (const child of pickList.children)
151 171 { child.classList.toggle("selected", child === btn); }
152 172 });
@@ -163,6 +183,7 @@ export function initAlchemy ({
163 183 pickPanel.hidden = true;
164 184 pickSlotIndex = null;
165 185 pickItemId = null;
186 pickInstance = null;
166 187 }
167 188
168 189 function confirmPick ()
@@ -174,7 +195,8 @@ export function initAlchemy ({
174 195 type: MessageType.cauldronSetSlot,
175 196 slotIndex: pickSlotIndex,
176 197 itemId: pickItemId,
177 quantity
198 quantity,
199 instance: pickInstance
178 200 });
179 201 closePick();
180 202 }
@@ -30,6 +30,7 @@ export function initAlchemy ({
30 let state = null;
30 let state = null;
31 let pickSlotIndex = null;
31 let pickSlotIndex = null;
32 let pickItemId = null;
32 let pickItemId = null;
33 let pickInstance = null;
33
34
34 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
35 document.getElementById("cauldron-close")?.addEventListener("click", () => close());
35 backdrop?.addEventListener("click", () => close());
36 backdrop?.addEventListener("click", () => close());
@@ -119,6 +120,7 @@ export function initAlchemy ({
119 {
120 {
120 pickSlotIndex = slotIndex;
121 pickSlotIndex = slotIndex;
121 pickItemId = null;
122 pickItemId = null;
123 pickInstance = null;
122 pickList.replaceChildren();
124 pickList.replaceChildren();
123 const counts = new Map();
125 const counts = new Map();
124 for (const slot of getInventorySlots?.() ?? [])
126 for (const slot of getInventorySlots?.() ?? [])
@@ -129,24 +131,42 @@ export function initAlchemy ({
129 if (!def || def.uniqueInstance || def.equipment
131 if (!def || def.uniqueInstance || def.equipment
130 || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
132 || slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
131 { continue; }
133 { continue; }
132 counts.set(slot.itemId, (counts.get(slot.itemId) ?? 0) + (slot.quantity | 0));
134 const identity = (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye)
135 ? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}`
136 : String(slot.itemId);
137 const prev = counts.get(identity);
138 if (prev)
139 { prev.quantity += slot.quantity | 0; }
140 else
141 {
142 counts.set(identity, {
143 itemId: slot.itemId,
144 quantity: slot.quantity | 0,
145 instance: slot.instance ? structuredClone(slot.instance) : null
146 });
147 }
133 }
148 }
134 for (const [itemId, quantity] of counts)
149 for (const entry of counts.values())
135 {
150 {
136 const stack = { itemId, quantity };
151 const stack = {
152 itemId: entry.itemId,
153 quantity: entry.quantity,
154 instance: entry.instance
155 };
137 const btn = document.createElement("button");
156 const btn = document.createElement("button");
138 btn.type = "button";
157 btn.type = "button";
139 btn.className = "cauldron-pick-item";
158 btn.className = "cauldron-pick-item";
140 const img = document.createElement("img");
159 const img = document.createElement("img");
141 applyItemIcon(img, stack, itemAssetPathForStack(stack));
160 applyItemIcon(img, stack, itemAssetPathForStack(stack));
142 const label = document.createElement("span");
161 const label = document.createElement("span");
143 label.textContent = `${itemDisplayName(stack)} (${formatQuantity(quantity)})`;
162 label.textContent = `${itemDisplayName(stack)} (${formatQuantity(entry.quantity)})`;
144 btn.append(img, label);
163 btn.append(img, label);
145 btn.addEventListener("click", () =>
164 btn.addEventListener("click", () =>
146 {
165 {
147 pickItemId = itemId;
166 pickItemId = entry.itemId;
148 pickQty.max = String(quantity);
167 pickInstance = entry.instance;
149 pickQty.value = String(Math.min(quantity, Number(pickQty.value) || 1));
168 pickQty.max = String(entry.quantity);
169 pickQty.value = String(Math.min(entry.quantity, Number(pickQty.value) || 1));
150 for (const child of pickList.children)
170 for (const child of pickList.children)
151 { child.classList.toggle("selected", child === btn); }
171 { child.classList.toggle("selected", child === btn); }
152 });
172 });
@@ -163,6 +183,7 @@ export function initAlchemy ({
163 pickPanel.hidden = true;
183 pickPanel.hidden = true;
164 pickSlotIndex = null;
184 pickSlotIndex = null;
165 pickItemId = null;
185 pickItemId = null;
186 pickInstance = null;
166 }
187 }
167
188
168 function confirmPick ()
189 function confirmPick ()
@@ -174,7 +195,8 @@ export function initAlchemy ({
174 type: MessageType.cauldronSetSlot,
195 type: MessageType.cauldronSetSlot,
175 slotIndex: pickSlotIndex,
196 slotIndex: pickSlotIndex,
176 itemId: pickItemId,
197 itemId: pickItemId,
177 quantity
198 quantity,
199 instance: pickInstance
178 });
200 });
179 closePick();
201 closePick();
180 }
202 }
client/src/play/crafting.js +159 −9
@@ -2,9 +2,10 @@ import {
2 2 itemDefinition,
3 3 itemDisplayName,
4 4 itemAssetPathForStack,
5 formatQuantity
5 formatQuantity,
6 ItemId
6 7 } from "/shared/definitions/items.js";
7 import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";
8 import { craftingStationDefinition, CraftingStationId } from "/shared/definitions/craftingStations.js";
8 9 import {
9 10 CRAFT_DURATION_MS,
10 11 canStartCraft,
@@ -12,6 +13,8 @@ import {
12 13 hasRecipeInputs,
13 14 recipesForStation
14 15 } from "/shared/crafting/recipes.js";
16 import { resolveTailorCraft } from "/shared/crafting/tailor.js";
17 import { CLOTH_TIER_ORDER, CLOTH_DISPLAY_NAME, ClothTier } from "/shared/definitions/materialTiers.js";
15 18 import { craftDurationMs } from "/shared/definitions/gathering.js";
16 19 import { applyItemIcon } from "../render/potionIcon.js";
17 20
@@ -28,6 +31,11 @@ export function initCrafting ({
28 31 const recipeGrid = document.getElementById("craft-recipe-grid");
29 32 const detailEmpty = document.getElementById("craft-detail-empty");
30 33 const detailBody = document.getElementById("craft-detail-body");
34 const tailorControls = document.getElementById("craft-tailor-controls");
35 const clothTierSelect = document.getElementById("craft-cloth-tier");
36 const dyePickBtn = document.getElementById("craft-dye-pick");
37 const dyeClearBtn = document.getElementById("craft-dye-clear");
38 const dyePreview = document.getElementById("craft-dye-preview");
31 39 const outputImg = document.getElementById("craft-output-img");
32 40 const outputName = document.getElementById("craft-output-name");
33 41 const inputsList = document.getElementById("craft-inputs");
@@ -35,11 +43,16 @@ export function initCrafting ({
35 43 const progressWrap = document.getElementById("craft-progress");
36 44 const progressFill = document.getElementById("craft-progress-fill");
37 45 const craftButton = document.getElementById("craft-button");
46 const dyeBackdrop = document.getElementById("dye-picker-backdrop");
47 const dyePanel = document.getElementById("dye-picker-panel");
48 const dyeGrid = document.getElementById("dye-picker-grid");
38 49
39 50 let open = false;
40 51 let stationId = null;
41 52 let recipes = [];
42 53 let selectedRecipeId = null;
54 let clothTier = ClothTier.cotton;
55 let dyeSlotIndex = null;
43 56 let crafting = false;
44 57 let craftTimer = null;
45 58 let craftAnimFrame = null;
@@ -48,6 +61,24 @@ export function initCrafting ({
48 61 document.getElementById("craft-close").addEventListener("click", () => close());
49 62 backdrop.addEventListener("click", () => close());
50 63 craftButton.addEventListener("click", () => startCraft());
64 clothTierSelect?.addEventListener("change", () =>
65 {
66 clothTier = clothTierSelect.value || ClothTier.cotton;
67 renderDetail();
68 });
69 dyePickBtn?.addEventListener("click", () => openDyePicker());
70 dyeClearBtn?.addEventListener("click", () =>
71 {
72 dyeSlotIndex = null;
73 renderDetail();
74 });
75 document.getElementById("dye-picker-close")?.addEventListener("click", () => closeDyePicker());
76 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
77
78 function isTailorStation ()
79 {
80 return stationId === CraftingStationId.tailorBench;
81 }
51 82
52 83 function selectedRecipe ()
53 84 {
@@ -60,6 +91,23 @@ export function initCrafting ({
60 91 return getSkillLevel?.(def?.skillId) ?? 1;
61 92 }
62 93
94 function activeRecipe ()
95 {
96 const base = selectedRecipe();
97 if (!base)
98 { return null; }
99 if (!base.tailorTemplate)
100 { return base; }
101 const slots = getInventorySlots?.() ?? [];
102 const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
103 const resolved = resolveTailorCraft({
104 templateId: base.tailorTemplate,
105 clothTier,
106 dyeStack
107 });
108 return resolved.ok ? resolved.recipe : base;
109 }
110
63 111 function refresh ()
64 112 {
65 113 if (!open)
@@ -68,6 +116,21 @@ export function initCrafting ({
68 116 renderDetail();
69 117 }
70 118
119 function fillClothTier ()
120 {
121 if (!clothTierSelect)
122 { return; }
123 clothTierSelect.replaceChildren();
124 for (const tier of CLOTH_TIER_ORDER)
125 {
126 const option = document.createElement("option");
127 option.value = tier;
128 option.textContent = CLOTH_DISPLAY_NAME[tier] ?? tier;
129 clothTierSelect.append(option);
130 }
131 clothTierSelect.value = clothTier;
132 }
133
71 134 function renderRecipeGrid ()
72 135 {
73 136 recipeGrid.replaceChildren();
@@ -93,7 +156,9 @@ export function initCrafting ({
93 156
94 157 const label = document.createElement("span");
95 158 label.className = "craft-recipe-name";
96 label.textContent = def?.displayName ?? "Item";
159 label.textContent = recipe.tailorTemplate
160 ? (def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment")
161 : (def?.displayName ?? "Item");
97 162
98 163 cell.append(img, label);
99 164 cell.addEventListener("click", () =>
@@ -109,7 +174,7 @@ export function initCrafting ({
109 174
110 175 function renderDetail ()
111 176 {
112 const recipe = selectedRecipe();
177 const recipe = activeRecipe();
113 178 if (!recipe)
114 179 {
115 180 detailEmpty.hidden = false;
@@ -119,9 +184,13 @@ export function initCrafting ({
119 184 detailEmpty.hidden = true;
120 185 detailBody.hidden = false;
121 186
187 if (tailorControls)
188 { tailorControls.hidden = !isTailorStation(); }
189
122 190 const outputStack = {
123 191 itemId: recipe.output.itemId,
124 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
192 quantity: Math.max(1, recipe.output.quantity | 0 || 1),
193 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
125 194 };
126 195 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
127 196 outputImg.alt = itemDisplayName(outputStack);
@@ -134,6 +203,32 @@ export function initCrafting ({
134 203 {
135 204 inputsList.append(renderInputRow(input, slots));
136 205 }
206 if (recipe.consumeDye)
207 {
208 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
209 const row = document.createElement("li");
210 row.className = "craft-input-row";
211 row.textContent = dye
212 ? `Dye — 1 use (${dye.instance?.fillLevel ?? "?"}/5)`
213 : "Dye — none selected";
214 inputsList.append(row);
215 }
216
217 if (dyePreview && dyeClearBtn)
218 {
219 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
220 if (dye?.itemId === ItemId.dye)
221 {
222 dyePreview.hidden = false;
223 dyeClearBtn.hidden = false;
224 applyItemIcon(dyePreview, dye, itemAssetPathForStack(dye));
225 }
226 else
227 {
228 dyePreview.hidden = true;
229 dyeClearBtn.hidden = true;
230 }
231 }
137 232
138 233 updateCraftState(slots, recipe);
139 234 }
@@ -191,9 +286,53 @@ export function initCrafting ({
191 286 craftButton.disabled = true;
192 287 }
193 288
289 function openDyePicker ()
290 {
291 const slots = getInventorySlots?.() ?? [];
292 dyeGrid.replaceChildren();
293 let found = false;
294 slots.forEach((stack, index) =>
295 {
296 if (!stack || stack.itemId !== ItemId.dye)
297 { return; }
298 found = true;
299 const cell = document.createElement("button");
300 cell.type = "button";
301 cell.className = "craft-recipe-cell";
302 const img = document.createElement("img");
303 applyItemIcon(img, stack, itemAssetPathForStack(stack));
304 const label = document.createElement("span");
305 label.className = "craft-recipe-name";
306 label.textContent = itemDisplayName(stack);
307 cell.append(img, label);
308 cell.addEventListener("click", () =>
309 {
310 dyeSlotIndex = index;
311 closeDyePicker();
312 renderDetail();
313 });
314 dyeGrid.append(cell);
315 });
316 if (!found)
317 {
318 const empty = document.createElement("p");
319 empty.className = "hint";
320 empty.textContent = "No dyes in your inventory.";
321 dyeGrid.append(empty);
322 }
323 dyePanel.hidden = false;
324 dyeBackdrop.hidden = false;
325 }
326
327 function closeDyePicker ()
328 {
329 dyePanel.hidden = true;
330 dyeBackdrop.hidden = true;
331 }
332
194 333 function startCraft ()
195 334 {
196 const recipe = selectedRecipe();
335 const recipe = activeRecipe();
197 336 if (!recipe || crafting)
198 337 { return; }
199 338 const slots = getInventorySlots?.() ?? [];
@@ -209,11 +348,17 @@ export function initCrafting ({
209 348 statusEl.textContent = "Crafting…";
210 349 craftStartedAt = performance.now();
211 350 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
212 socket.send({
351 const payload = {
213 352 type: MessageType.startCraft,
214 353 stationId,
215 recipeId: recipe.recipeId
216 });
354 recipeId: selectedRecipeId
355 };
356 if (isTailorStation())
357 {
358 payload.clothTier = clothTier;
359 payload.dyeSlotIndex = dyeSlotIndex;
360 }
361 socket.send(payload);
217 362 animateProgress(durationMs);
218 363 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
219 364 }
@@ -268,6 +413,9 @@ export function initCrafting ({
268 413 stationId = nextStationId;
269 414 recipes = recipesForStation(nextStationId);
270 415 selectedRecipeId = recipes[0]?.recipeId ?? null;
416 clothTier = ClothTier.cotton;
417 dyeSlotIndex = null;
418 fillClothTier();
271 419 stationName.textContent = def.displayName;
272 420 open = true;
273 421 panel.hidden = false;
@@ -286,10 +434,12 @@ export function initCrafting ({
286 434 socket.send({ type: MessageType.cancelCraft });
287 435 stopCraftAnimation();
288 436 }
437 closeDyePicker();
289 438 open = false;
290 439 stationId = null;
291 440 recipes = [];
292 441 selectedRecipeId = null;
442 dyeSlotIndex = null;
293 443 panel.hidden = true;
294 444 backdrop.hidden = true;
295 445 detailEmpty.hidden = false;
@@ -2,9 +2,10 @@ import {
2 itemDefinition,
2 itemDefinition,
3 itemDisplayName,
3 itemDisplayName,
4 itemAssetPathForStack,
4 itemAssetPathForStack,
5 formatQuantity
5 formatQuantity,
6 ItemId
6} from "/shared/definitions/items.js";
7} from "/shared/definitions/items.js";
7import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";
8import { craftingStationDefinition, CraftingStationId } from "/shared/definitions/craftingStations.js";
8import {
9import {
9 CRAFT_DURATION_MS,
10 CRAFT_DURATION_MS,
10 canStartCraft,
11 canStartCraft,
@@ -12,6 +13,8 @@ import {
12 hasRecipeInputs,
13 hasRecipeInputs,
13 recipesForStation
14 recipesForStation
14} from "/shared/crafting/recipes.js";
15} from "/shared/crafting/recipes.js";
16import { resolveTailorCraft } from "/shared/crafting/tailor.js";
17import { CLOTH_TIER_ORDER, CLOTH_DISPLAY_NAME, ClothTier } from "/shared/definitions/materialTiers.js";
15import { craftDurationMs } from "/shared/definitions/gathering.js";
18import { craftDurationMs } from "/shared/definitions/gathering.js";
16import { applyItemIcon } from "../render/potionIcon.js";
19import { applyItemIcon } from "../render/potionIcon.js";
17
20
@@ -28,6 +31,11 @@ export function initCrafting ({
28 const recipeGrid = document.getElementById("craft-recipe-grid");
31 const recipeGrid = document.getElementById("craft-recipe-grid");
29 const detailEmpty = document.getElementById("craft-detail-empty");
32 const detailEmpty = document.getElementById("craft-detail-empty");
30 const detailBody = document.getElementById("craft-detail-body");
33 const detailBody = document.getElementById("craft-detail-body");
34 const tailorControls = document.getElementById("craft-tailor-controls");
35 const clothTierSelect = document.getElementById("craft-cloth-tier");
36 const dyePickBtn = document.getElementById("craft-dye-pick");
37 const dyeClearBtn = document.getElementById("craft-dye-clear");
38 const dyePreview = document.getElementById("craft-dye-preview");
31 const outputImg = document.getElementById("craft-output-img");
39 const outputImg = document.getElementById("craft-output-img");
32 const outputName = document.getElementById("craft-output-name");
40 const outputName = document.getElementById("craft-output-name");
33 const inputsList = document.getElementById("craft-inputs");
41 const inputsList = document.getElementById("craft-inputs");
@@ -35,11 +43,16 @@ export function initCrafting ({
35 const progressWrap = document.getElementById("craft-progress");
43 const progressWrap = document.getElementById("craft-progress");
36 const progressFill = document.getElementById("craft-progress-fill");
44 const progressFill = document.getElementById("craft-progress-fill");
37 const craftButton = document.getElementById("craft-button");
45 const craftButton = document.getElementById("craft-button");
46 const dyeBackdrop = document.getElementById("dye-picker-backdrop");
47 const dyePanel = document.getElementById("dye-picker-panel");
48 const dyeGrid = document.getElementById("dye-picker-grid");
38
49
39 let open = false;
50 let open = false;
40 let stationId = null;
51 let stationId = null;
41 let recipes = [];
52 let recipes = [];
42 let selectedRecipeId = null;
53 let selectedRecipeId = null;
54 let clothTier = ClothTier.cotton;
55 let dyeSlotIndex = null;
43 let crafting = false;
56 let crafting = false;
44 let craftTimer = null;
57 let craftTimer = null;
45 let craftAnimFrame = null;
58 let craftAnimFrame = null;
@@ -48,6 +61,24 @@ export function initCrafting ({
48 document.getElementById("craft-close").addEventListener("click", () => close());
61 document.getElementById("craft-close").addEventListener("click", () => close());
49 backdrop.addEventListener("click", () => close());
62 backdrop.addEventListener("click", () => close());
50 craftButton.addEventListener("click", () => startCraft());
63 craftButton.addEventListener("click", () => startCraft());
64 clothTierSelect?.addEventListener("change", () =>
65 {
66 clothTier = clothTierSelect.value || ClothTier.cotton;
67 renderDetail();
68 });
69 dyePickBtn?.addEventListener("click", () => openDyePicker());
70 dyeClearBtn?.addEventListener("click", () =>
71 {
72 dyeSlotIndex = null;
73 renderDetail();
74 });
75 document.getElementById("dye-picker-close")?.addEventListener("click", () => closeDyePicker());
76 dyeBackdrop?.addEventListener("click", () => closeDyePicker());
77
78 function isTailorStation ()
79 {
80 return stationId === CraftingStationId.tailorBench;
81 }
51
82
52 function selectedRecipe ()
83 function selectedRecipe ()
53 {
84 {
@@ -60,6 +91,23 @@ export function initCrafting ({
60 return getSkillLevel?.(def?.skillId) ?? 1;
91 return getSkillLevel?.(def?.skillId) ?? 1;
61 }
92 }
62
93
94 function activeRecipe ()
95 {
96 const base = selectedRecipe();
97 if (!base)
98 { return null; }
99 if (!base.tailorTemplate)
100 { return base; }
101 const slots = getInventorySlots?.() ?? [];
102 const dyeStack = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
103 const resolved = resolveTailorCraft({
104 templateId: base.tailorTemplate,
105 clothTier,
106 dyeStack
107 });
108 return resolved.ok ? resolved.recipe : base;
109 }
110
63 function refresh ()
111 function refresh ()
64 {
112 {
65 if (!open)
113 if (!open)
@@ -68,6 +116,21 @@ export function initCrafting ({
68 renderDetail();
116 renderDetail();
69 }
117 }
70
118
119 function fillClothTier ()
120 {
121 if (!clothTierSelect)
122 { return; }
123 clothTierSelect.replaceChildren();
124 for (const tier of CLOTH_TIER_ORDER)
125 {
126 const option = document.createElement("option");
127 option.value = tier;
128 option.textContent = CLOTH_DISPLAY_NAME[tier] ?? tier;
129 clothTierSelect.append(option);
130 }
131 clothTierSelect.value = clothTier;
132 }
133
71 function renderRecipeGrid ()
134 function renderRecipeGrid ()
72 {
135 {
73 recipeGrid.replaceChildren();
136 recipeGrid.replaceChildren();
@@ -93,7 +156,9 @@ export function initCrafting ({
93
156
94 const label = document.createElement("span");
157 const label = document.createElement("span");
95 label.className = "craft-recipe-name";
158 label.className = "craft-recipe-name";
96 label.textContent = def?.displayName ?? "Item";
159 label.textContent = recipe.tailorTemplate
160 ? (def?.displayName?.replace(/^Cotton\s+/i, "") ?? "Garment")
161 : (def?.displayName ?? "Item");
97
162
98 cell.append(img, label);
163 cell.append(img, label);
99 cell.addEventListener("click", () =>
164 cell.addEventListener("click", () =>
@@ -109,7 +174,7 @@ export function initCrafting ({
109
174
110 function renderDetail ()
175 function renderDetail ()
111 {
176 {
112 const recipe = selectedRecipe();
177 const recipe = activeRecipe();
113 if (!recipe)
178 if (!recipe)
114 {
179 {
115 detailEmpty.hidden = false;
180 detailEmpty.hidden = false;
@@ -119,9 +184,13 @@ export function initCrafting ({
119 detailEmpty.hidden = true;
184 detailEmpty.hidden = true;
120 detailBody.hidden = false;
185 detailBody.hidden = false;
121
186
187 if (tailorControls)
188 { tailorControls.hidden = !isTailorStation(); }
189
122 const outputStack = {
190 const outputStack = {
123 itemId: recipe.output.itemId,
191 itemId: recipe.output.itemId,
124 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
192 quantity: Math.max(1, recipe.output.quantity | 0 || 1),
193 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
125 };
194 };
126 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
195 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
127 outputImg.alt = itemDisplayName(outputStack);
196 outputImg.alt = itemDisplayName(outputStack);
@@ -134,6 +203,32 @@ export function initCrafting ({
134 {
203 {
135 inputsList.append(renderInputRow(input, slots));
204 inputsList.append(renderInputRow(input, slots));
136 }
205 }
206 if (recipe.consumeDye)
207 {
208 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
209 const row = document.createElement("li");
210 row.className = "craft-input-row";
211 row.textContent = dye
212 ? `Dye — 1 use (${dye.instance?.fillLevel ?? "?"}/5)`
213 : "Dye — none selected";
214 inputsList.append(row);
215 }
216
217 if (dyePreview && dyeClearBtn)
218 {
219 const dye = dyeSlotIndex != null ? slots[dyeSlotIndex] : null;
220 if (dye?.itemId === ItemId.dye)
221 {
222 dyePreview.hidden = false;
223 dyeClearBtn.hidden = false;
224 applyItemIcon(dyePreview, dye, itemAssetPathForStack(dye));
225 }
226 else
227 {
228 dyePreview.hidden = true;
229 dyeClearBtn.hidden = true;
230 }
231 }
137
232
138 updateCraftState(slots, recipe);
233 updateCraftState(slots, recipe);
139 }
234 }
@@ -191,9 +286,53 @@ export function initCrafting ({
191 craftButton.disabled = true;
286 craftButton.disabled = true;
192 }
287 }
193
288
289 function openDyePicker ()
290 {
291 const slots = getInventorySlots?.() ?? [];
292 dyeGrid.replaceChildren();
293 let found = false;
294 slots.forEach((stack, index) =>
295 {
296 if (!stack || stack.itemId !== ItemId.dye)
297 { return; }
298 found = true;
299 const cell = document.createElement("button");
300 cell.type = "button";
301 cell.className = "craft-recipe-cell";
302 const img = document.createElement("img");
303 applyItemIcon(img, stack, itemAssetPathForStack(stack));
304 const label = document.createElement("span");
305 label.className = "craft-recipe-name";
306 label.textContent = itemDisplayName(stack);
307 cell.append(img, label);
308 cell.addEventListener("click", () =>
309 {
310 dyeSlotIndex = index;
311 closeDyePicker();
312 renderDetail();
313 });
314 dyeGrid.append(cell);
315 });
316 if (!found)
317 {
318 const empty = document.createElement("p");
319 empty.className = "hint";
320 empty.textContent = "No dyes in your inventory.";
321 dyeGrid.append(empty);
322 }
323 dyePanel.hidden = false;
324 dyeBackdrop.hidden = false;
325 }
326
327 function closeDyePicker ()
328 {
329 dyePanel.hidden = true;
330 dyeBackdrop.hidden = true;
331 }
332
194 function startCraft ()
333 function startCraft ()
195 {
334 {
196 const recipe = selectedRecipe();
335 const recipe = activeRecipe();
197 if (!recipe || crafting)
336 if (!recipe || crafting)
198 { return; }
337 { return; }
199 const slots = getInventorySlots?.() ?? [];
338 const slots = getInventorySlots?.() ?? [];
@@ -209,11 +348,17 @@ export function initCrafting ({
209 statusEl.textContent = "Crafting…";
348 statusEl.textContent = "Crafting…";
210 craftStartedAt = performance.now();
349 craftStartedAt = performance.now();
211 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
350 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
212 socket.send({
351 const payload = {
213 type: MessageType.startCraft,
352 type: MessageType.startCraft,
214 stationId,
353 stationId,
215 recipeId: recipe.recipeId
354 recipeId: selectedRecipeId
216 });
355 };
356 if (isTailorStation())
357 {
358 payload.clothTier = clothTier;
359 payload.dyeSlotIndex = dyeSlotIndex;
360 }
361 socket.send(payload);
217 animateProgress(durationMs);
362 animateProgress(durationMs);
218 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
363 craftTimer = window.setTimeout(() => finishCraft(true), durationMs);
219 }
364 }
@@ -268,6 +413,9 @@ export function initCrafting ({
268 stationId = nextStationId;
413 stationId = nextStationId;
269 recipes = recipesForStation(nextStationId);
414 recipes = recipesForStation(nextStationId);
270 selectedRecipeId = recipes[0]?.recipeId ?? null;
415 selectedRecipeId = recipes[0]?.recipeId ?? null;
416 clothTier = ClothTier.cotton;
417 dyeSlotIndex = null;
418 fillClothTier();
271 stationName.textContent = def.displayName;
419 stationName.textContent = def.displayName;
272 open = true;
420 open = true;
273 panel.hidden = false;
421 panel.hidden = false;
@@ -286,10 +434,12 @@ export function initCrafting ({
286 socket.send({ type: MessageType.cancelCraft });
434 socket.send({ type: MessageType.cancelCraft });
287 stopCraftAnimation();
435 stopCraftAnimation();
288 }
436 }
437 closeDyePicker();
289 open = false;
438 open = false;
290 stationId = null;
439 stationId = null;
291 recipes = [];
440 recipes = [];
292 selectedRecipeId = null;
441 selectedRecipeId = null;
442 dyeSlotIndex = null;
293 panel.hidden = true;
443 panel.hidden = true;
294 backdrop.hidden = true;
444 backdrop.hidden = true;
295 detailEmpty.hidden = false;
445 detailEmpty.hidden = false;
client/src/play/main.js +85 −1
@@ -1,5 +1,5 @@
1 1 import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2 import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock } from "/shared/definitions/tiles.js";
2 import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
3 3 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4 4 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5 5 import { WorldView } from "../render/worldView.js";
@@ -246,6 +246,17 @@ function requestChop (tileX, tileY)
246 246 { approachAdjacentTile(tileX, tileY); }
247 247 }
248 248
249 function requestPick (tileX, tileY)
250 {
251 clearAllPendingActions();
252 pendingInteract = { kind: "pick", tileX, tileY };
253 const local = view?.entities.get(view.localEntityId);
254 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
255 { flushPendingInteract(); }
256 else
257 { approachAdjacentTile(tileX, tileY); }
258 }
259
249 260 function requestTalk (targetEntityId)
250 261 {
251 262 clearAllPendingActions();
@@ -336,6 +347,19 @@ function flushPendingInteract ()
336 347 return;
337 348 }
338 349
350 if (pendingInteract.kind === "pick")
351 {
352 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
353 { return; }
354 socket.send({
355 type: MessageType.pick,
356 tileX: pendingInteract.tileX,
357 tileY: pendingInteract.tileY
358 });
359 clearPendingInteract();
360 return;
361 }
362
339 363 if (pendingInteract.kind === "talk")
340 364 {
341 365 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -453,10 +477,18 @@ function handleLeftClick (mouseX, mouseY)
453 477 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
454 478 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
455 479 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
480 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
481 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
482 else if (isLoomTile(view, tile.tileX, tile.tileY))
483 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
484 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
485 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
456 486 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
457 487 { requestMine(tile.tileX, tile.tileY); }
458 488 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
459 489 { requestChop(tile.tileX, tile.tileY); }
490 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
491 { requestPick(tile.tileX, tile.tileY); }
460 492 else
461 493 {
462 494 clearAllPendingActions();
@@ -596,6 +628,30 @@ function handleRightClick (event, mouseX, mouseY)
596 628 });
597 629 }
598 630
631 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
632 {
633 items.push({
634 label: "Spin",
635 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
636 });
637 }
638
639 if (isLoomTile(view, tile.tileX, tile.tileY))
640 {
641 items.push({
642 label: "Weave",
643 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
644 });
645 }
646
647 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
648 {
649 items.push({
650 label: "Tailor",
651 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
652 });
653 }
654
599 655 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
600 656 {
601 657 items.push({
@@ -612,6 +668,14 @@ function handleRightClick (event, mouseX, mouseY)
612 668 });
613 669 }
614 670
671 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
672 {
673 items.push({
674 label: "Pick",
675 onSelect: () => requestPick(tile.tileX, tile.tileY)
676 });
677 }
678
615 679 contextMenu.show(event.clientX, event.clientY, items);
616 680 }
617 681
@@ -1112,6 +1176,21 @@ function isCraftingBenchTile (view, tileX, tileY)
1112 1176 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1113 1177 }
1114 1178
1179 function isSpinningWheelTile (view, tileX, tileY)
1180 {
1181 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
1182 }
1183
1184 function isLoomTile (view, tileX, tileY)
1185 {
1186 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
1187 }
1188
1189 function isTailorBenchTile (view, tileX, tileY)
1190 {
1191 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
1192 }
1193
1115 1194 function isOreBoulderTile (view, tileX, tileY)
1116 1195 {
1117 1196 const block = blockAt(view, tileX, tileY);
@@ -1123,6 +1202,11 @@ function isChopableTreeTile (view, tileX, tileY)
1123 1202 return isChopableTreeBlock(blockAt(view, tileX, tileY));
1124 1203 }
1125 1204
1205 function isPickablePlantTile (view, tileX, tileY)
1206 {
1207 return isPickablePlantBlock(blockAt(view, tileX, tileY));
1208 }
1209
1126 1210 function hideWorldTooltip ()
1127 1211 {
1128 1212 if (worldTooltip)
@@ -1,5 +1,5 @@
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock } from "/shared/definitions/tiles.js";
2import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5import { WorldView } from "../render/worldView.js";
5import { WorldView } from "../render/worldView.js";
@@ -246,6 +246,17 @@ function requestChop (tileX, tileY)
246 { approachAdjacentTile(tileX, tileY); }
246 { approachAdjacentTile(tileX, tileY); }
247}
247}
248
248
249function requestPick (tileX, tileY)
250{
251 clearAllPendingActions();
252 pendingInteract = { kind: "pick", tileX, tileY };
253 const local = view?.entities.get(view.localEntityId);
254 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
255 { flushPendingInteract(); }
256 else
257 { approachAdjacentTile(tileX, tileY); }
258}
259
249function requestTalk (targetEntityId)
260function requestTalk (targetEntityId)
250{
261{
251 clearAllPendingActions();
262 clearAllPendingActions();
@@ -336,6 +347,19 @@ function flushPendingInteract ()
336 return;
347 return;
337 }
348 }
338
349
350 if (pendingInteract.kind === "pick")
351 {
352 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
353 { return; }
354 socket.send({
355 type: MessageType.pick,
356 tileX: pendingInteract.tileX,
357 tileY: pendingInteract.tileY
358 });
359 clearPendingInteract();
360 return;
361 }
362
339 if (pendingInteract.kind === "talk")
363 if (pendingInteract.kind === "talk")
340 {
364 {
341 const target = view.entities.get(pendingInteract.targetEntityId);
365 const target = view.entities.get(pendingInteract.targetEntityId);
@@ -453,10 +477,18 @@ function handleLeftClick (mouseX, mouseY)
453 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
477 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
454 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
478 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
455 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
479 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
480 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
481 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
482 else if (isLoomTile(view, tile.tileX, tile.tileY))
483 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
484 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
485 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
456 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
486 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
457 { requestMine(tile.tileX, tile.tileY); }
487 { requestMine(tile.tileX, tile.tileY); }
458 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
488 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
459 { requestChop(tile.tileX, tile.tileY); }
489 { requestChop(tile.tileX, tile.tileY); }
490 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
491 { requestPick(tile.tileX, tile.tileY); }
460 else
492 else
461 {
493 {
462 clearAllPendingActions();
494 clearAllPendingActions();
@@ -596,6 +628,30 @@ function handleRightClick (event, mouseX, mouseY)
596 });
628 });
597 }
629 }
598
630
631 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
632 {
633 items.push({
634 label: "Spin",
635 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
636 });
637 }
638
639 if (isLoomTile(view, tile.tileX, tile.tileY))
640 {
641 items.push({
642 label: "Weave",
643 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
644 });
645 }
646
647 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
648 {
649 items.push({
650 label: "Tailor",
651 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
652 });
653 }
654
599 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
655 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
600 {
656 {
601 items.push({
657 items.push({
@@ -612,6 +668,14 @@ function handleRightClick (event, mouseX, mouseY)
612 });
668 });
613 }
669 }
614
670
671 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
672 {
673 items.push({
674 label: "Pick",
675 onSelect: () => requestPick(tile.tileX, tile.tileY)
676 });
677 }
678
615 contextMenu.show(event.clientX, event.clientY, items);
679 contextMenu.show(event.clientX, event.clientY, items);
616}
680}
617
681
@@ -1112,6 +1176,21 @@ function isCraftingBenchTile (view, tileX, tileY)
1112 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1176 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
1113}
1177}
1114
1178
1179function isSpinningWheelTile (view, tileX, tileY)
1180{
1181 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
1182}
1183
1184function isLoomTile (view, tileX, tileY)
1185{
1186 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
1187}
1188
1189function isTailorBenchTile (view, tileX, tileY)
1190{
1191 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
1192}
1193
1115function isOreBoulderTile (view, tileX, tileY)
1194function isOreBoulderTile (view, tileX, tileY)
1116{
1195{
1117 const block = blockAt(view, tileX, tileY);
1196 const block = blockAt(view, tileX, tileY);
@@ -1123,6 +1202,11 @@ function isChopableTreeTile (view, tileX, tileY)
1123 return isChopableTreeBlock(blockAt(view, tileX, tileY));
1202 return isChopableTreeBlock(blockAt(view, tileX, tileY));
1124}
1203}
1125
1204
1205function isPickablePlantTile (view, tileX, tileY)
1206{
1207 return isPickablePlantBlock(blockAt(view, tileX, tileY));
1208}
1209
1126function hideWorldTooltip ()
1210function hideWorldTooltip ()
1127{
1211{
1128 if (worldTooltip)
1212 if (worldTooltip)
client/src/render/potionIcon.js +2 −1
@@ -99,7 +99,8 @@ export async function tintedItemIconDataUrl (assetPath, tint)
99 99
100 100 export function isPotionStack (stack)
101 101 {
102 return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
102 return (stack?.itemId === ItemId.potion && stack.instance?.kind === "potion")
103 || (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");
103 104 }
104 105
105 106 /** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
@@ -99,7 +99,8 @@ export async function tintedItemIconDataUrl (assetPath, tint)
99
99
100export function isPotionStack (stack)
100export function isPotionStack (stack)
101{
101{
102 return stack?.itemId === ItemId.potion && stack.instance?.kind === "potion";
102 return (stack?.itemId === ItemId.potion && stack.instance?.kind === "potion")
103 || (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye");
103}
104}
104
105
105/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
106/** Set img.src to tinted icon when the stack/def has a tint; else fallback path. */
docs/FEATURES.md +24 −13
@@ -228,23 +228,34 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228 228 ## Equipment tiers and worn stat bonuses
229 229
230 230 **Status:** partial
231 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting.
232 **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
233 **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.
231 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
232 **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
233 **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
234 234 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
235 235
236 236 ## Gathering, crafting, and production skills
237 237
238 **Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting live)
239 **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
240 **Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
238 **Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism live)
239 **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **plant clippers** (bronze clippers: anvil 1 bronze bar, or NPC shop); success yields a flower with a random dye colour and stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
240 **Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
241
242 ## Cloth, dyes, and tailoring
243
244 **Status:** partial (cotton loop + flower dyes + sweater live; higher cloth sources TBD)
245 **Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (sweater today; shirt/robe later) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (sweater = 3 yarn). Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
246 **TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
247 **Later design (document only for now):**
248 - **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
249 - **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
250 - **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
251 **Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
241 252
242 253 ## Crafting stations
243 254
244 **Status:** partial (furnace, anvil, woodworking bench, crafting bench live; UI shell for others)
245 **Spec:** Furnace / anvil / woodworking-bench / crafting-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle).
246 **TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated station sprites where still placeholder.
247 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench` / `craftingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
255 **Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
256 **Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring.
257 **TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
258 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
248 259
249 260 ## Stamina and running
250 261
@@ -254,9 +265,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
254 265
255 266 ## Alchemy / cauldron
256 267
257 **Status:** partial (scaffolding)
258 **Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs at a **Cauldron** block. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules.
259 **Code:** `shared/definitions/alchemy.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
268 **Status:** partial (potion scaffolding + flower→dye + dye mixing live)
269 **Spec:** **Herbalism** gathers flowers (clippers) and cotton (no tool). **Alchemy** uses herbs at a **Cauldron** block for potions; the same cauldron bottles dyes from flowers and mixes two dye colours (paint-style). Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules. **Glass bottle** (`ItemId.glassBottle`, sprite `potion-0`) is `npcShopAllowed` for vendor catalogs.
270 **Code:** `shared/definitions/alchemy.js`, `shared/definitions/dyes.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
260 271
261 272 ## Inventory, items, equipment, ground drops
262 273
@@ -228,23 +228,34 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
228## Equipment tiers and worn stat bonuses
228## Equipment tiers and worn stat bonuses
229
229
230**Status:** partial
230**Status:** partial
231**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting.
231**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
232**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
232**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
233**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes.
233**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
234**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
234**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
235
235
236## Gathering, crafting, and production skills
236## Gathering, crafting, and production skills
237
237
238**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting live)
238**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism live)
239**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
239**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **plant clippers** (bronze clippers: anvil 1 bronze bar, or NPC shop); success yields a flower with a random dye colour and stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
240**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
240**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
241
242## Cloth, dyes, and tailoring
243
244**Status:** partial (cotton loop + flower dyes + sweater live; higher cloth sources TBD)
245**Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (sweater today; shirt/robe later) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (sweater = 3 yarn). Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
246**TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
247**Later design (document only for now):**
248- **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
249- **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
250- **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
251**Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
241
252
242## Crafting stations
253## Crafting stations
243
254
244**Status:** partial (furnace, anvil, woodworking bench, crafting bench live; UI shell for others)
255**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
245**Spec:** Furnace / anvil / woodworking-bench / crafting-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle).
256**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring.
246**TODO:** oven/campfire burn, spinning wheel once sheep exist; dedicated station sprites where still placeholder.
257**TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
247**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js` (`BlockType.furnace` / `anvil` / `woodworkingBench` / `craftingBench`), `server/src/crafting/service.js`, `client/src/play/crafting.js`
258**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
248
259
249## Stamina and running
260## Stamina and running
250
261
@@ -254,9 +265,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
254
265
255## Alchemy / cauldron
266## Alchemy / cauldron
256
267
257**Status:** partial (scaffolding)
268**Status:** partial (potion scaffolding + flower→dye + dye mixing live)
258**Spec:** **Herbalism** gathers herbs from herb nodes with **plant clippers** (tiers like mining/woodcutting; gather loop TBD). **Alchemy** uses herbs at a **Cauldron** block. Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules.
269**Spec:** **Herbalism** gathers flowers (clippers) and cotton (no tool). **Alchemy** uses herbs at a **Cauldron** block for potions; the same cauldron bottles dyes from flowers and mixes two dye colours (paint-style). Nonstandard brew UI (slots, stir/heat/cool, bottle, clear, save recipe). See prior alchemy notes for recipe/unstable potion rules. **Glass bottle** (`ItemId.glassBottle`, sprite `potion-0`) is `npcShopAllowed` for vendor catalogs.
259**Code:** `shared/definitions/alchemy.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
270**Code:** `shared/definitions/alchemy.js`, `shared/definitions/dyes.js`, `server/src/alchemy/service.js`, `client/src/play/alchemy.js`, tests in `server/tests/alchemy.test.js`
260
271
261## Inventory, items, equipment, ground drops
272## Inventory, items, equipment, ground drops
262
273
server/src/alchemy/service.js +196 −7
@@ -8,6 +8,11 @@ import {
8 8 recipePaperBody,
9 9 resolvedAlchemyPotions
10 10 } from "../../../shared/alchemy/recipes.js";
11 import {
12 dyeItemInstance,
13 DEFAULT_DYE_FILL,
14 mixDyeBatches
15 } from "../../../shared/definitions/dyes.js";
11 16 import { bagView } from "../items/bags.js";
12 17 import {
13 18 countItemInSlots,
@@ -189,13 +194,47 @@ function setSlot (world, sessionId, command)
189 194 const def = itemDefinition(itemId);
190 195 if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)
191 196 { throw userError("That cannot go in a cauldron slot."); }
197 if (itemId === ItemId.dye || itemId === ItemId.flower)
198 {
199 // Allowed — instances are captured on insert.
200 }
201 else if (def.dye || def.flower)
202 { /* ok */ }
192 203
193 204 const inventory = ensureInventory(world, handle);
194 const have = countItemInSlots(inventory.slots, itemId);
195 if (have < quantity)
196 { throw userError("Not enough of that item in your inventory."); }
205 let instance = null;
206 if (itemId === ItemId.flower || itemId === ItemId.dye)
207 {
208 const wanted = command.instance ? structuredClone(command.instance) : null;
209 if (wanted)
210 { instance = wanted; }
211 else
212 {
213 for (const slot of inventory.slots)
214 {
215 if (slot?.itemId === itemId && slot.instance)
216 {
217 instance = structuredClone(slot.instance);
218 break;
219 }
220 }
221 }
222 if (!instance && itemId === ItemId.flower)
223 { throw userError("That flower has no colour."); }
224 if (!instance && itemId === ItemId.dye)
225 { throw userError("That dye has no colour."); }
226 const have = countMatchingInstance(inventory.slots, itemId, instance);
227 if (have < quantity)
228 { throw userError("Not enough of that item in your inventory."); }
229 }
230 else
231 {
232 const have = countItemInSlots(inventory.slots, itemId);
233 if (have < quantity)
234 { throw userError("Not enough of that item in your inventory."); }
235 }
197 236
198 session.slots[slotIndex] = { itemId, quantity };
237 session.slots[slotIndex] = { itemId, quantity, instance };
199 238 return {
200 239 events: [],
201 240 private: bagView(world.ecs, handle),
@@ -218,6 +257,7 @@ function insertFromSlot (world, sessionId, command)
218 257 const pulled = takeMatchingFromSlots(inventory.slots, {
219 258 itemId: reserved.itemId,
220 259 quantity: reserved.quantity,
260 instance: reserved.instance ?? null,
221 261 compact: false
222 262 });
223 263 if (!pulled.ok)
@@ -225,11 +265,21 @@ function insertFromSlot (world, sessionId, command)
225 265 inventory.slots = pulled.slots;
226 266 session.slots[slotIndex] = null;
227 267
228 const existing = session.brew.find((row) => row.itemId === reserved.itemId);
268 const brewRow = {
269 itemId: reserved.itemId,
270 quantity: reserved.quantity,
271 instance: reserved.instance
272 ? structuredClone(reserved.instance)
273 : (pulled.taken?.instance ? structuredClone(pulled.taken.instance) : null)
274 };
275
276 const existing = session.brew.find((row) =>
277 row.itemId === brewRow.itemId
278 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
229 279 if (existing)
230 { existing.quantity += reserved.quantity; }
280 { existing.quantity += brewRow.quantity; }
231 281 else
232 { session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); }
282 { session.brew.push(brewRow); }
233 283
234 284 session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
235 285 session.lastSuccessRecipe = null;
@@ -269,6 +319,14 @@ function bottle (world, sessionId, command)
269 319 { throw userError("The cauldron is empty."); }
270 320
271 321 const inventory = ensureInventory(world, handle);
322 const dyePath = evaluateDyeBrew(session.brew);
323 if (dyePath)
324 {
325 if (!dyePath.ok)
326 { throw userError(dyePath.reason); }
327 return bottleDyeResult(world, handle, session, inventory, dyePath);
328 }
329
272 330 const skills = world.ecs.get(handle, Component.skills) ?? {};
273 331
274 332 const evaluation = evaluateAlchemyBottle({
@@ -336,6 +394,122 @@ function bottle (world, sessionId, command)
336 394 };
337 395 }
338 396
397 /**
398 * @returns {null | { ok: false, reason: string } | { ok: true, mode: "flower"|"mix", ... }}
399 */
400 function evaluateDyeBrew (brew)
401 {
402 const rows = brew ?? [];
403 if (!rows.length)
404 { return null; }
405 const hasFlower = rows.some((row) => row.itemId === ItemId.flower);
406 const hasDye = rows.some((row) => row.itemId === ItemId.dye);
407 const hasOther = rows.some((row) => row.itemId !== ItemId.flower && row.itemId !== ItemId.dye);
408 if (!hasFlower && !hasDye)
409 { return null; }
410 if (hasOther)
411 { return { ok: false, reason: "Do not mix dyes or flowers with alchemy ingredients." }; }
412 if (hasFlower && hasDye)
413 { return { ok: false, reason: "Cannot mix flowers and dyes together." }; }
414
415 if (hasFlower)
416 {
417 const colors = new Set(rows.map((row) => row.instance?.colorId).filter(Boolean));
418 if (colors.size === 0)
419 { return { ok: false, reason: "Those flowers have no colour." }; }
420 if (colors.size > 1)
421 { return { ok: false, reason: "Use flowers of a single colour for dye." }; }
422 const sample = rows.find((row) => row.instance?.color);
423 const quantity = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
424 return {
425 ok: true,
426 mode: "flower",
427 quantity: Math.max(1, quantity),
428 instance: dyeItemInstance(sample.instance.color, DEFAULT_DYE_FILL, sample.instance.colorId)
429 };
430 }
431
432 const mixed = mixDyeBatches(rows);
433 if (!mixed.ok)
434 { return { ok: false, reason: mixed.reason }; }
435 return { ok: true, mode: "mix", ...mixed };
436 }
437
438 function bottleDyeResult (world, handle, session, inventory, dyePath)
439 {
440 const outputs = dyePath.mode === "flower"
441 ? Array.from({ length: dyePath.quantity }, () => ({
442 quantity: 1,
443 instance: dyePath.instance
444 }))
445 : dyePath.outputs;
446
447 // Flowers need empty glass bottles. Dye remixes reuse the bottles already
448 // consumed into the brew; only overflow bottles need extra glass.
449 const bottleNeed = dyePath.mode === "flower"
450 ? outputs.length
451 : Math.max(0, dyePath.extraBottles | 0);
452 if (bottleNeed > 0)
453 {
454 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
455 if (bottles < bottleNeed)
456 {
457 throw userError(
458 `You need ${bottleNeed} glass bottle${bottleNeed === 1 ? "" : "s"}.`
459 );
460 }
461 const takeBottles = takeMatchingFromSlots(inventory.slots, {
462 itemId: ItemId.glassBottle,
463 quantity: bottleNeed,
464 compact: false
465 });
466 if (!takeBottles.ok)
467 { throw userError("You need glass bottles to bottle the dye."); }
468 inventory.slots = takeBottles.slots;
469 }
470
471 const dyeDef = itemDefinition(ItemId.dye);
472 let slots = inventory.slots;
473 for (const out of outputs)
474 {
475 const inserted = insertStack(slots, {
476 itemId: ItemId.dye,
477 quantity: out.quantity,
478 instance: out.instance
479 }, dyeDef);
480 if (!inserted.ok)
481 {
482 throw userError("Not enough inventory space for dye.");
483 }
484 slots = inserted.slots;
485 }
486 inventory.slots = slots;
487 session.lastSuccessRecipe = null;
488 clearBrew(session);
489
490 const sample = outputs[0]?.instance;
491 return {
492 events: [],
493 private: bagView(world.ecs, handle),
494 cauldron: true,
495 cauldronState: sessionView(session),
496 alchemyResult: {
497 success: true,
498 reason: null,
499 produced: outputs.length,
500 wanted: outputs.length,
501 lost: 0,
502 potion: {
503 potionKey: "dye",
504 displayName: "Dye",
505 unstable: false,
506 color: sample?.color ?? null,
507 fillLevel: sample?.fillLevel ?? DEFAULT_DYE_FILL
508 }
509 }
510 };
511 }
512
339 513 function clear (world, sessionId, command)
340 514 {
341 515 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -399,3 +573,18 @@ function saveRecipe (world, sessionId, command)
399 573 cauldronState: sessionView(session)
400 574 };
401 575 }
576
577 function countMatchingInstance (slots, itemId, instance)
578 {
579 let total = 0;
580 const key = JSON.stringify(instance ?? null);
581 for (const slot of slots ?? [])
582 {
583 if (!slot || slot.itemId !== itemId)
584 { continue; }
585 if (JSON.stringify(slot.instance ?? null) !== key)
586 { continue; }
587 total += stackQuantity(slot.quantity);
588 }
589 return total;
590 }
@@ -8,6 +8,11 @@ import {
8 recipePaperBody,
8 recipePaperBody,
9 resolvedAlchemyPotions
9 resolvedAlchemyPotions
10} from "../../../shared/alchemy/recipes.js";
10} from "../../../shared/alchemy/recipes.js";
11import {
12 dyeItemInstance,
13 DEFAULT_DYE_FILL,
14 mixDyeBatches
15} from "../../../shared/definitions/dyes.js";
11import { bagView } from "../items/bags.js";
16import { bagView } from "../items/bags.js";
12import {
17import {
13 countItemInSlots,
18 countItemInSlots,
@@ -189,13 +194,47 @@ function setSlot (world, sessionId, command)
189 const def = itemDefinition(itemId);
194 const def = itemDefinition(itemId);
190 if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)
195 if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)
191 { throw userError("That cannot go in a cauldron slot."); }
196 { throw userError("That cannot go in a cauldron slot."); }
197 if (itemId === ItemId.dye || itemId === ItemId.flower)
198 {
199 // Allowed — instances are captured on insert.
200 }
201 else if (def.dye || def.flower)
202 { /* ok */ }
192
203
193 const inventory = ensureInventory(world, handle);
204 const inventory = ensureInventory(world, handle);
194 const have = countItemInSlots(inventory.slots, itemId);
205 let instance = null;
195 if (have < quantity)
206 if (itemId === ItemId.flower || itemId === ItemId.dye)
196 { throw userError("Not enough of that item in your inventory."); }
207 {
208 const wanted = command.instance ? structuredClone(command.instance) : null;
209 if (wanted)
210 { instance = wanted; }
211 else
212 {
213 for (const slot of inventory.slots)
214 {
215 if (slot?.itemId === itemId && slot.instance)
216 {
217 instance = structuredClone(slot.instance);
218 break;
219 }
220 }
221 }
222 if (!instance && itemId === ItemId.flower)
223 { throw userError("That flower has no colour."); }
224 if (!instance && itemId === ItemId.dye)
225 { throw userError("That dye has no colour."); }
226 const have = countMatchingInstance(inventory.slots, itemId, instance);
227 if (have < quantity)
228 { throw userError("Not enough of that item in your inventory."); }
229 }
230 else
231 {
232 const have = countItemInSlots(inventory.slots, itemId);
233 if (have < quantity)
234 { throw userError("Not enough of that item in your inventory."); }
235 }
197
236
198 session.slots[slotIndex] = { itemId, quantity };
237 session.slots[slotIndex] = { itemId, quantity, instance };
199 return {
238 return {
200 events: [],
239 events: [],
201 private: bagView(world.ecs, handle),
240 private: bagView(world.ecs, handle),
@@ -218,6 +257,7 @@ function insertFromSlot (world, sessionId, command)
218 const pulled = takeMatchingFromSlots(inventory.slots, {
257 const pulled = takeMatchingFromSlots(inventory.slots, {
219 itemId: reserved.itemId,
258 itemId: reserved.itemId,
220 quantity: reserved.quantity,
259 quantity: reserved.quantity,
260 instance: reserved.instance ?? null,
221 compact: false
261 compact: false
222 });
262 });
223 if (!pulled.ok)
263 if (!pulled.ok)
@@ -225,11 +265,21 @@ function insertFromSlot (world, sessionId, command)
225 inventory.slots = pulled.slots;
265 inventory.slots = pulled.slots;
226 session.slots[slotIndex] = null;
266 session.slots[slotIndex] = null;
227
267
228 const existing = session.brew.find((row) => row.itemId === reserved.itemId);
268 const brewRow = {
269 itemId: reserved.itemId,
270 quantity: reserved.quantity,
271 instance: reserved.instance
272 ? structuredClone(reserved.instance)
273 : (pulled.taken?.instance ? structuredClone(pulled.taken.instance) : null)
274 };
275
276 const existing = session.brew.find((row) =>
277 row.itemId === brewRow.itemId
278 && JSON.stringify(row.instance ?? null) === JSON.stringify(brewRow.instance ?? null));
229 if (existing)
279 if (existing)
230 { existing.quantity += reserved.quantity; }
280 { existing.quantity += brewRow.quantity; }
231 else
281 else
232 { session.brew.push({ itemId: reserved.itemId, quantity: reserved.quantity }); }
282 { session.brew.push(brewRow); }
233
283
234 session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
284 session.steps.push({ kind: AlchemyStepKind.insert, itemId: reserved.itemId });
235 session.lastSuccessRecipe = null;
285 session.lastSuccessRecipe = null;
@@ -269,6 +319,14 @@ function bottle (world, sessionId, command)
269 { throw userError("The cauldron is empty."); }
319 { throw userError("The cauldron is empty."); }
270
320
271 const inventory = ensureInventory(world, handle);
321 const inventory = ensureInventory(world, handle);
322 const dyePath = evaluateDyeBrew(session.brew);
323 if (dyePath)
324 {
325 if (!dyePath.ok)
326 { throw userError(dyePath.reason); }
327 return bottleDyeResult(world, handle, session, inventory, dyePath);
328 }
329
272 const skills = world.ecs.get(handle, Component.skills) ?? {};
330 const skills = world.ecs.get(handle, Component.skills) ?? {};
273
331
274 const evaluation = evaluateAlchemyBottle({
332 const evaluation = evaluateAlchemyBottle({
@@ -336,6 +394,122 @@ function bottle (world, sessionId, command)
336 };
394 };
337}
395}
338
396
397/**
398 * @returns {null | { ok: false, reason: string } | { ok: true, mode: "flower"|"mix", ... }}
399 */
400function evaluateDyeBrew (brew)
401{
402 const rows = brew ?? [];
403 if (!rows.length)
404 { return null; }
405 const hasFlower = rows.some((row) => row.itemId === ItemId.flower);
406 const hasDye = rows.some((row) => row.itemId === ItemId.dye);
407 const hasOther = rows.some((row) => row.itemId !== ItemId.flower && row.itemId !== ItemId.dye);
408 if (!hasFlower && !hasDye)
409 { return null; }
410 if (hasOther)
411 { return { ok: false, reason: "Do not mix dyes or flowers with alchemy ingredients." }; }
412 if (hasFlower && hasDye)
413 { return { ok: false, reason: "Cannot mix flowers and dyes together." }; }
414
415 if (hasFlower)
416 {
417 const colors = new Set(rows.map((row) => row.instance?.colorId).filter(Boolean));
418 if (colors.size === 0)
419 { return { ok: false, reason: "Those flowers have no colour." }; }
420 if (colors.size > 1)
421 { return { ok: false, reason: "Use flowers of a single colour for dye." }; }
422 const sample = rows.find((row) => row.instance?.color);
423 const quantity = rows.reduce((sum, row) => sum + (row.quantity | 0), 0);
424 return {
425 ok: true,
426 mode: "flower",
427 quantity: Math.max(1, quantity),
428 instance: dyeItemInstance(sample.instance.color, DEFAULT_DYE_FILL, sample.instance.colorId)
429 };
430 }
431
432 const mixed = mixDyeBatches(rows);
433 if (!mixed.ok)
434 { return { ok: false, reason: mixed.reason }; }
435 return { ok: true, mode: "mix", ...mixed };
436}
437
438function bottleDyeResult (world, handle, session, inventory, dyePath)
439{
440 const outputs = dyePath.mode === "flower"
441 ? Array.from({ length: dyePath.quantity }, () => ({
442 quantity: 1,
443 instance: dyePath.instance
444 }))
445 : dyePath.outputs;
446
447 // Flowers need empty glass bottles. Dye remixes reuse the bottles already
448 // consumed into the brew; only overflow bottles need extra glass.
449 const bottleNeed = dyePath.mode === "flower"
450 ? outputs.length
451 : Math.max(0, dyePath.extraBottles | 0);
452 if (bottleNeed > 0)
453 {
454 const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
455 if (bottles < bottleNeed)
456 {
457 throw userError(
458 `You need ${bottleNeed} glass bottle${bottleNeed === 1 ? "" : "s"}.`
459 );
460 }
461 const takeBottles = takeMatchingFromSlots(inventory.slots, {
462 itemId: ItemId.glassBottle,
463 quantity: bottleNeed,
464 compact: false
465 });
466 if (!takeBottles.ok)
467 { throw userError("You need glass bottles to bottle the dye."); }
468 inventory.slots = takeBottles.slots;
469 }
470
471 const dyeDef = itemDefinition(ItemId.dye);
472 let slots = inventory.slots;
473 for (const out of outputs)
474 {
475 const inserted = insertStack(slots, {
476 itemId: ItemId.dye,
477 quantity: out.quantity,
478 instance: out.instance
479 }, dyeDef);
480 if (!inserted.ok)
481 {
482 throw userError("Not enough inventory space for dye.");
483 }
484 slots = inserted.slots;
485 }
486 inventory.slots = slots;
487 session.lastSuccessRecipe = null;
488 clearBrew(session);
489
490 const sample = outputs[0]?.instance;
491 return {
492 events: [],
493 private: bagView(world.ecs, handle),
494 cauldron: true,
495 cauldronState: sessionView(session),
496 alchemyResult: {
497 success: true,
498 reason: null,
499 produced: outputs.length,
500 wanted: outputs.length,
501 lost: 0,
502 potion: {
503 potionKey: "dye",
504 displayName: "Dye",
505 unstable: false,
506 color: sample?.color ?? null,
507 fillLevel: sample?.fillLevel ?? DEFAULT_DYE_FILL
508 }
509 }
510 };
511}
512
339function clear (world, sessionId, command)
513function clear (world, sessionId, command)
340{
514{
341 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
515 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -399,3 +573,18 @@ function saveRecipe (world, sessionId, command)
399 cauldronState: sessionView(session)
573 cauldronState: sessionView(session)
400 };
574 };
401}
575}
576
577function countMatchingInstance (slots, itemId, instance)
578{
579 let total = 0;
580 const key = JSON.stringify(instance ?? null);
581 for (const slot of slots ?? [])
582 {
583 if (!slot || slot.itemId !== itemId)
584 { continue; }
585 if (JSON.stringify(slot.instance ?? null) !== key)
586 { continue; }
587 total += stackQuantity(slot.quantity);
588 }
589 return total;
590}
server/src/crafting/service.js +87 −8
@@ -1,7 +1,7 @@
1 1 import { Component } from "../ecs/components.js";
2 2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 3 import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
4 import { itemDefinition } from "../../../shared/definitions/items.js";
4 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5 5 import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6 6 import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7 7 import {
@@ -10,6 +10,7 @@ import {
10 10 canCraftFitInventory,
11 11 hasRecipeInputs
12 12 } from "../../../shared/crafting/recipes.js";
13 import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
13 14 import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14 15 import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
15 16 import {
@@ -69,6 +70,12 @@ function stationBlockType (stationId)
69 70 { return BlockType.woodworkingBench; }
70 71 if (stationId === CraftingStationId.craftingBench)
71 72 { return BlockType.craftingBench; }
73 if (stationId === CraftingStationId.spinningWheel)
74 { return BlockType.spinningWheel; }
75 if (stationId === CraftingStationId.loom)
76 { return BlockType.loom; }
77 if (stationId === CraftingStationId.tailorBench)
78 { return BlockType.tailorBench; }
72 79 return null;
73 80 }
74 81
@@ -96,7 +103,27 @@ function takeInputs (slots, inputs)
96 103 return { ok: true, slots: next };
97 104 }
98 105
99 export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
106 /** Spend one fill level of a dye bottle (remove at 0). */
107 function consumeDyeUse (slots, slotIndex)
108 {
109 const next = slots.map((slot) => (slot ? structuredClone(slot) : null));
110 const slot = next[slotIndex];
111 if (!slot || slot.itemId !== ItemId.dye || slot.instance?.kind !== "dye")
112 { return { ok: false }; }
113 const fill = Math.max(1, slot.instance.fillLevel | 0 || 4);
114 if (fill <= 1)
115 {
116 next[slotIndex] = null;
117 return { ok: true, slots: next };
118 }
119 slot.instance = {
120 ...slot.instance,
121 fillLevel: fill - 1
122 };
123 return { ok: true, slots: next };
124 }
125
126 export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
100 127 {
101 128 const entityId = world.characterEntities.get(characterId);
102 129 if (entityId == null)
@@ -111,7 +138,7 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
111 138 const stationDef = craftingStationDefinition(stationId);
112 139 if (!stationDef)
113 140 { throw userError("Unknown crafting station."); }
114 const recipe = recipeDefinition(recipeId);
141 let recipe = recipeDefinition(recipeId);
115 142 if (!recipe)
116 143 { throw userError("Unknown recipe."); }
117 144 const stationIds = Array.isArray(recipe.stationIds)
@@ -128,6 +155,27 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
128 155 const inventory = world.ecs.get(handle, Component.inventory);
129 156 const skills = world.ecs.get(handle, Component.skills);
130 157 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
158
159 let dyeSlotIndex = null;
160 if (recipe.tailorTemplate)
161 {
162 const dyeIdx = options.dyeSlotIndex;
163 let dyeStack = null;
164 if (dyeIdx != null && dyeIdx >= 0)
165 {
166 dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null;
167 dyeSlotIndex = dyeIdx | 0;
168 }
169 const resolved = resolveTailorCraft({
170 templateId: recipe.tailorTemplate,
171 clothTier: options.clothTier,
172 dyeStack
173 });
174 if (!resolved.ok)
175 { throw userError(resolved.reason); }
176 recipe = resolved.recipe;
177 }
178
131 179 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
132 180 {
133 181 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
@@ -136,6 +184,12 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
136 184 { throw userError("Missing materials."); }
137 185 throw userError("Not enough bag space for the result.");
138 186 }
187 if (recipe.consumeDye && dyeSlotIndex != null)
188 {
189 const dye = inventory?.slots?.[dyeSlotIndex];
190 if (!dye || dye.itemId !== ItemId.dye)
191 { throw userError("Selected dye is missing."); }
192 }
139 193
140 194 const sessions = ensureCraftSessions(world);
141 195 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
@@ -143,6 +197,8 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
143 197 sessionId,
144 198 stationId,
145 199 recipeId,
200 recipe,
201 dyeSlotIndex,
146 202 finishesAt: now + durationMs
147 203 });
148 204 const events = [];
@@ -245,7 +301,7 @@ export function stepCrafting (world, now)
245 301 continue;
246 302 }
247 303
248 const recipe = recipeDefinition(session.recipeId);
304 const recipe = session.recipe ?? recipeDefinition(session.recipeId);
249 305 const stationDef = craftingStationDefinition(session.stationId);
250 306 const inventory = world.ecs.get(handle, Component.inventory);
251 307 const skills = world.ecs.get(handle, Component.skills);
@@ -280,17 +336,36 @@ export function stepCrafting (world, now)
280 336 });
281 337 continue;
282 338 }
339 let slotsAfter = taken.slots;
340 if (recipe.consumeDye && session.dyeSlotIndex != null)
341 {
342 const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex);
343 if (!dyeTaken.ok)
344 {
345 events.push({
346 type: "craft-result",
347 sessionId: session.sessionId,
348 recipeId: session.recipeId,
349 ok: false,
350 error: "Selected dye is missing."
351 });
352 continue;
353 }
354 slotsAfter = dyeTaken.slots;
355 }
283 356 const outDef = itemDefinition(recipe.output.itemId);
284 357 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
285 358 const origin = craftOrigin(
286 359 craftOriginVerbForStation(session.stationId),
287 360 characterDisplayName(world, handle)
288 361 );
289 const added = insertStack(taken.slots, attachOrigins({
362 const outStack = {
290 363 itemId: recipe.output.itemId,
291 364 quantity: outQty,
292 origins: [{ origin, quantity: outQty }]
293 }), outDef);
365 origins: [{ origin, quantity: outQty }],
366 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
367 };
368 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
294 369 if (!added.ok || added.remainder > 0)
295 370 {
296 371 events.push({
@@ -354,7 +429,11 @@ export function handleCraftCommand (world, sessionId, command, now)
354 429 command.characterId,
355 430 command.stationId,
356 431 command.recipeId,
357 now
432 now,
433 {
434 clothTier: command.clothTier ?? null,
435 dyeSlotIndex: command.dyeSlotIndex ?? null
436 }
358 437 );
359 438 case "cancel-craft":
360 439 return cancelCraft(world, command.characterId);
@@ -1,7 +1,7 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
3import { CraftingStationId, CRAFT_DURATION_MS } from "../../../shared/definitions/craftingStations.js";
4import { itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import {
7import {
@@ -10,6 +10,7 @@ import {
10 canCraftFitInventory,
10 canCraftFitInventory,
11 hasRecipeInputs
11 hasRecipeInputs
12} from "../../../shared/crafting/recipes.js";
12} from "../../../shared/crafting/recipes.js";
13import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
13import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14import { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
15import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
15import {
16import {
@@ -69,6 +70,12 @@ function stationBlockType (stationId)
69 { return BlockType.woodworkingBench; }
70 { return BlockType.woodworkingBench; }
70 if (stationId === CraftingStationId.craftingBench)
71 if (stationId === CraftingStationId.craftingBench)
71 { return BlockType.craftingBench; }
72 { return BlockType.craftingBench; }
73 if (stationId === CraftingStationId.spinningWheel)
74 { return BlockType.spinningWheel; }
75 if (stationId === CraftingStationId.loom)
76 { return BlockType.loom; }
77 if (stationId === CraftingStationId.tailorBench)
78 { return BlockType.tailorBench; }
72 return null;
79 return null;
73}
80}
74
81
@@ -96,7 +103,27 @@ function takeInputs (slots, inputs)
96 return { ok: true, slots: next };
103 return { ok: true, slots: next };
97}
104}
98
105
99export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
106/** Spend one fill level of a dye bottle (remove at 0). */
107function consumeDyeUse (slots, slotIndex)
108{
109 const next = slots.map((slot) => (slot ? structuredClone(slot) : null));
110 const slot = next[slotIndex];
111 if (!slot || slot.itemId !== ItemId.dye || slot.instance?.kind !== "dye")
112 { return { ok: false }; }
113 const fill = Math.max(1, slot.instance.fillLevel | 0 || 4);
114 if (fill <= 1)
115 {
116 next[slotIndex] = null;
117 return { ok: true, slots: next };
118 }
119 slot.instance = {
120 ...slot.instance,
121 fillLevel: fill - 1
122 };
123 return { ok: true, slots: next };
124}
125
126export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
100{
127{
101 const entityId = world.characterEntities.get(characterId);
128 const entityId = world.characterEntities.get(characterId);
102 if (entityId == null)
129 if (entityId == null)
@@ -111,7 +138,7 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
111 const stationDef = craftingStationDefinition(stationId);
138 const stationDef = craftingStationDefinition(stationId);
112 if (!stationDef)
139 if (!stationDef)
113 { throw userError("Unknown crafting station."); }
140 { throw userError("Unknown crafting station."); }
114 const recipe = recipeDefinition(recipeId);
141 let recipe = recipeDefinition(recipeId);
115 if (!recipe)
142 if (!recipe)
116 { throw userError("Unknown recipe."); }
143 { throw userError("Unknown recipe."); }
117 const stationIds = Array.isArray(recipe.stationIds)
144 const stationIds = Array.isArray(recipe.stationIds)
@@ -128,6 +155,27 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
128 const inventory = world.ecs.get(handle, Component.inventory);
155 const inventory = world.ecs.get(handle, Component.inventory);
129 const skills = world.ecs.get(handle, Component.skills);
156 const skills = world.ecs.get(handle, Component.skills);
130 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
157 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
158
159 let dyeSlotIndex = null;
160 if (recipe.tailorTemplate)
161 {
162 const dyeIdx = options.dyeSlotIndex;
163 let dyeStack = null;
164 if (dyeIdx != null && dyeIdx >= 0)
165 {
166 dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null;
167 dyeSlotIndex = dyeIdx | 0;
168 }
169 const resolved = resolveTailorCraft({
170 templateId: recipe.tailorTemplate,
171 clothTier: options.clothTier,
172 dyeStack
173 });
174 if (!resolved.ok)
175 { throw userError(resolved.reason); }
176 recipe = resolved.recipe;
177 }
178
131 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
179 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
132 {
180 {
133 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
181 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
@@ -136,6 +184,12 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
136 { throw userError("Missing materials."); }
184 { throw userError("Missing materials."); }
137 throw userError("Not enough bag space for the result.");
185 throw userError("Not enough bag space for the result.");
138 }
186 }
187 if (recipe.consumeDye && dyeSlotIndex != null)
188 {
189 const dye = inventory?.slots?.[dyeSlotIndex];
190 if (!dye || dye.itemId !== ItemId.dye)
191 { throw userError("Selected dye is missing."); }
192 }
139
193
140 const sessions = ensureCraftSessions(world);
194 const sessions = ensureCraftSessions(world);
141 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
195 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
@@ -143,6 +197,8 @@ export function startCraft (world, sessionId, characterId, stationId, recipeId,
143 sessionId,
197 sessionId,
144 stationId,
198 stationId,
145 recipeId,
199 recipeId,
200 recipe,
201 dyeSlotIndex,
146 finishesAt: now + durationMs
202 finishesAt: now + durationMs
147 });
203 });
148 const events = [];
204 const events = [];
@@ -245,7 +301,7 @@ export function stepCrafting (world, now)
245 continue;
301 continue;
246 }
302 }
247
303
248 const recipe = recipeDefinition(session.recipeId);
304 const recipe = session.recipe ?? recipeDefinition(session.recipeId);
249 const stationDef = craftingStationDefinition(session.stationId);
305 const stationDef = craftingStationDefinition(session.stationId);
250 const inventory = world.ecs.get(handle, Component.inventory);
306 const inventory = world.ecs.get(handle, Component.inventory);
251 const skills = world.ecs.get(handle, Component.skills);
307 const skills = world.ecs.get(handle, Component.skills);
@@ -280,17 +336,36 @@ export function stepCrafting (world, now)
280 });
336 });
281 continue;
337 continue;
282 }
338 }
339 let slotsAfter = taken.slots;
340 if (recipe.consumeDye && session.dyeSlotIndex != null)
341 {
342 const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex);
343 if (!dyeTaken.ok)
344 {
345 events.push({
346 type: "craft-result",
347 sessionId: session.sessionId,
348 recipeId: session.recipeId,
349 ok: false,
350 error: "Selected dye is missing."
351 });
352 continue;
353 }
354 slotsAfter = dyeTaken.slots;
355 }
283 const outDef = itemDefinition(recipe.output.itemId);
356 const outDef = itemDefinition(recipe.output.itemId);
284 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
357 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
285 const origin = craftOrigin(
358 const origin = craftOrigin(
286 craftOriginVerbForStation(session.stationId),
359 craftOriginVerbForStation(session.stationId),
287 characterDisplayName(world, handle)
360 characterDisplayName(world, handle)
288 );
361 );
289 const added = insertStack(taken.slots, attachOrigins({
362 const outStack = {
290 itemId: recipe.output.itemId,
363 itemId: recipe.output.itemId,
291 quantity: outQty,
364 quantity: outQty,
292 origins: [{ origin, quantity: outQty }]
365 origins: [{ origin, quantity: outQty }],
293 }), outDef);
366 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
367 };
368 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
294 if (!added.ok || added.remainder > 0)
369 if (!added.ok || added.remainder > 0)
295 {
370 {
296 events.push({
371 events.push({
@@ -354,7 +429,11 @@ export function handleCraftCommand (world, sessionId, command, now)
354 command.characterId,
429 command.characterId,
355 command.stationId,
430 command.stationId,
356 command.recipeId,
431 command.recipeId,
357 now
432 now,
433 {
434 clothTier: command.clothTier ?? null,
435 dyeSlotIndex: command.dyeSlotIndex ?? null
436 }
358 );
437 );
359 case "cancel-craft":
438 case "cancel-craft":
360 return cancelCraft(world, command.characterId);
439 return cancelCraft(world, command.characterId);
server/src/ecs/serialize.js +9 −1
@@ -1,5 +1,6 @@
1 1 import { Component } from "./components.js";
2 2 import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
3 import { resolveEquipTint } from "../../../shared/render/tint.js";
3 4 import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4 5 import { mobDefinition } from "../../../shared/definitions/mobs.js";
5 6 import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
@@ -108,7 +109,14 @@ export function appearanceLayers (ecs, handle, appearance)
108 109 { continue; }
109 110 const overlay = itemEquipSprite(worn.itemId);
110 111 if (overlay)
111 { layers.push({ sprite: overlay, itemId: worn.itemId }); }
112 {
113 const tint = resolveEquipTint(worn.itemId, worn.instance);
114 layers.push({
115 sprite: overlay,
116 itemId: worn.itemId,
117 ...(tint ? { tint } : {})
118 });
119 }
112 120 }
113 121 return layers;
114 122 }
@@ -1,5 +1,6 @@
1import { Component } from "./components.js";
1import { Component } from "./components.js";
2import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
2import { EQUIPMENT_DRAW_ORDER, equippedLightRadiusTiles, itemEquipSprite } from "../../../shared/definitions/items.js";
3import { resolveEquipTint } from "../../../shared/render/tint.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
5import { mobDefinition } from "../../../shared/definitions/mobs.js";
5import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
6import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
@@ -108,7 +109,14 @@ export function appearanceLayers (ecs, handle, appearance)
108 { continue; }
109 { continue; }
109 const overlay = itemEquipSprite(worn.itemId);
110 const overlay = itemEquipSprite(worn.itemId);
110 if (overlay)
111 if (overlay)
111 { layers.push({ sprite: overlay, itemId: worn.itemId }); }
112 {
113 const tint = resolveEquipTint(worn.itemId, worn.instance);
114 layers.push({
115 sprite: overlay,
116 itemId: worn.itemId,
117 ...(tint ? { tint } : {})
118 });
119 }
112 }
120 }
113 return layers;
121 return layers;
114}
122}
server/src/gateway/websocket.js +14 −2
@@ -244,6 +244,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
244 244 tileY: message.tileY | 0
245 245 });
246 246 break;
247 case MessageType.pick:
248 requirePlaying(session);
249 simulation.enqueue(session.id, {
250 type: "pick",
251 characterId: session.characterId,
252 tileX: message.tileX | 0,
253 tileY: message.tileY | 0
254 });
255 break;
247 256 case MessageType.cancelGather:
248 257 requirePlaying(session);
249 258 simulation.enqueue(session.id, {
@@ -257,7 +266,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
257 266 type: "start-craft",
258 267 characterId: session.characterId,
259 268 stationId: message.stationId,
260 recipeId: message.recipeId
269 recipeId: message.recipeId,
270 clothTier: message.clothTier ?? null,
271 dyeSlotIndex: message.dyeSlotIndex ?? null
261 272 });
262 273 break;
263 274 case MessageType.cancelCraft:
@@ -274,7 +285,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
274 285 characterId: session.characterId,
275 286 slotIndex: message.slotIndex | 0,
276 287 itemId: message.itemId | 0,
277 quantity: message.quantity | 0
288 quantity: message.quantity | 0,
289 instance: message.instance ?? null
278 290 });
279 291 break;
280 292 case MessageType.cauldronInsert:
@@ -244,6 +244,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
244 tileY: message.tileY | 0
244 tileY: message.tileY | 0
245 });
245 });
246 break;
246 break;
247 case MessageType.pick:
248 requirePlaying(session);
249 simulation.enqueue(session.id, {
250 type: "pick",
251 characterId: session.characterId,
252 tileX: message.tileX | 0,
253 tileY: message.tileY | 0
254 });
255 break;
247 case MessageType.cancelGather:
256 case MessageType.cancelGather:
248 requirePlaying(session);
257 requirePlaying(session);
249 simulation.enqueue(session.id, {
258 simulation.enqueue(session.id, {
@@ -257,7 +266,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
257 type: "start-craft",
266 type: "start-craft",
258 characterId: session.characterId,
267 characterId: session.characterId,
259 stationId: message.stationId,
268 stationId: message.stationId,
260 recipeId: message.recipeId
269 recipeId: message.recipeId,
270 clothTier: message.clothTier ?? null,
271 dyeSlotIndex: message.dyeSlotIndex ?? null
261 });
272 });
262 break;
273 break;
263 case MessageType.cancelCraft:
274 case MessageType.cancelCraft:
@@ -274,7 +285,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
274 characterId: session.characterId,
285 characterId: session.characterId,
275 slotIndex: message.slotIndex | 0,
286 slotIndex: message.slotIndex | 0,
276 itemId: message.itemId | 0,
287 itemId: message.itemId | 0,
277 quantity: message.quantity | 0
288 quantity: message.quantity | 0,
289 instance: message.instance ?? null
278 });
290 });
279 break;
291 break;
280 case MessageType.cauldronInsert:
292 case MessageType.cauldronInsert:
server/src/gathering/service.js +252 −4
@@ -1,6 +1,6 @@
1 1 import { Component } from "../ecs/components.js";
2 import { BlockType, woodTierForTreeBlock, isChopableTreeBlock } from "../../../shared/definitions/tiles.js";
3 import { itemDefinition } from "../../../shared/definitions/items.js";
2 import { BlockType, woodTierForTreeBlock, isChopableTreeBlock, plantGatherForBlock } from "../../../shared/definitions/tiles.js";
3 import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4 4 import { SkillId } from "../../../shared/definitions/skills.js";
5 5 import {
6 6 materialFromOreBoulderState,
@@ -12,11 +12,21 @@ import {
12 12 EXHAUSTED_ORE_BOULDER_STATE,
13 13 resolveMiningPickaxe,
14 14 resolveWoodcuttingAxe,
15 resolvePlantClippers,
15 16 woodcuttingDurationMs,
16 17 woodcuttingXpForWood,
17 18 treeExhaustDurationMs,
18 logItemIdForWoodTier
19 logItemIdForWoodTier,
20 herbalismDurationMs,
21 herbalismXpForPick,
22 PLANT_EXHAUST_MS
19 23 } from "../../../shared/definitions/gathering.js";
24 import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
25 import { ClothTier } from "../../../shared/definitions/materialTiers.js";
26 import {
27 flowerItemInstance,
28 randomFlowerColorId
29 } from "../../../shared/definitions/dyes.js";
20 30 import { insertStack } from "../../../shared/items/inventory.js";
21 31 import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
22 32 import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
@@ -56,6 +66,13 @@ function ensureTreeRespawns (world)
56 66 return world.treeRespawns;
57 67 }
58 68
69 function ensurePlantRespawns (world)
70 {
71 if (!world.plantRespawns)
72 { world.plantRespawns = new Map(); }
73 return world.plantRespawns;
74 }
75
59 76 function blockAt (world, tileX, tileY)
60 77 {
61 78 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
@@ -97,6 +114,52 @@ function setTreeState (world, tileX, tileY, typeId, state)
97 114 return setBlockState(world, tileX, tileY, typeId, state);
98 115 }
99 116
117 function clearBlock (world, tileX, tileY, typeId)
118 {
119 const chunkX = tileToChunk(tileX);
120 const chunkY = tileToChunk(tileY);
121 const localX = tileToLocal(tileX);
122 const localY = tileToLocal(tileY);
123 const data = world.chunkData(chunkX, chunkY);
124 const index = localY * CHUNK_SIZE + localX;
125 const prev = data?.blocks?.[index];
126 if (!prev || prev.typeId !== typeId)
127 { return null; }
128 data.blocks[index] = null;
129 return {
130 type: "chunk-delta",
131 chunkX,
132 chunkY,
133 tileX,
134 tileY,
135 localX,
136 localY,
137 block: null
138 };
139 }
140
141 function placeBlock (world, tileX, tileY, typeId, state)
142 {
143 const chunkX = tileToChunk(tileX);
144 const chunkY = tileToChunk(tileY);
145 const localX = tileToLocal(tileX);
146 const localY = tileToLocal(tileY);
147 const data = world.chunkData(chunkX, chunkY);
148 const index = localY * CHUNK_SIZE + localX;
149 const block = { typeId, state, config: null };
150 data.blocks[index] = block;
151 return {
152 type: "chunk-delta",
153 chunkX,
154 chunkY,
155 tileX,
156 tileY,
157 localX,
158 localY,
159 block
160 };
161 }
162
100 163 function pickaxeForOre (world, handle, materialId)
101 164 {
102 165 const inventory = world.ecs.get(handle, Component.inventory);
@@ -162,6 +225,19 @@ export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
162 225 }
163 226 }
164 227
228 export function clearPlantRespawnsForChunk (world, chunkX, chunkY)
229 {
230 const respawns = world.plantRespawns;
231 if (!respawns?.size)
232 { return; }
233 for (const key of [...respawns.keys()])
234 {
235 const [tileX, tileY] = key.split(",").map(Number);
236 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
237 { respawns.delete(key); }
238 }
239 }
240
165 241 /**
166 242 * Restore exhausted ore boulders whose timers have elapsed.
167 243 */
@@ -210,6 +286,27 @@ export function stepTreeRespawns (world, now)
210 286 return { events };
211 287 }
212 288
289 export function stepPlantRespawns (world, now)
290 {
291 const respawns = world.plantRespawns;
292 if (!respawns?.size)
293 { return { events: [] }; }
294 const events = [];
295 for (const [key, entry] of [...respawns.entries()])
296 {
297 if (now < entry.respawnsAt)
298 { continue; }
299 respawns.delete(key);
300 const existing = blockAt(world, entry.tileX, entry.tileY);
301 if (existing)
302 { continue; }
303 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, entry.state);
304 if (delta)
305 { events.push(delta); }
306 }
307 return { events };
308 }
309
213 310 function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
214 311 {
215 312 clearEngage(world.ecs, entityId);
@@ -328,6 +425,57 @@ export function startChop (world, sessionId, characterId, tileX, tileY, now)
328 425 }, now);
329 426 }
330 427
428 /**
429 * Pick a plant node (flower with clippers, cotton without tools).
430 */
431 export function startPick (world, sessionId, characterId, tileX, tileY, now)
432 {
433 const entityId = world.characterEntities.get(characterId);
434 if (entityId == null)
435 { throw userError("Character is not in the world."); }
436 const handle = world.ecs.handleOf(entityId);
437 const identity = world.ecs.get(handle, Component.networkIdentity);
438 if (!identity || identity.sessionId !== sessionId)
439 { throw userError("Character is not in the world."); }
440 if (world.ecs.has(handle, Component.dead))
441 { throw userError("You are dead."); }
442
443 const position = world.ecs.get(handle, Component.position);
444 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
445 { throw userError("You need to stand next to the plant."); }
446
447 const block = blockAt(world, tileX, tileY);
448 const plant = plantGatherForBlock(block);
449 if (!plant)
450 { throw userError("There is nothing to pick there."); }
451
452 const inventory = world.ecs.get(handle, Component.inventory);
453 const equipment = world.ecs.get(handle, Component.equipment);
454 const skills = world.ecs.get(handle, Component.skills);
455 const clippers = resolvePlantClippers({
456 inventorySlots: inventory?.slots,
457 equipmentSlots: equipment?.slots,
458 skills,
459 requireTool: !!plant.requiresClippers
460 });
461 if (!clippers.ok)
462 { throw userError(clippers.reason); }
463
464 const toolTier = clippers.tool?.tier ?? null;
465 const durationMs = herbalismDurationMs(toolTier);
466 const toolItemId = clippers.tool?.stack?.itemId ?? null;
467 return beginGatherSwing(world, handle, entityId, position, {
468 kind: "plant",
469 plantKind: plant.kind,
470 tileX,
471 tileY,
472 typeId: block.typeId,
473 toolTier,
474 toolItemId,
475 durationMs
476 }, now);
477 }
478
331 479 function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
332 480 {
333 481 privates.push({
@@ -488,12 +636,100 @@ function completeWoodcutting (world, handle, entityId, character, gather, events
488 636 });
489 637 }
490 638
639 function completePlant (world, handle, entityId, character, gather, events, privates, now)
640 {
641 const inventory = world.ecs.get(handle, Component.inventory);
642 if (!inventory)
643 {
644 clearGather(world.ecs, handle);
645 return;
646 }
647
648 let itemId = null;
649 let instance = null;
650 if (gather.plantKind === "flower")
651 {
652 itemId = ItemId.flower;
653 instance = flowerItemInstance(randomFlowerColorId());
654 }
655 else if (gather.plantKind === "cotton")
656 {
657 itemId = rawClothItemId(ClothTier.cotton);
658 }
659 else
660 {
661 clearGather(world.ecs, handle);
662 return;
663 }
664
665 const def = itemDefinition(itemId);
666 if (!def)
667 {
668 clearGather(world.ecs, handle);
669 return;
670 }
671
672 const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle));
673 const stack = attachOrigins({
674 itemId,
675 quantity: 1,
676 instance,
677 origins: [{ origin, quantity: 1 }]
678 });
679 const inserted = insertStack(inventory.slots, stack, def);
680 if (!inserted.ok || inserted.remainder > 0)
681 {
682 clearGather(world.ecs, handle);
683 events.push({
684 type: "command-error",
685 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
686 message: "Your inventory is full."
687 });
688 return;
689 }
690 inventory.slots = inserted.slots;
691
692 const skills = world.ecs.get(handle, Component.skills);
693 let skillsChanged = false;
694 const levelUps = [];
695 if (skills?.xp)
696 {
697 const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind));
698 if (result.changed)
699 { skillsChanged = true; }
700 if (result.levelUp)
701 { levelUps.push(result.levelUp); }
702 }
703
704 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
705 if (delta)
706 { events.push(delta); }
707 ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
708 tileX: gather.tileX,
709 tileY: gather.tileY,
710 typeId: gather.typeId,
711 state: gather.plantKind === "flower" ? "flower" : "cotton-plant",
712 respawnsAt: now + PLANT_EXHAUST_MS
713 });
714
715 clearGather(world.ecs, handle);
716 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
717 events.push({
718 type: "gather-complete",
719 characterId: character.characterId,
720 kind: "plant",
721 plantKind: gather.plantKind,
722 itemId
723 });
724 }
725
491 726 export function stepGather (world, now)
492 727 {
493 728 const events = [];
494 729 const privates = [];
495 730 events.push(...stepOreRespawns(world, now).events);
496 731 events.push(...stepTreeRespawns(world, now).events);
732 events.push(...stepPlantRespawns(world, now).events);
497 733
498 734 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
499 735 {
@@ -527,6 +763,14 @@ export function stepGather (world, now)
527 763 continue;
528 764 }
529 765 }
766 else if (gather.kind === "plant")
767 {
768 if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block))
769 {
770 clearGather(world.ecs, handle);
771 continue;
772 }
773 }
530 774 else
531 775 {
532 776 clearGather(world.ecs, handle);
@@ -553,8 +797,10 @@ export function stepGather (world, now)
553 797
554 798 if (gather.kind === "mining")
555 799 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
556 else
800 else if (gather.kind === "woodcutting")
557 801 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
802 else
803 { completePlant(world, handle, entityId, character, gather, events, privates, now); }
558 804 }
559 805 return { events, privates };
560 806 }
@@ -567,6 +813,8 @@ export function handleGatherCommand (world, sessionId, command, now)
567 813 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
568 814 case "chop":
569 815 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
816 case "pick":
817 return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
570 818 case "cancel-gather":
571 819 {
572 820 const entityId = world.characterEntities.get(command.characterId);
@@ -1,6 +1,6 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { BlockType, woodTierForTreeBlock, isChopableTreeBlock } from "../../../shared/definitions/tiles.js";
2import { BlockType, woodTierForTreeBlock, isChopableTreeBlock, plantGatherForBlock } from "../../../shared/definitions/tiles.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
3import { itemDefinition, ItemId } from "../../../shared/definitions/items.js";
4import { SkillId } from "../../../shared/definitions/skills.js";
4import { SkillId } from "../../../shared/definitions/skills.js";
5import {
5import {
6 materialFromOreBoulderState,
6 materialFromOreBoulderState,
@@ -12,11 +12,21 @@ import {
12 EXHAUSTED_ORE_BOULDER_STATE,
12 EXHAUSTED_ORE_BOULDER_STATE,
13 resolveMiningPickaxe,
13 resolveMiningPickaxe,
14 resolveWoodcuttingAxe,
14 resolveWoodcuttingAxe,
15 resolvePlantClippers,
15 woodcuttingDurationMs,
16 woodcuttingDurationMs,
16 woodcuttingXpForWood,
17 woodcuttingXpForWood,
17 treeExhaustDurationMs,
18 treeExhaustDurationMs,
18 logItemIdForWoodTier
19 logItemIdForWoodTier,
20 herbalismDurationMs,
21 herbalismXpForPick,
22 PLANT_EXHAUST_MS
19} from "../../../shared/definitions/gathering.js";
23} from "../../../shared/definitions/gathering.js";
24import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
25import { ClothTier } from "../../../shared/definitions/materialTiers.js";
26import {
27 flowerItemInstance,
28 randomFlowerColorId
29} from "../../../shared/definitions/dyes.js";
20import { insertStack } from "../../../shared/items/inventory.js";
30import { insertStack } from "../../../shared/items/inventory.js";
21import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
31import { attachOrigins, GatherOriginVerb, gatherOrigin } from "../../../shared/items/origin.js";
22import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
32import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
@@ -56,6 +66,13 @@ function ensureTreeRespawns (world)
56 return world.treeRespawns;
66 return world.treeRespawns;
57}
67}
58
68
69function ensurePlantRespawns (world)
70{
71 if (!world.plantRespawns)
72 { world.plantRespawns = new Map(); }
73 return world.plantRespawns;
74}
75
59function blockAt (world, tileX, tileY)
76function blockAt (world, tileX, tileY)
60{
77{
61 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
78 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
@@ -97,6 +114,52 @@ function setTreeState (world, tileX, tileY, typeId, state)
97 return setBlockState(world, tileX, tileY, typeId, state);
114 return setBlockState(world, tileX, tileY, typeId, state);
98}
115}
99
116
117function clearBlock (world, tileX, tileY, typeId)
118{
119 const chunkX = tileToChunk(tileX);
120 const chunkY = tileToChunk(tileY);
121 const localX = tileToLocal(tileX);
122 const localY = tileToLocal(tileY);
123 const data = world.chunkData(chunkX, chunkY);
124 const index = localY * CHUNK_SIZE + localX;
125 const prev = data?.blocks?.[index];
126 if (!prev || prev.typeId !== typeId)
127 { return null; }
128 data.blocks[index] = null;
129 return {
130 type: "chunk-delta",
131 chunkX,
132 chunkY,
133 tileX,
134 tileY,
135 localX,
136 localY,
137 block: null
138 };
139}
140
141function placeBlock (world, tileX, tileY, typeId, state)
142{
143 const chunkX = tileToChunk(tileX);
144 const chunkY = tileToChunk(tileY);
145 const localX = tileToLocal(tileX);
146 const localY = tileToLocal(tileY);
147 const data = world.chunkData(chunkX, chunkY);
148 const index = localY * CHUNK_SIZE + localX;
149 const block = { typeId, state, config: null };
150 data.blocks[index] = block;
151 return {
152 type: "chunk-delta",
153 chunkX,
154 chunkY,
155 tileX,
156 tileY,
157 localX,
158 localY,
159 block
160 };
161}
162
100function pickaxeForOre (world, handle, materialId)
163function pickaxeForOre (world, handle, materialId)
101{
164{
102 const inventory = world.ecs.get(handle, Component.inventory);
165 const inventory = world.ecs.get(handle, Component.inventory);
@@ -162,6 +225,19 @@ export function clearTreeRespawnsForChunk (world, chunkX, chunkY)
162 }
225 }
163}
226}
164
227
228export function clearPlantRespawnsForChunk (world, chunkX, chunkY)
229{
230 const respawns = world.plantRespawns;
231 if (!respawns?.size)
232 { return; }
233 for (const key of [...respawns.keys()])
234 {
235 const [tileX, tileY] = key.split(",").map(Number);
236 if (tileToChunk(tileX) === chunkX && tileToChunk(tileY) === chunkY)
237 { respawns.delete(key); }
238 }
239}
240
165/**
241/**
166 * Restore exhausted ore boulders whose timers have elapsed.
242 * Restore exhausted ore boulders whose timers have elapsed.
167 */
243 */
@@ -210,6 +286,27 @@ export function stepTreeRespawns (world, now)
210 return { events };
286 return { events };
211}
287}
212
288
289export function stepPlantRespawns (world, now)
290{
291 const respawns = world.plantRespawns;
292 if (!respawns?.size)
293 { return { events: [] }; }
294 const events = [];
295 for (const [key, entry] of [...respawns.entries()])
296 {
297 if (now < entry.respawnsAt)
298 { continue; }
299 respawns.delete(key);
300 const existing = blockAt(world, entry.tileX, entry.tileY);
301 if (existing)
302 { continue; }
303 const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, entry.state);
304 if (delta)
305 { events.push(delta); }
306 }
307 return { events };
308}
309
213function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
310function beginGatherSwing (world, handle, entityId, position, gatherFields, now)
214{
311{
215 clearEngage(world.ecs, entityId);
312 clearEngage(world.ecs, entityId);
@@ -328,6 +425,57 @@ export function startChop (world, sessionId, characterId, tileX, tileY, now)
328 }, now);
425 }, now);
329}
426}
330
427
428/**
429 * Pick a plant node (flower with clippers, cotton without tools).
430 */
431export function startPick (world, sessionId, characterId, tileX, tileY, now)
432{
433 const entityId = world.characterEntities.get(characterId);
434 if (entityId == null)
435 { throw userError("Character is not in the world."); }
436 const handle = world.ecs.handleOf(entityId);
437 const identity = world.ecs.get(handle, Component.networkIdentity);
438 if (!identity || identity.sessionId !== sessionId)
439 { throw userError("Character is not in the world."); }
440 if (world.ecs.has(handle, Component.dead))
441 { throw userError("You are dead."); }
442
443 const position = world.ecs.get(handle, Component.position);
444 if (chebyshev(position.tileX, position.tileY, tileX, tileY) > 1)
445 { throw userError("You need to stand next to the plant."); }
446
447 const block = blockAt(world, tileX, tileY);
448 const plant = plantGatherForBlock(block);
449 if (!plant)
450 { throw userError("There is nothing to pick there."); }
451
452 const inventory = world.ecs.get(handle, Component.inventory);
453 const equipment = world.ecs.get(handle, Component.equipment);
454 const skills = world.ecs.get(handle, Component.skills);
455 const clippers = resolvePlantClippers({
456 inventorySlots: inventory?.slots,
457 equipmentSlots: equipment?.slots,
458 skills,
459 requireTool: !!plant.requiresClippers
460 });
461 if (!clippers.ok)
462 { throw userError(clippers.reason); }
463
464 const toolTier = clippers.tool?.tier ?? null;
465 const durationMs = herbalismDurationMs(toolTier);
466 const toolItemId = clippers.tool?.stack?.itemId ?? null;
467 return beginGatherSwing(world, handle, entityId, position, {
468 kind: "plant",
469 plantKind: plant.kind,
470 tileX,
471 tileY,
472 typeId: block.typeId,
473 toolTier,
474 toolItemId,
475 durationMs
476 }, now);
477}
478
331function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
479function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
332{
480{
333 privates.push({
481 privates.push({
@@ -488,12 +636,100 @@ function completeWoodcutting (world, handle, entityId, character, gather, events
488 });
636 });
489}
637}
490
638
639function completePlant (world, handle, entityId, character, gather, events, privates, now)
640{
641 const inventory = world.ecs.get(handle, Component.inventory);
642 if (!inventory)
643 {
644 clearGather(world.ecs, handle);
645 return;
646 }
647
648 let itemId = null;
649 let instance = null;
650 if (gather.plantKind === "flower")
651 {
652 itemId = ItemId.flower;
653 instance = flowerItemInstance(randomFlowerColorId());
654 }
655 else if (gather.plantKind === "cotton")
656 {
657 itemId = rawClothItemId(ClothTier.cotton);
658 }
659 else
660 {
661 clearGather(world.ecs, handle);
662 return;
663 }
664
665 const def = itemDefinition(itemId);
666 if (!def)
667 {
668 clearGather(world.ecs, handle);
669 return;
670 }
671
672 const origin = gatherOrigin(GatherOriginVerb.picked, characterDisplayName(world, handle));
673 const stack = attachOrigins({
674 itemId,
675 quantity: 1,
676 instance,
677 origins: [{ origin, quantity: 1 }]
678 });
679 const inserted = insertStack(inventory.slots, stack, def);
680 if (!inserted.ok || inserted.remainder > 0)
681 {
682 clearGather(world.ecs, handle);
683 events.push({
684 type: "command-error",
685 sessionId: world.ecs.get(handle, Component.networkIdentity)?.sessionId,
686 message: "Your inventory is full."
687 });
688 return;
689 }
690 inventory.slots = inserted.slots;
691
692 const skills = world.ecs.get(handle, Component.skills);
693 let skillsChanged = false;
694 const levelUps = [];
695 if (skills?.xp)
696 {
697 const result = applySkillXp(skills, SkillId.herbalism, herbalismXpForPick(gather.plantKind));
698 if (result.changed)
699 { skillsChanged = true; }
700 if (result.levelUp)
701 { levelUps.push(result.levelUp); }
702 }
703
704 const delta = clearBlock(world, gather.tileX, gather.tileY, gather.typeId);
705 if (delta)
706 { events.push(delta); }
707 ensurePlantRespawns(world).set(tileKey(gather.tileX, gather.tileY), {
708 tileX: gather.tileX,
709 tileY: gather.tileY,
710 typeId: gather.typeId,
711 state: gather.plantKind === "flower" ? "flower" : "cotton-plant",
712 respawnsAt: now + PLANT_EXHAUST_MS
713 });
714
715 clearGather(world.ecs, handle);
716 pushBagUpdate(events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps);
717 events.push({
718 type: "gather-complete",
719 characterId: character.characterId,
720 kind: "plant",
721 plantKind: gather.plantKind,
722 itemId
723 });
724}
725
491export function stepGather (world, now)
726export function stepGather (world, now)
492{
727{
493 const events = [];
728 const events = [];
494 const privates = [];
729 const privates = [];
495 events.push(...stepOreRespawns(world, now).events);
730 events.push(...stepOreRespawns(world, now).events);
496 events.push(...stepTreeRespawns(world, now).events);
731 events.push(...stepTreeRespawns(world, now).events);
732 events.push(...stepPlantRespawns(world, now).events);
497
733
498 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
734 for (const entity of world.ecs.query(Component.gather, Component.position, Component.character))
499 {
735 {
@@ -527,6 +763,14 @@ export function stepGather (world, now)
527 continue;
763 continue;
528 }
764 }
529 }
765 }
766 else if (gather.kind === "plant")
767 {
768 if (!block || block.typeId !== gather.typeId || !plantGatherForBlock(block))
769 {
770 clearGather(world.ecs, handle);
771 continue;
772 }
773 }
530 else
774 else
531 {
775 {
532 clearGather(world.ecs, handle);
776 clearGather(world.ecs, handle);
@@ -553,8 +797,10 @@ export function stepGather (world, now)
553
797
554 if (gather.kind === "mining")
798 if (gather.kind === "mining")
555 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
799 { completeMining(world, handle, entityId, character, gather, events, privates, now); }
556 else
800 else if (gather.kind === "woodcutting")
557 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
801 { completeWoodcutting(world, handle, entityId, character, gather, events, privates, now); }
802 else
803 { completePlant(world, handle, entityId, character, gather, events, privates, now); }
558 }
804 }
559 return { events, privates };
805 return { events, privates };
560}
806}
@@ -567,6 +813,8 @@ export function handleGatherCommand (world, sessionId, command, now)
567 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
813 return startMine(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
568 case "chop":
814 case "chop":
569 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
815 return startChop(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
816 case "pick":
817 return startPick(world, sessionId, command.characterId, command.tileX | 0, command.tileY | 0, now);
570 case "cancel-gather":
818 case "cancel-gather":
571 {
819 {
572 const entityId = world.characterEntities.get(command.characterId);
820 const entityId = world.characterEntities.get(command.characterId);
server/src/simulation/workerWorld.js +5 −1
@@ -36,7 +36,8 @@ import {
36 36 stepGather,
37 37 cancelGather,
38 38 clearOreRespawnsForChunk,
39 clearTreeRespawnsForChunk
39 clearTreeRespawnsForChunk,
40 clearPlantRespawnsForChunk
40 41 } from "../gathering/service.js";
41 42 import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
42 43 import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
@@ -216,6 +217,7 @@ export class WorkerWorld
216 217 {
217 218 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
218 219 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
220 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
219 221 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
220 222 data: cloneChunkData(chunk.data),
221 223 simulating: false,
@@ -233,6 +235,7 @@ export class WorkerWorld
233 235 const existing = this.chunks.get(key);
234 236 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
235 237 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
238 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
236 239 this.chunks.set(key, {
237 240 data: cloneChunkData(chunk.data),
238 241 simulating: existing?.simulating ?? false,
@@ -265,6 +268,7 @@ export class WorkerWorld
265 268 {
266 269 clearOreRespawnsForChunk(this, chunkX, chunkY);
267 270 clearTreeRespawnsForChunk(this, chunkX, chunkY);
271 clearPlantRespawnsForChunk(this, chunkX, chunkY);
268 272 this.chunks.delete(key);
269 273 }
270 274 }
@@ -36,7 +36,8 @@ import {
36 stepGather,
36 stepGather,
37 cancelGather,
37 cancelGather,
38 clearOreRespawnsForChunk,
38 clearOreRespawnsForChunk,
39 clearTreeRespawnsForChunk
39 clearTreeRespawnsForChunk,
40 clearPlantRespawnsForChunk
40} from "../gathering/service.js";
41} from "../gathering/service.js";
41import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
42import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
42import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
43import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
@@ -216,6 +217,7 @@ export class WorkerWorld
216 {
217 {
217 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
218 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
218 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
219 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
220 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
219 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
221 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
220 data: cloneChunkData(chunk.data),
222 data: cloneChunkData(chunk.data),
221 simulating: false,
223 simulating: false,
@@ -233,6 +235,7 @@ export class WorkerWorld
233 const existing = this.chunks.get(key);
235 const existing = this.chunks.get(key);
234 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
236 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
235 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
237 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
238 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
236 this.chunks.set(key, {
239 this.chunks.set(key, {
237 data: cloneChunkData(chunk.data),
240 data: cloneChunkData(chunk.data),
238 simulating: existing?.simulating ?? false,
241 simulating: existing?.simulating ?? false,
@@ -265,6 +268,7 @@ export class WorkerWorld
265 {
268 {
266 clearOreRespawnsForChunk(this, chunkX, chunkY);
269 clearOreRespawnsForChunk(this, chunkX, chunkY);
267 clearTreeRespawnsForChunk(this, chunkX, chunkY);
270 clearTreeRespawnsForChunk(this, chunkX, chunkY);
271 clearPlantRespawnsForChunk(this, chunkX, chunkY);
268 this.chunks.delete(key);
272 this.chunks.delete(key);
269 }
273 }
270 }
274 }
shared/appearance/layers.js +9 −2
@@ -1,4 +1,5 @@
1 1 import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../definitions/items.js";
2 import { resolveEquipTint } from "../render/tint.js";
2 3
3 4 export function bodySpriteName (sex)
4 5 {
@@ -16,8 +17,14 @@ export function layersFromBag (sex, bag)
16 17 if (!worn)
17 18 { continue; }
18 19 const overlay = itemEquipSprite(worn.itemId);
19 if (overlay)
20 { layers.push({ sprite: overlay }); }
20 if (!overlay)
21 { continue; }
22 const tint = resolveEquipTint(worn.itemId, worn.instance);
23 layers.push({
24 sprite: overlay,
25 itemId: worn.itemId,
26 ...(tint ? { tint } : {})
27 });
21 28 }
22 29 return layers;
23 30 }
@@ -1,4 +1,5 @@
1import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../definitions/items.js";
1import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../definitions/items.js";
2import { resolveEquipTint } from "../render/tint.js";
2
3
3export function bodySpriteName (sex)
4export function bodySpriteName (sex)
4{
5{
@@ -16,8 +17,14 @@ export function layersFromBag (sex, bag)
16 if (!worn)
17 if (!worn)
17 { continue; }
18 { continue; }
18 const overlay = itemEquipSprite(worn.itemId);
19 const overlay = itemEquipSprite(worn.itemId);
19 if (overlay)
20 if (!overlay)
20 { layers.push({ sprite: overlay }); }
21 { continue; }
22 const tint = resolveEquipTint(worn.itemId, worn.instance);
23 layers.push({
24 sprite: overlay,
25 itemId: worn.itemId,
26 ...(tint ? { tint } : {})
27 });
21 }
28 }
22 return layers;
29 return layers;
23}
30}
shared/crafting/stationRecipes.js +60 −1
@@ -13,6 +13,7 @@ import {
13 13 MaterialTier,
14 14 GatherMaterialId,
15 15 MATERIAL_TIER_ORDER,
16 CLOTH_TIER_ORDER,
16 17 woodTierForMetal,
17 18 tierSmeltSkillLevel,
18 19 tierCraftSkillLevel
@@ -25,6 +26,12 @@ import {
25 26 ARMOUR_CRAFT_PIECES,
26 27 armourItemIdForTier
27 28 } from "../definitions/armourItems.js";
29 import {
30 rawClothItemId,
31 yarnItemId,
32 wovenClothItemId,
33 CLOTHING_TEMPLATES
34 } from "../definitions/clothItems.js";
28 35
29 36 /**
30 37 * Craft recipe schema (shared client + server):
@@ -193,6 +200,46 @@ const AXE_ASSEMBLE_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
193 200 const ARMOUR_RECIPES = MATERIAL_TIER_ORDER.flatMap((tier) =>
194 201 ARMOUR_CRAFT_PIECES.map((piece) => armourRecipe(tier, piece)));
195 202
203 function yarnSpinRecipe (clothTier)
204 {
205 return Object.freeze({
206 recipeId: `yarn-${clothTier}`,
207 stationId: CraftingStationId.spinningWheel,
208 output: { itemId: yarnItemId(clothTier), quantity: 1 },
209 inputs: [{ itemId: rawClothItemId(clothTier), quantity: 1 }],
210 minSkillLevel: tierCraftSkillLevel(clothTier),
211 skillId: "tailoring",
212 xpMaterial: clothTier
213 });
214 }
215
216 function clothWeaveRecipe (clothTier)
217 {
218 return Object.freeze({
219 recipeId: `cloth-${clothTier}`,
220 stationId: CraftingStationId.loom,
221 output: { itemId: wovenClothItemId(clothTier), quantity: 1 },
222 inputs: [{ itemId: yarnItemId(clothTier), quantity: 1 }],
223 minSkillLevel: tierCraftSkillLevel(clothTier),
224 skillId: "tailoring",
225 xpMaterial: clothTier
226 });
227 }
228
229 const YARN_SPIN_RECIPES = CLOTH_TIER_ORDER.map((tier) => yarnSpinRecipe(tier));
230 const CLOTH_WEAVE_RECIPES = CLOTH_TIER_ORDER.map((tier) => clothWeaveRecipe(tier));
231
232 /** Tailor templates — client picks material; server resolves inputs/output. */
233 const TAILOR_TEMPLATE_RECIPES = Object.values(CLOTHING_TEMPLATES).map((template) => Object.freeze({
234 recipeId: `tailor-${template.templateId}`,
235 stationId: CraftingStationId.tailorBench,
236 tailorTemplate: template.templateId,
237 output: { itemId: template.outputItemIdForTier(CLOTH_TIER_ORDER[0]), quantity: 1 },
238 inputs: [],
239 minSkillLevel: template.minSkillLevel ?? 1,
240 skillId: "tailoring"
241 }));
242
196 243 /** @type {ReadonlyArray<object>} */
197 244 export const CRAFT_RECIPES = Object.freeze([
198 245 Object.freeze({
@@ -249,7 +296,19 @@ export const CRAFT_RECIPES = Object.freeze([
249 296 ...PICKAXE_ASSEMBLE_RECIPES,
250 297 ...AXE_HEAD_RECIPES,
251 298 ...AXE_ASSEMBLE_RECIPES,
252 ...ARMOUR_RECIPES
299 ...ARMOUR_RECIPES,
300 Object.freeze({
301 recipeId: "bronze-plant-clippers",
302 stationId: CraftingStationId.anvil,
303 output: { itemId: ItemId.bronzePlantClippers, quantity: 1 },
304 inputs: [{ itemId: CraftingItemId.bronzeBar, quantity: 1 }],
305 minSkillLevel: tierSmeltSkillLevel(MaterialTier.bronze),
306 skillId: "smithing",
307 xpMaterial: MaterialTier.bronze
308 }),
309 ...YARN_SPIN_RECIPES,
310 ...CLOTH_WEAVE_RECIPES,
311 ...TAILOR_TEMPLATE_RECIPES
253 312 ]);
254 313
255 314 const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
@@ -13,6 +13,7 @@ import {
13 MaterialTier,
13 MaterialTier,
14 GatherMaterialId,
14 GatherMaterialId,
15 MATERIAL_TIER_ORDER,
15 MATERIAL_TIER_ORDER,
16 CLOTH_TIER_ORDER,
16 woodTierForMetal,
17 woodTierForMetal,
17 tierSmeltSkillLevel,
18 tierSmeltSkillLevel,
18 tierCraftSkillLevel
19 tierCraftSkillLevel
@@ -25,6 +26,12 @@ import {
25 ARMOUR_CRAFT_PIECES,
26 ARMOUR_CRAFT_PIECES,
26 armourItemIdForTier
27 armourItemIdForTier
27} from "../definitions/armourItems.js";
28} from "../definitions/armourItems.js";
29import {
30 rawClothItemId,
31 yarnItemId,
32 wovenClothItemId,
33 CLOTHING_TEMPLATES
34} from "../definitions/clothItems.js";
28
35
29/**
36/**
30 * Craft recipe schema (shared client + server):
37 * Craft recipe schema (shared client + server):
@@ -193,6 +200,46 @@ const AXE_ASSEMBLE_RECIPES = MATERIAL_TIER_ORDER.map((tier) =>
193const ARMOUR_RECIPES = MATERIAL_TIER_ORDER.flatMap((tier) =>
200const ARMOUR_RECIPES = MATERIAL_TIER_ORDER.flatMap((tier) =>
194 ARMOUR_CRAFT_PIECES.map((piece) => armourRecipe(tier, piece)));
201 ARMOUR_CRAFT_PIECES.map((piece) => armourRecipe(tier, piece)));
195
202
203function yarnSpinRecipe (clothTier)
204{
205 return Object.freeze({
206 recipeId: `yarn-${clothTier}`,
207 stationId: CraftingStationId.spinningWheel,
208 output: { itemId: yarnItemId(clothTier), quantity: 1 },
209 inputs: [{ itemId: rawClothItemId(clothTier), quantity: 1 }],
210 minSkillLevel: tierCraftSkillLevel(clothTier),
211 skillId: "tailoring",
212 xpMaterial: clothTier
213 });
214}
215
216function clothWeaveRecipe (clothTier)
217{
218 return Object.freeze({
219 recipeId: `cloth-${clothTier}`,
220 stationId: CraftingStationId.loom,
221 output: { itemId: wovenClothItemId(clothTier), quantity: 1 },
222 inputs: [{ itemId: yarnItemId(clothTier), quantity: 1 }],
223 minSkillLevel: tierCraftSkillLevel(clothTier),
224 skillId: "tailoring",
225 xpMaterial: clothTier
226 });
227}
228
229const YARN_SPIN_RECIPES = CLOTH_TIER_ORDER.map((tier) => yarnSpinRecipe(tier));
230const CLOTH_WEAVE_RECIPES = CLOTH_TIER_ORDER.map((tier) => clothWeaveRecipe(tier));
231
232/** Tailor templates — client picks material; server resolves inputs/output. */
233const TAILOR_TEMPLATE_RECIPES = Object.values(CLOTHING_TEMPLATES).map((template) => Object.freeze({
234 recipeId: `tailor-${template.templateId}`,
235 stationId: CraftingStationId.tailorBench,
236 tailorTemplate: template.templateId,
237 output: { itemId: template.outputItemIdForTier(CLOTH_TIER_ORDER[0]), quantity: 1 },
238 inputs: [],
239 minSkillLevel: template.minSkillLevel ?? 1,
240 skillId: "tailoring"
241}));
242
196/** @type {ReadonlyArray<object>} */
243/** @type {ReadonlyArray<object>} */
197export const CRAFT_RECIPES = Object.freeze([
244export const CRAFT_RECIPES = Object.freeze([
198 Object.freeze({
245 Object.freeze({
@@ -249,7 +296,19 @@ export const CRAFT_RECIPES = Object.freeze([
249 ...PICKAXE_ASSEMBLE_RECIPES,
296 ...PICKAXE_ASSEMBLE_RECIPES,
250 ...AXE_HEAD_RECIPES,
297 ...AXE_HEAD_RECIPES,
251 ...AXE_ASSEMBLE_RECIPES,
298 ...AXE_ASSEMBLE_RECIPES,
252 ...ARMOUR_RECIPES
299 ...ARMOUR_RECIPES,
300 Object.freeze({
301 recipeId: "bronze-plant-clippers",
302 stationId: CraftingStationId.anvil,
303 output: { itemId: ItemId.bronzePlantClippers, quantity: 1 },
304 inputs: [{ itemId: CraftingItemId.bronzeBar, quantity: 1 }],
305 minSkillLevel: tierSmeltSkillLevel(MaterialTier.bronze),
306 skillId: "smithing",
307 xpMaterial: MaterialTier.bronze
308 }),
309 ...YARN_SPIN_RECIPES,
310 ...CLOTH_WEAVE_RECIPES,
311 ...TAILOR_TEMPLATE_RECIPES
253]);
312]);
254
313
255const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
314const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
shared/crafting/tailor.js added +55 −0
@@ -0,0 +1,55 @@
1 import { clothingTemplate, yarnItemId, wovenClothItemId } from "../definitions/clothItems.js";
2 import { CLOTH_TIER_ORDER, ClothTier, tierCraftSkillLevel } from "../definitions/materialTiers.js";
3 import { ItemId } from "../definitions/items.js";
4
5 /**
6 * Resolve a tailor craft into a concrete recipe (inputs/output) for the chosen cloth tier.
7 * @returns {{ ok: true, recipe: object } | { ok: false, reason: string }}
8 */
9 export function resolveTailorCraft ({ templateId, clothTier, dyeStack = null })
10 {
11 const template = clothingTemplate(templateId);
12 if (!template)
13 { return { ok: false, reason: "Unknown garment template." }; }
14 const tier = CLOTH_TIER_ORDER.includes(clothTier) ? clothTier : ClothTier.cotton;
15 const outputItemId = template.outputItemIdForTier(tier);
16 if (!outputItemId)
17 { return { ok: false, reason: "That material cannot make this garment." }; }
18
19 const inputs = [];
20 for (const need of template.inputs ?? [])
21 {
22 const quantity = Math.max(1, need.quantity | 0 || 1);
23 if (need.kind === "yarn")
24 { inputs.push({ itemId: yarnItemId(tier), quantity }); }
25 else if (need.kind === "cloth")
26 { inputs.push({ itemId: wovenClothItemId(tier), quantity }); }
27 else
28 { return { ok: false, reason: "Unsupported tailor ingredient." }; }
29 }
30
31 let dyeColor = null;
32 if (dyeStack)
33 {
34 if (dyeStack.itemId !== ItemId.dye || dyeStack.instance?.kind !== "dye")
35 { return { ok: false, reason: "That is not a dye." }; }
36 dyeColor = dyeStack.instance.color;
37 }
38
39 return {
40 ok: true,
41 recipe: Object.freeze({
42 recipeId: `tailor-${template.templateId}`,
43 stationId: "tailor-bench",
44 tailorTemplate: template.templateId,
45 clothTier: tier,
46 output: { itemId: outputItemId, quantity: 1 },
47 inputs,
48 minSkillLevel: Math.max(template.minSkillLevel | 0 || 1, tierCraftSkillLevel(tier)),
49 skillId: "tailoring",
50 xpMaterial: tier,
51 dyeColor,
52 consumeDye: !!dyeColor
53 })
54 };
55 }
@@ -0,0 +1,55 @@
1import { clothingTemplate, yarnItemId, wovenClothItemId } from "../definitions/clothItems.js";
2import { CLOTH_TIER_ORDER, ClothTier, tierCraftSkillLevel } from "../definitions/materialTiers.js";
3import { ItemId } from "../definitions/items.js";
4
5/**
6 * Resolve a tailor craft into a concrete recipe (inputs/output) for the chosen cloth tier.
7 * @returns {{ ok: true, recipe: object } | { ok: false, reason: string }}
8 */
9export function resolveTailorCraft ({ templateId, clothTier, dyeStack = null })
10{
11 const template = clothingTemplate(templateId);
12 if (!template)
13 { return { ok: false, reason: "Unknown garment template." }; }
14 const tier = CLOTH_TIER_ORDER.includes(clothTier) ? clothTier : ClothTier.cotton;
15 const outputItemId = template.outputItemIdForTier(tier);
16 if (!outputItemId)
17 { return { ok: false, reason: "That material cannot make this garment." }; }
18
19 const inputs = [];
20 for (const need of template.inputs ?? [])
21 {
22 const quantity = Math.max(1, need.quantity | 0 || 1);
23 if (need.kind === "yarn")
24 { inputs.push({ itemId: yarnItemId(tier), quantity }); }
25 else if (need.kind === "cloth")
26 { inputs.push({ itemId: wovenClothItemId(tier), quantity }); }
27 else
28 { return { ok: false, reason: "Unsupported tailor ingredient." }; }
29 }
30
31 let dyeColor = null;
32 if (dyeStack)
33 {
34 if (dyeStack.itemId !== ItemId.dye || dyeStack.instance?.kind !== "dye")
35 { return { ok: false, reason: "That is not a dye." }; }
36 dyeColor = dyeStack.instance.color;
37 }
38
39 return {
40 ok: true,
41 recipe: Object.freeze({
42 recipeId: `tailor-${template.templateId}`,
43 stationId: "tailor-bench",
44 tailorTemplate: template.templateId,
45 clothTier: tier,
46 output: { itemId: outputItemId, quantity: 1 },
47 inputs,
48 minSkillLevel: Math.max(template.minSkillLevel | 0 || 1, tierCraftSkillLevel(tier)),
49 skillId: "tailoring",
50 xpMaterial: tier,
51 dyeColor,
52 consumeDye: !!dyeColor
53 })
54 };
55}
shared/definitions/armourItems.js +3 −0
@@ -142,6 +142,9 @@ function armourDef (itemId, tier, piece)
142 142 maxStackSize: 1,
143 143 uniqueInstance: false,
144 144 category: ItemCategory.finished,
145 /** Shared magenta icons under items/armour/{overlay}.png */
146 iconKey: "armour",
147 defaultState: piece.overlay,
145 148 tintFromTier: true,
146 149 equipment: Object.freeze(equipment)
147 150 });
@@ -142,6 +142,9 @@ function armourDef (itemId, tier, piece)
142 maxStackSize: 1,
142 maxStackSize: 1,
143 uniqueInstance: false,
143 uniqueInstance: false,
144 category: ItemCategory.finished,
144 category: ItemCategory.finished,
145 /** Shared magenta icons under items/armour/{overlay}.png */
146 iconKey: "armour",
147 defaultState: piece.overlay,
145 tintFromTier: true,
148 tintFromTier: true,
146 equipment: Object.freeze(equipment)
149 equipment: Object.freeze(equipment)
147 });
150 });
shared/definitions/clothItems.js added +270 −0
@@ -0,0 +1,270 @@
1 import { ItemCategory } from "./itemCategories.js";
2 import { EquipmentKind } from "./equipmentKinds.js";
3 import { equipImageName } from "./tileSprites.js";
4 import {
5 ClothTier,
6 CLOTH_TIER_ORDER,
7 CLOTH_DISPLAY_NAME,
8 tierMinSkillLevel
9 } from "./materialTiers.js";
10
11 /**
12 * Cloth family: raw fibre (wool sprite), yarn, woven cloth — shared magenta
13 * sprites under items/cloth/{wool,yarn,cloth}.png with per-tier tint.
14 * Cotton raw reuses CraftingItemId.wool (11); yarn/cloth reuse 12/25.
15 */
16 export const ClothItemId = Object.freeze({
17 cotton: 11,
18 cottonYarn: 12,
19 cottonCloth: 25,
20 wool: 133,
21 woolYarn: 134,
22 woolCloth: 135,
23 linen: 136,
24 linenYarn: 137,
25 linenCloth: 138,
26 cashmere: 139,
27 cashmereYarn: 140,
28 cashmereCloth: 141,
29 silk: 142,
30 silkYarn: 143,
31 silkCloth: 144,
32 fairySilk: 145,
33 fairySilkYarn: 146,
34 fairySilkCloth: 147,
35 dragonweave: 148,
36 dragonweaveYarn: 149,
37 dragonweaveCloth: 150,
38 cottonSweater: 151,
39 woolSweater: 152,
40 linenSweater: 153,
41 cashmereSweater: 154,
42 silkSweater: 155,
43 fairySilkSweater: 156,
44 dragonweaveSweater: 157
45 });
46
47 const RAW_ID = Object.freeze({
48 [ClothTier.cotton]: ClothItemId.cotton,
49 [ClothTier.wool]: ClothItemId.wool,
50 [ClothTier.linen]: ClothItemId.linen,
51 [ClothTier.cashmere]: ClothItemId.cashmere,
52 [ClothTier.silk]: ClothItemId.silk,
53 [ClothTier.fairySilk]: ClothItemId.fairySilk,
54 [ClothTier.dragonweave]: ClothItemId.dragonweave
55 });
56
57 const YARN_ID = Object.freeze({
58 [ClothTier.cotton]: ClothItemId.cottonYarn,
59 [ClothTier.wool]: ClothItemId.woolYarn,
60 [ClothTier.linen]: ClothItemId.linenYarn,
61 [ClothTier.cashmere]: ClothItemId.cashmereYarn,
62 [ClothTier.silk]: ClothItemId.silkYarn,
63 [ClothTier.fairySilk]: ClothItemId.fairySilkYarn,
64 [ClothTier.dragonweave]: ClothItemId.dragonweaveYarn
65 });
66
67 const CLOTH_ID = Object.freeze({
68 [ClothTier.cotton]: ClothItemId.cottonCloth,
69 [ClothTier.wool]: ClothItemId.woolCloth,
70 [ClothTier.linen]: ClothItemId.linenCloth,
71 [ClothTier.cashmere]: ClothItemId.cashmereCloth,
72 [ClothTier.silk]: ClothItemId.silkCloth,
73 [ClothTier.fairySilk]: ClothItemId.fairySilkCloth,
74 [ClothTier.dragonweave]: ClothItemId.dragonweaveCloth
75 });
76
77 const SWEATER_ID = Object.freeze({
78 [ClothTier.cotton]: ClothItemId.cottonSweater,
79 [ClothTier.wool]: ClothItemId.woolSweater,
80 [ClothTier.linen]: ClothItemId.linenSweater,
81 [ClothTier.cashmere]: ClothItemId.cashmereSweater,
82 [ClothTier.silk]: ClothItemId.silkSweater,
83 [ClothTier.fairySilk]: ClothItemId.fairySilkSweater,
84 [ClothTier.dragonweave]: ClothItemId.dragonweaveSweater
85 });
86
87 const DEFAULT_STACK = 99;
88
89 function rawLabel (tier)
90 {
91 if (tier === ClothTier.cotton)
92 { return "Cotton"; }
93 return CLOTH_DISPLAY_NAME[tier] ?? tier;
94 }
95
96 function fibreDef (itemId, tier, key)
97 {
98 const name = rawLabel(tier);
99 return Object.freeze({
100 itemId,
101 key,
102 displayName: name,
103 description: `Raw ${name.toLowerCase()} fibre. Spin into yarn at a spinning wheel.`,
104 seedValue: 2,
105 stackable: true,
106 maxStackSize: DEFAULT_STACK,
107 uniqueInstance: false,
108 category: ItemCategory.ingredient,
109 iconKey: "cloth",
110 defaultState: "wool",
111 tier,
112 tintFromTier: true
113 });
114 }
115
116 function yarnDef (itemId, tier, key)
117 {
118 const name = CLOTH_DISPLAY_NAME[tier] ?? tier;
119 return Object.freeze({
120 itemId,
121 key,
122 displayName: `${name} yarn`,
123 description: `Spun ${name.toLowerCase()} yarn. Weave into cloth at a loom, or knit garments at a tailor's bench.`,
124 seedValue: 3,
125 stackable: true,
126 maxStackSize: DEFAULT_STACK,
127 uniqueInstance: false,
128 category: ItemCategory.intermediate,
129 iconKey: "cloth",
130 defaultState: "yarn",
131 tier,
132 tintFromTier: true
133 });
134 }
135
136 function clothDef (itemId, tier, key)
137 {
138 const name = CLOTH_DISPLAY_NAME[tier] ?? tier;
139 return Object.freeze({
140 itemId,
141 key,
142 displayName: `${name} cloth`,
143 description: `Woven ${name.toLowerCase()} cloth for tailored garments.`,
144 seedValue: 4,
145 stackable: true,
146 maxStackSize: DEFAULT_STACK,
147 uniqueInstance: false,
148 category: ItemCategory.intermediate,
149 iconKey: "cloth",
150 defaultState: "cloth",
151 tier,
152 tintFromTier: true
153 });
154 }
155
156 function sweaterDef (itemId, tier, key)
157 {
158 const name = CLOTH_DISPLAY_NAME[tier] ?? tier;
159 return Object.freeze({
160 itemId,
161 key,
162 displayName: `${name} sweater`,
163 description: `A warm ${name.toLowerCase()} sweater. Mostly cosmetic for now; optional dye overrides the material colour.`,
164 seedValue: 10,
165 stackable: false,
166 maxStackSize: 1,
167 uniqueInstance: false,
168 category: ItemCategory.finished,
169 iconKey: "clothing",
170 defaultState: "sweater",
171 tier,
172 tintFromTier: true,
173 clothing: Object.freeze({ warm: true, style: true }),
174 equipment: Object.freeze({
175 slot: "chest",
176 tier,
177 kind: EquipmentKind.clothArmour,
178 bonus: 0,
179 minSkillLevel: tierMinSkillLevel(tier),
180 tintFromTier: true,
181 equipSprite: equipImageName("item", "clothing", "sweater")
182 })
183 });
184 }
185
186 function buildClothDefinitions ()
187 {
188 const defs = {};
189 for (const tier of CLOTH_TIER_ORDER)
190 {
191 const label = String(tier);
192 defs[RAW_ID[tier]] = fibreDef(RAW_ID[tier], tier, label === "fairySilk" ? "fairy-silk" : label);
193 defs[YARN_ID[tier]] = yarnDef(
194 YARN_ID[tier],
195 tier,
196 `${label === "fairySilk" ? "fairy-silk" : label}-yarn`
197 );
198 defs[CLOTH_ID[tier]] = clothDef(
199 CLOTH_ID[tier],
200 tier,
201 `${label === "fairySilk" ? "fairy-silk" : label}-cloth`
202 );
203 defs[SWEATER_ID[tier]] = sweaterDef(
204 SWEATER_ID[tier],
205 tier,
206 `${label === "fairySilk" ? "fairy-silk" : label}-sweater`
207 );
208 }
209 // Prefer display key "cotton" for the plant fibre.
210 defs[ClothItemId.cotton] = fibreDef(ClothItemId.cotton, ClothTier.cotton, "cotton");
211 return Object.freeze(defs);
212 }
213
214 export const CLOTH_ITEM_DEFINITIONS = buildClothDefinitions();
215
216 export function rawClothItemId (tier)
217 {
218 return RAW_ID[tier] ?? null;
219 }
220
221 export function yarnItemId (tier)
222 {
223 return YARN_ID[tier] ?? null;
224 }
225
226 export function wovenClothItemId (tier)
227 {
228 return CLOTH_ID[tier] ?? null;
229 }
230
231 export function sweaterItemId (tier)
232 {
233 return SWEATER_ID[tier] ?? null;
234 }
235
236 export function clothTierForItemId (itemId)
237 {
238 for (const tier of CLOTH_TIER_ORDER)
239 {
240 if (RAW_ID[tier] === itemId || YARN_ID[tier] === itemId
241 || CLOTH_ID[tier] === itemId || SWEATER_ID[tier] === itemId)
242 { return tier; }
243 }
244 return null;
245 }
246
247 /** Tailor garment templates (UI + recipes). */
248 export const CLOTHING_TEMPLATES = Object.freeze({
249 sweater: Object.freeze({
250 templateId: "sweater",
251 displayName: "Sweater",
252 slot: "chest",
253 warm: true,
254 inputs: Object.freeze([{ kind: "yarn", quantity: 3 }]),
255 outputItemIdForTier: sweaterItemId,
256 minSkillLevel: 1
257 })
258 });
259
260 export function clothingTemplate (templateId)
261 {
262 return CLOTHING_TEMPLATES[templateId] ?? null;
263 }
264
265 export function listClothingTemplates ()
266 {
267 return Object.values(CLOTHING_TEMPLATES);
268 }
269
270 export { tierMinSkillLevel };
@@ -0,0 +1,270 @@
1import { ItemCategory } from "./itemCategories.js";
2import { EquipmentKind } from "./equipmentKinds.js";
3import { equipImageName } from "./tileSprites.js";
4import {
5 ClothTier,
6 CLOTH_TIER_ORDER,
7 CLOTH_DISPLAY_NAME,
8 tierMinSkillLevel
9} from "./materialTiers.js";
10
11/**
12 * Cloth family: raw fibre (wool sprite), yarn, woven cloth — shared magenta
13 * sprites under items/cloth/{wool,yarn,cloth}.png with per-tier tint.
14 * Cotton raw reuses CraftingItemId.wool (11); yarn/cloth reuse 12/25.
15 */
16export const ClothItemId = Object.freeze({
17 cotton: 11,
18 cottonYarn: 12,
19 cottonCloth: 25,
20 wool: 133,
21 woolYarn: 134,
22 woolCloth: 135,
23 linen: 136,
24 linenYarn: 137,
25 linenCloth: 138,
26 cashmere: 139,
27 cashmereYarn: 140,
28 cashmereCloth: 141,
29 silk: 142,
30 silkYarn: 143,
31 silkCloth: 144,
32 fairySilk: 145,
33 fairySilkYarn: 146,
34 fairySilkCloth: 147,
35 dragonweave: 148,
36 dragonweaveYarn: 149,
37 dragonweaveCloth: 150,
38 cottonSweater: 151,
39 woolSweater: 152,
40 linenSweater: 153,
41 cashmereSweater: 154,
42 silkSweater: 155,
43 fairySilkSweater: 156,
44 dragonweaveSweater: 157
45});
46
47const RAW_ID = Object.freeze({
48 [ClothTier.cotton]: ClothItemId.cotton,
49 [ClothTier.wool]: ClothItemId.wool,
50 [ClothTier.linen]: ClothItemId.linen,
51 [ClothTier.cashmere]: ClothItemId.cashmere,
52 [ClothTier.silk]: ClothItemId.silk,
53 [ClothTier.fairySilk]: ClothItemId.fairySilk,
54 [ClothTier.dragonweave]: ClothItemId.dragonweave
55});
56
57const YARN_ID = Object.freeze({
58 [ClothTier.cotton]: ClothItemId.cottonYarn,
59 [ClothTier.wool]: ClothItemId.woolYarn,
60 [ClothTier.linen]: ClothItemId.linenYarn,
61 [ClothTier.cashmere]: ClothItemId.cashmereYarn,
62 [ClothTier.silk]: ClothItemId.silkYarn,
63 [ClothTier.fairySilk]: ClothItemId.fairySilkYarn,
64 [ClothTier.dragonweave]: ClothItemId.dragonweaveYarn
65});
66
67const CLOTH_ID = Object.freeze({
68 [ClothTier.cotton]: ClothItemId.cottonCloth,
69 [ClothTier.wool]: ClothItemId.woolCloth,
70 [ClothTier.linen]: ClothItemId.linenCloth,
71 [ClothTier.cashmere]: ClothItemId.cashmereCloth,
72 [ClothTier.silk]: ClothItemId.silkCloth,
73 [ClothTier.fairySilk]: ClothItemId.fairySilkCloth,
74 [ClothTier.dragonweave]: ClothItemId.dragonweaveCloth
75});
76
77const SWEATER_ID = Object.freeze({
78 [ClothTier.cotton]: ClothItemId.cottonSweater,
79 [ClothTier.wool]: ClothItemId.woolSweater,
80 [ClothTier.linen]: ClothItemId.linenSweater,
81 [ClothTier.cashmere]: ClothItemId.cashmereSweater,
82 [ClothTier.silk]: ClothItemId.silkSweater,
83 [ClothTier.fairySilk]: ClothItemId.fairySilkSweater,
84 [ClothTier.dragonweave]: ClothItemId.dragonweaveSweater
85});
86
87const DEFAULT_STACK = 99;
88
89function rawLabel (tier)
90{
91 if (tier === ClothTier.cotton)
92 { return "Cotton"; }
93 return CLOTH_DISPLAY_NAME[tier] ?? tier;
94}
95
96function fibreDef (itemId, tier, key)
97{
98 const name = rawLabel(tier);
99 return Object.freeze({
100 itemId,
101 key,
102 displayName: name,
103 description: `Raw ${name.toLowerCase()} fibre. Spin into yarn at a spinning wheel.`,
104 seedValue: 2,
105 stackable: true,
106 maxStackSize: DEFAULT_STACK,
107 uniqueInstance: false,
108 category: ItemCategory.ingredient,
109 iconKey: "cloth",
110 defaultState: "wool",
111 tier,
112 tintFromTier: true
113 });
114}
115
116function yarnDef (itemId, tier, key)
117{
118 const name = CLOTH_DISPLAY_NAME[tier] ?? tier;
119 return Object.freeze({
120 itemId,
121 key,
122 displayName: `${name} yarn`,
123 description: `Spun ${name.toLowerCase()} yarn. Weave into cloth at a loom, or knit garments at a tailor's bench.`,
124 seedValue: 3,
125 stackable: true,
126 maxStackSize: DEFAULT_STACK,
127 uniqueInstance: false,
128 category: ItemCategory.intermediate,
129 iconKey: "cloth",
130 defaultState: "yarn",
131 tier,
132 tintFromTier: true
133 });
134}
135
136function clothDef (itemId, tier, key)
137{
138 const name = CLOTH_DISPLAY_NAME[tier] ?? tier;
139 return Object.freeze({
140 itemId,
141 key,
142 displayName: `${name} cloth`,
143 description: `Woven ${name.toLowerCase()} cloth for tailored garments.`,
144 seedValue: 4,
145 stackable: true,
146 maxStackSize: DEFAULT_STACK,
147 uniqueInstance: false,
148 category: ItemCategory.intermediate,
149 iconKey: "cloth",
150 defaultState: "cloth",
151 tier,
152 tintFromTier: true
153 });
154}
155
156function sweaterDef (itemId, tier, key)
157{
158 const name = CLOTH_DISPLAY_NAME[tier] ?? tier;
159 return Object.freeze({
160 itemId,
161 key,
162 displayName: `${name} sweater`,
163 description: `A warm ${name.toLowerCase()} sweater. Mostly cosmetic for now; optional dye overrides the material colour.`,
164 seedValue: 10,
165 stackable: false,
166 maxStackSize: 1,
167 uniqueInstance: false,
168 category: ItemCategory.finished,
169 iconKey: "clothing",
170 defaultState: "sweater",
171 tier,
172 tintFromTier: true,
173 clothing: Object.freeze({ warm: true, style: true }),
174 equipment: Object.freeze({
175 slot: "chest",
176 tier,
177 kind: EquipmentKind.clothArmour,
178 bonus: 0,
179 minSkillLevel: tierMinSkillLevel(tier),
180 tintFromTier: true,
181 equipSprite: equipImageName("item", "clothing", "sweater")
182 })
183 });
184}
185
186function buildClothDefinitions ()
187{
188 const defs = {};
189 for (const tier of CLOTH_TIER_ORDER)
190 {
191 const label = String(tier);
192 defs[RAW_ID[tier]] = fibreDef(RAW_ID[tier], tier, label === "fairySilk" ? "fairy-silk" : label);
193 defs[YARN_ID[tier]] = yarnDef(
194 YARN_ID[tier],
195 tier,
196 `${label === "fairySilk" ? "fairy-silk" : label}-yarn`
197 );
198 defs[CLOTH_ID[tier]] = clothDef(
199 CLOTH_ID[tier],
200 tier,
201 `${label === "fairySilk" ? "fairy-silk" : label}-cloth`
202 );
203 defs[SWEATER_ID[tier]] = sweaterDef(
204 SWEATER_ID[tier],
205 tier,
206 `${label === "fairySilk" ? "fairy-silk" : label}-sweater`
207 );
208 }
209 // Prefer display key "cotton" for the plant fibre.
210 defs[ClothItemId.cotton] = fibreDef(ClothItemId.cotton, ClothTier.cotton, "cotton");
211 return Object.freeze(defs);
212}
213
214export const CLOTH_ITEM_DEFINITIONS = buildClothDefinitions();
215
216export function rawClothItemId (tier)
217{
218 return RAW_ID[tier] ?? null;
219}
220
221export function yarnItemId (tier)
222{
223 return YARN_ID[tier] ?? null;
224}
225
226export function wovenClothItemId (tier)
227{
228 return CLOTH_ID[tier] ?? null;
229}
230
231export function sweaterItemId (tier)
232{
233 return SWEATER_ID[tier] ?? null;
234}
235
236export function clothTierForItemId (itemId)
237{
238 for (const tier of CLOTH_TIER_ORDER)
239 {
240 if (RAW_ID[tier] === itemId || YARN_ID[tier] === itemId
241 || CLOTH_ID[tier] === itemId || SWEATER_ID[tier] === itemId)
242 { return tier; }
243 }
244 return null;
245}
246
247/** Tailor garment templates (UI + recipes). */
248export const CLOTHING_TEMPLATES = Object.freeze({
249 sweater: Object.freeze({
250 templateId: "sweater",
251 displayName: "Sweater",
252 slot: "chest",
253 warm: true,
254 inputs: Object.freeze([{ kind: "yarn", quantity: 3 }]),
255 outputItemIdForTier: sweaterItemId,
256 minSkillLevel: 1
257 })
258});
259
260export function clothingTemplate (templateId)
261{
262 return CLOTHING_TEMPLATES[templateId] ?? null;
263}
264
265export function listClothingTemplates ()
266{
267 return Object.values(CLOTHING_TEMPLATES);
268}
269
270export { tierMinSkillLevel };
shared/definitions/craftingItems.js +1 −12
@@ -7,11 +7,10 @@ const DEFAULT_STACK = 99;
7 7 /**
8 8 * Reserved numeric IDs for gathering, crafting, and cooking content (9–25).
9 9 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
10 * IDs 11 / 12 / 25 are cotton fibre / yarn / cloth (see clothItems.js).
10 11 */
11 12 export const CraftingItemId = Object.freeze({
12 13 tinderbox: 10,
13 wool: 11,
14 thread: 12,
15 14 copperOre: 13,
16 15 bronzeBar: 14,
17 16 rawMeat: 15,
@@ -24,7 +23,6 @@ export const CraftingItemId = Object.freeze({
24 23 fishingRod: 22,
25 24 fishingNet: 23,
26 25 rawFish: 24,
27 cloth: 25,
28 26 tinOre: 53
29 27 });
30 28
@@ -53,12 +51,6 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
53 51 maxStackSize: 1,
54 52 description: "Lights campfires from dropped logs."
55 53 }),
56 [CraftingItemId.wool]: stub(CraftingItemId.wool, "wool", "Wool", ItemCategory.ingredient, {
57 description: "Shorn from sheep. Spin into thread at a spinning wheel."
58 }),
59 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
60 description: "Spun wool. Used at a loom."
61 }),
62 54 [CraftingItemId.copperOre]: Object.freeze({
63 55 itemId: CraftingItemId.copperOre,
64 56 key: "copper-ore",
@@ -169,8 +161,5 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
169 161 }),
170 162 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
171 163 description: "Caught fish. Cook like raw meat."
172 }),
173 [CraftingItemId.cloth]: stub(CraftingItemId.cloth, "cloth", "Cloth", ItemCategory.intermediate, {
174 description: "Woven fabric. Tailor into clothing at a loom."
175 164 })
176 165 });
@@ -7,11 +7,10 @@ const DEFAULT_STACK = 99;
7/**
7/**
8 * Reserved numeric IDs for gathering, crafting, and cooking content (9–25).
8 * Reserved numeric IDs for gathering, crafting, and cooking content (9–25).
9 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
9 * Metal ores/bars/pickaxes above bronze live in metalItems.js (35+).
10 * IDs 11 / 12 / 25 are cotton fibre / yarn / cloth (see clothItems.js).
10 */
11 */
11export const CraftingItemId = Object.freeze({
12export const CraftingItemId = Object.freeze({
12 tinderbox: 10,
13 tinderbox: 10,
13 wool: 11,
14 thread: 12,
15 copperOre: 13,
14 copperOre: 13,
16 bronzeBar: 14,
15 bronzeBar: 14,
17 rawMeat: 15,
16 rawMeat: 15,
@@ -24,7 +23,6 @@ export const CraftingItemId = Object.freeze({
24 fishingRod: 22,
23 fishingRod: 22,
25 fishingNet: 23,
24 fishingNet: 23,
26 rawFish: 24,
25 rawFish: 24,
27 cloth: 25,
28 tinOre: 53
26 tinOre: 53
29});
27});
30
28
@@ -53,12 +51,6 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
53 maxStackSize: 1,
51 maxStackSize: 1,
54 description: "Lights campfires from dropped logs."
52 description: "Lights campfires from dropped logs."
55 }),
53 }),
56 [CraftingItemId.wool]: stub(CraftingItemId.wool, "wool", "Wool", ItemCategory.ingredient, {
57 description: "Shorn from sheep. Spin into thread at a spinning wheel."
58 }),
59 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
60 description: "Spun wool. Used at a loom."
61 }),
62 [CraftingItemId.copperOre]: Object.freeze({
54 [CraftingItemId.copperOre]: Object.freeze({
63 itemId: CraftingItemId.copperOre,
55 itemId: CraftingItemId.copperOre,
64 key: "copper-ore",
56 key: "copper-ore",
@@ -169,8 +161,5 @@ export const CRAFTING_ITEM_STUBS = Object.freeze({
169 }),
161 }),
170 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
162 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
171 description: "Caught fish. Cook like raw meat."
163 description: "Caught fish. Cook like raw meat."
172 }),
173 [CraftingItemId.cloth]: stub(CraftingItemId.cloth, "cloth", "Cloth", ItemCategory.intermediate, {
174 description: "Woven fabric. Tailor into clothing at a loom."
175 })
164 })
176});
165});
shared/definitions/craftingStations.js +9 −2
@@ -9,6 +9,7 @@ export const CraftingStationId = Object.freeze({
9 9 leatherworkingStation: "leatherworking-station",
10 10 craftingBench: "crafting-bench",
11 11 woodworkingBench: "woodworking-bench",
12 tailorBench: "tailor-bench",
12 13 oven: "oven",
13 14 fireplace: "fireplace"
14 15 });
@@ -30,13 +31,19 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
30 31 stationId: CraftingStationId.spinningWheel,
31 32 displayName: "Spinning wheel",
32 33 skillId: SkillId.tailoring,
33 description: "Spin wool (from shorn sheep) into thread."
34 description: "Spin raw fibre into yarn."
34 35 }),
35 36 [CraftingStationId.loom]: Object.freeze({
36 37 stationId: CraftingStationId.loom,
37 38 displayName: "Loom",
38 39 skillId: SkillId.tailoring,
39 description: "Weave cloth garments."
40 description: "Weave yarn into cloth."
41 }),
42 [CraftingStationId.tailorBench]: Object.freeze({
43 stationId: CraftingStationId.tailorBench,
44 displayName: "Tailor's bench",
45 skillId: SkillId.tailoring,
46 description: "Sew garments from yarn or cloth. Optional dye colours the result."
40 47 }),
41 48 [CraftingStationId.anvil]: Object.freeze({
42 49 stationId: CraftingStationId.anvil,
@@ -9,6 +9,7 @@ export const CraftingStationId = Object.freeze({
9 leatherworkingStation: "leatherworking-station",
9 leatherworkingStation: "leatherworking-station",
10 craftingBench: "crafting-bench",
10 craftingBench: "crafting-bench",
11 woodworkingBench: "woodworking-bench",
11 woodworkingBench: "woodworking-bench",
12 tailorBench: "tailor-bench",
12 oven: "oven",
13 oven: "oven",
13 fireplace: "fireplace"
14 fireplace: "fireplace"
14});
15});
@@ -30,13 +31,19 @@ export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
30 stationId: CraftingStationId.spinningWheel,
31 stationId: CraftingStationId.spinningWheel,
31 displayName: "Spinning wheel",
32 displayName: "Spinning wheel",
32 skillId: SkillId.tailoring,
33 skillId: SkillId.tailoring,
33 description: "Spin wool (from shorn sheep) into thread."
34 description: "Spin raw fibre into yarn."
34 }),
35 }),
35 [CraftingStationId.loom]: Object.freeze({
36 [CraftingStationId.loom]: Object.freeze({
36 stationId: CraftingStationId.loom,
37 stationId: CraftingStationId.loom,
37 displayName: "Loom",
38 displayName: "Loom",
38 skillId: SkillId.tailoring,
39 skillId: SkillId.tailoring,
39 description: "Weave cloth garments."
40 description: "Weave yarn into cloth."
41 }),
42 [CraftingStationId.tailorBench]: Object.freeze({
43 stationId: CraftingStationId.tailorBench,
44 displayName: "Tailor's bench",
45 skillId: SkillId.tailoring,
46 description: "Sew garments from yarn or cloth. Optional dye colours the result."
40 }),
47 }),
41 [CraftingStationId.anvil]: Object.freeze({
48 [CraftingStationId.anvil]: Object.freeze({
42 stationId: CraftingStationId.anvil,
49 stationId: CraftingStationId.anvil,
shared/definitions/dyes.js added +208 −0
@@ -0,0 +1,208 @@
1 import { rgb } from "./materialTiers.js";
2 import { ItemCategory } from "./itemCategories.js";
3 import { POTION_MAX_STACK } from "./alchemy.js";
4
5 /** Flower / dye palette (paint-style mixing). */
6 export const FlowerColorId = Object.freeze({
7 red: "red",
8 blue: "blue",
9 cyan: "cyan",
10 violet: "violet",
11 yellow: "yellow",
12 magenta: "magenta",
13 white: "white",
14 black: "black",
15 pink: "pink"
16 });
17
18 export const FLOWER_COLOR_ORDER = Object.freeze([
19 FlowerColorId.red,
20 FlowerColorId.blue,
21 FlowerColorId.cyan,
22 FlowerColorId.violet,
23 FlowerColorId.yellow,
24 FlowerColorId.magenta,
25 FlowerColorId.white,
26 FlowerColorId.black,
27 FlowerColorId.pink
28 ]);
29
30 export const FLOWER_COLOR_RGB = Object.freeze({
31 [FlowerColorId.red]: rgb(220, 40, 40),
32 [FlowerColorId.blue]: rgb(40, 80, 220),
33 [FlowerColorId.cyan]: rgb(40, 200, 220),
34 [FlowerColorId.violet]: rgb(140, 50, 200),
35 [FlowerColorId.yellow]: rgb(240, 210, 40),
36 [FlowerColorId.magenta]: rgb(220, 40, 180),
37 [FlowerColorId.white]: rgb(245, 245, 250),
38 [FlowerColorId.black]: rgb(28, 28, 32),
39 [FlowerColorId.pink]: rgb(255, 140, 180)
40 });
41
42 export const FLOWER_COLOR_DISPLAY = Object.freeze({
43 [FlowerColorId.red]: "Red",
44 [FlowerColorId.blue]: "Blue",
45 [FlowerColorId.cyan]: "Cyan",
46 [FlowerColorId.violet]: "Violet",
47 [FlowerColorId.yellow]: "Yellow",
48 [FlowerColorId.magenta]: "Magenta",
49 [FlowerColorId.white]: "White",
50 [FlowerColorId.black]: "Black",
51 [FlowerColorId.pink]: "Pink"
52 });
53
54 /** Item IDs for flower petals and bottled dye (potion-look). */
55 export const DyeItemId = Object.freeze({
56 flower: 158,
57 dye: 159
58 });
59
60 export const DEFAULT_DYE_FILL = 4;
61
62 export function flowerColorRgb (colorId)
63 {
64 return FLOWER_COLOR_RGB[colorId] ?? FLOWER_COLOR_RGB[FlowerColorId.white];
65 }
66
67 export function randomFlowerColorId (rng = Math.random)
68 {
69 const index = Math.floor(rng() * FLOWER_COLOR_ORDER.length) % FLOWER_COLOR_ORDER.length;
70 return FLOWER_COLOR_ORDER[index];
71 }
72
73 export function flowerItemInstance (colorId)
74 {
75 const id = FLOWER_COLOR_ORDER.includes(colorId) ? colorId : FlowerColorId.white;
76 const color = flowerColorRgb(id);
77 return Object.freeze({
78 kind: "flower",
79 colorId: id,
80 color: Object.freeze({ r: color.r, g: color.g, b: color.b })
81 });
82 }
83
84 export function dyeItemInstance (color, fillLevel = DEFAULT_DYE_FILL, colorId = null)
85 {
86 const fill = Math.max(1, Math.min(5, fillLevel | 0 || DEFAULT_DYE_FILL));
87 return Object.freeze({
88 kind: "dye",
89 colorId: colorId ?? null,
90 color: Object.freeze({
91 r: Number(color?.r) || 0,
92 g: Number(color?.g) || 0,
93 b: Number(color?.b) || 0
94 }),
95 fillLevel: fill
96 });
97 }
98
99 /**
100 * Paint-style mix of two dye colours weighted by fill contribution.
101 * Output bottle count = sum of inserted dye bottles. Total fill is poured
102 * sequentially (fill to 5, overflow into the next bottle, …).
103 */
104 export function mixDyeBatches (batches)
105 {
106 const rows = (batches ?? []).filter((row) => row?.instance?.kind === "dye");
107 if (rows.length < 2)
108 { return { ok: false, reason: "Need two different dye colours to mix." }; }
109
110 const byColor = new Map();
111 for (const row of rows)
112 {
113 const key = colorKey(row.instance.color);
114 const qty = Math.max(1, row.quantity | 0);
115 const fill = Math.max(1, Math.min(5, row.instance.fillLevel | 0 || DEFAULT_DYE_FILL));
116 const prev = byColor.get(key) ?? { color: row.instance.color, quantity: 0, fillUnits: 0 };
117 prev.quantity += qty;
118 prev.fillUnits += qty * fill;
119 byColor.set(key, prev);
120 }
121 if (byColor.size < 2)
122 { return { ok: false, reason: "Need two different dye colours to mix." }; }
123 if (byColor.size > 2)
124 { return { ok: false, reason: "Mix exactly two dye colours at a time." }; }
125
126 let totalQty = 0;
127 let totalFill = 0;
128 let mixR = 0;
129 let mixG = 0;
130 let mixB = 0;
131 for (const entry of byColor.values())
132 {
133 totalQty += entry.quantity;
134 totalFill += entry.fillUnits;
135 mixR += entry.color.r * entry.fillUnits;
136 mixG += entry.color.g * entry.fillUnits;
137 mixB += entry.color.b * entry.fillUnits;
138 }
139 if (totalFill <= 0 || totalQty <= 0)
140 { return { ok: false, reason: "Nothing to mix." }; }
141
142 const color = Object.freeze({
143 r: mixR / totalFill,
144 g: mixG / totalFill,
145 b: mixB / totalFill
146 });
147
148 // Prefer ceil(fill/5) bottles when fill would overflow the input bottle count.
149 const packedBottles = Math.max(totalQty, Math.ceil(totalFill / 5));
150 const outputs = [];
151 let remaining = totalFill;
152 for (let i = 0; i < packedBottles; i++)
153 {
154 const bottlesLeft = packedBottles - i;
155 const fillLevel = Math.max(1, Math.min(5, remaining - (bottlesLeft - 1)));
156 remaining -= fillLevel;
157 outputs.push({
158 quantity: 1,
159 instance: dyeItemInstance(color, fillLevel)
160 });
161 }
162 return {
163 ok: true,
164 outputs,
165 color,
166 quantity: packedBottles,
167 extraBottles: Math.max(0, packedBottles - totalQty)
168 };
169 }
170
171 function colorKey (color)
172 {
173 return [
174 Math.round((color?.r ?? 0) * 1000),
175 Math.round((color?.g ?? 0) * 1000),
176 Math.round((color?.b ?? 0) * 1000)
177 ].join(",");
178 }
179
180 export const FLOWER_ITEM_DEFINITION = Object.freeze({
181 itemId: DyeItemId.flower,
182 key: "flower",
183 displayName: "Flower",
184 description: "A colourful flower. Brew into dye at a cauldron.",
185 seedValue: 2,
186 stackable: true,
187 maxStackSize: 99,
188 uniqueInstance: false,
189 category: ItemCategory.ingredient,
190 iconKey: "flower",
191 defaultState: "flower",
192 flower: true
193 });
194
195 export const DYE_ITEM_DEFINITION = Object.freeze({
196 itemId: DyeItemId.dye,
197 key: "dye",
198 displayName: "Dye",
199 description: "Bottled dye for cloth and clothing. Mix colours in a cauldron.",
200 seedValue: 4,
201 stackable: true,
202 maxStackSize: POTION_MAX_STACK,
203 uniqueInstance: false,
204 category: ItemCategory.ingredient,
205 iconKey: "potion",
206 defaultState: "potion",
207 dye: true
208 });
@@ -0,0 +1,208 @@
1import { rgb } from "./materialTiers.js";
2import { ItemCategory } from "./itemCategories.js";
3import { POTION_MAX_STACK } from "./alchemy.js";
4
5/** Flower / dye palette (paint-style mixing). */
6export const FlowerColorId = Object.freeze({
7 red: "red",
8 blue: "blue",
9 cyan: "cyan",
10 violet: "violet",
11 yellow: "yellow",
12 magenta: "magenta",
13 white: "white",
14 black: "black",
15 pink: "pink"
16});
17
18export const FLOWER_COLOR_ORDER = Object.freeze([
19 FlowerColorId.red,
20 FlowerColorId.blue,
21 FlowerColorId.cyan,
22 FlowerColorId.violet,
23 FlowerColorId.yellow,
24 FlowerColorId.magenta,
25 FlowerColorId.white,
26 FlowerColorId.black,
27 FlowerColorId.pink
28]);
29
30export const FLOWER_COLOR_RGB = Object.freeze({
31 [FlowerColorId.red]: rgb(220, 40, 40),
32 [FlowerColorId.blue]: rgb(40, 80, 220),
33 [FlowerColorId.cyan]: rgb(40, 200, 220),
34 [FlowerColorId.violet]: rgb(140, 50, 200),
35 [FlowerColorId.yellow]: rgb(240, 210, 40),
36 [FlowerColorId.magenta]: rgb(220, 40, 180),
37 [FlowerColorId.white]: rgb(245, 245, 250),
38 [FlowerColorId.black]: rgb(28, 28, 32),
39 [FlowerColorId.pink]: rgb(255, 140, 180)
40});
41
42export const FLOWER_COLOR_DISPLAY = Object.freeze({
43 [FlowerColorId.red]: "Red",
44 [FlowerColorId.blue]: "Blue",
45 [FlowerColorId.cyan]: "Cyan",
46 [FlowerColorId.violet]: "Violet",
47 [FlowerColorId.yellow]: "Yellow",
48 [FlowerColorId.magenta]: "Magenta",
49 [FlowerColorId.white]: "White",
50 [FlowerColorId.black]: "Black",
51 [FlowerColorId.pink]: "Pink"
52});
53
54/** Item IDs for flower petals and bottled dye (potion-look). */
55export const DyeItemId = Object.freeze({
56 flower: 158,
57 dye: 159
58});
59
60export const DEFAULT_DYE_FILL = 4;
61
62export function flowerColorRgb (colorId)
63{
64 return FLOWER_COLOR_RGB[colorId] ?? FLOWER_COLOR_RGB[FlowerColorId.white];
65}
66
67export function randomFlowerColorId (rng = Math.random)
68{
69 const index = Math.floor(rng() * FLOWER_COLOR_ORDER.length) % FLOWER_COLOR_ORDER.length;
70 return FLOWER_COLOR_ORDER[index];
71}
72
73export function flowerItemInstance (colorId)
74{
75 const id = FLOWER_COLOR_ORDER.includes(colorId) ? colorId : FlowerColorId.white;
76 const color = flowerColorRgb(id);
77 return Object.freeze({
78 kind: "flower",
79 colorId: id,
80 color: Object.freeze({ r: color.r, g: color.g, b: color.b })
81 });
82}
83
84export function dyeItemInstance (color, fillLevel = DEFAULT_DYE_FILL, colorId = null)
85{
86 const fill = Math.max(1, Math.min(5, fillLevel | 0 || DEFAULT_DYE_FILL));
87 return Object.freeze({
88 kind: "dye",
89 colorId: colorId ?? null,
90 color: Object.freeze({
91 r: Number(color?.r) || 0,
92 g: Number(color?.g) || 0,
93 b: Number(color?.b) || 0
94 }),
95 fillLevel: fill
96 });
97}
98
99/**
100 * Paint-style mix of two dye colours weighted by fill contribution.
101 * Output bottle count = sum of inserted dye bottles. Total fill is poured
102 * sequentially (fill to 5, overflow into the next bottle, …).
103 */
104export function mixDyeBatches (batches)
105{
106 const rows = (batches ?? []).filter((row) => row?.instance?.kind === "dye");
107 if (rows.length < 2)
108 { return { ok: false, reason: "Need two different dye colours to mix." }; }
109
110 const byColor = new Map();
111 for (const row of rows)
112 {
113 const key = colorKey(row.instance.color);
114 const qty = Math.max(1, row.quantity | 0);
115 const fill = Math.max(1, Math.min(5, row.instance.fillLevel | 0 || DEFAULT_DYE_FILL));
116 const prev = byColor.get(key) ?? { color: row.instance.color, quantity: 0, fillUnits: 0 };
117 prev.quantity += qty;
118 prev.fillUnits += qty * fill;
119 byColor.set(key, prev);
120 }
121 if (byColor.size < 2)
122 { return { ok: false, reason: "Need two different dye colours to mix." }; }
123 if (byColor.size > 2)
124 { return { ok: false, reason: "Mix exactly two dye colours at a time." }; }
125
126 let totalQty = 0;
127 let totalFill = 0;
128 let mixR = 0;
129 let mixG = 0;
130 let mixB = 0;
131 for (const entry of byColor.values())
132 {
133 totalQty += entry.quantity;
134 totalFill += entry.fillUnits;
135 mixR += entry.color.r * entry.fillUnits;
136 mixG += entry.color.g * entry.fillUnits;
137 mixB += entry.color.b * entry.fillUnits;
138 }
139 if (totalFill <= 0 || totalQty <= 0)
140 { return { ok: false, reason: "Nothing to mix." }; }
141
142 const color = Object.freeze({
143 r: mixR / totalFill,
144 g: mixG / totalFill,
145 b: mixB / totalFill
146 });
147
148 // Prefer ceil(fill/5) bottles when fill would overflow the input bottle count.
149 const packedBottles = Math.max(totalQty, Math.ceil(totalFill / 5));
150 const outputs = [];
151 let remaining = totalFill;
152 for (let i = 0; i < packedBottles; i++)
153 {
154 const bottlesLeft = packedBottles - i;
155 const fillLevel = Math.max(1, Math.min(5, remaining - (bottlesLeft - 1)));
156 remaining -= fillLevel;
157 outputs.push({
158 quantity: 1,
159 instance: dyeItemInstance(color, fillLevel)
160 });
161 }
162 return {
163 ok: true,
164 outputs,
165 color,
166 quantity: packedBottles,
167 extraBottles: Math.max(0, packedBottles - totalQty)
168 };
169}
170
171function colorKey (color)
172{
173 return [
174 Math.round((color?.r ?? 0) * 1000),
175 Math.round((color?.g ?? 0) * 1000),
176 Math.round((color?.b ?? 0) * 1000)
177 ].join(",");
178}
179
180export const FLOWER_ITEM_DEFINITION = Object.freeze({
181 itemId: DyeItemId.flower,
182 key: "flower",
183 displayName: "Flower",
184 description: "A colourful flower. Brew into dye at a cauldron.",
185 seedValue: 2,
186 stackable: true,
187 maxStackSize: 99,
188 uniqueInstance: false,
189 category: ItemCategory.ingredient,
190 iconKey: "flower",
191 defaultState: "flower",
192 flower: true
193});
194
195export const DYE_ITEM_DEFINITION = Object.freeze({
196 itemId: DyeItemId.dye,
197 key: "dye",
198 displayName: "Dye",
199 description: "Bottled dye for cloth and clothing. Mix colours in a cauldron.",
200 seedValue: 4,
201 stackable: true,
202 maxStackSize: POTION_MAX_STACK,
203 uniqueInstance: false,
204 category: ItemCategory.ingredient,
205 iconKey: "potion",
206 defaultState: "potion",
207 dye: true
208});
shared/definitions/gathering.js +31 −0
@@ -212,6 +212,37 @@ export function resolveWoodcuttingAxe ({ inventorySlots, equipmentSlots, skills,
212 212 return { ok: true, tool: usable[0] };
213 213 }
214 214
215 /**
216 * Best plant clippers for herbalism nodes (flowers). Cotton needs no tool.
217 * @returns {{ ok: true, tool: object|null } | { ok: false, reason: string }}
218 */
219 export function resolvePlantClippers ({ inventorySlots, equipmentSlots, skills, requireTool = true })
220 {
221 if (!requireTool)
222 { return { ok: true, tool: null }; }
223 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.plantClippers)
224 .filter((tool) => canEquipItem(skills, tool.def).ok)
225 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
226 if (!tools.length)
227 { return { ok: false, reason: "You need plant clippers to gather this!" }; }
228 return { ok: true, tool: tools[0] };
229 }
230
231 /** Herbalism gather duration (short; clippers reduce slightly). */
232 export function herbalismDurationMs (toolTier = null)
233 {
234 const rank = toolTier ? tierRank(toolTier) : 1;
235 return Math.max(500, 2500 - (rank - 1) * 250);
236 }
237
238 export function herbalismXpForPick (kind)
239 {
240 return kind === "flower" ? 4 : 3;
241 }
242
243 /** Plant node exhaust then respawn (ms). */
244 export const PLANT_EXHAUST_MS = 15_000;
245
215 246 /** Craft duration: furnace recipes scale by bar tier; others use the fixed craft duration. */
216 247 export function craftDurationMs (recipe, fallbackMs = 2000)
217 248 {
@@ -212,6 +212,37 @@ export function resolveWoodcuttingAxe ({ inventorySlots, equipmentSlots, skills,
212 return { ok: true, tool: usable[0] };
212 return { ok: true, tool: usable[0] };
213}
213}
214
214
215/**
216 * Best plant clippers for herbalism nodes (flowers). Cotton needs no tool.
217 * @returns {{ ok: true, tool: object|null } | { ok: false, reason: string }}
218 */
219export function resolvePlantClippers ({ inventorySlots, equipmentSlots, skills, requireTool = true })
220{
221 if (!requireTool)
222 { return { ok: true, tool: null }; }
223 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.plantClippers)
224 .filter((tool) => canEquipItem(skills, tool.def).ok)
225 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
226 if (!tools.length)
227 { return { ok: false, reason: "You need plant clippers to gather this!" }; }
228 return { ok: true, tool: tools[0] };
229}
230
231/** Herbalism gather duration (short; clippers reduce slightly). */
232export function herbalismDurationMs (toolTier = null)
233{
234 const rank = toolTier ? tierRank(toolTier) : 1;
235 return Math.max(500, 2500 - (rank - 1) * 250);
236}
237
238export function herbalismXpForPick (kind)
239{
240 return kind === "flower" ? 4 : 3;
241}
242
243/** Plant node exhaust then respawn (ms). */
244export const PLANT_EXHAUST_MS = 15_000;
245
215/** Craft duration: furnace recipes scale by bar tier; others use the fixed craft duration. */
246/** Craft duration: furnace recipes scale by bar tier; others use the fixed craft duration. */
216export function craftDurationMs (recipe, fallbackMs = 2000)
247export function craftDurationMs (recipe, fallbackMs = 2000)
217{
248{
shared/definitions/items.js +33 −6
@@ -9,6 +9,8 @@ import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
9 9 import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
10 10 import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
11 11 import { ArmourItemId, ARMOUR_ITEM_DEFINITIONS } from "./armourItems.js";
12 import { ClothItemId, CLOTH_ITEM_DEFINITIONS } from "./clothItems.js";
13 import { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
12 14 import { POTION_MAX_STACK } from "./alchemy.js";
13 15
14 16 export const ItemId = Object.freeze({
@@ -32,7 +34,9 @@ export const ItemId = Object.freeze({
32 34 bronzePlantClippers: 34,
33 35 ...MetalItemId,
34 36 ...WoodItemId,
35 ...ArmourItemId
37 ...ArmourItemId,
38 ...ClothItemId,
39 ...DyeItemId
36 40 });
37 41
38 42 export const EQUIPMENT_SLOT = Object.freeze({
@@ -222,12 +226,15 @@ export const ITEM_DEFINITIONS = Object.freeze({
222 226 itemId: ItemId.glassBottle,
223 227 key: "glass-bottle",
224 228 displayName: "Glass bottle",
225 description: "An empty bottle.",
229 description: "An empty bottle for potions and dyes.",
226 230 seedValue: 2,
227 231 stackable: true,
228 232 maxStackSize: DEFAULT_MAX_STACK,
229 233 uniqueInstance: false,
230 category: "tool"
234 category: "tool",
235 iconKey: "potion",
236 defaultState: "potion-0",
237 npcShopAllowed: true
231 238 }),
232 239 [ItemId.greenHerb]: Object.freeze({
233 240 itemId: ItemId.greenHerb,
@@ -281,12 +288,13 @@ export const ITEM_DEFINITIONS = Object.freeze({
281 288 itemId: ItemId.bronzePlantClippers,
282 289 key: "bronze-plant-clippers",
283 290 displayName: "Bronze plant clippers",
284 description: "Use this to gather herbs.",
291 description: "Use this to gather herbs and flowers.",
285 292 seedValue: 10,
286 293 stackable: false,
287 294 maxStackSize: 1,
288 295 uniqueInstance: false,
289 296 category: "tool",
297 npcShopAllowed: true,
290 298 equipment: Object.freeze({
291 299 slot: EQUIPMENT_SLOT.weapon,
292 300 tier: MaterialTier.bronze,
@@ -297,7 +305,10 @@ export const ITEM_DEFINITIONS = Object.freeze({
297 305 ...CRAFTING_ITEM_STUBS,
298 306 ...METAL_ITEM_DEFINITIONS,
299 307 ...WOOD_ITEM_DEFINITIONS,
300 ...ARMOUR_ITEM_DEFINITIONS
308 ...ARMOUR_ITEM_DEFINITIONS,
309 ...CLOTH_ITEM_DEFINITIONS,
310 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
311 [DyeItemId.dye]: DYE_ITEM_DEFINITION
301 312 });
302 313
303 314 export function itemDefinition (itemId)
@@ -316,6 +327,15 @@ export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
316 327 { return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
317 328 if (stack?.itemId === ItemId.potion && stack.instance?.displayName)
318 329 { return stack.instance.displayName; }
330 if (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye")
331 {
332 const fill = stack.instance.fillLevel | 0 || 4;
333 return `Dye (${fill}/5)`;
334 }
335 if (stack?.itemId === ItemId.flower && stack.instance?.colorId)
336 {
337 return `${FLOWER_COLOR_DISPLAY[stack.instance.colorId] ?? "Flower"} flower`;
338 }
319 339 if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
320 340 { return stack.instance.displayName; }
321 341 return def.displayName ?? "Item";
@@ -457,8 +477,15 @@ export function itemAssetPathForStack (stack)
457 477 const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
458 478 return `/assets/items/potion/potion-${fill}.png`;
459 479 }
480 if (stack.itemId === ItemId.dye)
481 {
482 const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
483 return `/assets/items/potion/potion-${fill}.png`;
484 }
460 485 if (stack.itemId === ItemId.glassBottle)
461 { return `/assets/items/glass-bottle/glass-bottle.png`; }
486 { return `/assets/items/potion/potion-0.png`; }
487 if (stack.itemId === ItemId.flower)
488 { return `/assets/items/flower/flower.png`; }
462 489 return itemAssetPath(stack.itemId, null, stack.instance);
463 490 }
464 491
@@ -9,6 +9,8 @@ import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
9import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
9import { MetalItemId, METAL_ITEM_DEFINITIONS } from "./metalItems.js";
10import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
10import { WoodItemId, WOOD_ITEM_DEFINITIONS } from "./woodItems.js";
11import { ArmourItemId, ARMOUR_ITEM_DEFINITIONS } from "./armourItems.js";
11import { ArmourItemId, ARMOUR_ITEM_DEFINITIONS } from "./armourItems.js";
12import { ClothItemId, CLOTH_ITEM_DEFINITIONS } from "./clothItems.js";
13import { DyeItemId, FLOWER_ITEM_DEFINITION, DYE_ITEM_DEFINITION, FLOWER_COLOR_DISPLAY } from "./dyes.js";
12import { POTION_MAX_STACK } from "./alchemy.js";
14import { POTION_MAX_STACK } from "./alchemy.js";
13
15
14export const ItemId = Object.freeze({
16export const ItemId = Object.freeze({
@@ -32,7 +34,9 @@ export const ItemId = Object.freeze({
32 bronzePlantClippers: 34,
34 bronzePlantClippers: 34,
33 ...MetalItemId,
35 ...MetalItemId,
34 ...WoodItemId,
36 ...WoodItemId,
35 ...ArmourItemId
37 ...ArmourItemId,
38 ...ClothItemId,
39 ...DyeItemId
36});
40});
37
41
38export const EQUIPMENT_SLOT = Object.freeze({
42export const EQUIPMENT_SLOT = Object.freeze({
@@ -222,12 +226,15 @@ export const ITEM_DEFINITIONS = Object.freeze({
222 itemId: ItemId.glassBottle,
226 itemId: ItemId.glassBottle,
223 key: "glass-bottle",
227 key: "glass-bottle",
224 displayName: "Glass bottle",
228 displayName: "Glass bottle",
225 description: "An empty bottle.",
229 description: "An empty bottle for potions and dyes.",
226 seedValue: 2,
230 seedValue: 2,
227 stackable: true,
231 stackable: true,
228 maxStackSize: DEFAULT_MAX_STACK,
232 maxStackSize: DEFAULT_MAX_STACK,
229 uniqueInstance: false,
233 uniqueInstance: false,
230 category: "tool"
234 category: "tool",
235 iconKey: "potion",
236 defaultState: "potion-0",
237 npcShopAllowed: true
231 }),
238 }),
232 [ItemId.greenHerb]: Object.freeze({
239 [ItemId.greenHerb]: Object.freeze({
233 itemId: ItemId.greenHerb,
240 itemId: ItemId.greenHerb,
@@ -281,12 +288,13 @@ export const ITEM_DEFINITIONS = Object.freeze({
281 itemId: ItemId.bronzePlantClippers,
288 itemId: ItemId.bronzePlantClippers,
282 key: "bronze-plant-clippers",
289 key: "bronze-plant-clippers",
283 displayName: "Bronze plant clippers",
290 displayName: "Bronze plant clippers",
284 description: "Use this to gather herbs.",
291 description: "Use this to gather herbs and flowers.",
285 seedValue: 10,
292 seedValue: 10,
286 stackable: false,
293 stackable: false,
287 maxStackSize: 1,
294 maxStackSize: 1,
288 uniqueInstance: false,
295 uniqueInstance: false,
289 category: "tool",
296 category: "tool",
297 npcShopAllowed: true,
290 equipment: Object.freeze({
298 equipment: Object.freeze({
291 slot: EQUIPMENT_SLOT.weapon,
299 slot: EQUIPMENT_SLOT.weapon,
292 tier: MaterialTier.bronze,
300 tier: MaterialTier.bronze,
@@ -297,7 +305,10 @@ export const ITEM_DEFINITIONS = Object.freeze({
297 ...CRAFTING_ITEM_STUBS,
305 ...CRAFTING_ITEM_STUBS,
298 ...METAL_ITEM_DEFINITIONS,
306 ...METAL_ITEM_DEFINITIONS,
299 ...WOOD_ITEM_DEFINITIONS,
307 ...WOOD_ITEM_DEFINITIONS,
300 ...ARMOUR_ITEM_DEFINITIONS
308 ...ARMOUR_ITEM_DEFINITIONS,
309 ...CLOTH_ITEM_DEFINITIONS,
310 [DyeItemId.flower]: FLOWER_ITEM_DEFINITION,
311 [DyeItemId.dye]: DYE_ITEM_DEFINITION
301});
312});
302
313
303export function itemDefinition (itemId)
314export function itemDefinition (itemId)
@@ -316,6 +327,15 @@ export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
316 { return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
327 { return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
317 if (stack?.itemId === ItemId.potion && stack.instance?.displayName)
328 if (stack?.itemId === ItemId.potion && stack.instance?.displayName)
318 { return stack.instance.displayName; }
329 { return stack.instance.displayName; }
330 if (stack?.itemId === ItemId.dye && stack.instance?.kind === "dye")
331 {
332 const fill = stack.instance.fillLevel | 0 || 4;
333 return `Dye (${fill}/5)`;
334 }
335 if (stack?.itemId === ItemId.flower && stack.instance?.colorId)
336 {
337 return `${FLOWER_COLOR_DISPLAY[stack.instance.colorId] ?? "Flower"} flower`;
338 }
319 if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
339 if (stack?.itemId === ItemId.recipePaper && stack.instance?.displayName)
320 { return stack.instance.displayName; }
340 { return stack.instance.displayName; }
321 return def.displayName ?? "Item";
341 return def.displayName ?? "Item";
@@ -457,8 +477,15 @@ export function itemAssetPathForStack (stack)
457 const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
477 const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
458 return `/assets/items/potion/potion-${fill}.png`;
478 return `/assets/items/potion/potion-${fill}.png`;
459 }
479 }
480 if (stack.itemId === ItemId.dye)
481 {
482 const fill = Math.max(1, Math.min(5, stack.instance?.fillLevel | 0 || 4));
483 return `/assets/items/potion/potion-${fill}.png`;
484 }
460 if (stack.itemId === ItemId.glassBottle)
485 if (stack.itemId === ItemId.glassBottle)
461 { return `/assets/items/glass-bottle/glass-bottle.png`; }
486 { return `/assets/items/potion/potion-0.png`; }
487 if (stack.itemId === ItemId.flower)
488 { return `/assets/items/flower/flower.png`; }
462 return itemAssetPath(stack.itemId, null, stack.instance);
489 return itemAssetPath(stack.itemId, null, stack.instance);
463}
490}
464
491
shared/definitions/materialTiers.js +67 −4
@@ -26,6 +26,20 @@ export const WoodTier = Object.freeze({
26 26 elder: "elder"
27 27 });
28 28
29 /**
30 * Cloth / fibre tiers (tailoring). Gathering methods vary (plant / shear / drop);
31 * ranks and equip gates match metal / wood.
32 */
33 export const ClothTier = Object.freeze({
34 cotton: "cotton",
35 wool: "wool",
36 linen: "linen",
37 cashmere: "cashmere",
38 silk: "silk",
39 fairySilk: "fairySilk",
40 dragonweave: "dragonweave"
41 });
42
29 43 /** Ordered low → high (metal smithing / tools). */
30 44 export const MATERIAL_TIER_ORDER = Object.freeze([
31 45 MaterialTier.bronze,
@@ -48,6 +62,17 @@ export const WOOD_TIER_ORDER = Object.freeze([
48 62 WoodTier.elder
49 63 ]);
50 64
65 /** Ordered low → high (tailoring). */
66 export const CLOTH_TIER_ORDER = Object.freeze([
67 ClothTier.cotton,
68 ClothTier.wool,
69 ClothTier.linen,
70 ClothTier.cashmere,
71 ClothTier.silk,
72 ClothTier.fairySilk,
73 ClothTier.dragonweave
74 ]);
75
51 76 /**
52 77 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
53 78 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
@@ -80,7 +105,14 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
80 105 [WoodTier.ebony]: 35,
81 106 [WoodTier.lignum]: 50,
82 107 [WoodTier.heartwood]: 70,
83 [WoodTier.elder]: 90
108 [WoodTier.elder]: 90,
109 [ClothTier.cotton]: 1,
110 [ClothTier.wool]: 10,
111 [ClothTier.linen]: 20,
112 [ClothTier.cashmere]: 35,
113 [ClothTier.silk]: 50,
114 [ClothTier.fairySilk]: 70,
115 [ClothTier.dragonweave]: 90
84 116 });
85 117
86 118 /** Rank used for mining duration and relative power (1 = bronze/pine … 7 = dragon/elder). */
@@ -100,7 +132,14 @@ export const TIER_RANK = Object.freeze({
100 132 [WoodTier.ebony]: 4,
101 133 [WoodTier.lignum]: 5,
102 134 [WoodTier.heartwood]: 6,
103 [WoodTier.elder]: 7
135 [WoodTier.elder]: 7,
136 [ClothTier.cotton]: 1,
137 [ClothTier.wool]: 2,
138 [ClothTier.linen]: 3,
139 [ClothTier.cashmere]: 4,
140 [ClothTier.silk]: 5,
141 [ClothTier.fairySilk]: 6,
142 [ClothTier.dragonweave]: 7
104 143 });
105 144
106 145 /** Stat bonus granted by tier for the equipment's bonus category. */
@@ -118,7 +157,14 @@ export const TIER_STAT_BONUS = Object.freeze({
118 157 [WoodTier.ebony]: 6,
119 158 [WoodTier.lignum]: 8,
120 159 [WoodTier.heartwood]: 10,
121 [WoodTier.elder]: 12
160 [WoodTier.elder]: 12,
161 [ClothTier.cotton]: 1,
162 [ClothTier.wool]: 2,
163 [ClothTier.linen]: 4,
164 [ClothTier.cashmere]: 6,
165 [ClothTier.silk]: 8,
166 [ClothTier.fairySilk]: 10,
167 [ClothTier.dragonweave]: 12
122 168 });
123 169
124 170 /** Display names for UI / editor. */
@@ -144,6 +190,16 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
144 190 [WoodTier.elder]: "Elder"
145 191 });
146 192
193 export const CLOTH_DISPLAY_NAME = Object.freeze({
194 [ClothTier.cotton]: "Cotton",
195 [ClothTier.wool]: "Wool",
196 [ClothTier.linen]: "Linen",
197 [ClothTier.cashmere]: "Cashmere",
198 [ClothTier.silk]: "Silk",
199 [ClothTier.fairySilk]: "Fairy silk",
200 [ClothTier.dragonweave]: "Dragonweave"
201 });
202
147 203 /**
148 204 * Author tint swatches via {@link rgb} (0–255) so editors can offer a colour picker.
149 205 * Also accepts `0xRRGGBB` / `"#RRGGBB"`; all forms become 0–1 RGB at module load.
@@ -183,7 +239,14 @@ export const MATERIAL_TINT_HEX = Object.freeze({
183 239 [WoodTier.ebony]: rgb(56, 41, 51),
184 240 [WoodTier.lignum]: rgb(107, 97, 56),
185 241 [WoodTier.heartwood]: rgb(184, 71, 56),
186 [WoodTier.elder]: rgb(184, 189, 199)
242 [WoodTier.elder]: rgb(184, 189, 199),
243 [ClothTier.cotton]: rgb(245, 240, 230),
244 [ClothTier.wool]: rgb(220, 210, 195),
245 [ClothTier.linen]: rgb(200, 185, 140),
246 [ClothTier.cashmere]: rgb(210, 175, 150),
247 [ClothTier.silk]: rgb(230, 220, 240),
248 [ClothTier.fairySilk]: rgb(180, 230, 255),
249 [ClothTier.dragonweave]: rgb(200, 60, 50)
187 250 });
188 251
189 252 /**
@@ -26,6 +26,20 @@ export const WoodTier = Object.freeze({
26 elder: "elder"
26 elder: "elder"
27});
27});
28
28
29/**
30 * Cloth / fibre tiers (tailoring). Gathering methods vary (plant / shear / drop);
31 * ranks and equip gates match metal / wood.
32 */
33export const ClothTier = Object.freeze({
34 cotton: "cotton",
35 wool: "wool",
36 linen: "linen",
37 cashmere: "cashmere",
38 silk: "silk",
39 fairySilk: "fairySilk",
40 dragonweave: "dragonweave"
41});
42
29/** Ordered low → high (metal smithing / tools). */
43/** Ordered low → high (metal smithing / tools). */
30export const MATERIAL_TIER_ORDER = Object.freeze([
44export const MATERIAL_TIER_ORDER = Object.freeze([
31 MaterialTier.bronze,
45 MaterialTier.bronze,
@@ -48,6 +62,17 @@ export const WOOD_TIER_ORDER = Object.freeze([
48 WoodTier.elder
62 WoodTier.elder
49]);
63]);
50
64
65/** Ordered low → high (tailoring). */
66export const CLOTH_TIER_ORDER = Object.freeze([
67 ClothTier.cotton,
68 ClothTier.wool,
69 ClothTier.linen,
70 ClothTier.cashmere,
71 ClothTier.silk,
72 ClothTier.fairySilk,
73 ClothTier.dragonweave
74]);
75
51/**
76/**
52 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
77 * Gatherable ores / fuels that are not always 1:1 with a gear tier.
53 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
78 * Tin + copper smelt into bronze; coal fuels steel. Gold and silver have ore +
@@ -80,7 +105,14 @@ export const TIER_MIN_SKILL_LEVEL = Object.freeze({
80 [WoodTier.ebony]: 35,
105 [WoodTier.ebony]: 35,
81 [WoodTier.lignum]: 50,
106 [WoodTier.lignum]: 50,
82 [WoodTier.heartwood]: 70,
107 [WoodTier.heartwood]: 70,
83 [WoodTier.elder]: 90
108 [WoodTier.elder]: 90,
109 [ClothTier.cotton]: 1,
110 [ClothTier.wool]: 10,
111 [ClothTier.linen]: 20,
112 [ClothTier.cashmere]: 35,
113 [ClothTier.silk]: 50,
114 [ClothTier.fairySilk]: 70,
115 [ClothTier.dragonweave]: 90
84});
116});
85
117
86/** Rank used for mining duration and relative power (1 = bronze/pine … 7 = dragon/elder). */
118/** Rank used for mining duration and relative power (1 = bronze/pine … 7 = dragon/elder). */
@@ -100,7 +132,14 @@ export const TIER_RANK = Object.freeze({
100 [WoodTier.ebony]: 4,
132 [WoodTier.ebony]: 4,
101 [WoodTier.lignum]: 5,
133 [WoodTier.lignum]: 5,
102 [WoodTier.heartwood]: 6,
134 [WoodTier.heartwood]: 6,
103 [WoodTier.elder]: 7
135 [WoodTier.elder]: 7,
136 [ClothTier.cotton]: 1,
137 [ClothTier.wool]: 2,
138 [ClothTier.linen]: 3,
139 [ClothTier.cashmere]: 4,
140 [ClothTier.silk]: 5,
141 [ClothTier.fairySilk]: 6,
142 [ClothTier.dragonweave]: 7
104});
143});
105
144
106/** Stat bonus granted by tier for the equipment's bonus category. */
145/** Stat bonus granted by tier for the equipment's bonus category. */
@@ -118,7 +157,14 @@ export const TIER_STAT_BONUS = Object.freeze({
118 [WoodTier.ebony]: 6,
157 [WoodTier.ebony]: 6,
119 [WoodTier.lignum]: 8,
158 [WoodTier.lignum]: 8,
120 [WoodTier.heartwood]: 10,
159 [WoodTier.heartwood]: 10,
121 [WoodTier.elder]: 12
160 [WoodTier.elder]: 12,
161 [ClothTier.cotton]: 1,
162 [ClothTier.wool]: 2,
163 [ClothTier.linen]: 4,
164 [ClothTier.cashmere]: 6,
165 [ClothTier.silk]: 8,
166 [ClothTier.fairySilk]: 10,
167 [ClothTier.dragonweave]: 12
122});
168});
123
169
124/** Display names for UI / editor. */
170/** Display names for UI / editor. */
@@ -144,6 +190,16 @@ export const MATERIAL_DISPLAY_NAME = Object.freeze({
144 [WoodTier.elder]: "Elder"
190 [WoodTier.elder]: "Elder"
145});
191});
146
192
193export const CLOTH_DISPLAY_NAME = Object.freeze({
194 [ClothTier.cotton]: "Cotton",
195 [ClothTier.wool]: "Wool",
196 [ClothTier.linen]: "Linen",
197 [ClothTier.cashmere]: "Cashmere",
198 [ClothTier.silk]: "Silk",
199 [ClothTier.fairySilk]: "Fairy silk",
200 [ClothTier.dragonweave]: "Dragonweave"
201});
202
147/**
203/**
148 * Author tint swatches via {@link rgb} (0–255) so editors can offer a colour picker.
204 * Author tint swatches via {@link rgb} (0–255) so editors can offer a colour picker.
149 * Also accepts `0xRRGGBB` / `"#RRGGBB"`; all forms become 0–1 RGB at module load.
205 * Also accepts `0xRRGGBB` / `"#RRGGBB"`; all forms become 0–1 RGB at module load.
@@ -183,7 +239,14 @@ export const MATERIAL_TINT_HEX = Object.freeze({
183 [WoodTier.ebony]: rgb(56, 41, 51),
239 [WoodTier.ebony]: rgb(56, 41, 51),
184 [WoodTier.lignum]: rgb(107, 97, 56),
240 [WoodTier.lignum]: rgb(107, 97, 56),
185 [WoodTier.heartwood]: rgb(184, 71, 56),
241 [WoodTier.heartwood]: rgb(184, 71, 56),
186 [WoodTier.elder]: rgb(184, 189, 199)
242 [WoodTier.elder]: rgb(184, 189, 199),
243 [ClothTier.cotton]: rgb(245, 240, 230),
244 [ClothTier.wool]: rgb(220, 210, 195),
245 [ClothTier.linen]: rgb(200, 185, 140),
246 [ClothTier.cashmere]: rgb(210, 175, 150),
247 [ClothTier.silk]: rgb(230, 220, 240),
248 [ClothTier.fairySilk]: rgb(180, 230, 255),
249 [ClothTier.dragonweave]: rgb(200, 60, 50)
187});
250});
188
251
189/**
252/**
shared/definitions/tiles.js +91 −1
@@ -35,7 +35,12 @@ export const BlockType = Object.freeze({
35 35 craftingBench: 11,
36 36 pineTree: 12,
37 37 marketplace: 13,
38 table: 14
38 table: 14,
39 flower: 15,
40 cottonPlant: 16,
41 spinningWheel: 17,
42 loom: 18,
43 tailorBench: 19
39 44 });
40 45
41 46 export const GROUND_DEFINITIONS = Object.freeze({
@@ -274,6 +279,73 @@ export const BLOCK_DEFINITIONS = Object.freeze({
274 279 neighborConnect: true,
275 280 neighborConnectByMaterial: true,
276 281 defaultNeighborMaterial: WoodTier.pine
282 }),
283 [BlockType.flower]: Object.freeze({
284 id: BlockType.flower,
285 key: "flower",
286 displayName: "Flower",
287 passable: true,
288 blocksLight: false,
289 lightRangeTiles: 0,
290 frames: 1,
291 framesPerRow: 1,
292 animationSpeed: 0,
293 outdoor: true,
294 gatherable: true,
295 plantGather: Object.freeze({ kind: "flower", requiresClippers: true, skillId: "herbalism" })
296 }),
297 [BlockType.cottonPlant]: Object.freeze({
298 id: BlockType.cottonPlant,
299 key: "cotton-plant",
300 displayName: "Cotton plant",
301 passable: true,
302 blocksLight: false,
303 lightRangeTiles: 0,
304 frames: 1,
305 framesPerRow: 1,
306 animationSpeed: 0,
307 outdoor: true,
308 gatherable: true,
309 plantGather: Object.freeze({ kind: "cotton", requiresClippers: false, skillId: "herbalism" })
310 }),
311 [BlockType.spinningWheel]: Object.freeze({
312 id: BlockType.spinningWheel,
313 key: "spinning-wheel",
314 displayName: "Spinning wheel",
315 passable: false,
316 blocksLight: false,
317 lightRangeTiles: 0,
318 frames: 1,
319 framesPerRow: 1,
320 animationSpeed: 0,
321 craftingStationId: "spinning-wheel",
322 outdoor: false
323 }),
324 [BlockType.loom]: Object.freeze({
325 id: BlockType.loom,
326 key: "loom",
327 displayName: "Loom",
328 passable: false,
329 blocksLight: false,
330 lightRangeTiles: 0,
331 frames: 1,
332 framesPerRow: 1,
333 animationSpeed: 0,
334 craftingStationId: "loom",
335 outdoor: false
336 }),
337 [BlockType.tailorBench]: Object.freeze({
338 id: BlockType.tailorBench,
339 key: "tailor-bench",
340 displayName: "Tailor's bench",
341 passable: false,
342 blocksLight: false,
343 lightRangeTiles: 0,
344 frames: 1,
345 framesPerRow: 1,
346 animationSpeed: 0,
347 craftingStationId: "tailor-bench",
348 outdoor: false
277 349 })
278 350 });
279 351
@@ -314,6 +386,10 @@ export function resourceNodeDisplayName (block)
314 386 const def = BLOCK_DEFINITIONS[block.typeId];
315 387 return def?.displayName ?? "Tree";
316 388 }
389 if (block.typeId === BlockType.flower)
390 { return "Flower"; }
391 if (block.typeId === BlockType.cottonPlant)
392 { return "Cotton plant"; }
317 393 return null;
318 394 }
319 395
@@ -332,6 +408,20 @@ export function isChopableTreeBlock (block)
332 408 return !isSeasonalStumpState(block.state);
333 409 }
334 410
411 /** Plant gather config from block def, or null. */
412 export function plantGatherForBlock (block)
413 {
414 if (!block)
415 { return null; }
416 const def = BLOCK_DEFINITIONS[block.typeId];
417 return def?.plantGather ?? null;
418 }
419
420 export function isPickablePlantBlock (block)
421 {
422 return !!plantGatherForBlock(block);
423 }
424
335 425 /**
336 426 * Editor palette cards: one entry per placeable, with boulder expanded into
337 427 * plain rock + each ore/coal variant (shared BlockType, distinct state).
@@ -35,7 +35,12 @@ export const BlockType = Object.freeze({
35 craftingBench: 11,
35 craftingBench: 11,
36 pineTree: 12,
36 pineTree: 12,
37 marketplace: 13,
37 marketplace: 13,
38 table: 14
38 table: 14,
39 flower: 15,
40 cottonPlant: 16,
41 spinningWheel: 17,
42 loom: 18,
43 tailorBench: 19
39});
44});
40
45
41export const GROUND_DEFINITIONS = Object.freeze({
46export const GROUND_DEFINITIONS = Object.freeze({
@@ -274,6 +279,73 @@ export const BLOCK_DEFINITIONS = Object.freeze({
274 neighborConnect: true,
279 neighborConnect: true,
275 neighborConnectByMaterial: true,
280 neighborConnectByMaterial: true,
276 defaultNeighborMaterial: WoodTier.pine
281 defaultNeighborMaterial: WoodTier.pine
282 }),
283 [BlockType.flower]: Object.freeze({
284 id: BlockType.flower,
285 key: "flower",
286 displayName: "Flower",
287 passable: true,
288 blocksLight: false,
289 lightRangeTiles: 0,
290 frames: 1,
291 framesPerRow: 1,
292 animationSpeed: 0,
293 outdoor: true,
294 gatherable: true,
295 plantGather: Object.freeze({ kind: "flower", requiresClippers: true, skillId: "herbalism" })
296 }),
297 [BlockType.cottonPlant]: Object.freeze({
298 id: BlockType.cottonPlant,
299 key: "cotton-plant",
300 displayName: "Cotton plant",
301 passable: true,
302 blocksLight: false,
303 lightRangeTiles: 0,
304 frames: 1,
305 framesPerRow: 1,
306 animationSpeed: 0,
307 outdoor: true,
308 gatherable: true,
309 plantGather: Object.freeze({ kind: "cotton", requiresClippers: false, skillId: "herbalism" })
310 }),
311 [BlockType.spinningWheel]: Object.freeze({
312 id: BlockType.spinningWheel,
313 key: "spinning-wheel",
314 displayName: "Spinning wheel",
315 passable: false,
316 blocksLight: false,
317 lightRangeTiles: 0,
318 frames: 1,
319 framesPerRow: 1,
320 animationSpeed: 0,
321 craftingStationId: "spinning-wheel",
322 outdoor: false
323 }),
324 [BlockType.loom]: Object.freeze({
325 id: BlockType.loom,
326 key: "loom",
327 displayName: "Loom",
328 passable: false,
329 blocksLight: false,
330 lightRangeTiles: 0,
331 frames: 1,
332 framesPerRow: 1,
333 animationSpeed: 0,
334 craftingStationId: "loom",
335 outdoor: false
336 }),
337 [BlockType.tailorBench]: Object.freeze({
338 id: BlockType.tailorBench,
339 key: "tailor-bench",
340 displayName: "Tailor's bench",
341 passable: false,
342 blocksLight: false,
343 lightRangeTiles: 0,
344 frames: 1,
345 framesPerRow: 1,
346 animationSpeed: 0,
347 craftingStationId: "tailor-bench",
348 outdoor: false
277 })
349 })
278});
350});
279
351
@@ -314,6 +386,10 @@ export function resourceNodeDisplayName (block)
314 const def = BLOCK_DEFINITIONS[block.typeId];
386 const def = BLOCK_DEFINITIONS[block.typeId];
315 return def?.displayName ?? "Tree";
387 return def?.displayName ?? "Tree";
316 }
388 }
389 if (block.typeId === BlockType.flower)
390 { return "Flower"; }
391 if (block.typeId === BlockType.cottonPlant)
392 { return "Cotton plant"; }
317 return null;
393 return null;
318}
394}
319
395
@@ -332,6 +408,20 @@ export function isChopableTreeBlock (block)
332 return !isSeasonalStumpState(block.state);
408 return !isSeasonalStumpState(block.state);
333}
409}
334
410
411/** Plant gather config from block def, or null. */
412export function plantGatherForBlock (block)
413{
414 if (!block)
415 { return null; }
416 const def = BLOCK_DEFINITIONS[block.typeId];
417 return def?.plantGather ?? null;
418}
419
420export function isPickablePlantBlock (block)
421{
422 return !!plantGatherForBlock(block);
423}
424
335/**
425/**
336 * Editor palette cards: one entry per placeable, with boulder expanded into
426 * Editor palette cards: one entry per placeable, with boulder expanded into
337 * plain rock + each ore/coal variant (shared BlockType, distinct state).
427 * plain rock + each ore/coal variant (shared BlockType, distinct state).
shared/items/origin.js +4 −1
@@ -30,7 +30,10 @@ export const CRAFT_ORIGIN_VERB_BY_STATION = Object.freeze({
30 30 furnace: CraftOriginVerb.forged,
31 31 anvil: CraftOriginVerb.smithed,
32 32 "woodworking-bench": CraftOriginVerb.carved,
33 "crafting-bench": CraftOriginVerb.assembled
33 "crafting-bench": CraftOriginVerb.assembled,
34 "spinning-wheel": CraftOriginVerb.made,
35 loom: CraftOriginVerb.made,
36 "tailor-bench": CraftOriginVerb.made
34 37 });
35 38
36 39 export function craftOriginVerbForStation (stationId)
@@ -30,7 +30,10 @@ export const CRAFT_ORIGIN_VERB_BY_STATION = Object.freeze({
30 furnace: CraftOriginVerb.forged,
30 furnace: CraftOriginVerb.forged,
31 anvil: CraftOriginVerb.smithed,
31 anvil: CraftOriginVerb.smithed,
32 "woodworking-bench": CraftOriginVerb.carved,
32 "woodworking-bench": CraftOriginVerb.carved,
33 "crafting-bench": CraftOriginVerb.assembled
33 "crafting-bench": CraftOriginVerb.assembled,
34 "spinning-wheel": CraftOriginVerb.made,
35 loom: CraftOriginVerb.made,
36 "tailor-bench": CraftOriginVerb.made
34});
37});
35
38
36export function craftOriginVerbForStation (stationId)
39export function craftOriginVerbForStation (stationId)
shared/protocol/constants.js +1 −0
@@ -151,6 +151,7 @@ export const MessageType = Object.freeze({
151 151 cauldronClear: "CAULDRON_CLEAR",
152 152 cauldronSaveRecipe: "CAULDRON_SAVE_RECIPE",
153 153 cauldronClose: "CAULDRON_CLOSE",
154 pick: "PICK",
154 155 mine: "MINE",
155 156 chop: "CHOP",
156 157 cancelGather: "CANCEL_GATHER",
@@ -151,6 +151,7 @@ export const MessageType = Object.freeze({
151 cauldronClear: "CAULDRON_CLEAR",
151 cauldronClear: "CAULDRON_CLEAR",
152 cauldronSaveRecipe: "CAULDRON_SAVE_RECIPE",
152 cauldronSaveRecipe: "CAULDRON_SAVE_RECIPE",
153 cauldronClose: "CAULDRON_CLOSE",
153 cauldronClose: "CAULDRON_CLOSE",
154 pick: "PICK",
154 mine: "MINE",
155 mine: "MINE",
155 chop: "CHOP",
156 chop: "CHOP",
156 cancelGather: "CANCEL_GATHER",
157 cancelGather: "CANCEL_GATHER",
shared/render/tint.js +9 −1
@@ -48,6 +48,12 @@ export function resolveItemTint (stackOrDef, def = null)
48 48 ?? null;
49 49 if (stack?.instance?.kind === "potion" && stack.instance.color)
50 50 { return normalizeRgb(stack.instance.color); }
51 if (stack?.instance?.kind === "dye" && stack.instance.color)
52 { return normalizeRgb(stack.instance.color); }
53 if (stack?.instance?.kind === "flower" && stack.instance.color)
54 { return normalizeRgb(stack.instance.color); }
55 if (stack?.instance?.dyeColor)
56 { return normalizeRgb(stack.instance.dyeColor); }
51 57 if (definition?.tint)
52 58 { return normalizeRgb(definition.tint); }
53 59 const tier = resolveTintTier(definition);
@@ -56,13 +62,15 @@ export function resolveItemTint (stackOrDef, def = null)
56 62 return null;
57 63 }
58 64
59 export function resolveEquipTint (itemIdOrDef)
65 export function resolveEquipTint (itemIdOrDef, instance = null)
60 66 {
61 67 const definition = typeof itemIdOrDef === "number"
62 68 ? itemDefinition(itemIdOrDef)
63 69 : itemIdOrDef;
64 70 if (!definition)
65 71 { return null; }
72 if (instance?.dyeColor)
73 { return normalizeRgb(instance.dyeColor); }
66 74 if (definition.tint)
67 75 { return normalizeRgb(definition.tint); }
68 76 const tier = resolveTintTier(definition);
@@ -48,6 +48,12 @@ export function resolveItemTint (stackOrDef, def = null)
48 ?? null;
48 ?? null;
49 if (stack?.instance?.kind === "potion" && stack.instance.color)
49 if (stack?.instance?.kind === "potion" && stack.instance.color)
50 { return normalizeRgb(stack.instance.color); }
50 { return normalizeRgb(stack.instance.color); }
51 if (stack?.instance?.kind === "dye" && stack.instance.color)
52 { return normalizeRgb(stack.instance.color); }
53 if (stack?.instance?.kind === "flower" && stack.instance.color)
54 { return normalizeRgb(stack.instance.color); }
55 if (stack?.instance?.dyeColor)
56 { return normalizeRgb(stack.instance.dyeColor); }
51 if (definition?.tint)
57 if (definition?.tint)
52 { return normalizeRgb(definition.tint); }
58 { return normalizeRgb(definition.tint); }
53 const tier = resolveTintTier(definition);
59 const tier = resolveTintTier(definition);
@@ -56,13 +62,15 @@ export function resolveItemTint (stackOrDef, def = null)
56 return null;
62 return null;
57}
63}
58
64
59export function resolveEquipTint (itemIdOrDef)
65export function resolveEquipTint (itemIdOrDef, instance = null)
60{
66{
61 const definition = typeof itemIdOrDef === "number"
67 const definition = typeof itemIdOrDef === "number"
62 ? itemDefinition(itemIdOrDef)
68 ? itemDefinition(itemIdOrDef)
63 : itemIdOrDef;
69 : itemIdOrDef;
64 if (!definition)
70 if (!definition)
65 { return null; }
71 { return null; }
72 if (instance?.dyeColor)
73 { return normalizeRgb(instance.dyeColor); }
66 if (definition.tint)
74 if (definition.tint)
67 { return normalizeRgb(definition.tint); }
75 { return normalizeRgb(definition.tint); }
68 const tier = resolveTintTier(definition);
76 const tier = resolveTintTier(definition);