Refine cauldron dyes tab, flower colours, and brew origins.
Split alchemy/dyes UI, tint flower nodes on respawn, drop clippers for flowers, and stamp Brewed/Mixed origins.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -295,27 +295,43 @@
295
295
<h2>Cauldron</h2>
296
296
<button id="cauldron-close" type="button">Close</button>
297
297
</header>
298
<div id="cauldron-slots" class="cauldron-slots"></div>
299
<div id="cauldron-inserts" class="cauldron-inserts"></div>
300
<div class="cauldron-vessel" aria-hidden="true">⚗</div>
301
<div class="cauldron-actions">
302
<button id="cauldron-stir" type="button">Stir</button>
303
<button id="cauldron-heat" type="button">Heat</button>
304
<button id="cauldron-cool" type="button">Cool</button>
298
<div class="cauldron-tabs" role="tablist">
299
<button id="cauldron-tab-alchemy" type="button" class="cauldron-tab active" role="tab" aria-selected="true">Alchemy</button>
300
<button id="cauldron-tab-dyes" type="button" class="cauldron-tab" role="tab" aria-selected="false">Dyes</button>
305
301
</div>
306
<div class="cauldron-finish">
307
<button id="cauldron-bottle" type="button">Bottle</button>
308
<button id="cauldron-clear" type="button">Clear</button>
309
<button id="cauldron-save-recipe" type="button" hidden>Save Recipe</button>
310
</div>
311
<ol id="cauldron-steps" class="cauldron-steps"></ol>
312
<p id="cauldron-status" class="hint"></p>
302
<section id="cauldron-alchemy-pane" class="cauldron-pane">
303
<div id="cauldron-slots" class="cauldron-slots"></div>
304
<div id="cauldron-inserts" class="cauldron-inserts"></div>
305
<div class="cauldron-vessel" aria-hidden="true">⚗</div>
306
<p id="cauldron-flavor" class="cauldron-flavor">The cauldron is empty</p>
307
<div class="cauldron-actions">
308
<button id="cauldron-stir" type="button" disabled>Stir</button>
309
<button id="cauldron-heat" type="button" disabled>Heat</button>
310
<button id="cauldron-cool" type="button" disabled>Cool</button>
311
</div>
312
<div class="cauldron-finish">
313
<button id="cauldron-bottle" type="button">Bottle</button>
314
<button id="cauldron-clear" type="button">Clear</button>
315
<button id="cauldron-save-recipe" type="button" hidden>Save Recipe</button>
316
</div>
317
<ol id="cauldron-steps" class="cauldron-steps"></ol>
318
<p id="cauldron-status" class="hint"></p>
319
</section>
320
<section id="cauldron-dyes-pane" class="cauldron-pane" hidden>
321
<p class="hint">Place flowers of any colours, then create dye.</p>
322
<div id="cauldron-dye-slots" class="cauldron-slots cauldron-dye-slots"></div>
323
<div class="cauldron-finish">
324
<button id="cauldron-create-dye" type="button">Create Dye</button>
325
<button id="cauldron-clear-dye" type="button">Clear</button>
326
</div>
327
<p id="cauldron-dye-status" class="hint"></p>
328
</section>
313
329
</aside>
314
330
315
331
<div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>
316
332
<aside id="cauldron-pick-panel" hidden>
317
333
<header>
318
<h2>Choose ingredient</h2>
334
<h2 id="cauldron-pick-title">Choose ingredient</h2>
319
335
<button id="cauldron-pick-cancel" type="button">Cancel</button>
320
336
</header>
321
337
<div id="cauldron-pick-list" class="cauldron-pick-list"></div>
@@ -323,6 +339,16 @@
323
339
<button id="cauldron-pick-confirm" type="button">Place in slot</button>
324
340
</aside>
325
341
342
<div id="cauldron-dye-confirm-backdrop" class="modal-backdrop" hidden></div>
343
<aside id="cauldron-dye-confirm-panel" hidden>
344
<header>
345
<h2>Not enough bottles</h2>
346
<button id="cauldron-dye-confirm-cancel" type="button">Cancel</button>
347
</header>
348
<p id="cauldron-dye-confirm-text" class="hint"></p>
349
<button id="cauldron-dye-confirm-ok" type="button">Create anyway</button>
350
</aside>
351
326
352
<div id="nametag" hidden></div>
327
353
<div id="damage-numbers"></div>
328
354
<div id="skill-level-floats"></div>
@@ -295,27 +295,43 @@295
<h2>Cauldron</h2>295
<h2>Cauldron</h2>296
<button id="cauldron-close" type="button">Close</button>296
<button id="cauldron-close" type="button">Close</button>297
</header>297
</header>298
<div id="cauldron-slots" class="cauldron-slots"></div>298
<div class="cauldron-tabs" role="tablist">299
<div id="cauldron-inserts" class="cauldron-inserts"></div>299
<button id="cauldron-tab-alchemy" type="button" class="cauldron-tab active" role="tab" aria-selected="true">Alchemy</button>300
<div class="cauldron-vessel" aria-hidden="true">⚗</div>300
<button id="cauldron-tab-dyes" type="button" class="cauldron-tab" role="tab" aria-selected="false">Dyes</button>301
<div class="cauldron-actions">302
<button id="cauldron-stir" type="button">Stir</button>303
<button id="cauldron-heat" type="button">Heat</button>304
<button id="cauldron-cool" type="button">Cool</button>305
</div>301
</div>306
<div class="cauldron-finish">302
<section id="cauldron-alchemy-pane" class="cauldron-pane">307
<button id="cauldron-bottle" type="button">Bottle</button>303
<div id="cauldron-slots" class="cauldron-slots"></div>308
<button id="cauldron-clear" type="button">Clear</button>304
<div id="cauldron-inserts" class="cauldron-inserts"></div>309
<button id="cauldron-save-recipe" type="button" hidden>Save Recipe</button>305
<div class="cauldron-vessel" aria-hidden="true">⚗</div>310
</div>306
<p id="cauldron-flavor" class="cauldron-flavor">The cauldron is empty</p>311
<ol id="cauldron-steps" class="cauldron-steps"></ol>307
<div class="cauldron-actions">312
<p id="cauldron-status" class="hint"></p>308
<button id="cauldron-stir" type="button" disabled>Stir</button>309
<button id="cauldron-heat" type="button" disabled>Heat</button>310
<button id="cauldron-cool" type="button" disabled>Cool</button>311
</div>312
<div class="cauldron-finish">313
<button id="cauldron-bottle" type="button">Bottle</button>314
<button id="cauldron-clear" type="button">Clear</button>315
<button id="cauldron-save-recipe" type="button" hidden>Save Recipe</button>316
</div>317
<ol id="cauldron-steps" class="cauldron-steps"></ol>318
<p id="cauldron-status" class="hint"></p>319
</section>320
<section id="cauldron-dyes-pane" class="cauldron-pane" hidden>321
<p class="hint">Place flowers of any colours, then create dye.</p>322
<div id="cauldron-dye-slots" class="cauldron-slots cauldron-dye-slots"></div>323
<div class="cauldron-finish">324
<button id="cauldron-create-dye" type="button">Create Dye</button>325
<button id="cauldron-clear-dye" type="button">Clear</button>326
</div>327
<p id="cauldron-dye-status" class="hint"></p>328
</section>313
</aside>329
</aside>314
330
315
<div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>331
<div id="cauldron-pick-backdrop" class="modal-backdrop" hidden></div>316
<aside id="cauldron-pick-panel" hidden>332
<aside id="cauldron-pick-panel" hidden>317
<header>333
<header>318
<h2>Choose ingredient</h2>334
<h2 id="cauldron-pick-title">Choose ingredient</h2>319
<button id="cauldron-pick-cancel" type="button">Cancel</button>335
<button id="cauldron-pick-cancel" type="button">Cancel</button>320
</header>336
</header>321
<div id="cauldron-pick-list" class="cauldron-pick-list"></div>337
<div id="cauldron-pick-list" class="cauldron-pick-list"></div>@@ -323,6 +339,16 @@323
<button id="cauldron-pick-confirm" type="button">Place in slot</button>339
<button id="cauldron-pick-confirm" type="button">Place in slot</button>324
</aside>340
</aside>325
341
342
<div id="cauldron-dye-confirm-backdrop" class="modal-backdrop" hidden></div>343
<aside id="cauldron-dye-confirm-panel" hidden>344
<header>345
<h2>Not enough bottles</h2>346
<button id="cauldron-dye-confirm-cancel" type="button">Cancel</button>347
</header>348
<p id="cauldron-dye-confirm-text" class="hint"></p>349
<button id="cauldron-dye-confirm-ok" type="button">Create anyway</button>350
</aside>351
326
<div id="nametag" hidden></div>352
<div id="nametag" hidden></div>327
<div id="damage-numbers"></div>353
<div id="damage-numbers"></div>328
<div id="skill-level-floats"></div>354
<div id="skill-level-floats"></div>@@ -5,7 +5,12 @@ import {
5
5
formatQuantity,
6
6
ItemId
7
7
} from "/shared/definitions/items.js";
8
import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "/shared/definitions/alchemy.js";
8
import {
9
AlchemyStepKind,
10
CAULDRON_SLOT_COUNT,
11
DYE_CAULDRON_SLOT_COUNT,
12
CAULDRON_EMPTY_FLAVOR
13
} from "/shared/definitions/alchemy.js";
9
14
import { applyItemIcon } from "../render/potionIcon.js";
10
15
11
16
export function initAlchemy ({
@@ -16,77 +21,145 @@ export function initAlchemy ({
16
21
{
17
22
const backdrop = document.getElementById("cauldron-backdrop");
18
23
const panel = document.getElementById("cauldron-panel");
24
const alchemyPane = document.getElementById("cauldron-alchemy-pane");
25
const dyesPane = document.getElementById("cauldron-dyes-pane");
26
const tabAlchemy = document.getElementById("cauldron-tab-alchemy");
27
const tabDyes = document.getElementById("cauldron-tab-dyes");
19
28
const slotsEl = document.getElementById("cauldron-slots");
29
const dyeSlotsEl = document.getElementById("cauldron-dye-slots");
20
30
const insertsEl = document.getElementById("cauldron-inserts");
21
31
const stepsEl = document.getElementById("cauldron-steps");
32
const flavorEl = document.getElementById("cauldron-flavor");
22
33
const statusEl = document.getElementById("cauldron-status");
34
const dyeStatusEl = document.getElementById("cauldron-dye-status");
23
35
const saveBtn = document.getElementById("cauldron-save-recipe");
36
const stirBtn = document.getElementById("cauldron-stir");
37
const heatBtn = document.getElementById("cauldron-heat");
38
const coolBtn = document.getElementById("cauldron-cool");
24
39
const pickBackdrop = document.getElementById("cauldron-pick-backdrop");
25
40
const pickPanel = document.getElementById("cauldron-pick-panel");
41
const pickTitle = document.getElementById("cauldron-pick-title");
26
42
const pickList = document.getElementById("cauldron-pick-list");
27
43
const pickQty = document.getElementById("cauldron-pick-qty");
44
const confirmBackdrop = document.getElementById("cauldron-dye-confirm-backdrop");
45
const confirmPanel = document.getElementById("cauldron-dye-confirm-panel");
46
const confirmText = document.getElementById("cauldron-dye-confirm-text");
28
47
29
48
let open = false;
30
49
let state = null;
50
let activeTab = "alchemy";
51
let pickMode = "alchemy";
31
52
let pickSlotIndex = null;
32
53
let pickItemId = null;
33
54
let pickInstance = null;
55
let pendingDyeConfirm = null;
34
56
35
57
document.getElementById("cauldron-close")?.addEventListener("click", () => close());
36
58
backdrop?.addEventListener("click", () => close());
37
document.getElementById("cauldron-stir")?.addEventListener("click", () =>
59
tabAlchemy?.addEventListener("click", () => setTab("alchemy"));
60
tabDyes?.addEventListener("click", () => setTab("dyes"));
61
stirBtn?.addEventListener("click", () =>
38
62
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); });
39
document.getElementById("cauldron-heat")?.addEventListener("click", () =>
63
heatBtn?.addEventListener("click", () =>
40
64
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); });
41
document.getElementById("cauldron-cool")?.addEventListener("click", () =>
65
coolBtn?.addEventListener("click", () =>
42
66
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); });
43
67
document.getElementById("cauldron-bottle")?.addEventListener("click", () =>
44
68
{ socket.send({ type: MessageType.cauldronBottle }); });
45
69
document.getElementById("cauldron-clear")?.addEventListener("click", () =>
46
70
{ socket.send({ type: MessageType.cauldronClear }); });
71
document.getElementById("cauldron-create-dye")?.addEventListener("click", () =>
72
{ socket.send({ type: MessageType.cauldronCreateDye, confirmOverflow: false }); });
73
document.getElementById("cauldron-clear-dye")?.addEventListener("click", () =>
74
{ socket.send({ type: MessageType.cauldronClearDye }); });
47
75
saveBtn?.addEventListener("click", () =>
48
76
{ socket.send({ type: MessageType.cauldronSaveRecipe }); });
49
77
document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());
50
78
document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick());
51
79
pickBackdrop?.addEventListener("click", () => closePick());
80
document.getElementById("cauldron-dye-confirm-cancel")?.addEventListener("click", () => closeDyeConfirm());
81
confirmBackdrop?.addEventListener("click", () => closeDyeConfirm());
82
document.getElementById("cauldron-dye-confirm-ok")?.addEventListener("click", () =>
83
{
84
closeDyeConfirm();
85
socket.send({ type: MessageType.cauldronCreateDye, confirmOverflow: true });
86
});
87
88
function setTab (tab)
89
{
90
activeTab = tab;
91
const alchemy = tab === "alchemy";
92
if (tabAlchemy)
93
{
94
tabAlchemy.classList.toggle("active", alchemy);
95
tabAlchemy.setAttribute("aria-selected", alchemy ? "true" : "false");
96
}
97
if (tabDyes)
98
{
99
tabDyes.classList.toggle("active", !alchemy);
100
tabDyes.setAttribute("aria-selected", alchemy ? "false" : "true");
101
}
102
if (alchemyPane)
103
{ alchemyPane.hidden = !alchemy; }
104
if (dyesPane)
105
{ dyesPane.hidden = alchemy; }
106
}
52
107
53
108
function render ()
54
109
{
55
110
if (!open || !panel)
56
111
{ return; }
57
renderSlots();
112
renderAlchemySlots();
113
renderDyeSlots();
58
114
renderSteps();
115
if (flavorEl)
116
{ flavorEl.textContent = state?.flavorText ?? CAULDRON_EMPTY_FLAVOR; }
117
const canAct = !!state?.canProcessActions;
118
if (stirBtn)
119
{ stirBtn.disabled = !canAct; }
120
if (heatBtn)
121
{ heatBtn.disabled = !canAct; }
122
if (coolBtn)
123
{ coolBtn.disabled = !canAct; }
59
124
if (saveBtn)
60
125
{ saveBtn.hidden = !state?.canSaveRecipe; }
61
126
}
62
127
63
function renderSlots ()
128
function renderSlotButton (reserved, onClick)
129
{
130
const slotBtn = document.createElement("button");
131
slotBtn.type = "button";
132
slotBtn.className = "cauldron-slot";
133
if (reserved)
134
{
135
const stack = {
136
itemId: reserved.itemId,
137
quantity: reserved.quantity,
138
instance: reserved.instance ?? null
139
};
140
const img = document.createElement("img");
141
applyItemIcon(img, stack, itemAssetPathForStack(stack));
142
img.alt = itemDisplayName(stack);
143
const qty = document.createElement("span");
144
qty.className = "qty";
145
qty.textContent = formatQuantity(reserved.quantity);
146
slotBtn.append(img, qty);
147
slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;
148
}
149
else
150
{ slotBtn.textContent = "+"; }
151
slotBtn.addEventListener("click", onClick);
152
return slotBtn;
153
}
154
155
function renderAlchemySlots ()
64
156
{
65
157
slotsEl.replaceChildren();
66
158
insertsEl.replaceChildren();
67
159
for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)
68
160
{
69
161
const reserved = state?.slots?.[i] ?? null;
70
const slotBtn = document.createElement("button");
71
slotBtn.type = "button";
72
slotBtn.className = "cauldron-slot";
73
if (reserved)
74
{
75
const img = document.createElement("img");
76
const stack = { itemId: reserved.itemId, quantity: reserved.quantity };
77
applyItemIcon(img, stack, itemAssetPathForStack(stack));
78
img.alt = itemDisplayName(stack);
79
const qty = document.createElement("span");
80
qty.className = "qty";
81
qty.textContent = formatQuantity(reserved.quantity);
82
slotBtn.append(img, qty);
83
slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;
84
}
85
else
86
{ slotBtn.textContent = "+"; }
87
slotBtn.addEventListener("click", () => openPick(i));
88
slotsEl.append(slotBtn);
89
162
slotsEl.append(renderSlotButton(reserved, () => openPick("alchemy", i)));
90
163
const insertBtn = document.createElement("button");
91
164
insertBtn.type = "button";
92
165
insertBtn.className = "cauldron-insert";
@@ -99,6 +172,18 @@ export function initAlchemy ({
99
172
}
100
173
}
101
174
175
function renderDyeSlots ()
176
{
177
if (!dyeSlotsEl)
178
{ return; }
179
dyeSlotsEl.replaceChildren();
180
for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)
181
{
182
const reserved = state?.dyeSlots?.[i] ?? null;
183
dyeSlotsEl.append(renderSlotButton(reserved, () => openPick("dye", i)));
184
}
185
}
186
102
187
function renderSteps ()
103
188
{
104
189
stepsEl.replaceChildren();
@@ -116,11 +201,14 @@ export function initAlchemy ({
116
201
}
117
202
}
118
203
119
function openPick (slotIndex)
204
function openPick (mode, slotIndex)
120
205
{
206
pickMode = mode;
121
207
pickSlotIndex = slotIndex;
122
208
pickItemId = null;
123
209
pickInstance = null;
210
if (pickTitle)
211
{ pickTitle.textContent = mode === "dye" ? "Choose flower" : "Choose ingredient"; }
124
212
pickList.replaceChildren();
125
213
const counts = new Map();
126
214
for (const slot of getInventorySlots?.() ?? [])
@@ -131,7 +219,15 @@ export function initAlchemy ({
131
219
if (!def || def.uniqueInstance || def.equipment
132
220
|| slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)
133
221
{ continue; }
134
const identity = (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye)
222
if (mode === "dye")
223
{
224
if (slot.itemId !== ItemId.flower)
225
{ continue; }
226
}
227
else if (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye || def.flower || def.dye)
228
{ continue; }
229
230
const identity = slot.itemId === ItemId.flower
135
231
? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}`
136
232
: String(slot.itemId);
137
233
const prev = counts.get(identity);
@@ -191,23 +287,57 @@ export function initAlchemy ({
191
287
if (pickSlotIndex == null || pickItemId == null)
192
288
{ return; }
193
289
const quantity = Math.max(1, pickQty.value | 0);
194
socket.send({
195
type: MessageType.cauldronSetSlot,
196
slotIndex: pickSlotIndex,
197
itemId: pickItemId,
198
quantity,
199
instance: pickInstance
200
});
290
if (pickMode === "dye")
291
{
292
socket.send({
293
type: MessageType.cauldronSetDyeSlot,
294
slotIndex: pickSlotIndex,
295
itemId: pickItemId,
296
quantity,
297
instance: pickInstance
298
});
299
}
300
else
301
{
302
socket.send({
303
type: MessageType.cauldronSetSlot,
304
slotIndex: pickSlotIndex,
305
itemId: pickItemId,
306
quantity,
307
instance: pickInstance
308
});
309
}
201
310
closePick();
202
311
}
203
312
313
function openDyeConfirm (confirm)
314
{
315
pendingDyeConfirm = confirm;
316
const wanted = confirm.wanted | 0;
317
const bottles = confirm.bottles | 0;
318
confirmText.textContent = `Je staat op het punt ${wanted} units aan dye te maken, maar je hebt maar genoeg lege flesjes om ${bottles} op te slaan. De rest gaat verloren. Weet je het zeker?`;
319
confirmBackdrop.hidden = false;
320
confirmPanel.hidden = false;
321
}
322
323
function closeDyeConfirm ()
324
{
325
pendingDyeConfirm = null;
326
confirmBackdrop.hidden = true;
327
confirmPanel.hidden = true;
328
}
329
204
330
function openFromServer (nextState)
205
331
{
206
332
open = true;
207
333
state = nextState;
208
334
backdrop.hidden = false;
209
335
panel.hidden = false;
210
statusEl.textContent = "";
336
if (statusEl)
337
{ statusEl.textContent = ""; }
338
if (dyeStatusEl)
339
{ dyeStatusEl.textContent = ""; }
340
setTab(activeTab);
211
341
render();
212
342
}
213
343
@@ -219,12 +349,17 @@ export function initAlchemy ({
219
349
backdrop.hidden = true;
220
350
panel.hidden = true;
221
351
closePick();
352
closeDyeConfirm();
222
353
socket.send({ type: MessageType.cauldronClose });
223
354
}
224
355
225
356
return {
226
357
isBlocking ()
227
{ return open || !pickPanel?.hidden; },
358
{
359
return open
360
|| !pickPanel?.hidden
361
|| !confirmPanel?.hidden;
362
},
228
363
reset ()
229
364
{
230
365
open = false;
@@ -234,6 +369,7 @@ export function initAlchemy ({
234
369
if (panel)
235
370
{ panel.hidden = true; }
236
371
closePick();
372
closeDyeConfirm();
237
373
},
238
374
handleSnapshot (message)
239
375
{
@@ -245,6 +381,7 @@ export function initAlchemy ({
245
381
if (panel)
246
382
{ panel.hidden = true; }
247
383
state = null;
384
closeDyeConfirm();
248
385
return;
249
386
}
250
387
if (!open)
@@ -254,14 +391,23 @@ export function initAlchemy ({
254
391
state = message.state;
255
392
render();
256
393
}
394
if (message.dyeConfirm)
395
{ openDyeConfirm(message.dyeConfirm); }
257
396
if (message.alchemyResult)
258
397
{
259
398
const result = message.alchemyResult;
260
399
const name = result.potion?.displayName ?? "Potion";
261
400
const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : "";
262
statusEl.textContent = result.success
401
const line = result.success
263
402
? `Bottled ${result.produced}× ${name}${lost}.`
264
403
: `Unstable brew: ${result.produced}× ${name}${lost}.`;
404
if (result.potion?.potionKey === "dye")
405
{
406
if (dyeStatusEl)
407
{ dyeStatusEl.textContent = line; }
408
}
409
else if (statusEl)
410
{ statusEl.textContent = line; }
265
411
}
266
412
},
267
413
refresh ()
@@ -5,7 +5,12 @@ import {5
formatQuantity,5
formatQuantity,6
ItemId6
ItemId7
} from "/shared/definitions/items.js";7
} from "/shared/definitions/items.js";8
import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "/shared/definitions/alchemy.js";8
import {9
AlchemyStepKind,10
CAULDRON_SLOT_COUNT,11
DYE_CAULDRON_SLOT_COUNT,12
CAULDRON_EMPTY_FLAVOR13
} from "/shared/definitions/alchemy.js";9
import { applyItemIcon } from "../render/potionIcon.js";14
import { applyItemIcon } from "../render/potionIcon.js";10
15
11
export function initAlchemy ({16
export function initAlchemy ({@@ -16,77 +21,145 @@ export function initAlchemy ({16
{21
{17
const backdrop = document.getElementById("cauldron-backdrop");22
const backdrop = document.getElementById("cauldron-backdrop");18
const panel = document.getElementById("cauldron-panel");23
const panel = document.getElementById("cauldron-panel");24
const alchemyPane = document.getElementById("cauldron-alchemy-pane");25
const dyesPane = document.getElementById("cauldron-dyes-pane");26
const tabAlchemy = document.getElementById("cauldron-tab-alchemy");27
const tabDyes = document.getElementById("cauldron-tab-dyes");19
const slotsEl = document.getElementById("cauldron-slots");28
const slotsEl = document.getElementById("cauldron-slots");29
const dyeSlotsEl = document.getElementById("cauldron-dye-slots");20
const insertsEl = document.getElementById("cauldron-inserts");30
const insertsEl = document.getElementById("cauldron-inserts");21
const stepsEl = document.getElementById("cauldron-steps");31
const stepsEl = document.getElementById("cauldron-steps");32
const flavorEl = document.getElementById("cauldron-flavor");22
const statusEl = document.getElementById("cauldron-status");33
const statusEl = document.getElementById("cauldron-status");34
const dyeStatusEl = document.getElementById("cauldron-dye-status");23
const saveBtn = document.getElementById("cauldron-save-recipe");35
const saveBtn = document.getElementById("cauldron-save-recipe");36
const stirBtn = document.getElementById("cauldron-stir");37
const heatBtn = document.getElementById("cauldron-heat");38
const coolBtn = document.getElementById("cauldron-cool");24
const pickBackdrop = document.getElementById("cauldron-pick-backdrop");39
const pickBackdrop = document.getElementById("cauldron-pick-backdrop");25
const pickPanel = document.getElementById("cauldron-pick-panel");40
const pickPanel = document.getElementById("cauldron-pick-panel");41
const pickTitle = document.getElementById("cauldron-pick-title");26
const pickList = document.getElementById("cauldron-pick-list");42
const pickList = document.getElementById("cauldron-pick-list");27
const pickQty = document.getElementById("cauldron-pick-qty");43
const pickQty = document.getElementById("cauldron-pick-qty");44
const confirmBackdrop = document.getElementById("cauldron-dye-confirm-backdrop");45
const confirmPanel = document.getElementById("cauldron-dye-confirm-panel");46
const confirmText = document.getElementById("cauldron-dye-confirm-text");28
47
29
let open = false;48
let open = false;30
let state = null;49
let state = null;50
let activeTab = "alchemy";51
let pickMode = "alchemy";31
let pickSlotIndex = null;52
let pickSlotIndex = null;32
let pickItemId = null;53
let pickItemId = null;33
let pickInstance = null;54
let pickInstance = null;55
let pendingDyeConfirm = null;34
56
35
document.getElementById("cauldron-close")?.addEventListener("click", () => close());57
document.getElementById("cauldron-close")?.addEventListener("click", () => close());36
backdrop?.addEventListener("click", () => close());58
backdrop?.addEventListener("click", () => close());37
document.getElementById("cauldron-stir")?.addEventListener("click", () =>59
tabAlchemy?.addEventListener("click", () => setTab("alchemy"));60
tabDyes?.addEventListener("click", () => setTab("dyes"));61
stirBtn?.addEventListener("click", () =>38
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); });62
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.stir }); });39
document.getElementById("cauldron-heat")?.addEventListener("click", () =>63
heatBtn?.addEventListener("click", () =>40
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); });64
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.heat }); });41
document.getElementById("cauldron-cool")?.addEventListener("click", () =>65
coolBtn?.addEventListener("click", () =>42
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); });66
{ socket.send({ type: MessageType.cauldronAction, action: AlchemyStepKind.cool }); });43
document.getElementById("cauldron-bottle")?.addEventListener("click", () =>67
document.getElementById("cauldron-bottle")?.addEventListener("click", () =>44
{ socket.send({ type: MessageType.cauldronBottle }); });68
{ socket.send({ type: MessageType.cauldronBottle }); });45
document.getElementById("cauldron-clear")?.addEventListener("click", () =>69
document.getElementById("cauldron-clear")?.addEventListener("click", () =>46
{ socket.send({ type: MessageType.cauldronClear }); });70
{ socket.send({ type: MessageType.cauldronClear }); });71
document.getElementById("cauldron-create-dye")?.addEventListener("click", () =>72
{ socket.send({ type: MessageType.cauldronCreateDye, confirmOverflow: false }); });73
document.getElementById("cauldron-clear-dye")?.addEventListener("click", () =>74
{ socket.send({ type: MessageType.cauldronClearDye }); });47
saveBtn?.addEventListener("click", () =>75
saveBtn?.addEventListener("click", () =>48
{ socket.send({ type: MessageType.cauldronSaveRecipe }); });76
{ socket.send({ type: MessageType.cauldronSaveRecipe }); });49
document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());77
document.getElementById("cauldron-pick-cancel")?.addEventListener("click", () => closePick());50
document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick());78
document.getElementById("cauldron-pick-confirm")?.addEventListener("click", () => confirmPick());51
pickBackdrop?.addEventListener("click", () => closePick());79
pickBackdrop?.addEventListener("click", () => closePick());80
document.getElementById("cauldron-dye-confirm-cancel")?.addEventListener("click", () => closeDyeConfirm());81
confirmBackdrop?.addEventListener("click", () => closeDyeConfirm());82
document.getElementById("cauldron-dye-confirm-ok")?.addEventListener("click", () =>83
{84
closeDyeConfirm();85
socket.send({ type: MessageType.cauldronCreateDye, confirmOverflow: true });86
});87
88
function setTab (tab)89
{90
activeTab = tab;91
const alchemy = tab === "alchemy";92
if (tabAlchemy)93
{94
tabAlchemy.classList.toggle("active", alchemy);95
tabAlchemy.setAttribute("aria-selected", alchemy ? "true" : "false");96
}97
if (tabDyes)98
{99
tabDyes.classList.toggle("active", !alchemy);100
tabDyes.setAttribute("aria-selected", alchemy ? "false" : "true");101
}102
if (alchemyPane)103
{ alchemyPane.hidden = !alchemy; }104
if (dyesPane)105
{ dyesPane.hidden = alchemy; }106
}52
107
53
function render ()108
function render ()54
{109
{55
if (!open || !panel)110
if (!open || !panel)56
{ return; }111
{ return; }57
renderSlots();112
renderAlchemySlots();113
renderDyeSlots();58
renderSteps();114
renderSteps();115
if (flavorEl)116
{ flavorEl.textContent = state?.flavorText ?? CAULDRON_EMPTY_FLAVOR; }117
const canAct = !!state?.canProcessActions;118
if (stirBtn)119
{ stirBtn.disabled = !canAct; }120
if (heatBtn)121
{ heatBtn.disabled = !canAct; }122
if (coolBtn)123
{ coolBtn.disabled = !canAct; }59
if (saveBtn)124
if (saveBtn)60
{ saveBtn.hidden = !state?.canSaveRecipe; }125
{ saveBtn.hidden = !state?.canSaveRecipe; }61
}126
}62
127
63
function renderSlots ()128
function renderSlotButton (reserved, onClick)129
{130
const slotBtn = document.createElement("button");131
slotBtn.type = "button";132
slotBtn.className = "cauldron-slot";133
if (reserved)134
{135
const stack = {136
itemId: reserved.itemId,137
quantity: reserved.quantity,138
instance: reserved.instance ?? null139
};140
const img = document.createElement("img");141
applyItemIcon(img, stack, itemAssetPathForStack(stack));142
img.alt = itemDisplayName(stack);143
const qty = document.createElement("span");144
qty.className = "qty";145
qty.textContent = formatQuantity(reserved.quantity);146
slotBtn.append(img, qty);147
slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;148
}149
else150
{ slotBtn.textContent = "+"; }151
slotBtn.addEventListener("click", onClick);152
return slotBtn;153
}154
155
function renderAlchemySlots ()64
{156
{65
slotsEl.replaceChildren();157
slotsEl.replaceChildren();66
insertsEl.replaceChildren();158
insertsEl.replaceChildren();67
for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)159
for (let i = 0; i < CAULDRON_SLOT_COUNT; i++)68
{160
{69
const reserved = state?.slots?.[i] ?? null;161
const reserved = state?.slots?.[i] ?? null;70
const slotBtn = document.createElement("button");162
slotsEl.append(renderSlotButton(reserved, () => openPick("alchemy", i)));71
slotBtn.type = "button";72
slotBtn.className = "cauldron-slot";73
if (reserved)74
{75
const img = document.createElement("img");76
const stack = { itemId: reserved.itemId, quantity: reserved.quantity };77
applyItemIcon(img, stack, itemAssetPathForStack(stack));78
img.alt = itemDisplayName(stack);79
const qty = document.createElement("span");80
qty.className = "qty";81
qty.textContent = formatQuantity(reserved.quantity);82
slotBtn.append(img, qty);83
slotBtn.title = `${itemDisplayName(stack)} ×${reserved.quantity}`;84
}85
else86
{ slotBtn.textContent = "+"; }87
slotBtn.addEventListener("click", () => openPick(i));88
slotsEl.append(slotBtn);89
90
const insertBtn = document.createElement("button");163
const insertBtn = document.createElement("button");91
insertBtn.type = "button";164
insertBtn.type = "button";92
insertBtn.className = "cauldron-insert";165
insertBtn.className = "cauldron-insert";@@ -99,6 +172,18 @@ export function initAlchemy ({99
}172
}100
}173
}101
174
175
function renderDyeSlots ()176
{177
if (!dyeSlotsEl)178
{ return; }179
dyeSlotsEl.replaceChildren();180
for (let i = 0; i < DYE_CAULDRON_SLOT_COUNT; i++)181
{182
const reserved = state?.dyeSlots?.[i] ?? null;183
dyeSlotsEl.append(renderSlotButton(reserved, () => openPick("dye", i)));184
}185
}186
102
function renderSteps ()187
function renderSteps ()103
{188
{104
stepsEl.replaceChildren();189
stepsEl.replaceChildren();@@ -116,11 +201,14 @@ export function initAlchemy ({116
}201
}117
}202
}118
203
119
function openPick (slotIndex)204
function openPick (mode, slotIndex)120
{205
{206
pickMode = mode;121
pickSlotIndex = slotIndex;207
pickSlotIndex = slotIndex;122
pickItemId = null;208
pickItemId = null;123
pickInstance = null;209
pickInstance = null;210
if (pickTitle)211
{ pickTitle.textContent = mode === "dye" ? "Choose flower" : "Choose ingredient"; }124
pickList.replaceChildren();212
pickList.replaceChildren();125
const counts = new Map();213
const counts = new Map();126
for (const slot of getInventorySlots?.() ?? [])214
for (const slot of getInventorySlots?.() ?? [])@@ -131,7 +219,15 @@ export function initAlchemy ({131
if (!def || def.uniqueInstance || def.equipment219
if (!def || def.uniqueInstance || def.equipment132
|| slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)220
|| slot.itemId === ItemId.potion || slot.itemId === ItemId.glassBottle)133
{ continue; }221
{ continue; }134
const identity = (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye)222
if (mode === "dye")223
{224
if (slot.itemId !== ItemId.flower)225
{ continue; }226
}227
else if (slot.itemId === ItemId.flower || slot.itemId === ItemId.dye || def.flower || def.dye)228
{ continue; }229
230
const identity = slot.itemId === ItemId.flower135
? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}`231
? `${slot.itemId}|${JSON.stringify(slot.instance ?? null)}`136
: String(slot.itemId);232
: String(slot.itemId);137
const prev = counts.get(identity);233
const prev = counts.get(identity);@@ -191,23 +287,57 @@ export function initAlchemy ({191
if (pickSlotIndex == null || pickItemId == null)287
if (pickSlotIndex == null || pickItemId == null)192
{ return; }288
{ return; }193
const quantity = Math.max(1, pickQty.value | 0);289
const quantity = Math.max(1, pickQty.value | 0);194
socket.send({290
if (pickMode === "dye")195
type: MessageType.cauldronSetSlot,291
{196
slotIndex: pickSlotIndex,292
socket.send({197
itemId: pickItemId,293
type: MessageType.cauldronSetDyeSlot,198
quantity,294
slotIndex: pickSlotIndex,199
instance: pickInstance295
itemId: pickItemId,200
});296
quantity,297
instance: pickInstance298
});299
}300
else301
{302
socket.send({303
type: MessageType.cauldronSetSlot,304
slotIndex: pickSlotIndex,305
itemId: pickItemId,306
quantity,307
instance: pickInstance308
});309
}201
closePick();310
closePick();202
}311
}203
312
313
function openDyeConfirm (confirm)314
{315
pendingDyeConfirm = confirm;316
const wanted = confirm.wanted | 0;317
const bottles = confirm.bottles | 0;318
confirmText.textContent = `Je staat op het punt ${wanted} units aan dye te maken, maar je hebt maar genoeg lege flesjes om ${bottles} op te slaan. De rest gaat verloren. Weet je het zeker?`;319
confirmBackdrop.hidden = false;320
confirmPanel.hidden = false;321
}322
323
function closeDyeConfirm ()324
{325
pendingDyeConfirm = null;326
confirmBackdrop.hidden = true;327
confirmPanel.hidden = true;328
}329
204
function openFromServer (nextState)330
function openFromServer (nextState)205
{331
{206
open = true;332
open = true;207
state = nextState;333
state = nextState;208
backdrop.hidden = false;334
backdrop.hidden = false;209
panel.hidden = false;335
panel.hidden = false;210
statusEl.textContent = "";336
if (statusEl)337
{ statusEl.textContent = ""; }338
if (dyeStatusEl)339
{ dyeStatusEl.textContent = ""; }340
setTab(activeTab);211
render();341
render();212
}342
}213
343
@@ -219,12 +349,17 @@ export function initAlchemy ({219
backdrop.hidden = true;349
backdrop.hidden = true;220
panel.hidden = true;350
panel.hidden = true;221
closePick();351
closePick();352
closeDyeConfirm();222
socket.send({ type: MessageType.cauldronClose });353
socket.send({ type: MessageType.cauldronClose });223
}354
}224
355
225
return {356
return {226
isBlocking ()357
isBlocking ()227
{ return open || !pickPanel?.hidden; },358
{359
return open360
|| !pickPanel?.hidden361
|| !confirmPanel?.hidden;362
},228
reset ()363
reset ()229
{364
{230
open = false;365
open = false;@@ -234,6 +369,7 @@ export function initAlchemy ({234
if (panel)369
if (panel)235
{ panel.hidden = true; }370
{ panel.hidden = true; }236
closePick();371
closePick();372
closeDyeConfirm();237
},373
},238
handleSnapshot (message)374
handleSnapshot (message)239
{375
{@@ -245,6 +381,7 @@ export function initAlchemy ({245
if (panel)381
if (panel)246
{ panel.hidden = true; }382
{ panel.hidden = true; }247
state = null;383
state = null;384
closeDyeConfirm();248
return;385
return;249
}386
}250
if (!open)387
if (!open)@@ -254,14 +391,23 @@ export function initAlchemy ({254
state = message.state;391
state = message.state;255
render();392
render();256
}393
}394
if (message.dyeConfirm)395
{ openDyeConfirm(message.dyeConfirm); }257
if (message.alchemyResult)396
if (message.alchemyResult)258
{397
{259
const result = message.alchemyResult;398
const result = message.alchemyResult;260
const name = result.potion?.displayName ?? "Potion";399
const name = result.potion?.displayName ?? "Potion";261
const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : "";400
const lost = result.lost > 0 ? ` (${result.lost} lost — not enough bottles)` : "";262
statusEl.textContent = result.success401
const line = result.success263
? `Bottled ${result.produced}× ${name}${lost}.`402
? `Bottled ${result.produced}× ${name}${lost}.`264
: `Unstable brew: ${result.produced}× ${name}${lost}.`;403
: `Unstable brew: ${result.produced}× ${name}${lost}.`;404
if (result.potion?.potionKey === "dye")405
{406
if (dyeStatusEl)407
{ dyeStatusEl.textContent = line; }408
}409
else if (statusEl)410
{ statusEl.textContent = line; }265
}411
}266
},412
},267
refresh ()413
refresh ()@@ -298,13 +298,12 @@ export function initCrafting ({
298
298
found = true;
299
299
const cell = document.createElement("button");
300
300
cell.type = "button";
301
cell.className = "craft-recipe-cell";
301
cell.className = "craft-recipe-cell craft-dye-cell";
302
cell.title = "Dye";
302
303
const img = document.createElement("img");
303
304
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);
305
img.alt = "Dye";
306
cell.append(img);
308
307
cell.addEventListener("click", () =>
309
308
{
310
309
dyeSlotIndex = index;
@@ -298,13 +298,12 @@ export function initCrafting ({298
found = true;298
found = true;299
const cell = document.createElement("button");299
const cell = document.createElement("button");300
cell.type = "button";300
cell.type = "button";301
cell.className = "craft-recipe-cell";301
cell.className = "craft-recipe-cell craft-dye-cell";302
cell.title = "Dye";302
const img = document.createElement("img");303
const img = document.createElement("img");303
applyItemIcon(img, stack, itemAssetPathForStack(stack));304
applyItemIcon(img, stack, itemAssetPathForStack(stack));304
const label = document.createElement("span");305
img.alt = "Dye";305
label.className = "craft-recipe-name";306
cell.append(img);306
label.textContent = itemDisplayName(stack);307
cell.append(img, label);308
cell.addEventListener("click", () =>307
cell.addEventListener("click", () =>309
{308
{310
dyeSlotIndex = index;309
dyeSlotIndex = index;@@ -436,7 +436,8 @@ a { color: #d4c48a; }
436
436
}
437
437
438
438
#cauldron-panel,
439
#cauldron-pick-panel {
439
#cauldron-pick-panel,
440
#cauldron-dye-confirm-panel {
440
441
position: fixed;
441
442
z-index: 6;
442
443
top: 50%;
@@ -450,19 +451,36 @@ a { color: #d4c48a; }
450
451
padding: 0.85rem 1rem 1rem;
451
452
}
452
453
453
#cauldron-pick-panel {
454
#cauldron-pick-panel,
455
#cauldron-dye-confirm-panel {
454
456
z-index: 7;
455
457
width: min(420px, 94vw);
456
458
}
457
459
458
460
#cauldron-panel header,
459
#cauldron-pick-panel header {
461
#cauldron-pick-panel header,
462
#cauldron-dye-confirm-panel header {
460
463
display: flex;
461
464
justify-content: space-between;
462
465
align-items: center;
463
466
margin-bottom: 0.5rem;
464
467
}
465
468
469
.cauldron-tabs {
470
display: flex;
471
gap: 0.35rem;
472
margin-bottom: 0.65rem;
473
}
474
475
.cauldron-tab {
476
flex: 1;
477
}
478
479
.cauldron-tab.active {
480
border-color: #d4c48a;
481
background: #2a3140;
482
}
483
466
484
.cauldron-slots,
467
485
.cauldron-inserts {
468
486
display: grid;
@@ -471,6 +489,10 @@ a { color: #d4c48a; }
471
489
margin-bottom: 0.35rem;
472
490
}
473
491
492
.cauldron-dye-slots {
493
grid-template-columns: repeat(3, 1fr);
494
}
495
474
496
.cauldron-slot,
475
497
.cauldron-insert,
476
498
.cauldron-pick-item {
@@ -502,6 +524,14 @@ a { color: #d4c48a; }
502
524
opacity: 0.85;
503
525
}
504
526
527
.cauldron-flavor {
528
margin: 0.15rem 0 0.45rem;
529
font-style: italic;
530
color: #c8c0a8;
531
font-size: 0.92rem;
532
text-align: center;
533
}
534
505
535
.cauldron-actions,
506
536
.cauldron-finish {
507
537
display: flex;
@@ -510,6 +540,11 @@ a { color: #d4c48a; }
510
540
margin: 0.35rem 0;
511
541
}
512
542
543
.cauldron-actions button:disabled {
544
opacity: 0.4;
545
cursor: not-allowed;
546
}
547
513
548
.cauldron-steps {
514
549
margin: 0.5rem 0 0;
515
550
padding-left: 1.2rem;
@@ -585,6 +620,11 @@ a { color: #d4c48a; }
585
620
image-rendering: pixelated;
586
621
}
587
622
623
.craft-dye-cell {
624
min-height: 48px;
625
justify-content: center;
626
}
627
588
628
.craft-recipe-name {
589
629
font-size: 0.72rem;
590
630
text-align: center;
@@ -836,6 +876,8 @@ a { color: #d4c48a; }
836
876
#cauldron-backdrop[hidden],
837
877
#cauldron-pick-panel[hidden],
838
878
#cauldron-pick-backdrop[hidden],
879
#cauldron-dye-confirm-panel[hidden],
880
#cauldron-dye-confirm-backdrop[hidden],
839
881
#shop-panel[hidden],
840
882
#shop-backdrop[hidden],
841
883
#shop-qty-panel[hidden],
@@ -436,7 +436,8 @@ a { color: #d4c48a; }436
}436
}437
437
438
#cauldron-panel,438
#cauldron-panel,439
#cauldron-pick-panel {439
#cauldron-pick-panel,440
#cauldron-dye-confirm-panel {440
position: fixed;441
position: fixed;441
z-index: 6;442
z-index: 6;442
top: 50%;443
top: 50%;@@ -450,19 +451,36 @@ a { color: #d4c48a; }450
padding: 0.85rem 1rem 1rem;451
padding: 0.85rem 1rem 1rem;451
}452
}452
453
453
#cauldron-pick-panel {454
#cauldron-pick-panel,455
#cauldron-dye-confirm-panel {454
z-index: 7;456
z-index: 7;455
width: min(420px, 94vw);457
width: min(420px, 94vw);456
}458
}457
459
458
#cauldron-panel header,460
#cauldron-panel header,459
#cauldron-pick-panel header {461
#cauldron-pick-panel header,462
#cauldron-dye-confirm-panel header {460
display: flex;463
display: flex;461
justify-content: space-between;464
justify-content: space-between;462
align-items: center;465
align-items: center;463
margin-bottom: 0.5rem;466
margin-bottom: 0.5rem;464
}467
}465
468
469
.cauldron-tabs {470
display: flex;471
gap: 0.35rem;472
margin-bottom: 0.65rem;473
}474
475
.cauldron-tab {476
flex: 1;477
}478
479
.cauldron-tab.active {480
border-color: #d4c48a;481
background: #2a3140;482
}483
466
.cauldron-slots,484
.cauldron-slots,467
.cauldron-inserts {485
.cauldron-inserts {468
display: grid;486
display: grid;@@ -471,6 +489,10 @@ a { color: #d4c48a; }471
margin-bottom: 0.35rem;489
margin-bottom: 0.35rem;472
}490
}473
491
492
.cauldron-dye-slots {493
grid-template-columns: repeat(3, 1fr);494
}495
474
.cauldron-slot,496
.cauldron-slot,475
.cauldron-insert,497
.cauldron-insert,476
.cauldron-pick-item {498
.cauldron-pick-item {@@ -502,6 +524,14 @@ a { color: #d4c48a; }502
opacity: 0.85;524
opacity: 0.85;503
}525
}504
526
527
.cauldron-flavor {528
margin: 0.15rem 0 0.45rem;529
font-style: italic;530
color: #c8c0a8;531
font-size: 0.92rem;532
text-align: center;533
}534
505
.cauldron-actions,535
.cauldron-actions,506
.cauldron-finish {536
.cauldron-finish {507
display: flex;537
display: flex;@@ -510,6 +540,11 @@ a { color: #d4c48a; }510
margin: 0.35rem 0;540
margin: 0.35rem 0;511
}541
}512
542
543
.cauldron-actions button:disabled {544
opacity: 0.4;545
cursor: not-allowed;546
}547
513
.cauldron-steps {548
.cauldron-steps {514
margin: 0.5rem 0 0;549
margin: 0.5rem 0 0;515
padding-left: 1.2rem;550
padding-left: 1.2rem;@@ -585,6 +620,11 @@ a { color: #d4c48a; }585
image-rendering: pixelated;620
image-rendering: pixelated;586
}621
}587
622
623
.craft-dye-cell {624
min-height: 48px;625
justify-content: center;626
}627
588
.craft-recipe-name {628
.craft-recipe-name {589
font-size: 0.72rem;629
font-size: 0.72rem;590
text-align: center;630
text-align: center;@@ -836,6 +876,8 @@ a { color: #d4c48a; }836
#cauldron-backdrop[hidden],876
#cauldron-backdrop[hidden],837
#cauldron-pick-panel[hidden],877
#cauldron-pick-panel[hidden],838
#cauldron-pick-backdrop[hidden],878
#cauldron-pick-backdrop[hidden],879
#cauldron-dye-confirm-panel[hidden],880
#cauldron-dye-confirm-backdrop[hidden],839
#shop-panel[hidden],881
#shop-panel[hidden],840
#shop-backdrop[hidden],882
#shop-backdrop[hidden],841
#shop-qty-panel[hidden],883
#shop-qty-panel[hidden],@@ -236,7 +236,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
236
236
## Gathering, crafting, and production skills
237
237
238
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.
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 **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, 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
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
241
242
242
## Cloth, dyes, and tailoring
@@ -266,7 +266,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
266
266
## Alchemy / cauldron
267
267
268
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.
269
**Spec:** **Herbalism** gathers flowers and cotton (**no tool**; flowers ~1s). Flower nodes respawn with a random colour tint; the visible colour is the flower you receive. **Alchemy** uses a cauldron with tabs **Alchemy** / **Dyes**. Alchemy: insert ingredients then stir/heat/cool (actions unlock after the first insert); step transcript hashes to a flavor line. Opening requires ≥1 empty glass bottle. **Dyes:** up to 6 flower slots of any colours; Create Dye mixes paint-style by quantity and bottles 1 dye per flower (confirm if bottles are short). Dye bottles stack to 16 on exact RGB. 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. **Plant clippers** remain for future herb nodes.
270
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`
271
271
272
272
## Inventory, items, equipment, ground drops
@@ -236,7 +236,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi236
## Gathering, crafting, and production skills236
## Gathering, crafting, and production skills237
237
238
**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower herbalism 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/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. 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 **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, 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`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
241
242
## Cloth, dyes, and tailoring242
## Cloth, dyes, and tailoring@@ -266,7 +266,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi266
## Alchemy / cauldron266
## Alchemy / cauldron267
267
268
**Status:** partial (potion scaffolding + flower→dye + dye mixing live) 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. 269
**Spec:** **Herbalism** gathers flowers and cotton (**no tool**; flowers ~1s). Flower nodes respawn with a random colour tint; the visible colour is the flower you receive. **Alchemy** uses a cauldron with tabs **Alchemy** / **Dyes**. Alchemy: insert ingredients then stir/heat/cool (actions unlock after the first insert); step transcript hashes to a flavor line. Opening requires ≥1 empty glass bottle. **Dyes:** up to 6 flower slots of any colours; Create Dye mixes paint-style by quantity and bottles 1 dye per flower (confirm if bottles are short). Dye bottles stack to 16 on exact RGB. 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. **Plant clippers** remain for future herb nodes.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`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`271
271
272
## Inventory, items, equipment, ground drops272
## Inventory, items, equipment, ground drops@@ -0,0 +1,30 @@
1
import { DatabaseSync } from "node:sqlite";
2
import { fileURLToPath } from "node:url";
3
import { dirname, join } from "node:path";
4
import { insertStack } from "../../shared/items/inventory.js";
5
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
6
7
const root = dirname(fileURLToPath(import.meta.url));
8
const dbPath = join(root, "../data/state.sqlite");
9
const db = new DatabaseSync(dbPath);
10
const char = db.prepare(`
11
SELECT character_id, first_name, last_name FROM characters
12
WHERE first_normalized = ? AND last_normalized = ?
13
`).get("tim", "falken");
14
if (!char)
15
{ throw new Error("character not found"); }
16
17
const row = db.prepare("SELECT inventory_blob FROM character_bags WHERE character_id = ?")
18
.get(char.character_id);
19
if (!row)
20
{ throw new Error("no bag row"); }
21
22
const slots = JSON.parse(row.inventory_blob || "[]");
23
const def = itemDefinition(ItemId.glassBottle);
24
const result = insertStack(slots, { itemId: ItemId.glassBottle, quantity: 20 }, def);
25
if (!result.ok || result.remainder > 0)
26
{ throw new Error(`inventory full / remainder ${result.remainder}`); }
27
28
db.prepare("UPDATE character_bags SET inventory_blob = ? WHERE character_id = ?")
29
.run(JSON.stringify(result.slots), char.character_id);
30
console.log(`granted 20 glass bottles to ${char.first_name} ${char.last_name} (id=${char.character_id})`);
@@ -0,0 +1,30 @@1
import { DatabaseSync } from "node:sqlite";2
import { fileURLToPath } from "node:url";3
import { dirname, join } from "node:path";4
import { insertStack } from "../../shared/items/inventory.js";5
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";6
7
const root = dirname(fileURLToPath(import.meta.url));8
const dbPath = join(root, "../data/state.sqlite");9
const db = new DatabaseSync(dbPath);10
const char = db.prepare(`11
SELECT character_id, first_name, last_name FROM characters12
WHERE first_normalized = ? AND last_normalized = ?13
`).get("tim", "falken");14
if (!char)15
{ throw new Error("character not found"); }16
17
const row = db.prepare("SELECT inventory_blob FROM character_bags WHERE character_id = ?")18
.get(char.character_id);19
if (!row)20
{ throw new Error("no bag row"); }21
22
const slots = JSON.parse(row.inventory_blob || "[]");23
const def = itemDefinition(ItemId.glassBottle);24
const result = insertStack(slots, { itemId: ItemId.glassBottle, quantity: 20 }, def);25
if (!result.ok || result.remainder > 0)26
{ throw new Error(`inventory full / remainder ${result.remainder}`); }27
28
db.prepare("UPDATE character_bags SET inventory_blob = ? WHERE character_id = ?")29
.run(JSON.stringify(result.slots), char.character_id);30
console.log(`granted 20 glass bottles to ${char.first_name} ${char.last_name} (id=${char.character_id})`);@@ -1,17 +1,21 @@
1
1
import { Component } from "../ecs/components.js";
2
2
import { BlockType } from "../../../shared/definitions/tiles.js";
3
import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js";
3
import {
4
AlchemyStepKind,
5
CAULDRON_SLOT_COUNT,
6
DYE_CAULDRON_SLOT_COUNT
7
} from "../../../shared/definitions/alchemy.js";
4
8
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5
9
import {
6
10
evaluateAlchemyBottle,
7
11
potionItemInstance,
8
12
recipePaperBody,
9
resolvedAlchemyPotions
13
resolvedAlchemyPotions,
14
cauldronFlavorText
10
15
} from "../../../shared/alchemy/recipes.js";
11
16
import {
12
dyeItemInstance,
13
17
DEFAULT_DYE_FILL,
14
mixDyeBatches
18
mixFlowersForDye
15
19
} from "../../../shared/definitions/dyes.js";
16
20
import { bagView } from "../items/bags.js";
17
21
import {
@@ -22,6 +26,7 @@ import {
22
26
takeMatchingFromSlots,
23
27
stackQuantity
24
28
} from "../../../shared/items/inventory.js";
29
import { attachOrigins, craftOrigin, CraftOriginVerb } from "../../../shared/items/origin.js";
25
30
import { tileToChunk, tileToLocal } from "../world/coordinates.js";
26
31
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
27
32
import { randomUUID } from "node:crypto";
@@ -39,6 +44,13 @@ function userError (message)
39
44
return error;
40
45
}
41
46
47
function characterDisplayName (world, handle)
48
{
49
const appearance = world.ecs.get(handle, Component.appearance);
50
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
51
return name || "someone";
52
}
53
42
54
function ensureSessions (world)
43
55
{
44
56
if (!world.cauldronSessions)
@@ -50,20 +62,45 @@ function emptySession ()
50
62
{
51
63
return {
52
64
slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),
65
dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),
53
66
brew: [],
54
67
steps: [],
55
68
lastSuccessRecipe: null
56
69
};
57
70
}
58
71
72
function normalizeSession (session)
73
{
74
if (!Array.isArray(session.dyeSlots) || session.dyeSlots.length !== DYE_CAULDRON_SLOT_COUNT)
75
{ session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null); }
76
return session;
77
}
78
79
function slotView (slot)
80
{
81
if (!slot)
82
{ return null; }
83
return {
84
itemId: slot.itemId,
85
quantity: slot.quantity | 0,
86
instance: slot.instance ? structuredClone(slot.instance) : null
87
};
88
}
89
59
90
function sessionView (session)
60
91
{
92
const steps = session.steps ?? [];
61
93
return {
62
slots: (session.slots ?? []).map((slot) => (slot
63
? { itemId: slot.itemId, quantity: slot.quantity | 0 }
64
: null)),
65
brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0 })),
66
steps: (session.steps ?? []).map((step) => ({ ...step })),
94
slots: (session.slots ?? []).map(slotView),
95
dyeSlots: (session.dyeSlots ?? []).map(slotView),
96
brew: (session.brew ?? []).map((row) => ({
97
itemId: row.itemId,
98
quantity: row.quantity | 0,
99
instance: row.instance ? structuredClone(row.instance) : null
100
})),
101
steps: steps.map((step) => ({ ...step })),
102
flavorText: cauldronFlavorText(steps),
103
canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),
67
104
canSaveRecipe: !!session.lastSuccessRecipe,
68
105
lastSuccess: session.lastSuccessRecipe
69
106
? {
@@ -102,16 +139,21 @@ function requireSession (world, characterId)
102
139
const session = ensureSessions(world).get(characterId);
103
140
if (!session)
104
141
{ throw userError("Open a cauldron first."); }
105
return session;
142
return normalizeSession(session);
106
143
}
107
144
108
function clearBrew (session)
145
function clearAlchemy (session)
109
146
{
110
147
session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);
111
148
session.brew = [];
112
149
session.steps = [];
113
150
}
114
151
152
function clearDyeSlots (session)
153
{
154
session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null);
155
}
156
115
157
function ensureInventory (world, handle)
116
158
{
117
159
let inventory = world.ecs.get(handle, Component.inventory);
@@ -129,14 +171,20 @@ export function handleAlchemyCommand (world, sessionId, command)
129
171
return openCauldron(world, sessionId, command);
130
172
case "cauldron-set-slot":
131
173
return setSlot(world, sessionId, command);
174
case "cauldron-set-dye-slot":
175
return setDyeSlot(world, sessionId, command);
132
176
case "cauldron-insert":
133
177
return insertFromSlot(world, sessionId, command);
134
178
case "cauldron-action":
135
179
return action(world, sessionId, command);
136
180
case "cauldron-bottle":
137
181
return bottle(world, sessionId, command);
182
case "cauldron-create-dye":
183
return createDye(world, sessionId, command);
138
184
case "cauldron-clear":
139
185
return clear(world, sessionId, command);
186
case "cauldron-clear-dye":
187
return clearDye(world, sessionId, command);
140
188
case "cauldron-save-recipe":
141
189
return saveRecipe(world, sessionId, command);
142
190
case "cauldron-close":
@@ -150,8 +198,12 @@ function openCauldron (world, sessionId, command)
150
198
{
151
199
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);
152
200
requireNearCauldron(world, handle);
201
const inventory = ensureInventory(world, handle);
202
if (countItemInSlots(inventory.slots, ItemId.glassBottle) < 1)
203
{ throw userError("I don't have any empty bottles."); }
204
153
205
const sessions = ensureSessions(world);
154
const existing = sessions.get(command.characterId) ?? emptySession();
206
const existing = normalizeSession(sessions.get(command.characterId) ?? emptySession());
155
207
sessions.set(command.characterId, existing);
156
208
const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);
157
209
return {
@@ -192,49 +244,72 @@ function setSlot (world, sessionId, command)
192
244
}
193
245
194
246
const def = itemDefinition(itemId);
195
if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)
196
{ throw userError("That cannot go in a cauldron slot."); }
197
if (itemId === ItemId.dye || itemId === ItemId.flower)
247
if (!def || def.uniqueInstance || def.equipment
248
|| itemId === ItemId.potion || itemId === ItemId.glassBottle
249
|| itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)
250
{ throw userError("Use the Dyes tab for flowers."); }
251
252
const inventory = ensureInventory(world, handle);
253
const have = countItemInSlots(inventory.slots, itemId);
254
if (have < quantity)
255
{ throw userError("Not enough of that item in your inventory."); }
256
257
session.slots[slotIndex] = { itemId, quantity, instance: null };
258
return {
259
events: [],
260
private: bagView(world.ecs, handle),
261
cauldron: true,
262
cauldronState: sessionView(session)
263
};
264
}
265
266
function setDyeSlot (world, sessionId, command)
267
{
268
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
269
requireNearCauldron(world, handle);
270
const session = requireSession(world, command.characterId);
271
const slotIndex = command.slotIndex | 0;
272
if (slotIndex < 0 || slotIndex >= DYE_CAULDRON_SLOT_COUNT)
273
{ throw userError("Invalid dye slot."); }
274
275
const itemId = command.itemId | 0;
276
const quantity = Math.max(0, command.quantity | 0);
277
if (!itemId || quantity <= 0)
198
278
{
199
// Allowed — instances are captured on insert.
279
session.dyeSlots[slotIndex] = null;
280
return {
281
events: [],
282
private: bagView(world.ecs, handle),
283
cauldron: true,
284
cauldronState: sessionView(session)
285
};
200
286
}
201
else if (def.dye || def.flower)
202
{ /* ok */ }
287
288
if (itemId !== ItemId.flower)
289
{ throw userError("Only flowers go in dye slots."); }
203
290
204
291
const inventory = ensureInventory(world, handle);
205
let instance = null;
206
if (itemId === ItemId.flower || itemId === ItemId.dye)
292
const wanted = command.instance ? structuredClone(command.instance) : null;
293
let instance = wanted;
294
if (!instance)
207
295
{
208
const wanted = command.instance ? structuredClone(command.instance) : null;
209
if (wanted)
210
{ instance = wanted; }
211
else
296
for (const slot of inventory.slots)
212
297
{
213
for (const slot of inventory.slots)
298
if (slot?.itemId === ItemId.flower && slot.instance)
214
299
{
215
if (slot?.itemId === itemId && slot.instance)
216
{
217
instance = structuredClone(slot.instance);
218
break;
219
}
300
instance = structuredClone(slot.instance);
301
break;
220
302
}
221
303
}
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
304
}
305
if (!instance?.color)
306
{ throw userError("That flower has no colour."); }
236
307
237
session.slots[slotIndex] = { itemId, quantity, instance };
308
const have = countMatchingInstance(inventory.slots, ItemId.flower, instance);
309
if (have < quantity)
310
{ throw userError("Not enough of that flower in your inventory."); }
311
312
session.dyeSlots[slotIndex] = { itemId: ItemId.flower, quantity, instance };
238
313
return {
239
314
events: [],
240
315
private: bagView(world.ecs, handle),
@@ -300,6 +375,8 @@ function action (world, sessionId, command)
300
375
const kind = command.action;
301
376
if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)
302
377
{ throw userError("Unknown cauldron action."); }
378
if (!session.steps.some((step) => step.kind === AlchemyStepKind.insert))
379
{ throw userError("Insert an ingredient first."); }
303
380
session.steps.push({ kind });
304
381
session.lastSuccessRecipe = null;
305
382
return {
@@ -319,14 +396,6 @@ function bottle (world, sessionId, command)
319
396
{ throw userError("The cauldron is empty."); }
320
397
321
398
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
330
399
const skills = world.ecs.get(handle, Component.skills) ?? {};
331
400
332
401
const evaluation = evaluateAlchemyBottle({
@@ -353,11 +422,13 @@ function bottle (world, sessionId, command)
353
422
354
423
const instance = potionItemInstance(evaluation.result);
355
424
const potionDef = itemDefinition(ItemId.potion);
356
const inserted = insertStack(inventory.slots, {
425
const origin = craftOrigin(CraftOriginVerb.brewed, characterDisplayName(world, handle));
426
const inserted = insertStack(inventory.slots, attachOrigins({
357
427
itemId: ItemId.potion,
358
428
quantity: produced,
359
instance
360
}, potionDef);
429
instance,
430
origins: [{ origin, quantity: produced }]
431
}), potionDef);
361
432
if (!inserted.ok)
362
433
{
363
434
const refund = insertStack(inventory.slots, {
@@ -370,7 +441,7 @@ function bottle (world, sessionId, command)
370
441
inventory.slots = inserted.slots;
371
442
372
443
session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;
373
clearBrew(session);
444
clearAlchemy(session);
374
445
375
446
return {
376
447
events: [],
@@ -394,100 +465,78 @@ function bottle (world, sessionId, command)
394
465
};
395
466
}
396
467
397
/**
398
* @returns {null | { ok: false, reason: string } | { ok: true, mode: "flower"|"mix", ... }}
399
*/
400
function evaluateDyeBrew (brew)
468
function createDye (world, sessionId, command)
401
469
{
402
const rows = brew ?? [];
470
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
471
requireNearCauldron(world, handle);
472
const session = requireSession(world, command.characterId);
473
const rows = (session.dyeSlots ?? []).filter((slot) => slot?.itemId === ItemId.flower);
403
474
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." }; }
475
{ throw userError("Add flowers to make dye."); }
476
477
const mixed = mixFlowersForDye(rows);
478
if (!mixed.ok)
479
{ throw userError(mixed.reason); }
414
480
415
if (hasFlower)
481
const wanted = mixed.quantity;
482
const inventory = ensureInventory(world, handle);
483
const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);
484
if (bottles < wanted && !command.confirmOverflow)
416
485
{
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
486
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)
487
events: [],
488
private: bagView(world.ecs, handle),
489
cauldron: true,
490
cauldronState: sessionView(session),
491
dyeConfirm: {
492
wanted,
493
bottles,
494
lost: Math.max(0, wanted - bottles)
495
}
429
496
};
430
497
}
431
498
432
const mixed = mixDyeBatches(rows);
433
if (!mixed.ok)
434
{ return { ok: false, reason: mixed.reason }; }
435
return { ok: true, mode: "mix", ...mixed };
436
}
499
const produced = Math.min(wanted, bottles);
500
if (produced <= 0)
501
{ throw userError("You need glass bottles to bottle the dye."); }
437
502
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)
503
for (const row of rows)
453
504
{
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,
505
const pulled = takeMatchingFromSlots(inventory.slots, {
506
itemId: ItemId.flower,
507
quantity: row.quantity,
508
instance: row.instance,
464
509
compact: false
465
510
});
466
if (!takeBottles.ok)
467
{ throw userError("You need glass bottles to bottle the dye."); }
468
inventory.slots = takeBottles.slots;
511
if (!pulled.ok)
512
{ throw userError("Not enough of those flowers in your inventory."); }
513
inventory.slots = pulled.slots;
469
514
}
470
515
516
const takeBottles = takeMatchingFromSlots(inventory.slots, {
517
itemId: ItemId.glassBottle,
518
quantity: produced,
519
compact: false
520
});
521
if (!takeBottles.ok)
522
{ throw userError("You need glass bottles to bottle the dye."); }
523
inventory.slots = takeBottles.slots;
524
471
525
const dyeDef = itemDefinition(ItemId.dye);
472
let slots = inventory.slots;
473
for (const out of outputs)
526
const origin = craftOrigin(CraftOriginVerb.mixed, characterDisplayName(world, handle));
527
const inserted = insertStack(inventory.slots, attachOrigins({
528
itemId: ItemId.dye,
529
quantity: produced,
530
instance: mixed.instance,
531
origins: [{ origin, quantity: produced }]
532
}), dyeDef);
533
if (!inserted.ok)
474
534
{
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;
535
throw userError("Not enough inventory space for dye.");
485
536
}
486
inventory.slots = slots;
487
session.lastSuccessRecipe = null;
488
clearBrew(session);
537
inventory.slots = inserted.slots;
538
clearDyeSlots(session);
489
539
490
const sample = outputs[0]?.instance;
491
540
return {
492
541
events: [],
493
542
private: bagView(world.ecs, handle),
@@ -496,15 +545,15 @@ function bottleDyeResult (world, handle, session, inventory, dyePath)
496
545
alchemyResult: {
497
546
success: true,
498
547
reason: null,
499
produced: outputs.length,
500
wanted: outputs.length,
501
lost: 0,
548
produced,
549
wanted,
550
lost: Math.max(0, wanted - produced),
502
551
potion: {
503
552
potionKey: "dye",
504
553
displayName: "Dye",
505
554
unstable: false,
506
color: sample?.color ?? null,
507
fillLevel: sample?.fillLevel ?? DEFAULT_DYE_FILL
555
color: mixed.instance?.color ?? null,
556
fillLevel: mixed.instance?.fillLevel ?? DEFAULT_DYE_FILL
508
557
}
509
558
}
510
559
};
@@ -515,7 +564,7 @@ function clear (world, sessionId, command)
515
564
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
516
565
requireNearCauldron(world, handle);
517
566
const session = requireSession(world, command.characterId);
518
clearBrew(session);
567
clearAlchemy(session);
519
568
session.lastSuccessRecipe = null;
520
569
return {
521
570
events: [],
@@ -525,6 +574,20 @@ function clear (world, sessionId, command)
525
574
};
526
575
}
527
576
577
function clearDye (world, sessionId, command)
578
{
579
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
580
requireNearCauldron(world, handle);
581
const session = requireSession(world, command.characterId);
582
clearDyeSlots(session);
583
return {
584
events: [],
585
private: bagView(world.ecs, handle),
586
cauldron: true,
587
cauldronState: sessionView(session)
588
};
589
}
590
528
591
function saveRecipe (world, sessionId, command)
529
592
{
530
593
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -537,8 +600,7 @@ function saveRecipe (world, sessionId, command)
537
600
const inventory = ensureInventory(world, handle);
538
601
const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);
539
602
if (paperIndex < 0)
540
{ throw userError("You need a sheet of paper."); }
541
603
{ throw userError("You need paper to write a recipe."); }
542
604
const paperSlot = inventory.slots[paperIndex];
543
605
const recipeStack = {
544
606
itemId: ItemId.recipePaper,
@@ -1,17 +1,21 @@1
import { Component } from "../ecs/components.js";1
import { Component } from "../ecs/components.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";2
import { BlockType } from "../../../shared/definitions/tiles.js";3
import { AlchemyStepKind, CAULDRON_SLOT_COUNT } from "../../../shared/definitions/alchemy.js";3
import {4
AlchemyStepKind,5
CAULDRON_SLOT_COUNT,6
DYE_CAULDRON_SLOT_COUNT7
} from "../../../shared/definitions/alchemy.js";4
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";8
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";5
import {9
import {6
evaluateAlchemyBottle,10
evaluateAlchemyBottle,7
potionItemInstance,11
potionItemInstance,8
recipePaperBody,12
recipePaperBody,9
resolvedAlchemyPotions13
resolvedAlchemyPotions,14
cauldronFlavorText10
} from "../../../shared/alchemy/recipes.js";15
} from "../../../shared/alchemy/recipes.js";11
import {16
import {12
dyeItemInstance,13
DEFAULT_DYE_FILL,17
DEFAULT_DYE_FILL,14
mixDyeBatches18
mixFlowersForDye15
} from "../../../shared/definitions/dyes.js";19
} from "../../../shared/definitions/dyes.js";16
import { bagView } from "../items/bags.js";20
import { bagView } from "../items/bags.js";17
import {21
import {@@ -22,6 +26,7 @@ import {22
takeMatchingFromSlots,26
takeMatchingFromSlots,23
stackQuantity27
stackQuantity24
} from "../../../shared/items/inventory.js";28
} from "../../../shared/items/inventory.js";29
import { attachOrigins, craftOrigin, CraftOriginVerb } from "../../../shared/items/origin.js";25
import { tileToChunk, tileToLocal } from "../world/coordinates.js";30
import { tileToChunk, tileToLocal } from "../world/coordinates.js";26
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";31
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";27
import { randomUUID } from "node:crypto";32
import { randomUUID } from "node:crypto";@@ -39,6 +44,13 @@ function userError (message)39
return error;44
return error;40
}45
}41
46
47
function characterDisplayName (world, handle)48
{49
const appearance = world.ecs.get(handle, Component.appearance);50
const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();51
return name || "someone";52
}53
42
function ensureSessions (world)54
function ensureSessions (world)43
{55
{44
if (!world.cauldronSessions)56
if (!world.cauldronSessions)@@ -50,20 +62,45 @@ function emptySession ()50
{62
{51
return {63
return {52
slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),64
slots: Array.from({ length: CAULDRON_SLOT_COUNT }, () => null),65
dyeSlots: Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null),53
brew: [],66
brew: [],54
steps: [],67
steps: [],55
lastSuccessRecipe: null68
lastSuccessRecipe: null56
};69
};57
}70
}58
71
72
function normalizeSession (session)73
{74
if (!Array.isArray(session.dyeSlots) || session.dyeSlots.length !== DYE_CAULDRON_SLOT_COUNT)75
{ session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null); }76
return session;77
}78
79
function slotView (slot)80
{81
if (!slot)82
{ return null; }83
return {84
itemId: slot.itemId,85
quantity: slot.quantity | 0,86
instance: slot.instance ? structuredClone(slot.instance) : null87
};88
}89
59
function sessionView (session)90
function sessionView (session)60
{91
{92
const steps = session.steps ?? [];61
return {93
return {62
slots: (session.slots ?? []).map((slot) => (slot94
slots: (session.slots ?? []).map(slotView),63
? { itemId: slot.itemId, quantity: slot.quantity | 0 }95
dyeSlots: (session.dyeSlots ?? []).map(slotView),64
: null)),96
brew: (session.brew ?? []).map((row) => ({65
brew: (session.brew ?? []).map((row) => ({ itemId: row.itemId, quantity: row.quantity | 0 })),97
itemId: row.itemId,66
steps: (session.steps ?? []).map((step) => ({ ...step })),98
quantity: row.quantity | 0,99
instance: row.instance ? structuredClone(row.instance) : null100
})),101
steps: steps.map((step) => ({ ...step })),102
flavorText: cauldronFlavorText(steps),103
canProcessActions: steps.some((step) => step.kind === AlchemyStepKind.insert),67
canSaveRecipe: !!session.lastSuccessRecipe,104
canSaveRecipe: !!session.lastSuccessRecipe,68
lastSuccess: session.lastSuccessRecipe105
lastSuccess: session.lastSuccessRecipe69
? {106
? {@@ -102,16 +139,21 @@ function requireSession (world, characterId)102
const session = ensureSessions(world).get(characterId);139
const session = ensureSessions(world).get(characterId);103
if (!session)140
if (!session)104
{ throw userError("Open a cauldron first."); }141
{ throw userError("Open a cauldron first."); }105
return session;142
return normalizeSession(session);106
}143
}107
144
108
function clearBrew (session)145
function clearAlchemy (session)109
{146
{110
session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);147
session.slots = Array.from({ length: CAULDRON_SLOT_COUNT }, () => null);111
session.brew = [];148
session.brew = [];112
session.steps = [];149
session.steps = [];113
}150
}114
151
152
function clearDyeSlots (session)153
{154
session.dyeSlots = Array.from({ length: DYE_CAULDRON_SLOT_COUNT }, () => null);155
}156
115
function ensureInventory (world, handle)157
function ensureInventory (world, handle)116
{158
{117
let inventory = world.ecs.get(handle, Component.inventory);159
let inventory = world.ecs.get(handle, Component.inventory);@@ -129,14 +171,20 @@ export function handleAlchemyCommand (world, sessionId, command)129
return openCauldron(world, sessionId, command);171
return openCauldron(world, sessionId, command);130
case "cauldron-set-slot":172
case "cauldron-set-slot":131
return setSlot(world, sessionId, command);173
return setSlot(world, sessionId, command);174
case "cauldron-set-dye-slot":175
return setDyeSlot(world, sessionId, command);132
case "cauldron-insert":176
case "cauldron-insert":133
return insertFromSlot(world, sessionId, command);177
return insertFromSlot(world, sessionId, command);134
case "cauldron-action":178
case "cauldron-action":135
return action(world, sessionId, command);179
return action(world, sessionId, command);136
case "cauldron-bottle":180
case "cauldron-bottle":137
return bottle(world, sessionId, command);181
return bottle(world, sessionId, command);182
case "cauldron-create-dye":183
return createDye(world, sessionId, command);138
case "cauldron-clear":184
case "cauldron-clear":139
return clear(world, sessionId, command);185
return clear(world, sessionId, command);186
case "cauldron-clear-dye":187
return clearDye(world, sessionId, command);140
case "cauldron-save-recipe":188
case "cauldron-save-recipe":141
return saveRecipe(world, sessionId, command);189
return saveRecipe(world, sessionId, command);142
case "cauldron-close":190
case "cauldron-close":@@ -150,8 +198,12 @@ function openCauldron (world, sessionId, command)150
{198
{151
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);199
const { handle, entityId } = world.requireOwnedEntity(sessionId, command.characterId);152
requireNearCauldron(world, handle);200
requireNearCauldron(world, handle);201
const inventory = ensureInventory(world, handle);202
if (countItemInSlots(inventory.slots, ItemId.glassBottle) < 1)203
{ throw userError("I don't have any empty bottles."); }204
153
const sessions = ensureSessions(world);205
const sessions = ensureSessions(world);154
const existing = sessions.get(command.characterId) ?? emptySession();206
const existing = normalizeSession(sessions.get(command.characterId) ?? emptySession());155
sessions.set(command.characterId, existing);207
sessions.set(command.characterId, existing);156
const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);208
const shove = tileShoveTowardBlock(world, handle, entityId, BlockType.cauldron);157
return {209
return {@@ -192,49 +244,72 @@ function setSlot (world, sessionId, command)192
}244
}193
245
194
const def = itemDefinition(itemId);246
const def = itemDefinition(itemId);195
if (!def || def.uniqueInstance || def.equipment || itemId === ItemId.potion || itemId === ItemId.glassBottle)247
if (!def || def.uniqueInstance || def.equipment196
{ throw userError("That cannot go in a cauldron slot."); }248
|| itemId === ItemId.potion || itemId === ItemId.glassBottle197
if (itemId === ItemId.dye || itemId === ItemId.flower)249
|| itemId === ItemId.flower || itemId === ItemId.dye || def.flower || def.dye)250
{ throw userError("Use the Dyes tab for flowers."); }251
252
const inventory = ensureInventory(world, handle);253
const have = countItemInSlots(inventory.slots, itemId);254
if (have < quantity)255
{ throw userError("Not enough of that item in your inventory."); }256
257
session.slots[slotIndex] = { itemId, quantity, instance: null };258
return {259
events: [],260
private: bagView(world.ecs, handle),261
cauldron: true,262
cauldronState: sessionView(session)263
};264
}265
266
function setDyeSlot (world, sessionId, command)267
{268
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);269
requireNearCauldron(world, handle);270
const session = requireSession(world, command.characterId);271
const slotIndex = command.slotIndex | 0;272
if (slotIndex < 0 || slotIndex >= DYE_CAULDRON_SLOT_COUNT)273
{ throw userError("Invalid dye slot."); }274
275
const itemId = command.itemId | 0;276
const quantity = Math.max(0, command.quantity | 0);277
if (!itemId || quantity <= 0)198
{278
{199
// Allowed — instances are captured on insert.279
session.dyeSlots[slotIndex] = null;280
return {281
events: [],282
private: bagView(world.ecs, handle),283
cauldron: true,284
cauldronState: sessionView(session)285
};200
}286
}201
else if (def.dye || def.flower)287
202
{ /* ok */ }288
if (itemId !== ItemId.flower)289
{ throw userError("Only flowers go in dye slots."); }203
290
204
const inventory = ensureInventory(world, handle);291
const inventory = ensureInventory(world, handle);205
let instance = null;292
const wanted = command.instance ? structuredClone(command.instance) : null;206
if (itemId === ItemId.flower || itemId === ItemId.dye)293
let instance = wanted;294
if (!instance)207
{295
{208
const wanted = command.instance ? structuredClone(command.instance) : null;296
for (const slot of inventory.slots)209
if (wanted)210
{ instance = wanted; }211
else212
{297
{213
for (const slot of inventory.slots)298
if (slot?.itemId === ItemId.flower && slot.instance)214
{299
{215
if (slot?.itemId === itemId && slot.instance)300
instance = structuredClone(slot.instance);216
{301
break;217
instance = structuredClone(slot.instance);218
break;219
}220
}302
}221
}303
}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
else231
{232
const have = countItemInSlots(inventory.slots, itemId);233
if (have < quantity)234
{ throw userError("Not enough of that item in your inventory."); }235
}304
}305
if (!instance?.color)306
{ throw userError("That flower has no colour."); }236
307
237
session.slots[slotIndex] = { itemId, quantity, instance };308
const have = countMatchingInstance(inventory.slots, ItemId.flower, instance);309
if (have < quantity)310
{ throw userError("Not enough of that flower in your inventory."); }311
312
session.dyeSlots[slotIndex] = { itemId: ItemId.flower, quantity, instance };238
return {313
return {239
events: [],314
events: [],240
private: bagView(world.ecs, handle),315
private: bagView(world.ecs, handle),@@ -300,6 +375,8 @@ function action (world, sessionId, command)300
const kind = command.action;375
const kind = command.action;301
if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)376
if (kind !== AlchemyStepKind.stir && kind !== AlchemyStepKind.heat && kind !== AlchemyStepKind.cool)302
{ throw userError("Unknown cauldron action."); }377
{ throw userError("Unknown cauldron action."); }378
if (!session.steps.some((step) => step.kind === AlchemyStepKind.insert))379
{ throw userError("Insert an ingredient first."); }303
session.steps.push({ kind });380
session.steps.push({ kind });304
session.lastSuccessRecipe = null;381
session.lastSuccessRecipe = null;305
return {382
return {@@ -319,14 +396,6 @@ function bottle (world, sessionId, command)319
{ throw userError("The cauldron is empty."); }396
{ throw userError("The cauldron is empty."); }320
397
321
const inventory = ensureInventory(world, handle);398
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
330
const skills = world.ecs.get(handle, Component.skills) ?? {};399
const skills = world.ecs.get(handle, Component.skills) ?? {};331
400
332
const evaluation = evaluateAlchemyBottle({401
const evaluation = evaluateAlchemyBottle({@@ -353,11 +422,13 @@ function bottle (world, sessionId, command)353
422
354
const instance = potionItemInstance(evaluation.result);423
const instance = potionItemInstance(evaluation.result);355
const potionDef = itemDefinition(ItemId.potion);424
const potionDef = itemDefinition(ItemId.potion);356
const inserted = insertStack(inventory.slots, {425
const origin = craftOrigin(CraftOriginVerb.brewed, characterDisplayName(world, handle));426
const inserted = insertStack(inventory.slots, attachOrigins({357
itemId: ItemId.potion,427
itemId: ItemId.potion,358
quantity: produced,428
quantity: produced,359
instance429
instance,360
}, potionDef);430
origins: [{ origin, quantity: produced }]431
}), potionDef);361
if (!inserted.ok)432
if (!inserted.ok)362
{433
{363
const refund = insertStack(inventory.slots, {434
const refund = insertStack(inventory.slots, {@@ -370,7 +441,7 @@ function bottle (world, sessionId, command)370
inventory.slots = inserted.slots;441
inventory.slots = inserted.slots;371
442
372
session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;443
session.lastSuccessRecipe = evaluation.success ? evaluation.recipe : null;373
clearBrew(session);444
clearAlchemy(session);374
445
375
return {446
return {376
events: [],447
events: [],@@ -394,100 +465,78 @@ function bottle (world, sessionId, command)394
};465
};395
}466
}396
467
397
/**468
function createDye (world, sessionId, command)398
* @returns {null | { ok: false, reason: string } | { ok: true, mode: "flower"|"mix", ... }}399
*/400
function evaluateDyeBrew (brew)401
{469
{402
const rows = brew ?? [];470
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);471
requireNearCauldron(world, handle);472
const session = requireSession(world, command.characterId);473
const rows = (session.dyeSlots ?? []).filter((slot) => slot?.itemId === ItemId.flower);403
if (!rows.length)474
if (!rows.length)404
{ return null; }475
{ throw userError("Add flowers to make dye."); }405
const hasFlower = rows.some((row) => row.itemId === ItemId.flower);476
406
const hasDye = rows.some((row) => row.itemId === ItemId.dye);477
const mixed = mixFlowersForDye(rows);407
const hasOther = rows.some((row) => row.itemId !== ItemId.flower && row.itemId !== ItemId.dye);478
if (!mixed.ok)408
if (!hasFlower && !hasDye)479
{ throw userError(mixed.reason); }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
480
415
if (hasFlower)481
const wanted = mixed.quantity;482
const inventory = ensureInventory(world, handle);483
const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);484
if (bottles < wanted && !command.confirmOverflow)416
{485
{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 {486
return {425
ok: true,487
events: [],426
mode: "flower",488
private: bagView(world.ecs, handle),427
quantity: Math.max(1, quantity),489
cauldron: true,428
instance: dyeItemInstance(sample.instance.color, DEFAULT_DYE_FILL, sample.instance.colorId)490
cauldronState: sessionView(session),491
dyeConfirm: {492
wanted,493
bottles,494
lost: Math.max(0, wanted - bottles)495
}429
};496
};430
}497
}431
498
432
const mixed = mixDyeBatches(rows);499
const produced = Math.min(wanted, bottles);433
if (!mixed.ok)500
if (produced <= 0)434
{ return { ok: false, reason: mixed.reason }; }501
{ throw userError("You need glass bottles to bottle the dye."); }435
return { ok: true, mode: "mix", ...mixed };436
}437
502
438
function bottleDyeResult (world, handle, session, inventory, dyePath)503
for (const row of rows)439
{440
const outputs = dyePath.mode === "flower"441
? Array.from({ length: dyePath.quantity }, () => ({442
quantity: 1,443
instance: dyePath.instance444
}))445
: dyePath.outputs;446
447
// Flowers need empty glass bottles. Dye remixes reuse the bottles already448
// consumed into the brew; only overflow bottles need extra glass.449
const bottleNeed = dyePath.mode === "flower"450
? outputs.length451
: Math.max(0, dyePath.extraBottles | 0);452
if (bottleNeed > 0)453
{504
{454
const bottles = countItemInSlots(inventory.slots, ItemId.glassBottle);505
const pulled = takeMatchingFromSlots(inventory.slots, {455
if (bottles < bottleNeed)506
itemId: ItemId.flower,456
{507
quantity: row.quantity,457
throw userError(508
instance: row.instance,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: false509
compact: false465
});510
});466
if (!takeBottles.ok)511
if (!pulled.ok)467
{ throw userError("You need glass bottles to bottle the dye."); }512
{ throw userError("Not enough of those flowers in your inventory."); }468
inventory.slots = takeBottles.slots;513
inventory.slots = pulled.slots;469
}514
}470
515
516
const takeBottles = takeMatchingFromSlots(inventory.slots, {517
itemId: ItemId.glassBottle,518
quantity: produced,519
compact: false520
});521
if (!takeBottles.ok)522
{ throw userError("You need glass bottles to bottle the dye."); }523
inventory.slots = takeBottles.slots;524
471
const dyeDef = itemDefinition(ItemId.dye);525
const dyeDef = itemDefinition(ItemId.dye);472
let slots = inventory.slots;526
const origin = craftOrigin(CraftOriginVerb.mixed, characterDisplayName(world, handle));473
for (const out of outputs)527
const inserted = insertStack(inventory.slots, attachOrigins({528
itemId: ItemId.dye,529
quantity: produced,530
instance: mixed.instance,531
origins: [{ origin, quantity: produced }]532
}), dyeDef);533
if (!inserted.ok)474
{534
{475
const inserted = insertStack(slots, {535
throw userError("Not enough inventory space for dye.");476
itemId: ItemId.dye,477
quantity: out.quantity,478
instance: out.instance479
}, dyeDef);480
if (!inserted.ok)481
{482
throw userError("Not enough inventory space for dye.");483
}484
slots = inserted.slots;485
}536
}486
inventory.slots = slots;537
inventory.slots = inserted.slots;487
session.lastSuccessRecipe = null;538
clearDyeSlots(session);488
clearBrew(session);489
539
490
const sample = outputs[0]?.instance;491
return {540
return {492
events: [],541
events: [],493
private: bagView(world.ecs, handle),542
private: bagView(world.ecs, handle),@@ -496,15 +545,15 @@ function bottleDyeResult (world, handle, session, inventory, dyePath)496
alchemyResult: {545
alchemyResult: {497
success: true,546
success: true,498
reason: null,547
reason: null,499
produced: outputs.length,548
produced,500
wanted: outputs.length,549
wanted,501
lost: 0,550
lost: Math.max(0, wanted - produced),502
potion: {551
potion: {503
potionKey: "dye",552
potionKey: "dye",504
displayName: "Dye",553
displayName: "Dye",505
unstable: false,554
unstable: false,506
color: sample?.color ?? null,555
color: mixed.instance?.color ?? null,507
fillLevel: sample?.fillLevel ?? DEFAULT_DYE_FILL556
fillLevel: mixed.instance?.fillLevel ?? DEFAULT_DYE_FILL508
}557
}509
}558
}510
};559
};@@ -515,7 +564,7 @@ function clear (world, sessionId, command)515
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);564
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);516
requireNearCauldron(world, handle);565
requireNearCauldron(world, handle);517
const session = requireSession(world, command.characterId);566
const session = requireSession(world, command.characterId);518
clearBrew(session);567
clearAlchemy(session);519
session.lastSuccessRecipe = null;568
session.lastSuccessRecipe = null;520
return {569
return {521
events: [],570
events: [],@@ -525,6 +574,20 @@ function clear (world, sessionId, command)525
};574
};526
}575
}527
576
577
function clearDye (world, sessionId, command)578
{579
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);580
requireNearCauldron(world, handle);581
const session = requireSession(world, command.characterId);582
clearDyeSlots(session);583
return {584
events: [],585
private: bagView(world.ecs, handle),586
cauldron: true,587
cauldronState: sessionView(session)588
};589
}590
528
function saveRecipe (world, sessionId, command)591
function saveRecipe (world, sessionId, command)529
{592
{530
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);593
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);@@ -537,8 +600,7 @@ function saveRecipe (world, sessionId, command)537
const inventory = ensureInventory(world, handle);600
const inventory = ensureInventory(world, handle);538
const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);601
const paperIndex = inventory.slots.findIndex((slot) => slot?.itemId === ItemId.paper);539
if (paperIndex < 0)602
if (paperIndex < 0)540
{ throw userError("You need a sheet of paper."); }603
{ throw userError("You need paper to write a recipe."); }541
542
const paperSlot = inventory.slots[paperIndex];604
const paperSlot = inventory.slots[paperIndex];543
const recipeStack = {605
const recipeStack = {544
itemId: ItemId.recipePaper,606
itemId: ItemId.recipePaper,@@ -9,6 +9,11 @@ import {
9
9
materialTintColor,
10
10
WOOD_TIER_ORDER
11
11
} from "../../../shared/definitions/materialTiers.js";
12
import {
13
FLOWER_COLOR_ORDER,
14
flowerBlockState,
15
flowerColorRgb
16
} from "../../../shared/definitions/dyes.js";
12
17
import {
13
18
bloomImageName,
14
19
equipBloomImageName,
@@ -200,6 +205,26 @@ function scanLayer (layerDir, definitions, layer, urlFolder)
200
205
}
201
206
}
202
207
208
if (layer === "block" && def.key === "flower")
209
{
210
states = [];
211
for (const colorId of FLOWER_COLOR_ORDER)
212
{
213
const state = flowerBlockState(colorId);
214
states.push(state);
215
const tint = flowerColorRgb(colorId);
216
imagesForType.push({
217
name: spriteImageName(layer, def.key, state),
218
url: `/assets/${urlFolder}/${def.key}/flower.png`,
219
subImgTotal: frames,
220
perRow: framesPerRow,
221
loop: animationSpeed > 0,
222
animationSpeed,
223
tint: { r: tint.r, g: tint.g, b: tint.b }
224
});
225
}
226
}
227
203
228
if (layer === "block" && def.key === "table")
204
229
{
205
230
// Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
@@ -9,6 +9,11 @@ import {9
materialTintColor,9
materialTintColor,10
WOOD_TIER_ORDER10
WOOD_TIER_ORDER11
} from "../../../shared/definitions/materialTiers.js";11
} from "../../../shared/definitions/materialTiers.js";12
import {13
FLOWER_COLOR_ORDER,14
flowerBlockState,15
flowerColorRgb16
} from "../../../shared/definitions/dyes.js";12
import {17
import {13
bloomImageName,18
bloomImageName,14
equipBloomImageName,19
equipBloomImageName,@@ -200,6 +205,26 @@ function scanLayer (layerDir, definitions, layer, urlFolder)200
}205
}201
}206
}202
207
208
if (layer === "block" && def.key === "flower")209
{210
states = [];211
for (const colorId of FLOWER_COLOR_ORDER)212
{213
const state = flowerBlockState(colorId);214
states.push(state);215
const tint = flowerColorRgb(colorId);216
imagesForType.push({217
name: spriteImageName(layer, def.key, state),218
url: `/assets/${urlFolder}/${def.key}/flower.png`,219
subImgTotal: frames,220
perRow: framesPerRow,221
loop: animationSpeed > 0,222
animationSpeed,223
tint: { r: tint.r, g: tint.g, b: tint.b }224
});225
}226
}227
203
if (layer === "block" && def.key === "table")228
if (layer === "block" && def.key === "table")204
{229
{205
// Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.230
// Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.@@ -289,6 +289,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
289
289
instance: message.instance ?? null
290
290
});
291
291
break;
292
case MessageType.cauldronSetDyeSlot:
293
requirePlaying(session);
294
simulation.enqueue(session.id, {
295
type: "cauldron-set-dye-slot",
296
characterId: session.characterId,
297
slotIndex: message.slotIndex | 0,
298
itemId: message.itemId | 0,
299
quantity: message.quantity | 0,
300
instance: message.instance ?? null
301
});
302
break;
292
303
case MessageType.cauldronInsert:
293
304
requirePlaying(session);
294
305
simulation.enqueue(session.id, {
@@ -312,6 +323,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
312
323
characterId: session.characterId
313
324
});
314
325
break;
326
case MessageType.cauldronCreateDye:
327
requirePlaying(session);
328
simulation.enqueue(session.id, {
329
type: "cauldron-create-dye",
330
characterId: session.characterId,
331
confirmOverflow: !!message.confirmOverflow
332
});
333
break;
315
334
case MessageType.cauldronClear:
316
335
requirePlaying(session);
317
336
simulation.enqueue(session.id, {
@@ -319,6 +338,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
319
338
characterId: session.characterId
320
339
});
321
340
break;
341
case MessageType.cauldronClearDye:
342
requirePlaying(session);
343
simulation.enqueue(session.id, {
344
type: "cauldron-clear-dye",
345
characterId: session.characterId
346
});
347
break;
322
348
case MessageType.cauldronSaveRecipe:
323
349
requirePlaying(session);
324
350
simulation.enqueue(session.id, {
@@ -834,7 +860,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
834
860
type: MessageType.cauldronSnapshot,
835
861
open: !!event.cauldron,
836
862
state: event.cauldronState ?? null,
837
alchemyResult: event.alchemyResult ?? null
863
alchemyResult: event.alchemyResult ?? null,
864
dyeConfirm: event.dyeConfirm ?? null
838
865
});
839
866
}
840
867
continue;
@@ -289,6 +289,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,289
instance: message.instance ?? null289
instance: message.instance ?? null290
});290
});291
break;291
break;292
case MessageType.cauldronSetDyeSlot:293
requirePlaying(session);294
simulation.enqueue(session.id, {295
type: "cauldron-set-dye-slot",296
characterId: session.characterId,297
slotIndex: message.slotIndex | 0,298
itemId: message.itemId | 0,299
quantity: message.quantity | 0,300
instance: message.instance ?? null301
});302
break;292
case MessageType.cauldronInsert:303
case MessageType.cauldronInsert:293
requirePlaying(session);304
requirePlaying(session);294
simulation.enqueue(session.id, {305
simulation.enqueue(session.id, {@@ -312,6 +323,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,312
characterId: session.characterId323
characterId: session.characterId313
});324
});314
break;325
break;326
case MessageType.cauldronCreateDye:327
requirePlaying(session);328
simulation.enqueue(session.id, {329
type: "cauldron-create-dye",330
characterId: session.characterId,331
confirmOverflow: !!message.confirmOverflow332
});333
break;315
case MessageType.cauldronClear:334
case MessageType.cauldronClear:316
requirePlaying(session);335
requirePlaying(session);317
simulation.enqueue(session.id, {336
simulation.enqueue(session.id, {@@ -319,6 +338,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,319
characterId: session.characterId338
characterId: session.characterId320
});339
});321
break;340
break;341
case MessageType.cauldronClearDye:342
requirePlaying(session);343
simulation.enqueue(session.id, {344
type: "cauldron-clear-dye",345
characterId: session.characterId346
});347
break;322
case MessageType.cauldronSaveRecipe:348
case MessageType.cauldronSaveRecipe:323
requirePlaying(session);349
requirePlaying(session);324
simulation.enqueue(session.id, {350
simulation.enqueue(session.id, {@@ -834,7 +860,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,834
type: MessageType.cauldronSnapshot,860
type: MessageType.cauldronSnapshot,835
open: !!event.cauldron,861
open: !!event.cauldron,836
state: event.cauldronState ?? null,862
state: event.cauldronState ?? null,837
alchemyResult: event.alchemyResult ?? null863
alchemyResult: event.alchemyResult ?? null,864
dyeConfirm: event.dyeConfirm ?? null838
});865
});839
}866
}840
continue;867
continue;@@ -25,6 +25,8 @@ import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
25
25
import { ClothTier } from "../../../shared/definitions/materialTiers.js";
26
26
import {
27
27
flowerItemInstance,
28
flowerColorIdFromBlockState,
29
flowerBlockState,
28
30
randomFlowerColorId
29
31
} from "../../../shared/definitions/dyes.js";
30
32
import { insertStack } from "../../../shared/items/inventory.js";
@@ -300,7 +302,10 @@ export function stepPlantRespawns (world, now)
300
302
const existing = blockAt(world, entry.tileX, entry.tileY);
301
303
if (existing)
302
304
{ continue; }
303
const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, entry.state);
305
const state = entry.typeId === BlockType.flower
306
? flowerBlockState(randomFlowerColorId())
307
: (entry.state ?? "cotton-plant");
308
const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);
304
309
if (delta)
305
310
{ events.push(delta); }
306
311
}
@@ -426,7 +431,7 @@ export function startChop (world, sessionId, characterId, tileX, tileY, now)
426
431
}
427
432
428
433
/**
429
* Pick a plant node (flower with clippers, cotton without tools).
434
* Pick a plant node (flower / cotton; no tools required).
430
435
*/
431
436
export function startPick (world, sessionId, characterId, tileX, tileY, now)
432
437
{
@@ -462,18 +467,43 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
462
467
{ throw userError(clippers.reason); }
463
468
464
469
const toolTier = clippers.tool?.tier ?? null;
465
const durationMs = herbalismDurationMs(toolTier);
470
const durationMs = herbalismDurationMs(plant.kind, toolTier);
466
471
const toolItemId = clippers.tool?.stack?.itemId ?? null;
467
return beginGatherSwing(world, handle, entityId, position, {
472
const prefixEvents = [];
473
let flowerColorId = null;
474
if (plant.kind === "flower")
475
{
476
flowerColorId = flowerColorIdFromBlockState(block.state);
477
if (!flowerColorId)
478
{
479
// Legacy / uncoloured placements: lock a colour before the pick starts.
480
flowerColorId = randomFlowerColorId();
481
const delta = setBlockState(
482
world,
483
tileX,
484
tileY,
485
BlockType.flower,
486
flowerBlockState(flowerColorId)
487
);
488
if (delta)
489
{ prefixEvents.push(delta); }
490
}
491
}
492
const started = beginGatherSwing(world, handle, entityId, position, {
468
493
kind: "plant",
469
494
plantKind: plant.kind,
470
495
tileX,
471
496
tileY,
472
497
typeId: block.typeId,
498
flowerColorId,
473
499
toolTier,
474
500
toolItemId,
475
501
durationMs
476
502
}, now);
503
return {
504
...started,
505
events: [...prefixEvents, ...(started.events ?? [])]
506
};
477
507
}
478
508
479
509
function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])
@@ -650,7 +680,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv
650
680
if (gather.plantKind === "flower")
651
681
{
652
682
itemId = ItemId.flower;
653
instance = flowerItemInstance(randomFlowerColorId());
683
const live = blockAt(world, gather.tileX, gather.tileY);
684
const colorId = gather.flowerColorId
685
?? flowerColorIdFromBlockState(live?.state)
686
?? randomFlowerColorId();
687
instance = flowerItemInstance(colorId);
654
688
}
655
689
else if (gather.plantKind === "cotton")
656
690
{
@@ -708,7 +742,8 @@ function completePlant (world, handle, entityId, character, gather, events, priv
708
742
tileX: gather.tileX,
709
743
tileY: gather.tileY,
710
744
typeId: gather.typeId,
711
state: gather.plantKind === "flower" ? "flower" : "cotton-plant",
745
// Colour is chosen when the node refreshes (see stepPlantRespawns).
746
state: gather.plantKind === "flower" ? null : "cotton-plant",
712
747
respawnsAt: now + PLANT_EXHAUST_MS
713
748
});
714
749
@@ -25,6 +25,8 @@ import { rawClothItemId } from "../../../shared/definitions/clothItems.js";25
import { ClothTier } from "../../../shared/definitions/materialTiers.js";25
import { ClothTier } from "../../../shared/definitions/materialTiers.js";26
import {26
import {27
flowerItemInstance,27
flowerItemInstance,28
flowerColorIdFromBlockState,29
flowerBlockState,28
randomFlowerColorId30
randomFlowerColorId29
} from "../../../shared/definitions/dyes.js";31
} from "../../../shared/definitions/dyes.js";30
import { insertStack } from "../../../shared/items/inventory.js";32
import { insertStack } from "../../../shared/items/inventory.js";@@ -300,7 +302,10 @@ export function stepPlantRespawns (world, now)300
const existing = blockAt(world, entry.tileX, entry.tileY);302
const existing = blockAt(world, entry.tileX, entry.tileY);301
if (existing)303
if (existing)302
{ continue; }304
{ continue; }303
const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, entry.state);305
const state = entry.typeId === BlockType.flower306
? flowerBlockState(randomFlowerColorId())307
: (entry.state ?? "cotton-plant");308
const delta = placeBlock(world, entry.tileX, entry.tileY, entry.typeId, state);304
if (delta)309
if (delta)305
{ events.push(delta); }310
{ events.push(delta); }306
}311
}@@ -426,7 +431,7 @@ export function startChop (world, sessionId, characterId, tileX, tileY, now)426
}431
}427
432
428
/**433
/**429
* Pick a plant node (flower with clippers, cotton without tools).434
* Pick a plant node (flower / cotton; no tools required).430
*/435
*/431
export function startPick (world, sessionId, characterId, tileX, tileY, now)436
export function startPick (world, sessionId, characterId, tileX, tileY, now)432
{437
{@@ -462,18 +467,43 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)462
{ throw userError(clippers.reason); }467
{ throw userError(clippers.reason); }463
468
464
const toolTier = clippers.tool?.tier ?? null;469
const toolTier = clippers.tool?.tier ?? null;465
const durationMs = herbalismDurationMs(toolTier);470
const durationMs = herbalismDurationMs(plant.kind, toolTier);466
const toolItemId = clippers.tool?.stack?.itemId ?? null;471
const toolItemId = clippers.tool?.stack?.itemId ?? null;467
return beginGatherSwing(world, handle, entityId, position, {472
const prefixEvents = [];473
let flowerColorId = null;474
if (plant.kind === "flower")475
{476
flowerColorId = flowerColorIdFromBlockState(block.state);477
if (!flowerColorId)478
{479
// Legacy / uncoloured placements: lock a colour before the pick starts.480
flowerColorId = randomFlowerColorId();481
const delta = setBlockState(482
world,483
tileX,484
tileY,485
BlockType.flower,486
flowerBlockState(flowerColorId)487
);488
if (delta)489
{ prefixEvents.push(delta); }490
}491
}492
const started = beginGatherSwing(world, handle, entityId, position, {468
kind: "plant",493
kind: "plant",469
plantKind: plant.kind,494
plantKind: plant.kind,470
tileX,495
tileX,471
tileY,496
tileY,472
typeId: block.typeId,497
typeId: block.typeId,498
flowerColorId,473
toolTier,499
toolTier,474
toolItemId,500
toolItemId,475
durationMs501
durationMs476
}, now);502
}, now);503
return {504
...started,505
events: [...prefixEvents, ...(started.events ?? [])]506
};477
}507
}478
508
479
function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])509
function pushBagUpdate (events, privates, world, handle, entityId, character, skillsChanged, skills, levelUps = [])@@ -650,7 +680,11 @@ function completePlant (world, handle, entityId, character, gather, events, priv650
if (gather.plantKind === "flower")680
if (gather.plantKind === "flower")651
{681
{652
itemId = ItemId.flower;682
itemId = ItemId.flower;653
instance = flowerItemInstance(randomFlowerColorId());683
const live = blockAt(world, gather.tileX, gather.tileY);684
const colorId = gather.flowerColorId685
?? flowerColorIdFromBlockState(live?.state)686
?? randomFlowerColorId();687
instance = flowerItemInstance(colorId);654
}688
}655
else if (gather.plantKind === "cotton")689
else if (gather.plantKind === "cotton")656
{690
{@@ -708,7 +742,8 @@ function completePlant (world, handle, entityId, character, gather, events, priv708
tileX: gather.tileX,742
tileX: gather.tileX,709
tileY: gather.tileY,743
tileY: gather.tileY,710
typeId: gather.typeId,744
typeId: gather.typeId,711
state: gather.plantKind === "flower" ? "flower" : "cotton-plant",745
// Colour is chosen when the node refreshes (see stepPlantRespawns).746
state: gather.plantKind === "flower" ? null : "cotton-plant",712
respawnsAt: now + PLANT_EXHAUST_MS747
respawnsAt: now + PLANT_EXHAUST_MS713
});748
});714
749
@@ -52,8 +52,8 @@ test("green draught ratios and steps evaluate to a success batch", () =>
52
52
{ itemId: ItemId.apple, quantity: 2 }
53
53
],
54
54
takenSteps: [
55
{ kind: AlchemyStepKind.heat },
56
55
{ kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },
56
{ kind: AlchemyStepKind.heat },
57
57
{ kind: AlchemyStepKind.stir },
58
58
{ kind: AlchemyStepKind.insert, itemId: ItemId.apple },
59
59
{ kind: AlchemyStepKind.cool }
@@ -118,12 +118,12 @@ test("cauldron bottles green draught when steps and ratios match", () =>
118
118
});
119
119
harness.simulation.step();
120
120
121
harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });
121
122
harness.simulation.enqueue(1, {
122
123
type: "cauldron-action",
123
124
characterId: cid,
124
125
action: AlchemyStepKind.heat
125
126
});
126
harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });
127
127
harness.simulation.enqueue(1, {
128
128
type: "cauldron-action",
129
129
characterId: cid,
@@ -52,8 +52,8 @@ test("green draught ratios and steps evaluate to a success batch", () =>52
{ itemId: ItemId.apple, quantity: 2 }52
{ itemId: ItemId.apple, quantity: 2 }53
],53
],54
takenSteps: [54
takenSteps: [55
{ kind: AlchemyStepKind.heat },56
{ kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },55
{ kind: AlchemyStepKind.insert, itemId: ItemId.greenHerb },56
{ kind: AlchemyStepKind.heat },57
{ kind: AlchemyStepKind.stir },57
{ kind: AlchemyStepKind.stir },58
{ kind: AlchemyStepKind.insert, itemId: ItemId.apple },58
{ kind: AlchemyStepKind.insert, itemId: ItemId.apple },59
{ kind: AlchemyStepKind.cool }59
{ kind: AlchemyStepKind.cool }@@ -118,12 +118,12 @@ test("cauldron bottles green draught when steps and ratios match", () =>118
});118
});119
harness.simulation.step();119
harness.simulation.step();120
120
121
harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });121
harness.simulation.enqueue(1, {122
harness.simulation.enqueue(1, {122
type: "cauldron-action",123
type: "cauldron-action",123
characterId: cid,124
characterId: cid,124
action: AlchemyStepKind.heat125
action: AlchemyStepKind.heat125
});126
});126
harness.simulation.enqueue(1, { type: "cauldron-insert", characterId: cid, slotIndex: 0 });127
harness.simulation.enqueue(1, {127
harness.simulation.enqueue(1, {128
type: "cauldron-action",128
type: "cauldron-action",129
characterId: cid,129
characterId: cid,