BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

service.js 12.7 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { CraftingStationId, CRAFT_DURATION_MS } 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, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
15import { takeFromSlot, insertStack, stackQuantity } 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 return null;
80}
81
82function takeInputs (slots, inputs)
83{
84 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
85 for (const input of inputs ?? [])
86 {
87 let remaining = Math.max(0, stackQuantity(input.quantity));
88 if (!remaining)
89 { continue; }
90 for (let i = 0; i < next.length && remaining > 0; i++)
91 {
92 if (!next[i] || next[i].itemId !== input.itemId)
93 { continue; }
94 const taken = takeFromSlot(next, i, remaining);
95 if (!taken.ok)
96 { continue; }
97 next = taken.slots;
98 remaining -= stackQuantity(taken.taken?.quantity);
99 }
100 if (remaining > 0)
101 { return { ok: false, slots }; }
102 }
103 return { ok: true, slots: next };
104}
105
106/** Spend one fill level of a dye bottle (remove at 0). */
107function consumeDyeUse (slots, slotIndex)
108{
109 const next = slots.map((slot) => (slot ? structuredClone(slot) : null));
110 const slot = next[slotIndex];
111 if (!slot || slot.itemId !== ItemId.dye || slot.instance?.kind !== "dye")
112 { return { ok: false }; }
113 const fill = Math.max(1, slot.instance.fillLevel | 0 || 4);
114 if (fill <= 1)
115 {
116 next[slotIndex] = null;
117 return { ok: true, slots: next };
118 }
119 slot.instance = {
120 ...slot.instance,
121 fillLevel: fill - 1
122 };
123 return { ok: true, slots: next };
124}
125
126export function startCraft (world, sessionId, characterId, stationId, recipeId, now, options = {})
127{
128 const entityId = world.characterEntities.get(characterId);
129 if (entityId == null)
130 { throw userError("Character is not in the world."); }
131 const handle = world.ecs.handleOf(entityId);
132 const identity = world.ecs.get(handle, Component.networkIdentity);
133 if (!identity || identity.sessionId !== sessionId)
134 { throw userError("Character is not in the world."); }
135 if (world.ecs.has(handle, Component.dead))
136 { throw userError("You are dead."); }
137
138 const stationDef = craftingStationDefinition(stationId);
139 if (!stationDef)
140 { throw userError("Unknown crafting station."); }
141 let recipe = recipeDefinition(recipeId);
142 if (!recipe)
143 { throw userError("Unknown recipe."); }
144 const stationIds = Array.isArray(recipe.stationIds)
145 ? recipe.stationIds
146 : [recipe.stationId];
147 if (!stationIds.includes(stationId))
148 { throw userError("That recipe cannot be made here."); }
149
150 const position = world.ecs.get(handle, Component.position);
151 const blockType = stationBlockType(stationId);
152 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
153 { throw userError("You need to stand next to the station."); }
154
155 const inventory = world.ecs.get(handle, Component.inventory);
156 const skills = world.ecs.get(handle, Component.skills);
157 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
158
159 let dyeSlotIndex = null;
160 if (recipe.tailorTemplate)
161 {
162 const dyeIdx = options.dyeSlotIndex;
163 let dyeStack = null;
164 if (dyeIdx != null && dyeIdx >= 0)
165 {
166 dyeStack = inventory?.slots?.[dyeIdx | 0] ?? null;
167 dyeSlotIndex = dyeIdx | 0;
168 }
169 const resolved = resolveTailorCraft({
170 templateId: recipe.tailorTemplate,
171 clothTier: options.clothTier,
172 dyeStack
173 });
174 if (!resolved.ok)
175 { throw userError(resolved.reason); }
176 recipe = resolved.recipe;
177 }
178
179 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
180 {
181 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
182 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
183 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
184 { throw userError("Missing materials."); }
185 throw userError("Not enough bag space for the result.");
186 }
187 if (recipe.consumeDye && dyeSlotIndex != null)
188 {
189 const dye = inventory?.slots?.[dyeSlotIndex];
190 if (!dye || dye.itemId !== ItemId.dye)
191 { throw userError("Selected dye is missing."); }
192 }
193
194 const sessions = ensureCraftSessions(world);
195 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
196 sessions.set(characterId, {
197 sessionId,
198 stationId,
199 recipeId,
200 recipe,
201 dyeSlotIndex,
202 finishesAt: now + durationMs
203 });
204 const events = [];
205 if (blockType)
206 {
207 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
208 if (shove)
209 { events.push(shove); }
210 }
211 events.push({
212 type: "item-bubble",
213 entityId,
214 itemId: recipe.output.itemId,
215 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
216 });
217 events.push({
218 type: "craft-started",
219 sessionId,
220 characterId,
221 recipeId,
222 durationMs
223 });
224 return { events };
225}
226
227export function openStation (world, sessionId, characterId, stationId)
228{
229 const entityId = world.characterEntities.get(characterId);
230 if (entityId == null)
231 { throw userError("Character is not in the world."); }
232 const handle = world.ecs.handleOf(entityId);
233 const identity = world.ecs.get(handle, Component.networkIdentity);
234 if (!identity || identity.sessionId !== sessionId)
235 { throw userError("Character is not in the world."); }
236 if (world.ecs.has(handle, Component.dead))
237 { throw userError("You are dead."); }
238
239 const stationDef = craftingStationDefinition(stationId);
240 if (!stationDef)
241 { throw userError("Unknown crafting station."); }
242 const blockType = stationBlockType(stationId);
243 const position = world.ecs.get(handle, Component.position);
244 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
245 { throw userError("You need to stand next to the station."); }
246
247 const events = [];
248 if (blockType)
249 {
250 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
251 if (shove)
252 { events.push(shove); }
253 }
254 events.push({
255 type: "station-open",
256 sessionId,
257 characterId,
258 stationId
259 });
260 return { events };
261}
262
263export function cancelCraft (world, characterId)
264{
265 ensureCraftSessions(world).delete(characterId);
266 return { events: [] };
267}
268
269export function stepCrafting (world, now)
270{
271 const sessions = ensureCraftSessions(world);
272 const events = [];
273 const privates = [];
274 for (const [characterId, session] of [...sessions.entries()])
275 {
276 if (now < session.finishesAt)
277 { continue; }
278 sessions.delete(characterId);
279 const entityId = world.characterEntities.get(characterId);
280 if (entityId == null)
281 {
282 events.push({
283 type: "craft-result",
284 sessionId: session.sessionId,
285 recipeId: session.recipeId,
286 ok: false,
287 error: "Character left the world."
288 });
289 continue;
290 }
291 const handle = world.ecs.handleOf(entityId);
292 if (world.ecs.has(handle, Component.dead))
293 {
294 events.push({
295 type: "craft-result",
296 sessionId: session.sessionId,
297 recipeId: session.recipeId,
298 ok: false,
299 error: "You are dead."
300 });
301 continue;
302 }
303
304 const recipe = session.recipe ?? recipeDefinition(session.recipeId);
305 const stationDef = craftingStationDefinition(session.stationId);
306 const inventory = world.ecs.get(handle, Component.inventory);
307 const skills = world.ecs.get(handle, Component.skills);
308 const position = world.ecs.get(handle, Component.position);
309 const blockType = stationBlockType(session.stationId);
310 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
311
312 if (!recipe || !stationDef || !inventory
313 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
314 || !canCraftFitInventory(inventory.slots, recipe)
315 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
316 {
317 events.push({
318 type: "craft-result",
319 sessionId: session.sessionId,
320 recipeId: session.recipeId,
321 ok: false,
322 error: "Could not finish crafting."
323 });
324 continue;
325 }
326
327 const taken = takeInputs(inventory.slots, recipe.inputs);
328 if (!taken.ok)
329 {
330 events.push({
331 type: "craft-result",
332 sessionId: session.sessionId,
333 recipeId: session.recipeId,
334 ok: false,
335 error: "Missing materials."
336 });
337 continue;
338 }
339 let slotsAfter = taken.slots;
340 if (recipe.consumeDye && session.dyeSlotIndex != null)
341 {
342 const dyeTaken = consumeDyeUse(slotsAfter, session.dyeSlotIndex);
343 if (!dyeTaken.ok)
344 {
345 events.push({
346 type: "craft-result",
347 sessionId: session.sessionId,
348 recipeId: session.recipeId,
349 ok: false,
350 error: "Selected dye is missing."
351 });
352 continue;
353 }
354 slotsAfter = dyeTaken.slots;
355 }
356 const outDef = itemDefinition(recipe.output.itemId);
357 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
358 const origin = craftOrigin(
359 craftOriginVerbForStation(session.stationId),
360 characterDisplayName(world, handle)
361 );
362 const outStack = {
363 itemId: recipe.output.itemId,
364 quantity: outQty,
365 origins: [{ origin, quantity: outQty }],
366 ...(recipe.dyeColor ? { instance: { kind: "clothing", dyeColor: recipe.dyeColor } } : {})
367 };
368 const added = insertStack(slotsAfter, attachOrigins(outStack, origin), outDef);
369 if (!added.ok || added.remainder > 0)
370 {
371 events.push({
372 type: "craft-result",
373 sessionId: session.sessionId,
374 recipeId: session.recipeId,
375 ok: false,
376 error: "Not enough bag space for the result."
377 });
378 continue;
379 }
380 inventory.slots = added.slots;
381
382 let skillsChanged = false;
383 const levelUps = [];
384 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
385 {
386 const result = applySkillXp(
387 skills,
388 stationDef.skillId,
389 smeltingXpForMaterial(recipe.xpMaterial)
390 );
391 if (result.changed)
392 { skillsChanged = true; }
393 if (result.levelUp)
394 { levelUps.push(result.levelUp); }
395 }
396
397 privates.push({ characterId, bag: bagView(world.ecs, handle) });
398 if (skillsChanged)
399 {
400 events.push({
401 type: "skills-updated",
402 entityId,
403 characterId,
404 skills: publicSkillsView(skills),
405 stored: storedSkillXp(skills),
406 levelUps
407 });
408 }
409 events.push({
410 type: "craft-result",
411 sessionId: session.sessionId,
412 recipeId: session.recipeId,
413 ok: true
414 });
415 }
416 return { events, privates };
417}
418
419export function handleCraftCommand (world, sessionId, command, now)
420{
421 switch (command.type)
422 {
423 case "open-station":
424 return openStation(world, sessionId, command.characterId, command.stationId);
425 case "start-craft":
426 return startCraft(
427 world,
428 sessionId,
429 command.characterId,
430 command.stationId,
431 command.recipeId,
432 now,
433 {
434 clothTier: command.clothTier ?? null,
435 dyeSlotIndex: command.dyeSlotIndex ?? null
436 }
437 );
438 case "cancel-craft":
439 return cancelCraft(world, command.characterId);
440 default:
441 return null;
442 }
443}