BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

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