BlueGit

timfa questward

Files

questward / server / src / shearing / service.js

service.js

service.js 10.8 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3import { resolveShears } from "../../../shared/definitions/gathering.js";
4import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
5import {
6 clothExhaustDurationMs
7} from "../../../shared/definitions/materialTiers.js";
8import { itemDefinition } from "../../../shared/definitions/items.js";
9import { SkillId } from "../../../shared/definitions/skills.js";
10import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
11import { insertStack } from "../../../shared/items/inventory.js";
12import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
13import { bagView } from "../items/bags.js";
14import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
15import { publicEntityView, replicationAppearance } from "../ecs/serialize.js";
16import { scaleRegrowDurationMs } from "../../../shared/world/season.js";
17import { tileShoveEvent } from "../simulation/tileInteract.js";
18
19const SHEAR_DURATION_MS = 3000;
20const SHEAR_SHOVE_MS = 1000;
21
22function userError (message)
23{
24 const error = new Error(message);
25 error.userFacing = true;
26 return error;
27}
28
29function characterDisplayName (world, handle)
30{
31 const appearance = world.ecs.get(handle, Component.appearance);
32 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
33 return name || "someone";
34}
35
36function ensureShearSessions (world)
37{
38 if (!world.shearSessions)
39 { world.shearSessions = new Map(); }
40 return world.shearSessions;
41}
42
43function clearShearSession (world, characterId)
44{
45 const sessions = world.shearSessions;
46 if (!sessions)
47 { return; }
48 const session = sessions.get(characterId);
49 if (session)
50 {
51 unpinShearTarget(world, session.targetEntityId, characterId);
52 sessions.delete(characterId);
53 }
54}
55
56function pinShearTarget (world, entityId, characterId)
57{
58 const handle = world.ecs.handleOf(entityId | 0);
59 if (handle == null)
60 { return; }
61 const origin = world.ecs.get(handle, Component.spawnOrigin);
62 if (!origin)
63 { return; }
64 if (!origin.shearBrowsers || typeof origin.shearBrowsers !== "object")
65 { origin.shearBrowsers = Object.create(null); }
66 origin.shearBrowsers[characterId | 0] = true;
67 const path = world.ecs.get(handle, Component.path);
68 if (path)
69 { path.tiles = []; }
70}
71
72function unpinShearTarget (world, entityId, characterId)
73{
74 const handle = world.ecs.handleOf(entityId | 0);
75 if (handle == null)
76 { return; }
77 const origin = world.ecs.get(handle, Component.spawnOrigin);
78 if (!origin?.shearBrowsers)
79 { return; }
80 delete origin.shearBrowsers[characterId | 0];
81}
82
83function hasShearBrowsers (origin)
84{
85 const browsers = origin?.shearBrowsers;
86 if (!browsers || typeof browsers !== "object")
87 { return false; }
88 return Object.keys(browsers).length > 0;
89}
90
91export function originIsBusyPinned (origin)
92{
93 const dialogue = origin?.dialogueBrowsers;
94 const hasDialogue = dialogue && typeof dialogue === "object" && Object.keys(dialogue).length > 0;
95 return hasDialogue || hasShearBrowsers(origin);
96}
97
98/**
99 * Start shearing a fleece-bearing mob (3s channel, shears overlay, freeze target).
100 */
101export function startShear (world, sessionId, characterId, targetEntityId, now)
102{
103 const entityId = world.characterEntities.get(characterId);
104 if (entityId == null)
105 { throw userError("Character is not in the world."); }
106 const handle = world.ecs.handleOf(entityId);
107 const identity = world.ecs.get(handle, Component.networkIdentity);
108 if (!identity || identity.sessionId !== sessionId)
109 { throw userError("Character is not in the world."); }
110 if (world.ecs.has(handle, Component.dead))
111 { throw userError("You are dead."); }
112
113 const targetHandle = world.ecs.handleOf(targetEntityId | 0);
114 if (targetHandle == null)
115 { throw userError("That creature is gone."); }
116 if (world.ecs.has(targetHandle, Component.dead))
117 { throw userError("That creature is dead."); }
118
119 const creature = world.ecs.get(targetHandle, Component.creature);
120 const mob = mobDefinition(creature?.mobTypeId);
121 const shearable = mob?.shearable;
122 if (!shearable)
123 { throw userError("You cannot shear that."); }
124
125 const fleeceState = creature.fleeceState ?? shearable.fleeceState;
126 if (fleeceState === shearable.shornState)
127 { throw userError("That fleece has not grown back yet."); }
128
129 const playerPos = world.ecs.get(handle, Component.position);
130 const targetPos = world.ecs.get(targetHandle, Component.position);
131 if (!isAdjacentTile(playerPos.tileX, playerPos.tileY, targetPos.tileX, targetPos.tileY))
132 { throw userError("You need to stand next to it."); }
133
134 const inventory = world.ecs.get(handle, Component.inventory);
135 const equipment = world.ecs.get(handle, Component.equipment);
136 const skills = world.ecs.get(handle, Component.skills);
137 const resolved = resolveShears({
138 inventorySlots: inventory?.slots,
139 equipmentSlots: equipment?.slots,
140 skills,
141 clothTier: shearable.clothTier
142 });
143 if (!resolved.ok)
144 { throw userError(resolved.reason); }
145
146 clearShearSession(world, characterId);
147 if (world.ecs.has(handle, Component.gather))
148 { world.ecs.remove(handle, Component.gather); }
149 const path = world.ecs.get(handle, Component.path);
150 if (path)
151 { path.tiles = []; }
152
153 pinShearTarget(world, targetEntityId | 0, characterId);
154
155 ensureShearSessions(world).set(characterId, {
156 sessionId,
157 targetEntityId: targetEntityId | 0,
158 clothTier: shearable.clothTier,
159 fleeceState: shearable.fleeceState,
160 shornState: shearable.shornState,
161 mobTypeId: creature.mobTypeId,
162 toolItemId: resolved.tool.stack.itemId,
163 startedAt: now,
164 endsAt: now + SHEAR_DURATION_MS,
165 nextShoveAt: now
166 });
167
168 return { events: [], private: bagView(world.ecs, handle) };
169}
170
171export function cancelShearing (world, characterId)
172{
173 clearShearSession(world, characterId);
174}
175
176export function handleShearingCommand (world, sessionId, command, now = Date.now())
177{
178 if (command.type === "shear")
179 {
180 return startShear(world, sessionId, command.characterId, command.targetEntityId, now);
181 }
182 if (command.type === "cancel-shear")
183 {
184 cancelShearing(world, command.characterId);
185 return { events: [] };
186 }
187 return null;
188}
189
190function completeShear (world, handle, entityId, characterId, session, events, privates, now)
191{
192 const character = world.ecs.get(handle, Component.character);
193 const inventory = world.ecs.get(handle, Component.inventory);
194 const targetHandle = world.ecs.handleOf(session.targetEntityId);
195 if (targetHandle == null || !inventory || !character)
196 {
197 clearShearSession(world, characterId);
198 return;
199 }
200
201 const itemId = rawClothItemId(session.clothTier);
202 const def = itemDefinition(itemId);
203 if (!def)
204 {
205 clearShearSession(world, characterId);
206 return;
207 }
208
209 const origin = gatherOrigin(GatherOriginVerb.sheared, characterDisplayName(world, handle));
210 const stack = attachOrigins({
211 itemId,
212 quantity: 1,
213 origins: [{ origin, quantity: 1 }]
214 });
215 const inserted = insertStack(inventory.slots, stack, def);
216 if (!inserted.ok || inserted.remainder > 0)
217 {
218 events.push({
219 type: "command-error",
220 sessionId: session.sessionId,
221 message: "Your inventory is full."
222 });
223 clearShearSession(world, characterId);
224 return;
225 }
226 inventory.slots = inserted.slots;
227
228 const creature = world.ecs.get(targetHandle, Component.creature);
229 const appearance = world.ecs.get(targetHandle, Component.appearance);
230 if (creature)
231 {
232 creature.fleeceState = session.shornState;
233 creature.woolReadyAt = now + scaleRegrowDurationMs(
234 clothExhaustDurationMs(session.clothTier),
235 now
236 );
237 }
238 if (appearance)
239 {
240 appearance.sprite = mobSpriteName(session.mobTypeId, session.shornState);
241 const view = publicEntityView(world.ecs, session.targetEntityId);
242 const appearanceEvent = replicationAppearance(view);
243 if (appearanceEvent)
244 { events.push(appearanceEvent); }
245 }
246
247 const skills = world.ecs.get(handle, Component.skills);
248 let skillsChanged = false;
249 const levelUps = [];
250 if (skills?.xp)
251 {
252 const result = applySkillXp(skills, SkillId.herbalism, 4 + Math.max(1, Math.floor(
253 (clothExhaustDurationMs(session.clothTier) / 10_000)
254 )));
255 if (result.changed)
256 { skillsChanged = true; }
257 if (result.levelUp)
258 { levelUps.push(result.levelUp); }
259 }
260 if (skillsChanged)
261 {
262 events.push({
263 type: "skills-updated",
264 entityId,
265 characterId,
266 ...publicSkillsPayload(skills),
267 stored: storedSkillXp(skills),
268 levelUps
269 });
270 }
271
272 privates.push({ characterId, bag: bagView(world.ecs, handle) });
273 clearShearSession(world, characterId);
274}
275
276/**
277 * Advance shear channels and fleece regrowth.
278 */
279export function stepShearing (world, now)
280{
281 const events = [];
282 const privates = [];
283
284 for (const entity of world.ecs.query(Component.creature, Component.appearance))
285 {
286 const creature = entity.creature;
287 if (creature?.woolReadyAt == null || now < creature.woolReadyAt)
288 { continue; }
289 const mob = mobDefinition(creature.mobTypeId);
290 const shearable = mob?.shearable;
291 if (!shearable)
292 {
293 creature.woolReadyAt = null;
294 continue;
295 }
296 creature.fleeceState = shearable.fleeceState;
297 creature.woolReadyAt = null;
298 entity.appearance.sprite = mobSpriteName(creature.mobTypeId, shearable.fleeceState);
299 const view = publicEntityView(world.ecs, entity.entityId);
300 const appearanceEvent = replicationAppearance(view);
301 if (appearanceEvent)
302 { events.push(appearanceEvent); }
303 }
304
305 const sessions = ensureShearSessions(world);
306 for (const [characterId, session] of [...sessions.entries()])
307 {
308 const entityId = world.characterEntities.get(characterId);
309 if (entityId == null)
310 {
311 clearShearSession(world, characterId);
312 continue;
313 }
314 const handle = world.ecs.handleOf(entityId);
315 if (world.ecs.has(handle, Component.dead))
316 {
317 clearShearSession(world, characterId);
318 continue;
319 }
320
321 const targetHandle = world.ecs.handleOf(session.targetEntityId);
322 if (targetHandle == null || world.ecs.has(targetHandle, Component.dead))
323 {
324 events.push({
325 type: "command-error",
326 sessionId: session.sessionId,
327 message: "The creature got away."
328 });
329 clearShearSession(world, characterId);
330 continue;
331 }
332
333 const position = world.ecs.get(handle, Component.position);
334 const targetPos = world.ecs.get(targetHandle, Component.position);
335 if (!isAdjacentTile(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY))
336 {
337 clearShearSession(world, characterId);
338 continue;
339 }
340
341 if (now >= session.nextShoveAt && now < session.endsAt)
342 {
343 session.nextShoveAt = now + SHEAR_SHOVE_MS;
344 events.push(tileShoveEvent(
345 entityId,
346 position.tileX,
347 position.tileY,
348 targetPos.tileX,
349 targetPos.tileY
350 ));
351 events.push({
352 type: "gather-swing",
353 attackerId: entityId,
354 tileX: targetPos.tileX,
355 tileY: targetPos.tileY,
356 fromTileX: position.tileX,
357 fromTileY: position.tileY,
358 toolItemId: session.toolItemId,
359 swipe: false
360 });
361 }
362
363 if (now < session.endsAt)
364 { continue; }
365
366 completeShear(world, handle, entityId, characterId, session, events, privates, now);
367 }
368
369 return { events, privates };
370}