BlueGit

timfa questward

Add shears, shearable animals, and flax gathering.

Smith shears from one bar and plant clippers from bar+leather; sheep/goats yield wool/cashmere with fleece regrowth; flax plants clip into Flax for linen yarn.

timfa Tim Falken · pushed by timfa

Authored 2026-08-31 · 2 months ago

Hash
2555c4a11372d07adcffe793bf0471d415efc19a
Parent
fb5a4a89
31 files changed +952 −31
client/assets/blocks/flax-plant/flax-plant.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-plant-clippers/bronze-plant-clippers-equip.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/bronze-plant-clippers/bronze-plant-clippers.png deleted Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/plant-clippers/plant-clippers-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/plant-clippers/plant-clippers.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/shears/shears-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/shears/shears.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/mobs/cashmere-goat/fleece.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/mobs/cashmere-goat/shorn.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/mobs/sheep/fleece.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/mobs/sheep/shorn.png added Binary file +0 −0

The contents of this binary file are not shown.

client/src/play/main.js +71 −0
@@ -38,6 +38,8 @@ import { formatQuantity } from "/shared/items/formatQuantity.js";
38 38 import { ItemId, itemDefinition } from "/shared/definitions/items.js";
39 39 import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
40 40 import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
41 import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
42 import { mobDefinition } from "/shared/definitions/mobs.js";
41 43 import { countCoinsInSlots } from "/shared/items/inventory.js";
42 44
43 45 const game = new Game();
@@ -581,6 +583,48 @@ function requestTalk (targetEntityId, purpose = null)
581 583 { flushPendingInteract(); }
582 584 }
583 585
586 function playerHasShears ()
587 {
588 const slots = inventory?.getInventorySlots?.() ?? [];
589 const equipment = inventory?.getEquipment?.() ?? {};
590 for (const stack of [...slots, equipment.weapon])
591 {
592 if (!stack?.itemId)
593 { continue; }
594 if (itemDefinition(stack.itemId)?.equipment?.kind === EquipmentKind.shears)
595 { return true; }
596 }
597 return false;
598 }
599
600 function entityCanShear (entity)
601 {
602 if (!entity?.mobTypeId)
603 { return false; }
604 const def = mobDefinition(entity.mobTypeId);
605 const shearable = def?.shearable;
606 if (!shearable)
607 { return false; }
608 const sprite = entity.layers?.[0]?.sprite ?? entity.sprite ?? "";
609 if (String(sprite).endsWith(`:${shearable.shornState}`))
610 { return false; }
611 return playerHasShears();
612 }
613
614 function requestShear (targetEntityId)
615 {
616 clearAllPendingActions();
617 pendingInteract = { kind: "shear", targetEntityId };
618 const target = view?.entities.get(targetEntityId);
619 if (!target)
620 {
621 clearPendingInteract();
622 return;
623 }
624 if (approachAdjacentTile(target.tileX, target.tileY))
625 { flushPendingInteract(); }
626 }
627
584 628 function setUiFocus (focus)
585 629 {
586 630 uiFocus = focus;
@@ -884,6 +928,26 @@ function flushPendingInteract ()
884 928 });
885 929 clearPendingInteract();
886 930 }
931
932 if (pendingInteract.kind === "shear")
933 {
934 const target = view.entities.get(pendingInteract.targetEntityId);
935 if (!target)
936 {
937 clearPendingInteract();
938 return;
939 }
940 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
941 {
942 approachAdjacentTile(target.tileX, target.tileY);
943 return;
944 }
945 socket.send({
946 type: MessageType.shear,
947 targetEntityId: pendingInteract.targetEntityId
948 });
949 clearPendingInteract();
950 }
887 951 }
888 952
889 953 function requestPickup (ground)
@@ -1113,6 +1177,13 @@ function handleRightClick (event, mouseX, mouseY)
1113 1177 onSelect: () => requestTalk(entity.entityId, "talk")
1114 1178 });
1115 1179 }
1180 if (entityCanShear(entity))
1181 {
1182 items.push({
1183 label: `Shear ${targetName}`,
1184 onSelect: () => requestShear(entity.entityId)
1185 });
1186 }
1116 1187 if (entity.characterId)
1117 1188 {
1118 1189 items.push({
@@ -38,6 +38,8 @@ import { formatQuantity } from "/shared/items/formatQuantity.js";
38import { ItemId, itemDefinition } from "/shared/definitions/items.js";
38import { ItemId, itemDefinition } from "/shared/definitions/items.js";
39import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
39import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
40import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
40import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
41import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
42import { mobDefinition } from "/shared/definitions/mobs.js";
41import { countCoinsInSlots } from "/shared/items/inventory.js";
43import { countCoinsInSlots } from "/shared/items/inventory.js";
42
44
43const game = new Game();
45const game = new Game();
@@ -581,6 +583,48 @@ function requestTalk (targetEntityId, purpose = null)
581 { flushPendingInteract(); }
583 { flushPendingInteract(); }
582}
584}
583
585
586function playerHasShears ()
587{
588 const slots = inventory?.getInventorySlots?.() ?? [];
589 const equipment = inventory?.getEquipment?.() ?? {};
590 for (const stack of [...slots, equipment.weapon])
591 {
592 if (!stack?.itemId)
593 { continue; }
594 if (itemDefinition(stack.itemId)?.equipment?.kind === EquipmentKind.shears)
595 { return true; }
596 }
597 return false;
598}
599
600function entityCanShear (entity)
601{
602 if (!entity?.mobTypeId)
603 { return false; }
604 const def = mobDefinition(entity.mobTypeId);
605 const shearable = def?.shearable;
606 if (!shearable)
607 { return false; }
608 const sprite = entity.layers?.[0]?.sprite ?? entity.sprite ?? "";
609 if (String(sprite).endsWith(`:${shearable.shornState}`))
610 { return false; }
611 return playerHasShears();
612}
613
614function requestShear (targetEntityId)
615{
616 clearAllPendingActions();
617 pendingInteract = { kind: "shear", targetEntityId };
618 const target = view?.entities.get(targetEntityId);
619 if (!target)
620 {
621 clearPendingInteract();
622 return;
623 }
624 if (approachAdjacentTile(target.tileX, target.tileY))
625 { flushPendingInteract(); }
626}
627
584function setUiFocus (focus)
628function setUiFocus (focus)
585{
629{
586 uiFocus = focus;
630 uiFocus = focus;
@@ -884,6 +928,26 @@ function flushPendingInteract ()
884 });
928 });
885 clearPendingInteract();
929 clearPendingInteract();
886 }
930 }
931
932 if (pendingInteract.kind === "shear")
933 {
934 const target = view.entities.get(pendingInteract.targetEntityId);
935 if (!target)
936 {
937 clearPendingInteract();
938 return;
939 }
940 if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1)
941 {
942 approachAdjacentTile(target.tileX, target.tileY);
943 return;
944 }
945 socket.send({
946 type: MessageType.shear,
947 targetEntityId: pendingInteract.targetEntityId
948 });
949 clearPendingInteract();
950 }
887}
951}
888
952
889function requestPickup (ground)
953function requestPickup (ground)
@@ -1113,6 +1177,13 @@ function handleRightClick (event, mouseX, mouseY)
1113 onSelect: () => requestTalk(entity.entityId, "talk")
1177 onSelect: () => requestTalk(entity.entityId, "talk")
1114 });
1178 });
1115 }
1179 }
1180 if (entityCanShear(entity))
1181 {
1182 items.push({
1183 label: `Shear ${targetName}`,
1184 onSelect: () => requestShear(entity.entityId)
1185 });
1186 }
1116 if (entity.characterId)
1187 if (entity.characterId)
1117 {
1188 {
1118 items.push({
1189 items.push({
server/src/gateway/websocket.js +8 −0
@@ -452,6 +452,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
452 452 groundItemId: message.groundItemId | 0
453 453 });
454 454 break;
455 case MessageType.shear:
456 requirePlaying(session);
457 simulation.enqueue(session.id, {
458 type: "shear",
459 characterId: session.characterId,
460 targetEntityId: message.targetEntityId | 0
461 });
462 break;
455 463 case MessageType.startFish:
456 464 requirePlaying(session);
457 465 simulation.enqueue(session.id, {
@@ -452,6 +452,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
452 groundItemId: message.groundItemId | 0
452 groundItemId: message.groundItemId | 0
453 });
453 });
454 break;
454 break;
455 case MessageType.shear:
456 requirePlaying(session);
457 simulation.enqueue(session.id, {
458 type: "shear",
459 characterId: session.characterId,
460 targetEntityId: message.targetEntityId | 0
461 });
462 break;
455 case MessageType.startFish:
463 case MessageType.startFish:
456 requirePlaying(session);
464 requirePlaying(session);
457 simulation.enqueue(session.id, {
465 simulation.enqueue(session.id, {
server/src/gathering/service.js +8 −1
@@ -469,7 +469,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
469 469 inventorySlots: inventory?.slots,
470 470 equipmentSlots: equipment?.slots,
471 471 skills,
472 requireTool: !!plant.requiresClippers
472 requireTool: !!plant.requiresClippers,
473 minClothTier: plant.minClothTier ?? null
473 474 });
474 475 if (!clippers.ok)
475 476 { throw userError(clippers.reason); }
@@ -711,6 +712,10 @@ function completePlant (world, handle, entityId, character, gather, events, priv
711 712 {
712 713 itemId = rawClothItemId(ClothTier.cotton);
713 714 }
715 else if (gather.plantKind === "flax")
716 {
717 itemId = rawClothItemId(ClothTier.linen);
718 }
714 719 else if (gather.plantKind === "herb")
715 720 {
716 721 const herb = herbDefinition(gather.herbId);
@@ -898,5 +903,7 @@ function defaultPlantState (typeId)
898 903 {
899 904 if (typeId === BlockType.herbPlant)
900 905 { return "mint"; }
906 if (typeId === BlockType.flaxPlant)
907 { return "flax-plant"; }
901 908 return "cotton-plant";
902 909 }
@@ -469,7 +469,8 @@ export function startPick (world, sessionId, characterId, tileX, tileY, now)
469 inventorySlots: inventory?.slots,
469 inventorySlots: inventory?.slots,
470 equipmentSlots: equipment?.slots,
470 equipmentSlots: equipment?.slots,
471 skills,
471 skills,
472 requireTool: !!plant.requiresClippers
472 requireTool: !!plant.requiresClippers,
473 minClothTier: plant.minClothTier ?? null
473 });
474 });
474 if (!clippers.ok)
475 if (!clippers.ok)
475 { throw userError(clippers.reason); }
476 { throw userError(clippers.reason); }
@@ -711,6 +712,10 @@ function completePlant (world, handle, entityId, character, gather, events, priv
711 {
712 {
712 itemId = rawClothItemId(ClothTier.cotton);
713 itemId = rawClothItemId(ClothTier.cotton);
713 }
714 }
715 else if (gather.plantKind === "flax")
716 {
717 itemId = rawClothItemId(ClothTier.linen);
718 }
714 else if (gather.plantKind === "herb")
719 else if (gather.plantKind === "herb")
715 {
720 {
716 const herb = herbDefinition(gather.herbId);
721 const herb = herbDefinition(gather.herbId);
@@ -898,5 +903,7 @@ function defaultPlantState (typeId)
898{
903{
899 if (typeId === BlockType.herbPlant)
904 if (typeId === BlockType.herbPlant)
900 { return "mint"; }
905 { return "mint"; }
906 if (typeId === BlockType.flaxPlant)
907 { return "flax-plant"; }
901 return "cotton-plant";
908 return "cotton-plant";
902}
909}
server/src/shearing/service.js added +370 −0
@@ -0,0 +1,370 @@
1 import { Component } from "../ecs/components.js";
2 import { mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3 import { resolveShears } from "../../../shared/definitions/gathering.js";
4 import { rawClothItemId } from "../../../shared/definitions/clothItems.js";
5 import {
6 clothExhaustDurationMs
7 } from "../../../shared/definitions/materialTiers.js";
8 import { itemDefinition } from "../../../shared/definitions/items.js";
9 import { SkillId } from "../../../shared/definitions/skills.js";
10 import { applySkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
11 import { insertStack } from "../../../shared/items/inventory.js";
12 import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
13 import { bagView } from "../items/bags.js";
14 import { chebyshev } from "../combat/service.js";
15 import { publicEntityView, replicationAppearance } from "../ecs/serialize.js";
16 import { scaleRegrowDurationMs } from "../../../shared/world/season.js";
17 import { tileShoveEvent } from "../simulation/tileInteract.js";
18
19 const SHEAR_DURATION_MS = 3000;
20 const SHEAR_SHOVE_MS = 1000;
21
22 function userError (message)
23 {
24 const error = new Error(message);
25 error.userFacing = true;
26 return error;
27 }
28
29 function 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
36 function ensureShearSessions (world)
37 {
38 if (!world.shearSessions)
39 { world.shearSessions = new Map(); }
40 return world.shearSessions;
41 }
42
43 function 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
56 function 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
72 function 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
83 function 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
91 export 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 */
101 export 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 (chebyshev(playerPos.tileX, playerPos.tileY, targetPos.tileX, targetPos.tileY) > 1)
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
171 export function cancelShearing (world, characterId)
172 {
173 clearShearSession(world, characterId);
174 }
175
176 export 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
190 function 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 skills: publicSkillsView(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 */
279 export 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 (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) > 1)
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 }
@@ -0,0 +1,370 @@
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, publicSkillsView, 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 { chebyshev } from "../combat/service.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 (chebyshev(playerPos.tileX, playerPos.tileY, targetPos.tileX, targetPos.tileY) > 1)
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 skills: publicSkillsView(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 (chebyshev(position.tileX, position.tileY, targetPos.tileX, targetPos.tileY) > 1)
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}
server/src/simulation/spawners.js +9 −2
@@ -235,7 +235,8 @@ export function mobComponents (request)
235 235 }
236 236 else
237 237 {
238 const sprite = mobSpriteName(def.mobTypeId);
238 const fleeceState = def.shearable?.fleeceState ?? null;
239 const sprite = mobSpriteName(def.mobTypeId, fleeceState);
239 240 if (sprite)
240 241 { appearance.sprite = sprite; }
241 242 }
@@ -272,7 +273,13 @@ export function mobComponents (request)
272 273 mobTypeId: def.mobTypeId,
273 274 level,
274 275 ...(element ? { element } : {}),
275 ...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {})
276 ...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {}),
277 ...(def.shearable
278 ? {
279 fleeceState: def.shearable.fleeceState,
280 woolReadyAt: null
281 }
282 : {})
276 283 },
277 284 health: { current: maxHp, max: maxHp }
278 285 };
@@ -235,7 +235,8 @@ export function mobComponents (request)
235 }
235 }
236 else
236 else
237 {
237 {
238 const sprite = mobSpriteName(def.mobTypeId);
238 const fleeceState = def.shearable?.fleeceState ?? null;
239 const sprite = mobSpriteName(def.mobTypeId, fleeceState);
239 if (sprite)
240 if (sprite)
240 { appearance.sprite = sprite; }
241 { appearance.sprite = sprite; }
241 }
242 }
@@ -272,7 +273,13 @@ export function mobComponents (request)
272 mobTypeId: def.mobTypeId,
273 mobTypeId: def.mobTypeId,
273 level,
274 level,
274 ...(element ? { element } : {}),
275 ...(element ? { element } : {}),
275 ...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {})
276 ...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {}),
277 ...(def.shearable
278 ? {
279 fleeceState: def.shearable.fleeceState,
280 woolReadyAt: null
281 }
282 : {})
276 },
283 },
277 health: { current: maxHp, max: maxHp }
284 health: { current: maxHp, max: maxHp }
278 };
285 };
server/src/simulation/workerWorld.js +46 −10
@@ -46,6 +46,7 @@ import {
46 46 import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
47 47 import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
48 48 import { handleFishingCommand, stepFishing } from "../fishing/service.js";
49 import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
49 50 import { handleAlchemyCommand } from "../alchemy/service.js";
50 51 import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
51 52 import {
@@ -502,6 +503,9 @@ export class WorkerWorld
502 503 const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
503 504 if (fishing)
504 505 { return fishing; }
506 const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
507 if (shearing)
508 { return shearing; }
505 509 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
506 510 if (craft)
507 511 { return craft; }
@@ -1331,6 +1335,16 @@ export class WorkerWorld
1331 1335 ...entry.bag
1332 1336 });
1333 1337 }
1338 const shearing = stepShearing(this, now);
1339 events.push(...shearing.events);
1340 for (const entry of shearing.privates ?? [])
1341 {
1342 events.push({
1343 type: "inventory",
1344 characterId: entry.characterId,
1345 ...entry.bag
1346 });
1347 }
1334 1348 const craft = stepCrafting(this, now);
1335 1349 events.push(...craft.events);
1336 1350 for (const entry of craft.privates ?? [])
@@ -1550,7 +1564,7 @@ export class WorkerWorld
1550 1564 if (shopHasActiveBrowsers(shop))
1551 1565 { continue; }
1552 1566 const origin = entity.spawnOrigin;
1553 if (hasDialogueBrowsers(origin))
1567 if (originIsBusyPinned(origin))
1554 1568 { continue; }
1555 1569 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1556 1570 { continue; }
@@ -1720,15 +1734,19 @@ export class WorkerWorld
1720 1734 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1721 1735 {
1722 1736 const browsers = entity.spawnOrigin?.dialogueBrowsers;
1723 if (!browsers || typeof browsers !== "object")
1724 { continue; }
1725 const ids = Object.keys(browsers).map((id) => Number(id));
1726 if (!ids.length)
1737 const shearBrowsers = entity.spawnOrigin?.shearBrowsers;
1738 const dialogueIds = browsers && typeof browsers === "object"
1739 ? Object.keys(browsers).map((id) => Number(id))
1740 : [];
1741 const shearIds = shearBrowsers && typeof shearBrowsers === "object"
1742 ? Object.keys(shearBrowsers).map((id) => Number(id))
1743 : [];
1744 if (!dialogueIds.length && !shearIds.length)
1727 1745 { continue; }
1728 1746 const path = this.ecs.get(entity.handle, Component.path);
1729 1747 if (path)
1730 1748 { path.tiles = []; }
1731 for (const characterId of ids)
1749 for (const characterId of dialogueIds)
1732 1750 {
1733 1751 const playerEntityId = this.characterEntities.get(characterId);
1734 1752 if (playerEntityId == null)
@@ -1756,6 +1774,27 @@ export class WorkerWorld
1756 1774 npcEntityId: entity.entityId
1757 1775 });
1758 1776 }
1777 for (const characterId of shearIds)
1778 {
1779 const playerEntityId = this.characterEntities.get(characterId);
1780 if (playerEntityId == null)
1781 {
1782 delete shearBrowsers[characterId];
1783 continue;
1784 }
1785 const playerHandle = this.ecs.handleOf(playerEntityId);
1786 const playerPos = this.ecs.get(playerHandle, Component.position);
1787 const stillNear = playerPos
1788 && chebyshev(
1789 playerPos.tileX,
1790 playerPos.tileY,
1791 entity.position.tileX,
1792 entity.position.tileY
1793 ) <= 1;
1794 if (stillNear)
1795 { continue; }
1796 delete shearBrowsers[characterId];
1797 }
1759 1798 }
1760 1799 return events;
1761 1800 }
@@ -2140,10 +2179,7 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)
2140 2179
2141 2180 function hasDialogueBrowsers (origin)
2142 2181 {
2143 const browsers = origin?.dialogueBrowsers;
2144 if (!browsers || typeof browsers !== "object")
2145 { return false; }
2146 return Object.keys(browsers).length > 0;
2182 return originIsBusyPinned(origin);
2147 2183 }
2148 2184
2149 2185 function randInt (min, max)
@@ -46,6 +46,7 @@ import {
46import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
46import { handleCraftCommand, stepCrafting } from "../crafting/service.js";
47import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
47import { handleFirestartingCommand, stepFirestarting } from "../firestarting/service.js";
48import { handleFishingCommand, stepFishing } from "../fishing/service.js";
48import { handleFishingCommand, stepFishing } from "../fishing/service.js";
49import { handleShearingCommand, stepShearing, originIsBusyPinned } from "../shearing/service.js";
49import { handleAlchemyCommand } from "../alchemy/service.js";
50import { handleAlchemyCommand } from "../alchemy/service.js";
50import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
51import { handleShopCommand, openShop, shopHasInterface, shopHasActiveBrowsers, pruneShopBrowsers, releaseShopBrowsersForCharacter } from "../shop/service.js";
51import {
52import {
@@ -502,6 +503,9 @@ export class WorkerWorld
502 const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
503 const fishing = handleFishingCommand(this, sessionId, command, message.now ?? Date.now());
503 if (fishing)
504 if (fishing)
504 { return fishing; }
505 { return fishing; }
506 const shearing = handleShearingCommand(this, sessionId, command, message.now ?? Date.now());
507 if (shearing)
508 { return shearing; }
505 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
509 const craft = handleCraftCommand(this, sessionId, command, message.now ?? Date.now());
506 if (craft)
510 if (craft)
507 { return craft; }
511 { return craft; }
@@ -1331,6 +1335,16 @@ export class WorkerWorld
1331 ...entry.bag
1335 ...entry.bag
1332 });
1336 });
1333 }
1337 }
1338 const shearing = stepShearing(this, now);
1339 events.push(...shearing.events);
1340 for (const entry of shearing.privates ?? [])
1341 {
1342 events.push({
1343 type: "inventory",
1344 characterId: entry.characterId,
1345 ...entry.bag
1346 });
1347 }
1334 const craft = stepCrafting(this, now);
1348 const craft = stepCrafting(this, now);
1335 events.push(...craft.events);
1349 events.push(...craft.events);
1336 for (const entry of craft.privates ?? [])
1350 for (const entry of craft.privates ?? [])
@@ -1550,7 +1564,7 @@ export class WorkerWorld
1550 if (shopHasActiveBrowsers(shop))
1564 if (shopHasActiveBrowsers(shop))
1551 { continue; }
1565 { continue; }
1552 const origin = entity.spawnOrigin;
1566 const origin = entity.spawnOrigin;
1553 if (hasDialogueBrowsers(origin))
1567 if (originIsBusyPinned(origin))
1554 { continue; }
1568 { continue; }
1555 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1569 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1556 { continue; }
1570 { continue; }
@@ -1720,15 +1734,19 @@ export class WorkerWorld
1720 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1734 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1721 {
1735 {
1722 const browsers = entity.spawnOrigin?.dialogueBrowsers;
1736 const browsers = entity.spawnOrigin?.dialogueBrowsers;
1723 if (!browsers || typeof browsers !== "object")
1737 const shearBrowsers = entity.spawnOrigin?.shearBrowsers;
1724 { continue; }
1738 const dialogueIds = browsers && typeof browsers === "object"
1725 const ids = Object.keys(browsers).map((id) => Number(id));
1739 ? Object.keys(browsers).map((id) => Number(id))
1726 if (!ids.length)
1740 : [];
1741 const shearIds = shearBrowsers && typeof shearBrowsers === "object"
1742 ? Object.keys(shearBrowsers).map((id) => Number(id))
1743 : [];
1744 if (!dialogueIds.length && !shearIds.length)
1727 { continue; }
1745 { continue; }
1728 const path = this.ecs.get(entity.handle, Component.path);
1746 const path = this.ecs.get(entity.handle, Component.path);
1729 if (path)
1747 if (path)
1730 { path.tiles = []; }
1748 { path.tiles = []; }
1731 for (const characterId of ids)
1749 for (const characterId of dialogueIds)
1732 {
1750 {
1733 const playerEntityId = this.characterEntities.get(characterId);
1751 const playerEntityId = this.characterEntities.get(characterId);
1734 if (playerEntityId == null)
1752 if (playerEntityId == null)
@@ -1756,6 +1774,27 @@ export class WorkerWorld
1756 npcEntityId: entity.entityId
1774 npcEntityId: entity.entityId
1757 });
1775 });
1758 }
1776 }
1777 for (const characterId of shearIds)
1778 {
1779 const playerEntityId = this.characterEntities.get(characterId);
1780 if (playerEntityId == null)
1781 {
1782 delete shearBrowsers[characterId];
1783 continue;
1784 }
1785 const playerHandle = this.ecs.handleOf(playerEntityId);
1786 const playerPos = this.ecs.get(playerHandle, Component.position);
1787 const stillNear = playerPos
1788 && chebyshev(
1789 playerPos.tileX,
1790 playerPos.tileY,
1791 entity.position.tileX,
1792 entity.position.tileY
1793 ) <= 1;
1794 if (stillNear)
1795 { continue; }
1796 delete shearBrowsers[characterId];
1797 }
1759 }
1798 }
1760 return events;
1799 return events;
1761 }
1800 }
@@ -2140,10 +2179,7 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)
2140
2179
2141function hasDialogueBrowsers (origin)
2180function hasDialogueBrowsers (origin)
2142{
2181{
2143 const browsers = origin?.dialogueBrowsers;
2182 return originIsBusyPinned(origin);
2144 if (!browsers || typeof browsers !== "object")
2145 { return false; }
2146 return Object.keys(browsers).length > 0;
2147}
2183}
2148
2184
2149function randInt (min, max)
2185function randInt (min, max)
server/tests/shearing.test.js added +185 −0
@@ -0,0 +1,185 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType, plantGatherForBlock } from "../../shared/definitions/tiles.js";
4 import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
5 import { MetalItemId } from "../../shared/definitions/metalItems.js";
6 import { LeatherItemId } from "../../shared/definitions/leatherItems.js";
7 import { ClothItemId, rawClothItemId } from "../../shared/definitions/clothItems.js";
8 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
9 import {
10 ClothTier,
11 MaterialTier,
12 metalTierForCloth,
13 clothExhaustDurationMs,
14 tierRank
15 } from "../../shared/definitions/materialTiers.js";
16 import { MobId, mobDefinition, mobSpriteName } from "../../shared/definitions/mobs.js";
17 import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
18 import { recipeDefinition, recipesForStation } from "../../shared/crafting/stationRecipes.js";
19 import { resolveItemDualTint } from "../../shared/render/tint.js";
20 import { resolvePlantClippers } from "../../shared/definitions/gathering.js";
21 import { SkillId } from "../../shared/definitions/skills.js";
22 import { normalizePlayerSkills } from "../../shared/skills/state.js";
23 import { totalXpForLevel } from "../../shared/skills/progression.js";
24 import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
25 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
26 import { Component } from "../src/ecs/components.js";
27 import { mobComponents } from "../src/simulation/spawners.js";
28
29 function workerOf (simulation, playerId)
30 {
31 const record = simulation.entityRecord(playerId);
32 return simulation.workers[record.workerId];
33 }
34
35 function advanceMs (harness, ms)
36 {
37 const ticks = Math.ceil(ms / 50) + 3;
38 for (let i = 0; i < ticks; i++)
39 {
40 harness.advance(50);
41 harness.simulation.step();
42 }
43 }
44
45 function setSkillLevel (worker, playerId, skillId, level)
46 {
47 const handle = worker.world.ecs.handleOf(playerId);
48 const skills = worker.world.ecs.get(handle, Component.skills);
49 skills.xp[skillId] = totalXpForLevel(level);
50 }
51
52 function giveInventory (harness, playerId, items)
53 {
54 const inventory = emptySlots();
55 items.forEach((stack, index) =>
56 {
57 inventory[index] = {
58 itemId: stack.itemId,
59 quantity: stack.quantity,
60 ...(stack.instance ? { instance: structuredClone(stack.instance) } : {})
61 };
62 });
63 harness.simulation.applyBag(playerId, {
64 inventory,
65 equipment: emptyEquipment(),
66 vault: [],
67 vaultReserved: []
68 });
69 }
70
71 test("plant clippers use dual metal/leather tint and bar+leather recipe", () =>
72 {
73 const def = itemDefinition(MetalItemId.bronzePlantClippers);
74 assert.equal(def.iconKey, "plant-clippers");
75 assert.equal(def.dualTintFromTier, true);
76 assert.equal(def.leatherTier, "softLeather");
77 const dual = resolveItemDualTint({ itemId: MetalItemId.bronzePlantClippers }, def);
78 assert.ok(dual?.shaft);
79 assert.ok(dual?.tip);
80 const recipe = recipeDefinition("plant-clippers-bronze");
81 assert.deepEqual(recipe.inputs, [
82 { itemId: ItemId.bronzeBar, quantity: 1 },
83 { itemId: LeatherItemId.softLeather, quantity: 1 }
84 ]);
85 assert.equal(recipe.stationId, CraftingStationId.anvil);
86 });
87
88 test("shears are magenta-tinted metal and craft from one bar", () =>
89 {
90 const def = itemDefinition(MetalItemId.ironShears);
91 assert.equal(def.equipment.kind, EquipmentKind.shears);
92 assert.equal(def.tintFromTier, true);
93 assert.equal(def.dualTintFromTier, undefined);
94 const recipe = recipeDefinition("shears-iron");
95 assert.deepEqual(recipe.inputs, [{ itemId: ItemId.ironBar, quantity: 1 }]);
96 assert.equal(
97 recipesForStation(CraftingStationId.anvil).filter((r) => r.craftGroup === "shears").length,
98 7
99 );
100 });
101
102 test("sheep and cashmere goat are shearable with fleece/shorn sprites", () =>
103 {
104 const sheep = mobDefinition(MobId.sheep);
105 assert.equal(sheep.shearable.clothTier, ClothTier.wool);
106 assert.equal(mobSpriteName(MobId.sheep), "mob:sheep:fleece");
107 assert.equal(mobSpriteName(MobId.sheep, "shorn"), "mob:sheep:shorn");
108 const goat = mobDefinition(MobId.cashmereGoat);
109 assert.equal(goat.shearable.clothTier, ClothTier.cashmere);
110 assert.equal(mobSpriteName(MobId.cashmereGoat, "fleece"), "mob:cashmere-goat:fleece");
111 });
112
113 test("flax needs steel-or-better clippers; linen fibre is named Flax", () =>
114 {
115 assert.equal(itemDefinition(ClothItemId.linen).displayName, "Flax");
116 assert.equal(metalTierForCloth(ClothTier.linen), MaterialTier.steel);
117 const skills = normalizePlayerSkills(null);
118 skills.xp[SkillId.herbalism] = totalXpForLevel(20);
119 const bronze = resolvePlantClippers({
120 inventorySlots: [{ itemId: MetalItemId.bronzePlantClippers, quantity: 1 }],
121 equipmentSlots: emptyEquipment().slots,
122 skills,
123 minClothTier: ClothTier.linen
124 });
125 assert.equal(bronze.ok, false);
126 const steel = resolvePlantClippers({
127 inventorySlots: [{ itemId: MetalItemId.steelPlantClippers, quantity: 1 }],
128 equipmentSlots: emptyEquipment().slots,
129 skills,
130 minClothTier: ClothTier.linen
131 });
132 assert.equal(steel.ok, true);
133 const plant = plantGatherForBlock({ typeId: BlockType.flaxPlant, state: "flax-plant" });
134 assert.equal(plant.kind, "flax");
135 assert.equal(plant.requiresClippers, true);
136 assert.equal(plant.minClothTier, "linen");
137 });
138
139 test("shearing a sheep grants wool and sets shorn state", () =>
140 {
141 const harness = makeSimulation({ workerCount: 1 });
142 try
143 {
144 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
145 const playerId = harness.simulation.spawnCharacter(1, character);
146 const worker = workerOf(harness.simulation, playerId);
147 setSkillLevel(worker, playerId, SkillId.herbalism, 10);
148 giveInventory(harness, playerId, [
149 { itemId: MetalItemId.ironShears, quantity: 1 }
150 ]);
151
152 const sheepId = harness.simulation.spawnEntity(mobComponents({
153 tileX: 9,
154 tileY: 8,
155 mobTypeId: MobId.sheep,
156 spawnerId: "test-sheep",
157 displayName: "Woolly"
158 }));
159
160 harness.simulation.enqueue(1, {
161 type: "shear",
162 characterId: character.character_id,
163 targetEntityId: sheepId
164 });
165 advanceMs(harness, 3500);
166
167 const creature = worker.world.ecs.get(
168 worker.world.ecs.handleOf(sheepId),
169 Component.creature
170 );
171 assert.equal(creature.fleeceState, "shorn");
172 assert.ok(creature.woolReadyAt > harness.now());
173 const bag = harness.simulation.bagOf(playerId);
174 const woolId = rawClothItemId(ClothTier.wool);
175 assert.ok(bag.inventory.some((s) => s?.itemId === woolId));
176 assert.equal(
177 clothExhaustDurationMs(ClothTier.wool),
178 tierRank(ClothTier.wool) * 10_000
179 );
180 }
181 finally
182 {
183 harness.close();
184 }
185 });
@@ -0,0 +1,185 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType, plantGatherForBlock } from "../../shared/definitions/tiles.js";
4import { CraftingStationId } from "../../shared/definitions/craftingStations.js";
5import { MetalItemId } from "../../shared/definitions/metalItems.js";
6import { LeatherItemId } from "../../shared/definitions/leatherItems.js";
7import { ClothItemId, rawClothItemId } from "../../shared/definitions/clothItems.js";
8import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
9import {
10 ClothTier,
11 MaterialTier,
12 metalTierForCloth,
13 clothExhaustDurationMs,
14 tierRank
15} from "../../shared/definitions/materialTiers.js";
16import { MobId, mobDefinition, mobSpriteName } from "../../shared/definitions/mobs.js";
17import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
18import { recipeDefinition, recipesForStation } from "../../shared/crafting/stationRecipes.js";
19import { resolveItemDualTint } from "../../shared/render/tint.js";
20import { resolvePlantClippers } from "../../shared/definitions/gathering.js";
21import { SkillId } from "../../shared/definitions/skills.js";
22import { normalizePlayerSkills } from "../../shared/skills/state.js";
23import { totalXpForLevel } from "../../shared/skills/progression.js";
24import { emptyEquipment, emptySlots } from "../../shared/items/inventory.js";
25import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
26import { Component } from "../src/ecs/components.js";
27import { mobComponents } from "../src/simulation/spawners.js";
28
29function workerOf (simulation, playerId)
30{
31 const record = simulation.entityRecord(playerId);
32 return simulation.workers[record.workerId];
33}
34
35function advanceMs (harness, ms)
36{
37 const ticks = Math.ceil(ms / 50) + 3;
38 for (let i = 0; i < ticks; i++)
39 {
40 harness.advance(50);
41 harness.simulation.step();
42 }
43}
44
45function setSkillLevel (worker, playerId, skillId, level)
46{
47 const handle = worker.world.ecs.handleOf(playerId);
48 const skills = worker.world.ecs.get(handle, Component.skills);
49 skills.xp[skillId] = totalXpForLevel(level);
50}
51
52function giveInventory (harness, playerId, items)
53{
54 const inventory = emptySlots();
55 items.forEach((stack, index) =>
56 {
57 inventory[index] = {
58 itemId: stack.itemId,
59 quantity: stack.quantity,
60 ...(stack.instance ? { instance: structuredClone(stack.instance) } : {})
61 };
62 });
63 harness.simulation.applyBag(playerId, {
64 inventory,
65 equipment: emptyEquipment(),
66 vault: [],
67 vaultReserved: []
68 });
69}
70
71test("plant clippers use dual metal/leather tint and bar+leather recipe", () =>
72{
73 const def = itemDefinition(MetalItemId.bronzePlantClippers);
74 assert.equal(def.iconKey, "plant-clippers");
75 assert.equal(def.dualTintFromTier, true);
76 assert.equal(def.leatherTier, "softLeather");
77 const dual = resolveItemDualTint({ itemId: MetalItemId.bronzePlantClippers }, def);
78 assert.ok(dual?.shaft);
79 assert.ok(dual?.tip);
80 const recipe = recipeDefinition("plant-clippers-bronze");
81 assert.deepEqual(recipe.inputs, [
82 { itemId: ItemId.bronzeBar, quantity: 1 },
83 { itemId: LeatherItemId.softLeather, quantity: 1 }
84 ]);
85 assert.equal(recipe.stationId, CraftingStationId.anvil);
86});
87
88test("shears are magenta-tinted metal and craft from one bar", () =>
89{
90 const def = itemDefinition(MetalItemId.ironShears);
91 assert.equal(def.equipment.kind, EquipmentKind.shears);
92 assert.equal(def.tintFromTier, true);
93 assert.equal(def.dualTintFromTier, undefined);
94 const recipe = recipeDefinition("shears-iron");
95 assert.deepEqual(recipe.inputs, [{ itemId: ItemId.ironBar, quantity: 1 }]);
96 assert.equal(
97 recipesForStation(CraftingStationId.anvil).filter((r) => r.craftGroup === "shears").length,
98 7
99 );
100});
101
102test("sheep and cashmere goat are shearable with fleece/shorn sprites", () =>
103{
104 const sheep = mobDefinition(MobId.sheep);
105 assert.equal(sheep.shearable.clothTier, ClothTier.wool);
106 assert.equal(mobSpriteName(MobId.sheep), "mob:sheep:fleece");
107 assert.equal(mobSpriteName(MobId.sheep, "shorn"), "mob:sheep:shorn");
108 const goat = mobDefinition(MobId.cashmereGoat);
109 assert.equal(goat.shearable.clothTier, ClothTier.cashmere);
110 assert.equal(mobSpriteName(MobId.cashmereGoat, "fleece"), "mob:cashmere-goat:fleece");
111});
112
113test("flax needs steel-or-better clippers; linen fibre is named Flax", () =>
114{
115 assert.equal(itemDefinition(ClothItemId.linen).displayName, "Flax");
116 assert.equal(metalTierForCloth(ClothTier.linen), MaterialTier.steel);
117 const skills = normalizePlayerSkills(null);
118 skills.xp[SkillId.herbalism] = totalXpForLevel(20);
119 const bronze = resolvePlantClippers({
120 inventorySlots: [{ itemId: MetalItemId.bronzePlantClippers, quantity: 1 }],
121 equipmentSlots: emptyEquipment().slots,
122 skills,
123 minClothTier: ClothTier.linen
124 });
125 assert.equal(bronze.ok, false);
126 const steel = resolvePlantClippers({
127 inventorySlots: [{ itemId: MetalItemId.steelPlantClippers, quantity: 1 }],
128 equipmentSlots: emptyEquipment().slots,
129 skills,
130 minClothTier: ClothTier.linen
131 });
132 assert.equal(steel.ok, true);
133 const plant = plantGatherForBlock({ typeId: BlockType.flaxPlant, state: "flax-plant" });
134 assert.equal(plant.kind, "flax");
135 assert.equal(plant.requiresClippers, true);
136 assert.equal(plant.minClothTier, "linen");
137});
138
139test("shearing a sheep grants wool and sets shorn state", () =>
140{
141 const harness = makeSimulation({ workerCount: 1 });
142 try
143 {
144 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
145 const playerId = harness.simulation.spawnCharacter(1, character);
146 const worker = workerOf(harness.simulation, playerId);
147 setSkillLevel(worker, playerId, SkillId.herbalism, 10);
148 giveInventory(harness, playerId, [
149 { itemId: MetalItemId.ironShears, quantity: 1 }
150 ]);
151
152 const sheepId = harness.simulation.spawnEntity(mobComponents({
153 tileX: 9,
154 tileY: 8,
155 mobTypeId: MobId.sheep,
156 spawnerId: "test-sheep",
157 displayName: "Woolly"
158 }));
159
160 harness.simulation.enqueue(1, {
161 type: "shear",
162 characterId: character.character_id,
163 targetEntityId: sheepId
164 });
165 advanceMs(harness, 3500);
166
167 const creature = worker.world.ecs.get(
168 worker.world.ecs.handleOf(sheepId),
169 Component.creature
170 );
171 assert.equal(creature.fleeceState, "shorn");
172 assert.ok(creature.woolReadyAt > harness.now());
173 const bag = harness.simulation.bagOf(playerId);
174 const woolId = rawClothItemId(ClothTier.wool);
175 assert.ok(bag.inventory.some((s) => s?.itemId === woolId));
176 assert.equal(
177 clothExhaustDurationMs(ClothTier.wool),
178 tierRank(ClothTier.wool) * 10_000
179 );
180 }
181 finally
182 {
183 harness.close();
184 }
185});
shared/crafting/tierRecipes.js +28 −4
@@ -191,13 +191,36 @@ function axeAssembleRecipes ()
191 191 }
192 192
193 193 function plantClippersRecipes ()
194 {
195 return MATERIAL_TIER_ORDER.map((metalTier) =>
196 {
197 const leatherId = leatherMaterialItemId(leatherTierForMetal(metalTier));
198 return tierRecipe({
199 recipeId: `plant-clippers-${metalTier}`,
200 craftGroup: "plant-clippers",
201 craftGroupLabel: "Plant clippers",
202 stationId: CraftingStationId.anvil,
203 outputFamily: ItemFamilyId.plantClippers,
204 outputTier: metalTier,
205 inputs: [
206 { itemId: familyItemId(ItemFamilyId.bar, metalTier), quantity: 1 },
207 { itemId: leatherId, quantity: 1 }
208 ],
209 minSkillLevel: tierSmeltSkillLevel(metalTier),
210 skillId: "smithing",
211 xpMaterial: metalTier
212 });
213 });
214 }
215
216 function shearsRecipes ()
194 217 {
195 218 return MATERIAL_TIER_ORDER.map((metalTier) => tierRecipe({
196 recipeId: `plant-clippers-${metalTier}`,
197 craftGroup: "plant-clippers",
198 craftGroupLabel: "Plant clippers",
219 recipeId: `shears-${metalTier}`,
220 craftGroup: "shears",
221 craftGroupLabel: "Shears",
199 222 stationId: CraftingStationId.anvil,
200 outputFamily: ItemFamilyId.plantClippers,
223 outputFamily: ItemFamilyId.shears,
201 224 outputTier: metalTier,
202 225 inputs: [{ itemId: familyItemId(ItemFamilyId.bar, metalTier), quantity: 1 }],
203 226 minSkillLevel: tierSmeltSkillLevel(metalTier),
@@ -460,6 +483,7 @@ export const TIER_FAMILY_RECIPES = Object.freeze([
460 483 ...axeHeadRecipes(),
461 484 ...axeAssembleRecipes(),
462 485 ...plantClippersRecipes(),
486 ...shearsRecipes(),
463 487 ...swordBladeRecipes(),
464 488 ...swordAssembleRecipes(),
465 489 ...warAxeHeadRecipes(),
@@ -191,13 +191,36 @@ function axeAssembleRecipes ()
191}
191}
192
192
193function plantClippersRecipes ()
193function plantClippersRecipes ()
194{
195 return MATERIAL_TIER_ORDER.map((metalTier) =>
196 {
197 const leatherId = leatherMaterialItemId(leatherTierForMetal(metalTier));
198 return tierRecipe({
199 recipeId: `plant-clippers-${metalTier}`,
200 craftGroup: "plant-clippers",
201 craftGroupLabel: "Plant clippers",
202 stationId: CraftingStationId.anvil,
203 outputFamily: ItemFamilyId.plantClippers,
204 outputTier: metalTier,
205 inputs: [
206 { itemId: familyItemId(ItemFamilyId.bar, metalTier), quantity: 1 },
207 { itemId: leatherId, quantity: 1 }
208 ],
209 minSkillLevel: tierSmeltSkillLevel(metalTier),
210 skillId: "smithing",
211 xpMaterial: metalTier
212 });
213 });
214}
215
216function shearsRecipes ()
194{
217{
195 return MATERIAL_TIER_ORDER.map((metalTier) => tierRecipe({
218 return MATERIAL_TIER_ORDER.map((metalTier) => tierRecipe({
196 recipeId: `plant-clippers-${metalTier}`,
219 recipeId: `shears-${metalTier}`,
197 craftGroup: "plant-clippers",
220 craftGroup: "shears",
198 craftGroupLabel: "Plant clippers",
221 craftGroupLabel: "Shears",
199 stationId: CraftingStationId.anvil,
222 stationId: CraftingStationId.anvil,
200 outputFamily: ItemFamilyId.plantClippers,
223 outputFamily: ItemFamilyId.shears,
201 outputTier: metalTier,
224 outputTier: metalTier,
202 inputs: [{ itemId: familyItemId(ItemFamilyId.bar, metalTier), quantity: 1 }],
225 inputs: [{ itemId: familyItemId(ItemFamilyId.bar, metalTier), quantity: 1 }],
203 minSkillLevel: tierSmeltSkillLevel(metalTier),
226 minSkillLevel: tierSmeltSkillLevel(metalTier),
@@ -460,6 +483,7 @@ export const TIER_FAMILY_RECIPES = Object.freeze([
460 ...axeHeadRecipes(),
483 ...axeHeadRecipes(),
461 ...axeAssembleRecipes(),
484 ...axeAssembleRecipes(),
462 ...plantClippersRecipes(),
485 ...plantClippersRecipes(),
486 ...shearsRecipes(),
463 ...swordBladeRecipes(),
487 ...swordBladeRecipes(),
464 ...swordAssembleRecipes(),
488 ...swordAssembleRecipes(),
465 ...warAxeHeadRecipes(),
489 ...warAxeHeadRecipes(),
shared/definitions/clothItems.js +8 −1
@@ -165,17 +165,24 @@ function rawLabel (tier)
165 165 {
166 166 if (tier === ClothTier.cotton)
167 167 { return "Cotton"; }
168 if (tier === ClothTier.linen)
169 { return "Flax"; }
168 170 return CLOTH_DISPLAY_NAME[tier] ?? tier;
169 171 }
170 172
171 173 function fibreDef (itemId, tier, key)
172 174 {
173 175 const name = rawLabel(tier);
176 const spinHint = tier === ClothTier.linen
177 ? "Spin into linen yarn at a spinning wheel."
178 : `Spin into yarn at a spinning wheel.`;
174 179 return Object.freeze({
175 180 itemId,
176 181 key,
177 182 displayName: name,
178 description: `Raw ${name.toLowerCase()} fibre. Spin into yarn at a spinning wheel.`,
183 description: tier === ClothTier.linen
184 ? `Harvested flax stems. ${spinHint}`
185 : `Raw ${name.toLowerCase()} fibre. ${spinHint}`,
179 186 seedValue: 2,
180 187 stackable: true,
181 188 maxStackSize: DEFAULT_STACK,
@@ -165,17 +165,24 @@ function rawLabel (tier)
165{
165{
166 if (tier === ClothTier.cotton)
166 if (tier === ClothTier.cotton)
167 { return "Cotton"; }
167 { return "Cotton"; }
168 if (tier === ClothTier.linen)
169 { return "Flax"; }
168 return CLOTH_DISPLAY_NAME[tier] ?? tier;
170 return CLOTH_DISPLAY_NAME[tier] ?? tier;
169}
171}
170
172
171function fibreDef (itemId, tier, key)
173function fibreDef (itemId, tier, key)
172{
174{
173 const name = rawLabel(tier);
175 const name = rawLabel(tier);
176 const spinHint = tier === ClothTier.linen
177 ? "Spin into linen yarn at a spinning wheel."
178 : `Spin into yarn at a spinning wheel.`;
174 return Object.freeze({
179 return Object.freeze({
175 itemId,
180 itemId,
176 key,
181 key,
177 displayName: name,
182 displayName: name,
178 description: `Raw ${name.toLowerCase()} fibre. Spin into yarn at a spinning wheel.`,
183 description: tier === ClothTier.linen
184 ? `Harvested flax stems. ${spinHint}`
185 : `Raw ${name.toLowerCase()} fibre. ${spinHint}`,
179 seedValue: 2,
186 seedValue: 2,
180 stackable: true,
187 stackable: true,
181 maxStackSize: DEFAULT_STACK,
188 maxStackSize: DEFAULT_STACK,
shared/definitions/equipmentKinds.js +1 −0
@@ -14,5 +14,6 @@ export const EquipmentKind = Object.freeze({
14 14 fishingRod: "fishingRod",
15 15 fishingNet: "fishingNet",
16 16 plantClippers: "plantClippers",
17 shears: "shears",
17 18 arrowAmmo: "arrowAmmo"
18 19 });
@@ -14,5 +14,6 @@ export const EquipmentKind = Object.freeze({
14 fishingRod: "fishingRod",
14 fishingRod: "fishingRod",
15 fishingNet: "fishingNet",
15 fishingNet: "fishingNet",
16 plantClippers: "plantClippers",
16 plantClippers: "plantClippers",
17 shears: "shears",
17 arrowAmmo: "arrowAmmo"
18 arrowAmmo: "arrowAmmo"
18});
19});
shared/definitions/familyItemIds.js +3 −1
@@ -6,7 +6,8 @@ import {
6 6 AXE_HEAD_ITEM_BY_METAL,
7 7 PICKAXE_ITEM_BY_METAL,
8 8 AXE_ITEM_BY_METAL,
9 PLANT_CLIPPERS_ITEM_BY_METAL
9 PLANT_CLIPPERS_ITEM_BY_METAL,
10 SHEARS_ITEM_BY_METAL
10 11 } from "./metalItems.js";
11 12 import {
12 13 SWORD_BLADE_ITEM_BY_METAL,
@@ -35,6 +36,7 @@ export const FAMILY_ITEM_IDS = Object.freeze({
35 36 [ItemFamilyId.pickaxe]: PICKAXE_ITEM_BY_METAL,
36 37 [ItemFamilyId.axe]: AXE_ITEM_BY_METAL,
37 38 [ItemFamilyId.plantClippers]: PLANT_CLIPPERS_ITEM_BY_METAL,
39 [ItemFamilyId.shears]: SHEARS_ITEM_BY_METAL,
38 40 [ItemFamilyId.swordBlade]: SWORD_BLADE_ITEM_BY_METAL,
39 41 [ItemFamilyId.sword]: SWORD_ITEM_BY_METAL,
40 42 [ItemFamilyId.warAxeHead]: WAR_AXE_HEAD_ITEM_BY_METAL,
@@ -6,7 +6,8 @@ import {
6 AXE_HEAD_ITEM_BY_METAL,
6 AXE_HEAD_ITEM_BY_METAL,
7 PICKAXE_ITEM_BY_METAL,
7 PICKAXE_ITEM_BY_METAL,
8 AXE_ITEM_BY_METAL,
8 AXE_ITEM_BY_METAL,
9 PLANT_CLIPPERS_ITEM_BY_METAL
9 PLANT_CLIPPERS_ITEM_BY_METAL,
10 SHEARS_ITEM_BY_METAL
10} from "./metalItems.js";
11} from "./metalItems.js";
11import {
12import {
12 SWORD_BLADE_ITEM_BY_METAL,
13 SWORD_BLADE_ITEM_BY_METAL,
@@ -35,6 +36,7 @@ export const FAMILY_ITEM_IDS = Object.freeze({
35 [ItemFamilyId.pickaxe]: PICKAXE_ITEM_BY_METAL,
36 [ItemFamilyId.pickaxe]: PICKAXE_ITEM_BY_METAL,
36 [ItemFamilyId.axe]: AXE_ITEM_BY_METAL,
37 [ItemFamilyId.axe]: AXE_ITEM_BY_METAL,
37 [ItemFamilyId.plantClippers]: PLANT_CLIPPERS_ITEM_BY_METAL,
38 [ItemFamilyId.plantClippers]: PLANT_CLIPPERS_ITEM_BY_METAL,
39 [ItemFamilyId.shears]: SHEARS_ITEM_BY_METAL,
38 [ItemFamilyId.swordBlade]: SWORD_BLADE_ITEM_BY_METAL,
40 [ItemFamilyId.swordBlade]: SWORD_BLADE_ITEM_BY_METAL,
39 [ItemFamilyId.sword]: SWORD_ITEM_BY_METAL,
41 [ItemFamilyId.sword]: SWORD_ITEM_BY_METAL,
40 [ItemFamilyId.warAxeHead]: WAR_AXE_HEAD_ITEM_BY_METAL,
42 [ItemFamilyId.warAxeHead]: WAR_AXE_HEAD_ITEM_BY_METAL,
shared/definitions/gathering.js +53 −3
@@ -23,7 +23,9 @@ import
23 23 oreBoulderState,
24 24 materialFromOreBoulderState,
25 25 isOreBoulderState,
26 isGemstoneMaterial
26 isGemstoneMaterial,
27 metalTierForCloth,
28 MATERIAL_DISPLAY_NAME
27 29 } from "./materialTiers.js";
28 30 import { gemItemId } from "./gemItems.js";
29 31 import { herbDefinition, herbGatherSkillLevel } from "./herbs.js";
@@ -295,10 +297,17 @@ export function resolveFishingTool ({ inventorySlots, equipmentSlots, skills })
295 297 }
296 298
297 299 /**
298 * Best plant clippers for herbalism nodes (flowers). Cotton needs no tool.
300 * Best plant clippers for herbalism nodes.
301 * @param {{ inventorySlots: object[], equipmentSlots: object, skills: object, requireTool?: boolean, minClothTier?: string|null }} args
299 302 * @returns {{ ok: true, tool: object|null } | { ok: false, reason: string }}
300 303 */
301 export function resolvePlantClippers ({ inventorySlots, equipmentSlots, skills, requireTool = true })
304 export function resolvePlantClippers ({
305 inventorySlots,
306 equipmentSlots,
307 skills,
308 requireTool = true,
309 minClothTier = null
310 })
302 311 {
303 312 if (!requireTool)
304 313 { return { ok: true, tool: null }; }
@@ -307,6 +316,40 @@ export function resolvePlantClippers ({ inventorySlots, equipmentSlots, skills,
307 316 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
308 317 if (!tools.length)
309 318 { return { ok: false, reason: "You need plant clippers to gather this!" }; }
319 if (minClothTier)
320 {
321 const needMetal = metalTierForCloth(minClothTier);
322 const usable = tools.filter((tool) => tierRank(tool.tier) >= tierRank(needMetal));
323 if (!usable.length)
324 {
325 return {
326 ok: false,
327 reason: `You need ${MATERIAL_DISPLAY_NAME[needMetal] ?? needMetal} plant clippers or better.`
328 };
329 }
330 return { ok: true, tool: usable[0] };
331 }
332 return { ok: true, tool: tools[0] };
333 }
334
335 /**
336 * Best shears for clipping fleece (inventory or weapon slot).
337 * @returns {{ ok: true, tool: object } | { ok: false, reason: string }}
338 */
339 export function resolveShears ({ inventorySlots, equipmentSlots, skills, clothTier })
340 {
341 const needMetal = metalTierForCloth(clothTier);
342 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.shears)
343 .filter((tool) => canEquipItem(skills, tool.def).ok)
344 .filter((tool) => tierRank(tool.tier) >= tierRank(needMetal))
345 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
346 if (!tools.length)
347 {
348 return {
349 ok: false,
350 reason: `You need ${MATERIAL_DISPLAY_NAME[needMetal] ?? needMetal} shears or better.`
351 };
352 }
310 353 return { ok: true, tool: tools[0] };
311 354 }
312 355
@@ -337,6 +380,11 @@ export function herbalismDurationMs (plantKind = null, toolTier = null, herbTier
337 380 const rank = toolTier ? tierRank(toolTier) : 1;
338 381 return Math.max(800, 1600 + tier * 250 - (rank - 1) * 150);
339 382 }
383 if (plantKind === "flax")
384 {
385 const rank = toolTier ? tierRank(toolTier) : 1;
386 return Math.max(800, 2200 - (rank - 1) * 200);
387 }
340 388 const rank = toolTier ? tierRank(toolTier) : 1;
341 389 return Math.max(500, 2500 - (rank - 1) * 250);
342 390 }
@@ -347,6 +395,8 @@ export function herbalismXpForPick (kind, herbTier = null)
347 395 { return 4; }
348 396 if (kind === "herb")
349 397 { return 4 + Math.max(1, herbTier | 0 || 1) * 2; }
398 if (kind === "flax")
399 { return 5; }
350 400 return 3;
351 401 }
352 402
@@ -23,7 +23,9 @@ import
23 oreBoulderState,
23 oreBoulderState,
24 materialFromOreBoulderState,
24 materialFromOreBoulderState,
25 isOreBoulderState,
25 isOreBoulderState,
26 isGemstoneMaterial
26 isGemstoneMaterial,
27 metalTierForCloth,
28 MATERIAL_DISPLAY_NAME
27 } from "./materialTiers.js";
29 } from "./materialTiers.js";
28import { gemItemId } from "./gemItems.js";
30import { gemItemId } from "./gemItems.js";
29import { herbDefinition, herbGatherSkillLevel } from "./herbs.js";
31import { herbDefinition, herbGatherSkillLevel } from "./herbs.js";
@@ -295,10 +297,17 @@ export function resolveFishingTool ({ inventorySlots, equipmentSlots, skills })
295}
297}
296
298
297/**
299/**
298 * Best plant clippers for herbalism nodes (flowers). Cotton needs no tool.
300 * Best plant clippers for herbalism nodes.
301 * @param {{ inventorySlots: object[], equipmentSlots: object, skills: object, requireTool?: boolean, minClothTier?: string|null }} args
299 * @returns {{ ok: true, tool: object|null } | { ok: false, reason: string }}
302 * @returns {{ ok: true, tool: object|null } | { ok: false, reason: string }}
300 */
303 */
301export function resolvePlantClippers ({ inventorySlots, equipmentSlots, skills, requireTool = true })
304export function resolvePlantClippers ({
305 inventorySlots,
306 equipmentSlots,
307 skills,
308 requireTool = true,
309 minClothTier = null
310})
302{
311{
303 if (!requireTool)
312 if (!requireTool)
304 { return { ok: true, tool: null }; }
313 { return { ok: true, tool: null }; }
@@ -307,6 +316,40 @@ export function resolvePlantClippers ({ inventorySlots, equipmentSlots, skills,
307 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
316 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
308 if (!tools.length)
317 if (!tools.length)
309 { return { ok: false, reason: "You need plant clippers to gather this!" }; }
318 { return { ok: false, reason: "You need plant clippers to gather this!" }; }
319 if (minClothTier)
320 {
321 const needMetal = metalTierForCloth(minClothTier);
322 const usable = tools.filter((tool) => tierRank(tool.tier) >= tierRank(needMetal));
323 if (!usable.length)
324 {
325 return {
326 ok: false,
327 reason: `You need ${MATERIAL_DISPLAY_NAME[needMetal] ?? needMetal} plant clippers or better.`
328 };
329 }
330 return { ok: true, tool: usable[0] };
331 }
332 return { ok: true, tool: tools[0] };
333}
334
335/**
336 * Best shears for clipping fleece (inventory or weapon slot).
337 * @returns {{ ok: true, tool: object } | { ok: false, reason: string }}
338 */
339export function resolveShears ({ inventorySlots, equipmentSlots, skills, clothTier })
340{
341 const needMetal = metalTierForCloth(clothTier);
342 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.shears)
343 .filter((tool) => canEquipItem(skills, tool.def).ok)
344 .filter((tool) => tierRank(tool.tier) >= tierRank(needMetal))
345 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
346 if (!tools.length)
347 {
348 return {
349 ok: false,
350 reason: `You need ${MATERIAL_DISPLAY_NAME[needMetal] ?? needMetal} shears or better.`
351 };
352 }
310 return { ok: true, tool: tools[0] };
353 return { ok: true, tool: tools[0] };
311}
354}
312
355
@@ -337,6 +380,11 @@ export function herbalismDurationMs (plantKind = null, toolTier = null, herbTier
337 const rank = toolTier ? tierRank(toolTier) : 1;
380 const rank = toolTier ? tierRank(toolTier) : 1;
338 return Math.max(800, 1600 + tier * 250 - (rank - 1) * 150);
381 return Math.max(800, 1600 + tier * 250 - (rank - 1) * 150);
339 }
382 }
383 if (plantKind === "flax")
384 {
385 const rank = toolTier ? tierRank(toolTier) : 1;
386 return Math.max(800, 2200 - (rank - 1) * 200);
387 }
340 const rank = toolTier ? tierRank(toolTier) : 1;
388 const rank = toolTier ? tierRank(toolTier) : 1;
341 return Math.max(500, 2500 - (rank - 1) * 250);
389 return Math.max(500, 2500 - (rank - 1) * 250);
342}
390}
@@ -347,6 +395,8 @@ export function herbalismXpForPick (kind, herbTier = null)
347 { return 4; }
395 { return 4; }
348 if (kind === "herb")
396 if (kind === "herb")
349 { return 4 + Math.max(1, herbTier | 0 || 1) * 2; }
397 { return 4 + Math.max(1, herbTier | 0 || 1) * 2; }
398 if (kind === "flax")
399 { return 5; }
350 return 3;
400 return 3;
351}
401}
352
402
shared/definitions/materialTiers.js +13 −0
@@ -584,6 +584,19 @@ export function metalTierForWood (woodTier)
584 584 return METAL_TIER_FOR_WOOD[woodTier] ?? MaterialTier.bronze;
585 585 }
586 586
587 /** Matching metal tier for a cloth fibre (cotton↔bronze … dragonweave↔dragon). */
588 export function metalTierForCloth (clothTier)
589 {
590 const idx = CLOTH_TIER_ORDER.indexOf(clothTier);
591 return MATERIAL_TIER_ORDER[idx >= 0 ? idx : 0] ?? MaterialTier.bronze;
592 }
593
594 /** Fleece / plant fibre node exhaust duration (same curve as ore/trees). */
595 export function clothExhaustDurationMs (clothTier)
596 {
597 return oreExhaustDurationMs(clothTier);
598 }
599
587 600 /**
588 601 * Mining action duration in ms.
589 602 * (resourceRank * 8s) − (toolRank * 3s), floored at 0.5s.
@@ -584,6 +584,19 @@ export function metalTierForWood (woodTier)
584 return METAL_TIER_FOR_WOOD[woodTier] ?? MaterialTier.bronze;
584 return METAL_TIER_FOR_WOOD[woodTier] ?? MaterialTier.bronze;
585}
585}
586
586
587/** Matching metal tier for a cloth fibre (cotton↔bronze … dragonweave↔dragon). */
588export function metalTierForCloth (clothTier)
589{
590 const idx = CLOTH_TIER_ORDER.indexOf(clothTier);
591 return MATERIAL_TIER_ORDER[idx >= 0 ? idx : 0] ?? MaterialTier.bronze;
592}
593
594/** Fleece / plant fibre node exhaust duration (same curve as ore/trees). */
595export function clothExhaustDurationMs (clothTier)
596{
597 return oreExhaustDurationMs(clothTier);
598}
599
587/**
600/**
588 * Mining action duration in ms.
601 * Mining action duration in ms.
589 * (resourceRank * 8s) − (toolRank * 3s), floored at 0.5s.
602 * (resourceRank * 8s) − (toolRank * 3s), floored at 0.5s.
shared/definitions/metalItems.js +20 −1
@@ -66,7 +66,14 @@ export const MetalItemId = Object.freeze({
66 66 mithrilPlantClippers: 186,
67 67 adamantiumPlantClippers: 187,
68 68 orichalcumPlantClippers: 188,
69 dragonPlantClippers: 189
69 dragonPlantClippers: 189,
70 bronzeShears: 497,
71 ironShears: 498,
72 steelShears: 499,
73 mithrilShears: 500,
74 adamantiumShears: 501,
75 orichalcumShears: 502,
76 dragonShears: 503
70 77 });
71 78
72 79 const DEFAULT_STACK = 99;
@@ -152,6 +159,17 @@ export const PLANT_CLIPPERS_ITEM_BY_METAL = Object.freeze({
152 159 [MaterialTier.dragon]: MetalItemId.dragonPlantClippers
153 160 });
154 161
162 /** Shears item id by metal tier. */
163 export const SHEARS_ITEM_BY_METAL = Object.freeze({
164 [MaterialTier.bronze]: MetalItemId.bronzeShears,
165 [MaterialTier.iron]: MetalItemId.ironShears,
166 [MaterialTier.steel]: MetalItemId.steelShears,
167 [MaterialTier.mithril]: MetalItemId.mithrilShears,
168 [MaterialTier.adamantium]: MetalItemId.adamantiumShears,
169 [MaterialTier.orichalcum]: MetalItemId.orichalcumShears,
170 [MaterialTier.dragon]: MetalItemId.dragonShears
171 });
172
155 173 /** Full defs for metal family (merged into ITEM_DEFINITIONS). */
156 174 const BAR_ITEM_DEFINITIONS = buildFamilyDefinitionMap(ItemFamilyId.bar, BAR_BY_TIER);
157 175
@@ -163,6 +181,7 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
163 181 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxe, PICKAXE_ITEM_BY_METAL),
164 182 ...buildFamilyDefinitionMap(ItemFamilyId.axe, AXE_ITEM_BY_METAL),
165 183 ...buildFamilyDefinitionMap(ItemFamilyId.plantClippers, PLANT_CLIPPERS_ITEM_BY_METAL),
184 ...buildFamilyDefinitionMap(ItemFamilyId.shears, SHEARS_ITEM_BY_METAL),
166 185 [MetalItemId.electrumBar]: Object.freeze({
167 186 ...BAR_ITEM_DEFINITIONS[MetalItemId.electrumBar],
168 187 description: "A pale gold-silver alloy. Fit for fine jewellery."
@@ -66,7 +66,14 @@ export const MetalItemId = Object.freeze({
66 mithrilPlantClippers: 186,
66 mithrilPlantClippers: 186,
67 adamantiumPlantClippers: 187,
67 adamantiumPlantClippers: 187,
68 orichalcumPlantClippers: 188,
68 orichalcumPlantClippers: 188,
69 dragonPlantClippers: 189
69 dragonPlantClippers: 189,
70 bronzeShears: 497,
71 ironShears: 498,
72 steelShears: 499,
73 mithrilShears: 500,
74 adamantiumShears: 501,
75 orichalcumShears: 502,
76 dragonShears: 503
70});
77});
71
78
72const DEFAULT_STACK = 99;
79const DEFAULT_STACK = 99;
@@ -152,6 +159,17 @@ export const PLANT_CLIPPERS_ITEM_BY_METAL = Object.freeze({
152 [MaterialTier.dragon]: MetalItemId.dragonPlantClippers
159 [MaterialTier.dragon]: MetalItemId.dragonPlantClippers
153});
160});
154
161
162/** Shears item id by metal tier. */
163export const SHEARS_ITEM_BY_METAL = Object.freeze({
164 [MaterialTier.bronze]: MetalItemId.bronzeShears,
165 [MaterialTier.iron]: MetalItemId.ironShears,
166 [MaterialTier.steel]: MetalItemId.steelShears,
167 [MaterialTier.mithril]: MetalItemId.mithrilShears,
168 [MaterialTier.adamantium]: MetalItemId.adamantiumShears,
169 [MaterialTier.orichalcum]: MetalItemId.orichalcumShears,
170 [MaterialTier.dragon]: MetalItemId.dragonShears
171});
172
155/** Full defs for metal family (merged into ITEM_DEFINITIONS). */
173/** Full defs for metal family (merged into ITEM_DEFINITIONS). */
156const BAR_ITEM_DEFINITIONS = buildFamilyDefinitionMap(ItemFamilyId.bar, BAR_BY_TIER);
174const BAR_ITEM_DEFINITIONS = buildFamilyDefinitionMap(ItemFamilyId.bar, BAR_BY_TIER);
157
175
@@ -163,6 +181,7 @@ export const METAL_ITEM_DEFINITIONS = Object.freeze({
163 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxe, PICKAXE_ITEM_BY_METAL),
181 ...buildFamilyDefinitionMap(ItemFamilyId.pickaxe, PICKAXE_ITEM_BY_METAL),
164 ...buildFamilyDefinitionMap(ItemFamilyId.axe, AXE_ITEM_BY_METAL),
182 ...buildFamilyDefinitionMap(ItemFamilyId.axe, AXE_ITEM_BY_METAL),
165 ...buildFamilyDefinitionMap(ItemFamilyId.plantClippers, PLANT_CLIPPERS_ITEM_BY_METAL),
183 ...buildFamilyDefinitionMap(ItemFamilyId.plantClippers, PLANT_CLIPPERS_ITEM_BY_METAL),
184 ...buildFamilyDefinitionMap(ItemFamilyId.shears, SHEARS_ITEM_BY_METAL),
166 [MetalItemId.electrumBar]: Object.freeze({
185 [MetalItemId.electrumBar]: Object.freeze({
167 ...BAR_ITEM_DEFINITIONS[MetalItemId.electrumBar],
186 ...BAR_ITEM_DEFINITIONS[MetalItemId.electrumBar],
168 description: "A pale gold-silver alloy. Fit for fine jewellery."
187 description: "A pale gold-silver alloy. Fit for fine jewellery."
shared/definitions/mobs.js +79 −2
@@ -7,12 +7,15 @@ import { ArmourItemId } from "./armourItems.js";
7 7 import { WoodItemId } from "./woodItems.js";
8 8 import { ItemId } from "./items.js";
9 9 import { spellDefinition } from "./spells.js";
10 import { ClothTier } from "./materialTiers.js";
10 11
11 12 export const MobId = Object.freeze({
12 13 deer: "deer",
13 14 pigeon: "pigeon",
14 15 rat: "rat",
15 16 chicken: "chicken",
17 sheep: "sheep",
18 cashmereGoat: "cashmere-goat",
16 19 humanoid: "humanoid",
17 20 /** Humanoid guards that respond to bounty kills within wander range. */
18 21 townGuard: "town-guard",
@@ -149,6 +152,74 @@ export const MOB_DEFINITIONS = Object.freeze({
149 152 framesPerRow: 1,
150 153 animationSpeed: 0
151 154 }),
155 [MobId.sheep]: Object.freeze({
156 mobTypeId: MobId.sheep,
157 key: "sheep",
158 assetFolder: "mobs",
159 displayName: "Sheep",
160 health: 8,
161 maxHealth: 8,
162 attackSkill: 1,
163 attackCooldownMs: 1200,
164 drops: Object.freeze([
165 { itemId: LeatherItemId.softLeather, chance: 0.5 },
166 { itemId: CraftingItemId.rawMeat, chance: 1 }
167 ]),
168 sells: Object.freeze([]),
169 dialogue: Object.freeze([]),
170 persistent: false,
171 flying: false,
172 freeFlight: false,
173 ambient: false,
174 talkable: false,
175 untargetable: false,
176 aggressive: false,
177 gait: "walk",
178 sex: "female",
179 frames: 1,
180 framesPerRow: 1,
181 animationSpeed: 0,
182 defaultState: "fleece",
183 shearable: Object.freeze({
184 clothTier: ClothTier.wool,
185 fleeceState: "fleece",
186 shornState: "shorn"
187 })
188 }),
189 [MobId.cashmereGoat]: Object.freeze({
190 mobTypeId: MobId.cashmereGoat,
191 key: "cashmere-goat",
192 assetFolder: "mobs",
193 displayName: "Cashmere goat",
194 health: 10,
195 maxHealth: 10,
196 attackSkill: 2,
197 attackCooldownMs: 1100,
198 drops: Object.freeze([
199 { itemId: LeatherItemId.softLeather, chance: 0.6 },
200 { itemId: CraftingItemId.rawMeat, chance: 1 }
201 ]),
202 sells: Object.freeze([]),
203 dialogue: Object.freeze([]),
204 persistent: false,
205 flying: false,
206 freeFlight: false,
207 ambient: false,
208 talkable: false,
209 untargetable: false,
210 aggressive: false,
211 gait: "walk",
212 sex: "female",
213 frames: 1,
214 framesPerRow: 1,
215 animationSpeed: 0,
216 defaultState: "fleece",
217 shearable: Object.freeze({
218 clothTier: ClothTier.cashmere,
219 fleeceState: "fleece",
220 shornState: "shorn"
221 })
222 }),
152 223 [MobId.shade]: Object.freeze({
153 224 mobTypeId: MobId.shade,
154 225 key: "shade",
@@ -295,7 +366,7 @@ export function mobDefinition (mobTypeId)
295 366 return MOB_DEFINITIONS[mobTypeId] ?? null;
296 367 }
297 368
298 export function mobSpriteName (mobTypeId)
369 export function mobSpriteName (mobTypeId, visualState = null)
299 370 {
300 371 const def = mobDefinition(mobTypeId);
301 372 const key = def?.spriteKey ?? def?.key ?? def?.mobTypeId ?? "deer";
@@ -306,10 +377,16 @@ export function mobSpriteName (mobTypeId)
306 377 }
307 378 if (def?.sprite)
308 379 { return def.sprite; }
309 const state = def?.defaultState ?? key;
380 const state = visualState ?? def?.defaultState ?? key;
310 381 return spriteImageName("mob", key, state);
311 382 }
312 383
384 /** Whether this mob definition can be sheared for cloth fibre. */
385 export function mobIsShearable (mobTypeId)
386 {
387 return !!mobDefinition(mobTypeId)?.shearable;
388 }
389
313 390 export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
314 391 {
315 392 const humanoid = isHumanoidMob(mobTypeId) || mobTypeId === MobId.humanoid;
@@ -7,12 +7,15 @@ import { ArmourItemId } from "./armourItems.js";
7import { WoodItemId } from "./woodItems.js";
7import { WoodItemId } from "./woodItems.js";
8import { ItemId } from "./items.js";
8import { ItemId } from "./items.js";
9import { spellDefinition } from "./spells.js";
9import { spellDefinition } from "./spells.js";
10import { ClothTier } from "./materialTiers.js";
10
11
11export const MobId = Object.freeze({
12export const MobId = Object.freeze({
12 deer: "deer",
13 deer: "deer",
13 pigeon: "pigeon",
14 pigeon: "pigeon",
14 rat: "rat",
15 rat: "rat",
15 chicken: "chicken",
16 chicken: "chicken",
17 sheep: "sheep",
18 cashmereGoat: "cashmere-goat",
16 humanoid: "humanoid",
19 humanoid: "humanoid",
17 /** Humanoid guards that respond to bounty kills within wander range. */
20 /** Humanoid guards that respond to bounty kills within wander range. */
18 townGuard: "town-guard",
21 townGuard: "town-guard",
@@ -149,6 +152,74 @@ export const MOB_DEFINITIONS = Object.freeze({
149 framesPerRow: 1,
152 framesPerRow: 1,
150 animationSpeed: 0
153 animationSpeed: 0
151 }),
154 }),
155 [MobId.sheep]: Object.freeze({
156 mobTypeId: MobId.sheep,
157 key: "sheep",
158 assetFolder: "mobs",
159 displayName: "Sheep",
160 health: 8,
161 maxHealth: 8,
162 attackSkill: 1,
163 attackCooldownMs: 1200,
164 drops: Object.freeze([
165 { itemId: LeatherItemId.softLeather, chance: 0.5 },
166 { itemId: CraftingItemId.rawMeat, chance: 1 }
167 ]),
168 sells: Object.freeze([]),
169 dialogue: Object.freeze([]),
170 persistent: false,
171 flying: false,
172 freeFlight: false,
173 ambient: false,
174 talkable: false,
175 untargetable: false,
176 aggressive: false,
177 gait: "walk",
178 sex: "female",
179 frames: 1,
180 framesPerRow: 1,
181 animationSpeed: 0,
182 defaultState: "fleece",
183 shearable: Object.freeze({
184 clothTier: ClothTier.wool,
185 fleeceState: "fleece",
186 shornState: "shorn"
187 })
188 }),
189 [MobId.cashmereGoat]: Object.freeze({
190 mobTypeId: MobId.cashmereGoat,
191 key: "cashmere-goat",
192 assetFolder: "mobs",
193 displayName: "Cashmere goat",
194 health: 10,
195 maxHealth: 10,
196 attackSkill: 2,
197 attackCooldownMs: 1100,
198 drops: Object.freeze([
199 { itemId: LeatherItemId.softLeather, chance: 0.6 },
200 { itemId: CraftingItemId.rawMeat, chance: 1 }
201 ]),
202 sells: Object.freeze([]),
203 dialogue: Object.freeze([]),
204 persistent: false,
205 flying: false,
206 freeFlight: false,
207 ambient: false,
208 talkable: false,
209 untargetable: false,
210 aggressive: false,
211 gait: "walk",
212 sex: "female",
213 frames: 1,
214 framesPerRow: 1,
215 animationSpeed: 0,
216 defaultState: "fleece",
217 shearable: Object.freeze({
218 clothTier: ClothTier.cashmere,
219 fleeceState: "fleece",
220 shornState: "shorn"
221 })
222 }),
152 [MobId.shade]: Object.freeze({
223 [MobId.shade]: Object.freeze({
153 mobTypeId: MobId.shade,
224 mobTypeId: MobId.shade,
154 key: "shade",
225 key: "shade",
@@ -295,7 +366,7 @@ export function mobDefinition (mobTypeId)
295 return MOB_DEFINITIONS[mobTypeId] ?? null;
366 return MOB_DEFINITIONS[mobTypeId] ?? null;
296}
367}
297
368
298export function mobSpriteName (mobTypeId)
369export function mobSpriteName (mobTypeId, visualState = null)
299{
370{
300 const def = mobDefinition(mobTypeId);
371 const def = mobDefinition(mobTypeId);
301 const key = def?.spriteKey ?? def?.key ?? def?.mobTypeId ?? "deer";
372 const key = def?.spriteKey ?? def?.key ?? def?.mobTypeId ?? "deer";
@@ -306,10 +377,16 @@ export function mobSpriteName (mobTypeId)
306 }
377 }
307 if (def?.sprite)
378 if (def?.sprite)
308 { return def.sprite; }
379 { return def.sprite; }
309 const state = def?.defaultState ?? key;
380 const state = visualState ?? def?.defaultState ?? key;
310 return spriteImageName("mob", key, state);
381 return spriteImageName("mob", key, state);
311}
382}
312
383
384/** Whether this mob definition can be sheared for cloth fibre. */
385export function mobIsShearable (mobTypeId)
386{
387 return !!mobDefinition(mobTypeId)?.shearable;
388}
389
313export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
390export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
314{
391{
315 const humanoid = isHumanoidMob(mobTypeId) || mobTypeId === MobId.humanoid;
392 const humanoid = isHumanoidMob(mobTypeId) || mobTypeId === MobId.humanoid;
shared/definitions/tierFamilies.js +22 −4
@@ -37,6 +37,7 @@ export const ItemFamilyId = Object.freeze({
37 37 swordBlade: "swordBlade",
38 38 sword: "sword",
39 39 plantClippers: "plantClippers",
40 shears: "shears",
40 41 arrowShaft: "arrowShaft",
41 42 arrowTip: "arrowTip",
42 43 arrow: "arrow",
@@ -229,16 +230,33 @@ export const ITEM_FAMILIES = Object.freeze({
229 230 familyId: ItemFamilyId.plantClippers,
230 231 axis: TierAxis.metal,
231 232 label: "plant clippers",
232 description: () => "Fine shears for cutting herbs and blooms.",
233 description: () => "Sharp clippers for cutting herbs, flax, and blooms.",
233 234 category: ItemCategory.tool,
234 iconKey: "bronze-plant-clippers",
235 defaultState: "bronze-plant-clippers",
235 iconKey: "plant-clippers",
236 defaultState: "plant-clippers",
237 stackable: false,
238 maxStackSize: 1,
239 seedValue: 10,
240 /** Red = metal blades, blue = leather grips. */
241 dualTintFromTier: true,
242 leatherTierFromMetal: true,
243 npcShopAllowed: true,
244 equipmentKind: EquipmentKind.plantClippers
245 }),
246 [ItemFamilyId.shears]: Object.freeze({
247 familyId: ItemFamilyId.shears,
248 axis: TierAxis.metal,
249 label: "shears",
250 description: () => "All-metal shears for clipping fleece from animals.",
251 category: ItemCategory.tool,
252 iconKey: "shears",
253 defaultState: "shears",
236 254 stackable: false,
237 255 maxStackSize: 1,
238 256 seedValue: 10,
239 257 tintFromTier: true,
240 258 npcShopAllowed: true,
241 equipmentKind: EquipmentKind.plantClippers,
259 equipmentKind: EquipmentKind.shears,
242 260 equipmentTintFromTier: true
243 261 }),
244 262 [ItemFamilyId.arrow]: Object.freeze({
@@ -37,6 +37,7 @@ export const ItemFamilyId = Object.freeze({
37 swordBlade: "swordBlade",
37 swordBlade: "swordBlade",
38 sword: "sword",
38 sword: "sword",
39 plantClippers: "plantClippers",
39 plantClippers: "plantClippers",
40 shears: "shears",
40 arrowShaft: "arrowShaft",
41 arrowShaft: "arrowShaft",
41 arrowTip: "arrowTip",
42 arrowTip: "arrowTip",
42 arrow: "arrow",
43 arrow: "arrow",
@@ -229,16 +230,33 @@ export const ITEM_FAMILIES = Object.freeze({
229 familyId: ItemFamilyId.plantClippers,
230 familyId: ItemFamilyId.plantClippers,
230 axis: TierAxis.metal,
231 axis: TierAxis.metal,
231 label: "plant clippers",
232 label: "plant clippers",
232 description: () => "Fine shears for cutting herbs and blooms.",
233 description: () => "Sharp clippers for cutting herbs, flax, and blooms.",
233 category: ItemCategory.tool,
234 category: ItemCategory.tool,
234 iconKey: "bronze-plant-clippers",
235 iconKey: "plant-clippers",
235 defaultState: "bronze-plant-clippers",
236 defaultState: "plant-clippers",
237 stackable: false,
238 maxStackSize: 1,
239 seedValue: 10,
240 /** Red = metal blades, blue = leather grips. */
241 dualTintFromTier: true,
242 leatherTierFromMetal: true,
243 npcShopAllowed: true,
244 equipmentKind: EquipmentKind.plantClippers
245 }),
246 [ItemFamilyId.shears]: Object.freeze({
247 familyId: ItemFamilyId.shears,
248 axis: TierAxis.metal,
249 label: "shears",
250 description: () => "All-metal shears for clipping fleece from animals.",
251 category: ItemCategory.tool,
252 iconKey: "shears",
253 defaultState: "shears",
236 stackable: false,
254 stackable: false,
237 maxStackSize: 1,
255 maxStackSize: 1,
238 seedValue: 10,
256 seedValue: 10,
239 tintFromTier: true,
257 tintFromTier: true,
240 npcShopAllowed: true,
258 npcShopAllowed: true,
241 equipmentKind: EquipmentKind.plantClippers,
259 equipmentKind: EquipmentKind.shears,
242 equipmentTintFromTier: true
260 equipmentTintFromTier: true
243 }),
261 }),
244 [ItemFamilyId.arrow]: Object.freeze({
262 [ItemFamilyId.arrow]: Object.freeze({
shared/definitions/tiles.js +24 −1
@@ -72,7 +72,8 @@ export const BlockType = Object.freeze({
72 72 campfire: 31,
73 73 oven: 32,
74 74 fishingSpot: 33,
75 jeweleringStation: 34
75 jeweleringStation: 34,
76 flaxPlant: 35
76 77 });
77 78
78 79 export const GROUND_DEFINITIONS = Object.freeze({
@@ -427,6 +428,26 @@ export const BLOCK_DEFINITIONS = Object.freeze({
427 428 gatherable: true,
428 429 plantGather: Object.freeze({ kind: "cotton", requiresClippers: false, skillId: "herbalism" })
429 430 }),
431 [BlockType.flaxPlant]: Object.freeze({
432 id: BlockType.flaxPlant,
433 key: "flax-plant",
434 displayName: "Flax plant",
435 passable: true,
436 blocksLight: false,
437 lightRangeTiles: 0,
438 frames: 1,
439 framesPerRow: 1,
440 animationSpeed: 0,
441 outdoor: true,
442 gatherable: true,
443 plantGather: Object.freeze({
444 kind: "flax",
445 requiresClippers: true,
446 /** Linen-rank clippers or better (steel↔linen). */
447 minClothTier: "linen",
448 skillId: "herbalism"
449 })
450 }),
430 451 [BlockType.spinningWheel]: Object.freeze({
431 452 id: BlockType.spinningWheel,
432 453 key: "spinning-wheel",
@@ -590,6 +611,8 @@ export function resourceNodeDisplayName (block)
590 611 }
591 612 if (block.typeId === BlockType.cottonPlant)
592 613 { return "Cotton plant"; }
614 if (block.typeId === BlockType.flaxPlant)
615 { return "Flax plant"; }
593 616 if (block.typeId === BlockType.herbPlant)
594 617 {
595 618 const herb = herbDefinition(block.state);
@@ -72,7 +72,8 @@ export const BlockType = Object.freeze({
72 campfire: 31,
72 campfire: 31,
73 oven: 32,
73 oven: 32,
74 fishingSpot: 33,
74 fishingSpot: 33,
75 jeweleringStation: 34
75 jeweleringStation: 34,
76 flaxPlant: 35
76});
77});
77
78
78export const GROUND_DEFINITIONS = Object.freeze({
79export const GROUND_DEFINITIONS = Object.freeze({
@@ -427,6 +428,26 @@ export const BLOCK_DEFINITIONS = Object.freeze({
427 gatherable: true,
428 gatherable: true,
428 plantGather: Object.freeze({ kind: "cotton", requiresClippers: false, skillId: "herbalism" })
429 plantGather: Object.freeze({ kind: "cotton", requiresClippers: false, skillId: "herbalism" })
429 }),
430 }),
431 [BlockType.flaxPlant]: Object.freeze({
432 id: BlockType.flaxPlant,
433 key: "flax-plant",
434 displayName: "Flax plant",
435 passable: true,
436 blocksLight: false,
437 lightRangeTiles: 0,
438 frames: 1,
439 framesPerRow: 1,
440 animationSpeed: 0,
441 outdoor: true,
442 gatherable: true,
443 plantGather: Object.freeze({
444 kind: "flax",
445 requiresClippers: true,
446 /** Linen-rank clippers or better (steel↔linen). */
447 minClothTier: "linen",
448 skillId: "herbalism"
449 })
450 }),
430 [BlockType.spinningWheel]: Object.freeze({
451 [BlockType.spinningWheel]: Object.freeze({
431 id: BlockType.spinningWheel,
452 id: BlockType.spinningWheel,
432 key: "spinning-wheel",
453 key: "spinning-wheel",
@@ -590,6 +611,8 @@ export function resourceNodeDisplayName (block)
590 }
611 }
591 if (block.typeId === BlockType.cottonPlant)
612 if (block.typeId === BlockType.cottonPlant)
592 { return "Cotton plant"; }
613 { return "Cotton plant"; }
614 if (block.typeId === BlockType.flaxPlant)
615 { return "Flax plant"; }
593 if (block.typeId === BlockType.herbPlant)
616 if (block.typeId === BlockType.herbPlant)
594 {
617 {
595 const herb = herbDefinition(block.state);
618 const herb = herbDefinition(block.state);
shared/equipment/stats.js +1 −0
@@ -37,6 +37,7 @@ export function equipMinSkillId (equipmentDef)
37 37 case EquipmentKind.fishingNet:
38 38 return SkillId.fishing;
39 39 case EquipmentKind.plantClippers:
40 case EquipmentKind.shears:
40 41 return SkillId.herbalism;
41 42 default:
42 43 return null;
@@ -37,6 +37,7 @@ export function equipMinSkillId (equipmentDef)
37 case EquipmentKind.fishingNet:
37 case EquipmentKind.fishingNet:
38 return SkillId.fishing;
38 return SkillId.fishing;
39 case EquipmentKind.plantClippers:
39 case EquipmentKind.plantClippers:
40 case EquipmentKind.shears:
40 return SkillId.herbalism;
41 return SkillId.herbalism;
41 default:
42 default:
42 return null;
43 return null;
shared/items/origin.js +2 −1
@@ -25,7 +25,8 @@ export const GatherOriginVerb = Object.freeze({
25 25 mined: "Mined",
26 26 felled: "Felled",
27 27 caught: "Caught",
28 picked: "Picked"
28 picked: "Picked",
29 sheared: "Sheared"
29 30 });
30 31
31 32 /**
@@ -25,7 +25,8 @@ export const GatherOriginVerb = Object.freeze({
25 mined: "Mined",
25 mined: "Mined",
26 felled: "Felled",
26 felled: "Felled",
27 caught: "Caught",
27 caught: "Caught",
28 picked: "Picked"
28 picked: "Picked",
29 sheared: "Sheared"
29});
30});
30
31
31/**
32/**
shared/protocol/constants.js +1 −0
@@ -187,6 +187,7 @@ export const MessageType = Object.freeze({
187 187 startCraft: "START_CRAFT",
188 188 startFire: "START_FIRE",
189 189 startFish: "START_FISH",
190 shear: "SHEAR",
190 191 cancelCraft: "CANCEL_CRAFT",
191 192 craftResult: "CRAFT_RESULT",
192 193 openCauldron: "OPEN_CAULDRON",
@@ -187,6 +187,7 @@ export const MessageType = Object.freeze({
187 startCraft: "START_CRAFT",
187 startCraft: "START_CRAFT",
188 startFire: "START_FIRE",
188 startFire: "START_FIRE",
189 startFish: "START_FISH",
189 startFish: "START_FISH",
190 shear: "SHEAR",
190 cancelCraft: "CANCEL_CRAFT",
191 cancelCraft: "CANCEL_CRAFT",
191 craftResult: "CRAFT_RESULT",
192 craftResult: "CRAFT_RESULT",
192 openCauldron: "OPEN_CAULDRON",
193 openCauldron: "OPEN_CAULDRON",