BlueGit

timfa questward

Files

questward / server / src / shearing / service.js

service.js

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