BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

service.js 17.6 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingStationId, CRAFT_DURATION_MS, COOK_BURN_CHANCE_OVEN, COOK_BURN_CHANCE_CAMPFIRE } from "../../../shared/definitions/craftingStations.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
6import { craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import
8{
9 recipeDefinition,
10 canStartCraft,
11 canCraftFitInventory,
12 hasRecipeInputs
13} from "../../../shared/crafting/recipes.js";
14import { resolveTailorCraft } from "../../../shared/crafting/tailor.js";
15import { pickEmptiestDyeSlot } from "../../../shared/crafting/dye.js";
16import { pickEmptiestPotionSlot } from "../../../shared/crafting/potionCharge.js";
17import { dyeColorKey as dyeInstanceColorKey } from "../../../shared/definitions/dyes.js";
18import { craftDurationMs, craftXpForConsumedInputs } from "../../../shared/definitions/gathering.js";
19import { takeFromSlot, insertStack, stackQuantity, consumeFillCharge } from "../../../shared/items/inventory.js";
20import
21{
22 attachOrigins,
23 craftOrigin,
24 craftOriginVerbForStation,
25 CraftOriginVerb
26} from "../../../shared/items/origin.js";
27import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
28import { craftDurationMultiplier } from "../../../shared/equipment/jewelryEffects.js";
29import { bagView } from "../items/bags.js";
30import { tileToChunk, tileToLocal } from "../world/coordinates.js";
31import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
32import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
33
34function userError (message)
35{
36 const error = new Error(message);
37 error.userFacing = true;
38 return error;
39}
40
41function characterDisplayName (world, handle)
42{
43 const appearance = world.ecs.get(handle, Component.appearance);
44 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
45 return name || "someone";
46}
47
48function ensureCraftSessions (world)
49{
50 if (!world.craftSessions)
51 { world.craftSessions = new Map(); }
52 return world.craftSessions;
53}
54
55function nearStationBlock (world, tileX, tileY, blockType)
56{
57 for (let dy = -1; dy <= 1; dy++)
58 {
59 for (let dx = -1; dx <= 1; dx++)
60 {
61 if (dx === 0 && dy === 0)
62 { continue; }
63 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
64 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
65 if (data.blocks[index]?.typeId === blockType)
66 { return true; }
67 }
68 }
69 return false;
70}
71
72function stationBlockType (stationId)
73{
74 if (stationId === CraftingStationId.furnace)
75 { return BlockType.furnace; }
76 if (stationId === CraftingStationId.anvil)
77 { return BlockType.anvil; }
78 if (stationId === CraftingStationId.jeweleringStation)
79 { return BlockType.jeweleringStation; }
80 if (stationId === CraftingStationId.woodworkingBench)
81 { return BlockType.woodworkingBench; }
82 if (stationId === CraftingStationId.craftingBench)
83 { return BlockType.craftingBench; }
84 if (stationId === CraftingStationId.spinningWheel)
85 { return BlockType.spinningWheel; }
86 if (stationId === CraftingStationId.loom)
87 { return BlockType.loom; }
88 if (stationId === CraftingStationId.tailorBench)
89 { return BlockType.tailorBench; }
90 if (stationId === CraftingStationId.leatherworkingStation)
91 { return BlockType.leatherworkingTable; }
92 if (stationId === CraftingStationId.oven)
93 { return BlockType.oven; }
94 if (stationId === CraftingStationId.fireplace)
95 { return BlockType.campfire; }
96 return null;
97}
98
99function cookBurnChance (stationId)
100{
101 if (stationId === CraftingStationId.fireplace)
102 { return COOK_BURN_CHANCE_CAMPFIRE; }
103 if (stationId === CraftingStationId.oven)
104 { return COOK_BURN_CHANCE_OVEN; }
105 return 0;
106}
107
108function takeInputs (slots, inputs)
109{
110 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
111 for (const input of inputs ?? [])
112 {
113 let remaining = Math.max(0, stackQuantity(input.quantity));
114 if (!remaining)
115 { continue; }
116 for (let i = 0; i < next.length && remaining > 0; i++)
117 {
118 if (!next[i] || next[i].itemId !== input.itemId)
119 { continue; }
120 const taken = takeFromSlot(next, i, remaining);
121 if (!taken.ok)
122 { continue; }
123 next = taken.slots;
124 remaining -= stackQuantity(taken.taken?.quantity);
125 }
126 if (remaining > 0)
127 { return { ok: false, slots }; }
128 }
129 return { ok: true, slots: next };
130}
131
132/** Spend one fill level of a dye bottle (remove at 0). Never loses the leftover. */
133function consumeDyeUse (slots, slotIndex)
134{
135 return consumeFillCharge(slots, slotIndex, {
136 kind: "dye",
137 itemId: ItemId.dye
138 });
139}
140
141/** Spend one fill of a potion bottle; exhausted bottles become empty glass. */
142function consumePotionUse (slots, slotIndex)
143{
144 return consumeFillCharge(slots, slotIndex, {
145 kind: "potion",
146 itemId: ItemId.potion,
147 returnEmptyItemId: ItemId.glassBottle
148 });
149}
150
151export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
152{
153 const entityId = world.characterEntities.get(characterId);
154 if (entityId == null)
155 { throw userError("Character is not in the world."); }
156 const handle = world.ecs.handleOf(entityId);
157 const identity = world.ecs.get(handle, Component.networkIdentity);
158 if (!identity || identity.sessionId !== sessionId)
159 { throw userError("Character is not in the world."); }
160 if (world.ecs.has(handle, Component.dead))
161 { throw userError("You are dead."); }
162
163 const stationDef = craftingStationDefinition(stationId);
164 if (!stationDef)
165 { throw userError("Unknown crafting station."); }
166 let recipe = recipeDefinition(recipeId);
167 if (!recipe)
168 { throw userError("Unknown recipe."); }
169 const stationIds = Array.isArray(recipe.stationIds)
170 ? recipe.stationIds
171 : [recipe.stationId];
172 if (!stationIds.includes(stationId))
173 { throw userError("That recipe cannot be made here."); }
174
175 const position = world.ecs.get(handle, Component.position);
176 const blockType = stationBlockType(stationId);
177 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
178 { throw userError("You need to stand next to the station."); }
179
180 const inventory = world.ecs.get(handle, Component.inventory);
181 const skills = world.ecs.get(handle, Component.skills);
182 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
183
184 let dyeColorKey = null;
185 if (recipe.tailorTemplate)
186 {
187 if (stationId !== CraftingStationId.tailorBench)
188 { throw userError("That garment can only be made at a tailor's bench."); }
189 const dyeIdx = options.dyeSlotIndex;
190 let dyeStack = null;
191 if (dyeIdx != null && dyeIdx >= 0)
192 {
193 dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null;
194 dyeColorKey = dyeStack ? dyeInstanceColorKey(dyeStack.instance) : null;
195 }
196 const resolved = resolveTailorCraft({
197 templateId: recipe.tailorTemplate,
198 clothTier: options.clothTier,
199 dyeStack
200 });
201 if (!resolved.ok)
202 { throw userError(resolved.reason); }
203 recipe = resolved.recipe;
204 }
205 else if (options.dyeSlotIndex != null)
206 {
207 // Dye is tailor-only; ignore client-supplied dye on other stations.
208 dyeColorKey = null;
209 }
210
211 if (!canStartCraft(inventory?.slots ?? [], recipe, level, { dyeColorKey, dyeSlotIndex: options.dyeSlotIndex ?? null }))
212 {
213 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
214 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
215 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
216 { throw userError("Missing materials."); }
217 if (recipe.consumeDye && dyeColorKey != null)
218 {
219 const probeSlot = pickEmptiestDyeSlot(inventory?.slots ?? [], dyeColorKey);
220 const dyeProbe = consumeDyeUse(inventory?.slots ?? [], probeSlot);
221 if (!dyeProbe.ok)
222 { throw userError("Need bag space to separate the partially used dye."); }
223 }
224 if (recipe.consumePotionKey)
225 {
226 const probeSlot = pickEmptiestPotionSlot(inventory?.slots ?? [], recipe.consumePotionKey);
227 const potionProbe = consumePotionUse(inventory?.slots ?? [], probeSlot);
228 if (!potionProbe.ok)
229 { throw userError("Need bag space to separate the partially used brew."); }
230 }
231 throw userError("Not enough bag space for the result.");
232 }
233 if (recipe.consumeDye && dyeColorKey != null)
234 {
235 const probeSlot = pickEmptiestDyeSlot(inventory?.slots ?? [], dyeColorKey);
236 const dye = inventory?.slots?.[probeSlot];
237 if (!dye || dye.itemId !== ItemId.dye)
238 { throw userError("Selected dye is missing."); }
239 }
240 if (recipe.consumePotionKey)
241 {
242 const probeSlot = pickEmptiestPotionSlot(inventory?.slots ?? [], recipe.consumePotionKey);
243 if (probeSlot == null)
244 { throw userError("Missing materials."); }
245 }
246
247 const sessions = ensureCraftSessions(world);
248 const equipment = world.ecs.get(handle, Component.equipment);
249 const durationMs = Math.max(
250 1,
251 Math.floor(craftDurationMs(recipe, CRAFT_DURATION_MS) * craftDurationMultiplier(equipment))
252 );
253 let batchRemaining = 1;
254 if (options.batchAll)
255 { batchRemaining = Infinity; }
256 else if (options.batchCount != null)
257 { batchRemaining = Math.max(1, options.batchCount | 0); }
258 sessions.set(characterId, {
259 sessionId,
260 stationId,
261 recipeId,
262 recipe,
263 dyeColorKey,
264 batchRemaining,
265 durationMs,
266 finishesAt: now + durationMs
267 });
268 const events = [];
269 if (blockType)
270 {
271 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
272 if (shove)
273 { events.push(shove); }
274 }
275 events.push({
276 type: "item-bubble",
277 entityId,
278 itemId: recipe.output.itemId,
279 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
280 });
281 events.push({
282 type: "craft-started",
283 sessionId,
284 characterId,
285 recipeId,
286 durationMs
287 });
288 return { events };
289}
290
291export function openStation (world, sessionId, characterId, stationId)
292{
293 const entityId = world.characterEntities.get(characterId);
294 if (entityId == null)
295 { throw userError("Character is not in the world."); }
296 const handle = world.ecs.handleOf(entityId);
297 const identity = world.ecs.get(handle, Component.networkIdentity);
298 if (!identity || identity.sessionId !== sessionId)
299 { throw userError("Character is not in the world."); }
300 if (world.ecs.has(handle, Component.dead))
301 { throw userError("You are dead."); }
302
303 const stationDef = craftingStationDefinition(stationId);
304 if (!stationDef)
305 { throw userError("Unknown crafting station."); }
306 const blockType = stationBlockType(stationId);
307 const position = world.ecs.get(handle, Component.position);
308 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
309 { throw userError("You need to stand next to the station."); }
310
311 const events = [];
312 if (blockType)
313 {
314 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
315 if (shove)
316 { events.push(shove); }
317 }
318 events.push({
319 type: "station-open",
320 sessionId,
321 characterId,
322 stationId
323 });
324 return { events };
325}
326
327export function cancelCraft (world, characterId)
328{
329 ensureCraftSessions(world).delete(characterId);
330 return { events: [] };
331}
332
333export function stepCrafting (world, now)
334{
335 const sessions = ensureCraftSessions(world);
336 const events = [];
337 const privates = [];
338 for (const [characterId, session] of [...sessions.entries()])
339 {
340 if (now < session.finishesAt)
341 { continue; }
342 sessions.delete(characterId);
343 const entityId = world.characterEntities.get(characterId);
344 if (entityId == null)
345 {
346 events.push({
347 type: "craft-result",
348 sessionId: session.sessionId,
349 recipeId: session.recipeId,
350 ok: false,
351 error: "Character left the world."
352 });
353 continue;
354 }
355 const handle = world.ecs.handleOf(entityId);
356 if (world.ecs.has(handle, Component.dead))
357 {
358 events.push({
359 type: "craft-result",
360 sessionId: session.sessionId,
361 recipeId: session.recipeId,
362 ok: false,
363 error: "You are dead."
364 });
365 continue;
366 }
367
368 const recipe = session.recipe ?? recipeDefinition(session.recipeId);
369 const stationDef = craftingStationDefinition(session.stationId);
370 const inventory = world.ecs.get(handle, Component.inventory);
371 const skills = world.ecs.get(handle, Component.skills);
372 const position = world.ecs.get(handle, Component.position);
373 const blockType = stationBlockType(session.stationId);
374 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
375
376 if (!recipe || !stationDef || !inventory
377 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
378 || !canCraftFitInventory(inventory.slots, recipe, { dyeColorKey: session.dyeColorKey })
379 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
380 {
381 events.push({
382 type: "craft-result",
383 sessionId: session.sessionId,
384 recipeId: session.recipeId,
385 ok: false,
386 error: "Could not finish crafting."
387 });
388 continue;
389 }
390
391 const taken = takeInputs(inventory.slots, recipe.inputs);
392 if (!taken.ok)
393 {
394 events.push({
395 type: "craft-result",
396 sessionId: session.sessionId,
397 recipeId: session.recipeId,
398 ok: false,
399 error: "Missing materials."
400 });
401 continue;
402 }
403 let slotsAfter = taken.slots;
404 if (recipe.consumeDye && session.dyeColorKey != null)
405 {
406 const consumeSlot = pickEmptiestDyeSlot(slotsAfter, session.dyeColorKey);
407 const dyeTaken = consumeDyeUse(slotsAfter, consumeSlot);
408 if (!dyeTaken.ok)
409 {
410 events.push({
411 type: "craft-result",
412 sessionId: session.sessionId,
413 recipeId: session.recipeId,
414 ok: false,
415 error: dyeTaken.reason === "space"
416 ? "Need bag space to separate the partially used dye."
417 : "Selected dye is missing."
418 });
419 continue;
420 }
421 slotsAfter = dyeTaken.slots;
422 }
423 if (recipe.consumePotionKey)
424 {
425 const consumeSlot = pickEmptiestPotionSlot(slotsAfter, recipe.consumePotionKey);
426 const potionTaken = consumePotionUse(slotsAfter, consumeSlot);
427 if (!potionTaken.ok)
428 {
429 events.push({
430 type: "craft-result",
431 sessionId: session.sessionId,
432 recipeId: session.recipeId,
433 ok: false,
434 error: potionTaken.reason === "space"
435 ? "Need bag space to separate the partially used brew."
436 : "Missing materials."
437 });
438 continue;
439 }
440 slotsAfter = potionTaken.slots;
441 }
442
443 const burnChance = cookBurnChance(session.stationId);
444 const burned = burnChance > 0
445 && recipe.burntOutput?.itemId
446 && ((world.rng?.() ?? Math.random()) < burnChance);
447 const outSpec = burned ? recipe.burntOutput : recipe.output;
448 const outDef = itemDefinition(outSpec.itemId);
449 const outQty = Math.max(1, outSpec.quantity | 0 || 1);
450 const origin = craftOrigin(
451 burned ? CraftOriginVerb.ruined : craftOriginVerbForStation(session.stationId),
452 characterDisplayName(world, handle)
453 );
454 const outStack = {
455 itemId: outSpec.itemId,
456 quantity: outQty,
457 origins: [{ origin, quantity: outQty }],
458 ...(recipe.dyeColor && !burned ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
459 };
460 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
461 if (!added.ok || added.remainder > 0)
462 {
463 events.push({
464 type: "craft-result",
465 sessionId: session.sessionId,
466 recipeId: session.recipeId,
467 ok: false,
468 error: "Not enough bag space for the result."
469 });
470 continue;
471 }
472 inventory.slots = added.slots;
473
474 let skillsChanged = false;
475 const levelUps = [];
476 if (!burned && skills?.xp && stationDef?.skillId)
477 {
478 const result = applySkillXp(
479 skills,
480 stationDef.skillId,
481 craftXpForConsumedInputs(recipe.inputs, stationDef.skillId),
482 world.ecs.get(handle, Component.equipment)
483 );
484 if (result.changed)
485 { skillsChanged = true; }
486 if (result.levelUp)
487 { levelUps.push(result.levelUp); }
488 }
489
490 privates.push({ characterId, bag: bagView(world.ecs, handle) });
491 if (skillsChanged)
492 {
493 events.push({
494 type: "skills-updated",
495 entityId,
496 characterId,
497 ...publicSkillsPayload(skills),
498 stored: storedSkillXp(skills),
499 levelUps
500 });
501 }
502
503 if (burned)
504 {
505 events.push({
506 type: "command-error",
507 sessionId: session.sessionId,
508 message: "You burn the food."
509 });
510 }
511
512 let continuing = false;
513 const batchRemaining = session.batchRemaining ?? 1;
514 const nextRemaining = batchRemaining === Infinity
515 ? Infinity
516 : Math.max(0, (batchRemaining | 0) - 1);
517 if (nextRemaining !== 0 && canStartCraft(
518 inventory.slots,
519 recipe,
520 level,
521 { dyeColorKey: session.dyeColorKey, dyeSlotIndex: null }
522 ))
523 {
524 const equipment = world.ecs.get(handle, Component.equipment);
525 const durationMs = session.durationMs ?? Math.max(
526 1,
527 Math.floor(craftDurationMs(recipe, CRAFT_DURATION_MS) * craftDurationMultiplier(equipment))
528 );
529 sessions.set(characterId, {
530 ...session,
531 recipe,
532 batchRemaining: nextRemaining,
533 durationMs,
534 finishesAt: now + durationMs
535 });
536 continuing = true;
537 if (blockType)
538 {
539 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
540 if (shove)
541 { events.push(shove); }
542 }
543 events.push({
544 type: "item-bubble",
545 entityId,
546 itemId: outSpec.itemId,
547 quantity: outQty
548 });
549 events.push({
550 type: "craft-started",
551 sessionId: session.sessionId,
552 characterId,
553 recipeId: session.recipeId,
554 durationMs
555 });
556 }
557 events.push({
558 type: "craft-result",
559 sessionId: session.sessionId,
560 recipeId: session.recipeId,
561 ok: true,
562 continuing
563 });
564 }
565 return { events, privates };
566}
567
568export function handleCraftCommand (world, sessionId, command, now)
569{
570 switch (command.type)
571 {
572 case "open-station":
573 return openStation(world, sessionId, command.characterId, command.stationId);
574 case "start-craft":
575 return startCraft(
576 world,
577 sessionId,
578 command.characterId,
579 command.stationId,
580 command.recipeId,
581 now,
582 {
583 clothTier: command.clothTier ?? null,
584 dyeSlotIndex: command.dyeSlotIndex ?? null,
585 batchCount: command.batchCount ?? null,
586 batchAll: !!command.batchAll
587 }
588 );
589 case "cancel-craft":
590 return cancelCraft(world, command.characterId);
591 default:
592 return null;
593 }
594}