BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

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