BlueGit

timfa questward

Files

questward / server / src / crafting / service.js

service.js

service.js 10.5 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 { 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 { craftDurationMs, smeltingXpForMaterial } from "../../../shared/definitions/gathering.js";
14import { takeFromSlot, insertStack, stackQuantity } from "../../../shared/items/inventory.js";
15import {
16 attachOrigins,
17 craftOrigin,
18 craftOriginVerbForStation
19} from "../../../shared/items/origin.js";
20import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
21import { bagView } from "../items/bags.js";
22import { tileToChunk, tileToLocal } from "../world/coordinates.js";
23import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
24import { tileShoveTowardBlock } from "../simulation/tileInteract.js";
25
26function userError (message)
27{
28 const error = new Error(message);
29 error.userFacing = true;
30 return error;
31}
32
33function characterDisplayName (world, handle)
34{
35 const appearance = world.ecs.get(handle, Component.appearance);
36 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
37 return name || "someone";
38}
39
40function ensureCraftSessions (world)
41{
42 if (!world.craftSessions)
43 { world.craftSessions = new Map(); }
44 return world.craftSessions;
45}
46
47function nearStationBlock (world, tileX, tileY, blockType)
48{
49 for (let dy = -1; dy <= 1; dy++)
50 {
51 for (let dx = -1; dx <= 1; dx++)
52 {
53 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
54 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
55 if (data.blocks[index]?.typeId === blockType)
56 { return true; }
57 }
58 }
59 return false;
60}
61
62function stationBlockType (stationId)
63{
64 if (stationId === CraftingStationId.furnace)
65 { return BlockType.furnace; }
66 if (stationId === CraftingStationId.anvil)
67 { return BlockType.anvil; }
68 if (stationId === CraftingStationId.woodworkingBench)
69 { return BlockType.woodworkingBench; }
70 if (stationId === CraftingStationId.craftingBench)
71 { return BlockType.craftingBench; }
72 return null;
73}
74
75function takeInputs (slots, inputs)
76{
77 let next = slots.map((slot) => (slot ? structuredClone(slot) : null));
78 for (const input of inputs ?? [])
79 {
80 let remaining = Math.max(0, stackQuantity(input.quantity));
81 if (!remaining)
82 { continue; }
83 for (let i = 0; i < next.length && remaining > 0; i++)
84 {
85 if (!next[i] || next[i].itemId !== input.itemId)
86 { continue; }
87 const taken = takeFromSlot(next, i, remaining);
88 if (!taken.ok)
89 { continue; }
90 next = taken.slots;
91 remaining -= stackQuantity(taken.taken?.quantity);
92 }
93 if (remaining > 0)
94 { return { ok: false, slots }; }
95 }
96 return { ok: true, slots: next };
97}
98
99export function startCraft (world, sessionId, characterId, stationId, recipeId, now)
100{
101 const entityId = world.characterEntities.get(characterId);
102 if (entityId == null)
103 { throw userError("Character is not in the world."); }
104 const handle = world.ecs.handleOf(entityId);
105 const identity = world.ecs.get(handle, Component.networkIdentity);
106 if (!identity || identity.sessionId !== sessionId)
107 { throw userError("Character is not in the world."); }
108 if (world.ecs.has(handle, Component.dead))
109 { throw userError("You are dead."); }
110
111 const stationDef = craftingStationDefinition(stationId);
112 if (!stationDef)
113 { throw userError("Unknown crafting station."); }
114 const recipe = recipeDefinition(recipeId);
115 if (!recipe)
116 { throw userError("Unknown recipe."); }
117 const stationIds = Array.isArray(recipe.stationIds)
118 ? recipe.stationIds
119 : [recipe.stationId];
120 if (!stationIds.includes(stationId))
121 { throw userError("That recipe cannot be made here."); }
122
123 const position = world.ecs.get(handle, Component.position);
124 const blockType = stationBlockType(stationId);
125 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
126 { throw userError("You need to stand next to the station."); }
127
128 const inventory = world.ecs.get(handle, Component.inventory);
129 const skills = world.ecs.get(handle, Component.skills);
130 const level = skillLevel(skills, stationDef.skillId ?? SkillId.smithing);
131 if (!canStartCraft(inventory?.slots ?? [], recipe, level))
132 {
133 if ((level | 0) < (recipe.minSkillLevel | 0 || 1))
134 { throw userError(`Requires ${stationDef.skillId} ${recipe.minSkillLevel}.`); }
135 if (!hasRecipeInputs(inventory?.slots ?? [], recipe))
136 { throw userError("Missing materials."); }
137 throw userError("Not enough bag space for the result.");
138 }
139
140 const sessions = ensureCraftSessions(world);
141 const durationMs = craftDurationMs(recipe, CRAFT_DURATION_MS);
142 sessions.set(characterId, {
143 sessionId,
144 stationId,
145 recipeId,
146 finishesAt: now + durationMs
147 });
148 const events = [];
149 if (blockType)
150 {
151 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
152 if (shove)
153 { events.push(shove); }
154 }
155 events.push({
156 type: "item-bubble",
157 entityId,
158 itemId: recipe.output.itemId,
159 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
160 });
161 events.push({
162 type: "craft-started",
163 sessionId,
164 characterId,
165 recipeId,
166 durationMs
167 });
168 return { events };
169}
170
171export function openStation (world, sessionId, characterId, stationId)
172{
173 const entityId = world.characterEntities.get(characterId);
174 if (entityId == null)
175 { throw userError("Character is not in the world."); }
176 const handle = world.ecs.handleOf(entityId);
177 const identity = world.ecs.get(handle, Component.networkIdentity);
178 if (!identity || identity.sessionId !== sessionId)
179 { throw userError("Character is not in the world."); }
180 if (world.ecs.has(handle, Component.dead))
181 { throw userError("You are dead."); }
182
183 const stationDef = craftingStationDefinition(stationId);
184 if (!stationDef)
185 { throw userError("Unknown crafting station."); }
186 const blockType = stationBlockType(stationId);
187 const position = world.ecs.get(handle, Component.position);
188 if (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
189 { throw userError("You need to stand next to the station."); }
190
191 const events = [];
192 if (blockType)
193 {
194 const shove = tileShoveTowardBlock(world, handle, entityId, blockType);
195 if (shove)
196 { events.push(shove); }
197 }
198 events.push({
199 type: "station-open",
200 sessionId,
201 characterId,
202 stationId
203 });
204 return { events };
205}
206
207export function cancelCraft (world, characterId)
208{
209 ensureCraftSessions(world).delete(characterId);
210 return { events: [] };
211}
212
213export function stepCrafting (world, now)
214{
215 const sessions = ensureCraftSessions(world);
216 const events = [];
217 const privates = [];
218 for (const [characterId, session] of [...sessions.entries()])
219 {
220 if (now < session.finishesAt)
221 { continue; }
222 sessions.delete(characterId);
223 const entityId = world.characterEntities.get(characterId);
224 if (entityId == null)
225 {
226 events.push({
227 type: "craft-result",
228 sessionId: session.sessionId,
229 recipeId: session.recipeId,
230 ok: false,
231 error: "Character left the world."
232 });
233 continue;
234 }
235 const handle = world.ecs.handleOf(entityId);
236 if (world.ecs.has(handle, Component.dead))
237 {
238 events.push({
239 type: "craft-result",
240 sessionId: session.sessionId,
241 recipeId: session.recipeId,
242 ok: false,
243 error: "You are dead."
244 });
245 continue;
246 }
247
248 const recipe = recipeDefinition(session.recipeId);
249 const stationDef = craftingStationDefinition(session.stationId);
250 const inventory = world.ecs.get(handle, Component.inventory);
251 const skills = world.ecs.get(handle, Component.skills);
252 const position = world.ecs.get(handle, Component.position);
253 const blockType = stationBlockType(session.stationId);
254 const level = skillLevel(skills, stationDef?.skillId ?? SkillId.smithing);
255
256 if (!recipe || !stationDef || !inventory
257 || (blockType && !nearStationBlock(world, position.tileX, position.tileY, blockType))
258 || !canCraftFitInventory(inventory.slots, recipe)
259 || (level | 0) < (recipe.minSkillLevel | 0 || 1))
260 {
261 events.push({
262 type: "craft-result",
263 sessionId: session.sessionId,
264 recipeId: session.recipeId,
265 ok: false,
266 error: "Could not finish crafting."
267 });
268 continue;
269 }
270
271 const taken = takeInputs(inventory.slots, recipe.inputs);
272 if (!taken.ok)
273 {
274 events.push({
275 type: "craft-result",
276 sessionId: session.sessionId,
277 recipeId: session.recipeId,
278 ok: false,
279 error: "Missing materials."
280 });
281 continue;
282 }
283 const outDef = itemDefinition(recipe.output.itemId);
284 const outQty = Math.max(1, recipe.output.quantity | 0 || 1);
285 const origin = craftOrigin(
286 craftOriginVerbForStation(session.stationId),
287 characterDisplayName(world, handle)
288 );
289 const added = insertStack(taken.slots, attachOrigins({
290 itemId: recipe.output.itemId,
291 quantity: outQty,
292 origins: [{ origin, quantity: outQty }]
293 }), outDef);
294 if (!added.ok || added.remainder > 0)
295 {
296 events.push({
297 type: "craft-result",
298 sessionId: session.sessionId,
299 recipeId: session.recipeId,
300 ok: false,
301 error: "Not enough bag space for the result."
302 });
303 continue;
304 }
305 inventory.slots = added.slots;
306
307 let skillsChanged = false;
308 const levelUps = [];
309 if (skills?.xp && recipe.xpMaterial && stationDef?.skillId)
310 {
311 const result = applySkillXp(
312 skills,
313 stationDef.skillId,
314 smeltingXpForMaterial(recipe.xpMaterial)
315 );
316 if (result.changed)
317 { skillsChanged = true; }
318 if (result.levelUp)
319 { levelUps.push(result.levelUp); }
320 }
321
322 privates.push({ characterId, bag: bagView(world.ecs, handle) });
323 if (skillsChanged)
324 {
325 events.push({
326 type: "skills-updated",
327 entityId,
328 characterId,
329 skills: publicSkillsView(skills),
330 stored: storedSkillXp(skills),
331 levelUps
332 });
333 }
334 events.push({
335 type: "craft-result",
336 sessionId: session.sessionId,
337 recipeId: session.recipeId,
338 ok: true
339 });
340 }
341 return { events, privates };
342}
343
344export function handleCraftCommand (world, sessionId, command, now)
345{
346 switch (command.type)
347 {
348 case "open-station":
349 return openStation(world, sessionId, command.characterId, command.stationId);
350 case "start-craft":
351 return startCraft(
352 world,
353 sessionId,
354 command.characterId,
355 command.stationId,
356 command.recipeId,
357 now
358 );
359 case "cancel-craft":
360 return cancelCraft(world, command.characterId);
361 default:
362 return null;
363 }
364}