BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

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