BlueGit

timfa questward

Files

questward / server / src / fishing / service.js

service.js

service.js 16.3 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import {
3 BlockType,
4 GroundType,
5 isLiquidWaterGround,
6 normalizeGround
7} from "../../../shared/definitions/tiles.js";
8import {
9 FISH_SPECIES,
10 fishTierRankFromItemId,
11 fishingDifficulty,
12 fishingExhaustDurationMs,
13 baitItemIdForCloth,
14 BaitItemId,
15 normalizeFishingSpotConfig,
16 fishingPoleItemIdForWood,
17 woodTierFromFishingRodItemId
18} from "../../../shared/definitions/fishItems.js";
19import { resolveFishingTool } from "../../../shared/definitions/gathering.js";
20import { EquipmentKind } from "../../../shared/definitions/equipmentKinds.js";
21import {
22 ClothTier,
23 tierRank,
24 clothTierForWood
25} from "../../../shared/definitions/materialTiers.js";
26import { yarnItemId } from "../../../shared/definitions/clothItems.js";
27import { itemDefinition } from "../../../shared/definitions/items.js";
28import { SkillId, skillLevel } from "../../../shared/definitions/skills.js";
29import { applySkillXp, publicSkillsPayload, storedSkillXp } from "../../../shared/skills/state.js";
30import
31{
32 gatherDurationMultiplier,
33 harvestYieldMultiplier
34} from "../../../shared/equipment/jewelryEffects.js";
35import { rollSkill } from "../../../shared/combat/rolls.js";
36import {
37 insertStack,
38 stackQuantity,
39 takeMatchingFromSlots,
40 takeFromSlot
41} from "../../../shared/items/inventory.js";
42import { attachOrigins, gatherOrigin, GatherOriginVerb } from "../../../shared/items/origin.js";
43import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
44import { isAdjacentTile } from "../../../shared/navigation/adjacency.js";
45import { tileToChunk, tileToLocal } from "../world/coordinates.js";
46import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
47import { tileShoveEvent } from "../simulation/tileInteract.js";
48import { seasonIdAt } from "../../../shared/world/season.js";
49
50const FISH_ATTEMPT_MS = 3000;
51const FISH_SHOVE_MS = 1000;
52const MAX_FISH_ATTEMPTS = 3;
53/** Chance the fishing line snaps after a fully failed rod session. */
54const LINE_BREAK_CHANCE = 0.05;
55
56function userError (message)
57{
58 const error = new Error(message);
59 error.userFacing = true;
60 return error;
61}
62
63function tileKey (tileX, tileY)
64{
65 return `${tileX},${tileY}`;
66}
67
68function characterDisplayName (world, handle)
69{
70 const appearance = world.ecs.get(handle, Component.appearance);
71 const name = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
72 return name || "someone";
73}
74
75function ensureFishSessions (world)
76{
77 if (!world.fishSessions)
78 { world.fishSessions = new Map(); }
79 return world.fishSessions;
80}
81
82function ensureFishSpotRespawns (world)
83{
84 if (!world.fishingSpotRespawns)
85 { world.fishingSpotRespawns = new Map(); }
86 return world.fishingSpotRespawns;
87}
88
89function clearFishSession (world, characterId)
90{
91 ensureFishSessions(world).delete(characterId);
92}
93
94function blockAt (world, tileX, tileY)
95{
96 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
97 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
98 return data.blocks[index] ?? null;
99}
100
101function groundAt (world, tileX, tileY)
102{
103 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
104 const index = tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX);
105 return normalizeGround(data.grounds[index]).typeId;
106}
107
108function setBlockState (world, tileX, tileY, state)
109{
110 const chunkX = tileToChunk(tileX);
111 const chunkY = tileToChunk(tileY);
112 const localX = tileToLocal(tileX);
113 const localY = tileToLocal(tileY);
114 const data = world.chunkData(chunkX, chunkY);
115 const index = localY * CHUNK_SIZE + localX;
116 const existing = data.blocks[index];
117 if (!existing)
118 { return null; }
119 const block = { ...existing, state };
120 data.blocks[index] = block;
121 return {
122 type: "chunk-delta",
123 chunkX,
124 chunkY,
125 tileX,
126 tileY,
127 localX,
128 localY,
129 block
130 };
131}
132
133function spotFishItemIds (block)
134{
135 return normalizeFishingSpotConfig(block?.config).fishes;
136}
137
138function maxFishTierInList (fishItemIds)
139{
140 let max = 0;
141 for (const itemId of fishItemIds)
142 { max = Math.max(max, fishTierRankFromItemId(itemId)); }
143 return max;
144}
145
146function eligibleFishItemIds (fishItemIds, baitTierRank)
147{
148 return fishItemIds.filter((itemId) => fishTierRankFromItemId(itemId) <= baitTierRank);
149}
150
151function findBestBaitSlot (slots, maxRank)
152{
153 let best = null;
154 for (let i = 0; i < (slots?.length ?? 0); i++)
155 {
156 const slot = slots[i];
157 if (!slot || stackQuantity(slot.quantity) <= 0)
158 { continue; }
159 const def = itemDefinition(slot.itemId);
160 if (!def?.bait || !def.tier)
161 { continue; }
162 const rank = tierRank(def.tier);
163 if (rank < 1 || rank > maxRank)
164 { continue; }
165 if (!best || rank > best.rank)
166 { best = { slotIndex: i, itemId: slot.itemId, rank, tier: def.tier }; }
167 }
168 return best;
169}
170
171function toolTierRank (tool)
172{
173 const tier = tool?.def?.equipment?.tier ?? tool?.tier;
174 return tierRank(tier);
175}
176
177/**
178 * Start fishing at a fishing-spot block tile.
179 */
180export function startFish (world, sessionId, characterId, tileX, tileY, now = Date.now())
181{
182 const entityId = world.characterEntities.get(characterId);
183 if (entityId == null)
184 { throw userError("Character is not in the world."); }
185 const handle = world.ecs.handleOf(entityId);
186 const identity = world.ecs.get(handle, Component.networkIdentity);
187 if (!identity || identity.sessionId !== sessionId)
188 { throw userError("Character is not in the world."); }
189 if (world.ecs.has(handle, Component.dead))
190 { throw userError("You are dead."); }
191
192 const position = world.ecs.get(handle, Component.position);
193 if (!isAdjacentTile(position.tileX, position.tileY, tileX, tileY))
194 { throw userError("You need to stand next to the fishing spot."); }
195
196 const block = blockAt(world, tileX, tileY);
197 if (!block || block.typeId !== BlockType.fishingSpot)
198 { throw userError("There is no fishing spot there."); }
199 if (block.state === "exhausted" || ensureFishSpotRespawns(world).has(tileKey(tileX, tileY)))
200 { throw userError("The fish have scattered. Wait for them to return."); }
201
202 const ground = groundAt(world, tileX, tileY);
203 const season = seasonIdAt(now);
204 if (ground !== GroundType.water && ground !== GroundType.deepWater)
205 { throw userError("Fishing spots must be on water."); }
206 if (!isLiquidWaterGround(ground, season))
207 { throw userError("The water is frozen solid."); }
208
209 const fishList = spotFishItemIds(block);
210 if (!fishList.length)
211 { throw userError("No fish swim here."); }
212
213 const inventory = world.ecs.get(handle, Component.inventory);
214 const equipment = world.ecs.get(handle, Component.equipment);
215 const skills = world.ecs.get(handle, Component.skills);
216 const resolved = resolveFishingTool({
217 inventorySlots: inventory?.slots,
218 equipmentSlots: equipment?.slots,
219 skills
220 });
221 if (!resolved.ok)
222 { throw userError(resolved.reason); }
223
224 const isNet = resolved.kind === EquipmentKind.fishingNet;
225 const rodRank = isNet ? 1 : toolTierRank(resolved.tool);
226 const maxInSpot = maxFishTierInList(fishList);
227 const usefulMax = Math.min(rodRank, maxInSpot);
228
229 let baitRank = 1;
230 let baitItemId = null;
231 let baitConsumedRank = 0;
232
233 if (isNet)
234 {
235 baitRank = 1;
236 baitConsumedRank = 0;
237 }
238 else
239 {
240 const bait = findBestBaitSlot(inventory?.slots, usefulMax);
241 if (!bait)
242 { throw userError("You need suitable bait for this spot."); }
243 baitRank = bait.rank;
244 baitItemId = bait.itemId;
245 baitConsumedRank = bait.rank;
246 }
247
248 const eligible = eligibleFishItemIds(fishList, baitRank);
249 if (!eligible.length)
250 { throw userError("No fish here match your bait."); }
251
252 if (!isNet)
253 {
254 const taken = takeMatchingFromSlots(inventory.slots, {
255 itemId: baitItemId,
256 quantity: 1,
257 compact: false
258 });
259 if (!taken.ok)
260 { throw userError("You need suitable bait for this spot."); }
261 inventory.slots = taken.slots;
262 }
263
264 clearFishSession(world, characterId);
265 if (world.ecs.has(handle, Component.gather))
266 { world.ecs.remove(handle, Component.gather); }
267 const path = world.ecs.get(handle, Component.path);
268 if (path)
269 { path.tiles = []; }
270
271 ensureFishSessions(world).set(characterId, {
272 sessionId,
273 tileX,
274 tileY,
275 toolItemId: resolved.tool.def.itemId,
276 isNet,
277 baitRank,
278 baitConsumedRank,
279 baitItemId,
280 eligible,
281 difficulty: fishingDifficulty(baitRank),
282 attemptsLeft: MAX_FISH_ATTEMPTS,
283 attemptStartedAt: now,
284 nextShoveAt: now,
285 attemptEndsAt: now + Math.max(
286 1,
287 Math.floor(FISH_ATTEMPT_MS * gatherDurationMultiplier(equipment))
288 )
289 });
290
291 return {
292 events: [],
293 private: isNet ? null : bagView(world.ecs, handle)
294 };
295}
296
297export function handleFishingCommand (world, sessionId, command, now = Date.now())
298{
299 if (command.type === "start-fish")
300 {
301 return startFish(
302 world,
303 sessionId,
304 command.characterId,
305 command.tileX | 0,
306 command.tileY | 0,
307 now
308 );
309 }
310 if (command.type === "cancel-fish")
311 {
312 clearFishSession(world, command.characterId);
313 return { events: [] };
314 }
315 return null;
316}
317
318function completeCatch (world, handle, entityId, characterId, session, events, privates, now)
319{
320 const eligible = session.eligible ?? [];
321 if (!eligible.length)
322 {
323 events.push({
324 type: "command-error",
325 sessionId: session.sessionId,
326 message: "The fish got away."
327 });
328 clearFishSession(world, characterId);
329 return;
330 }
331 const rng = world.rng ?? Math.random;
332 const pick = eligible[Math.floor(rng() * eligible.length) % eligible.length];
333 const fishRank = fishTierRankFromItemId(pick);
334 const inventory = world.ecs.get(handle, Component.inventory);
335 const def = itemDefinition(pick);
336 const origin = gatherOrigin(GatherOriginVerb.caught, characterDisplayName(world, handle));
337 const quantity = Math.max(1, Math.floor(1 * harvestYieldMultiplier(world.ecs.get(handle, Component.equipment))));
338 const stack = attachOrigins({
339 itemId: pick,
340 quantity,
341 origins: [{ origin, quantity }]
342 });
343 const inserted = insertStack(inventory.slots, stack, def);
344 if (!inserted.ok || inserted.remainder > 0)
345 {
346 events.push({
347 type: "command-error",
348 sessionId: session.sessionId,
349 message: "Your inventory is full."
350 });
351 clearFishSession(world, characterId);
352 return;
353 }
354 inventory.slots = inserted.slots;
355
356 const xpAmount = (session.baitConsumedRank | 0) + fishRank;
357 const skills = world.ecs.get(handle, Component.skills);
358 let skillsChanged = false;
359 const levelUps = [];
360 if (skills?.xp && xpAmount > 0)
361 {
362 const result = applySkillXp(
363 skills,
364 SkillId.fishing,
365 xpAmount,
366 world.ecs.get(handle, Component.equipment)
367 );
368 if (result.changed)
369 { skillsChanged = true; }
370 if (result.levelUp)
371 { levelUps.push(result.levelUp); }
372 }
373 if (skillsChanged)
374 {
375 events.push({
376 type: "skills-updated",
377 entityId,
378 characterId,
379 ...publicSkillsPayload(skills),
380 stored: storedSkillXp(skills),
381 levelUps
382 });
383 }
384
385 const exhausted = setBlockState(world, session.tileX, session.tileY, "exhausted");
386 if (exhausted)
387 { events.push(exhausted); }
388 ensureFishSpotRespawns(world).set(tileKey(session.tileX, session.tileY), {
389 tileX: session.tileX,
390 tileY: session.tileY,
391 respawnsAt: now + fishingExhaustDurationMs(fishRank)
392 });
393
394 privates.push({ characterId, bag: bagView(world.ecs, handle) });
395 events.push({
396 type: "item-bubble",
397 entityId,
398 itemId: pick,
399 quantity: 1
400 });
401 clearFishSession(world, characterId);
402}
403
404export function stepFishing (world, now)
405{
406 const events = [];
407 const privates = [];
408 events.push(...stepFishingSpotRespawns(world, now).events);
409
410 const sessions = ensureFishSessions(world);
411 for (const [characterId, session] of [...sessions.entries()])
412 {
413 const entityId = world.characterEntities.get(characterId);
414 if (entityId == null)
415 {
416 clearFishSession(world, characterId);
417 continue;
418 }
419 const handle = world.ecs.handleOf(entityId);
420 if (world.ecs.has(handle, Component.dead))
421 {
422 clearFishSession(world, characterId);
423 continue;
424 }
425 const position = world.ecs.get(handle, Component.position);
426 if (!isAdjacentTile(position.tileX, position.tileY, session.tileX, session.tileY))
427 {
428 clearFishSession(world, characterId);
429 continue;
430 }
431
432 if (now >= session.nextShoveAt && now < session.attemptEndsAt)
433 {
434 session.nextShoveAt = now + FISH_SHOVE_MS;
435 events.push(tileShoveEvent(
436 entityId,
437 position.tileX,
438 position.tileY,
439 session.tileX,
440 session.tileY
441 ));
442 // Also emit gather-swing so tool overlay shows.
443 events.push({
444 type: "gather-swing",
445 attackerId: entityId,
446 tileX: session.tileX,
447 tileY: session.tileY,
448 fromTileX: position.tileX,
449 fromTileY: position.tileY,
450 toolItemId: session.toolItemId,
451 swipe: false
452 });
453 }
454
455 if (now < session.attemptEndsAt)
456 { continue; }
457
458 const skills = world.ecs.get(handle, Component.skills);
459 const level = skillLevel(skills, SkillId.fishing);
460 const roll = rollSkill(level, world.rng ?? Math.random);
461 session.attemptsLeft -= 1;
462
463 if (roll >= session.difficulty)
464 {
465 completeCatch(world, handle, entityId, characterId, session, events, privates, now);
466 continue;
467 }
468
469 if (session.attemptsLeft <= 0)
470 {
471 events.push({
472 type: "command-error",
473 sessionId: session.sessionId,
474 message: "The fish got away."
475 });
476 maybeBreakFishingLine(world, handle, entityId, characterId, session, events, privates, now);
477 clearFishSession(world, characterId);
478 continue;
479 }
480
481 session.attemptStartedAt = now;
482 session.nextShoveAt = now;
483 session.attemptEndsAt = now + Math.max(
484 1,
485 Math.floor(FISH_ATTEMPT_MS * gatherDurationMultiplier(world.ecs.get(handle, Component.equipment)))
486 );
487 }
488
489 return { events, privates };
490}
491
492function spawnGroundStack (world, tileX, tileY, itemId, now, events, source = "fishing-line-break")
493{
494 const stack = attachOrigins({
495 itemId,
496 quantity: 1,
497 origins: []
498 });
499 const placed = placeOrMergeGroundStack(world, {
500 tileX,
501 tileY,
502 stack,
503 now,
504 source
505 });
506 events.push(...placed.events);
507}
508
509/**
510 * After a fully failed rod session: 5% chance the line snaps → rod becomes pole + 1 yarn.
511 */
512function maybeBreakFishingLine (world, handle, entityId, characterId, session, events, privates, now)
513{
514 if (session.isNet)
515 { return; }
516 const rng = world.rng ?? Math.random;
517 if (rng() >= LINE_BREAK_CHANCE)
518 { return; }
519
520 const rodItemId = session.toolItemId | 0;
521 const rodDef = itemDefinition(rodItemId);
522 const woodTier = woodTierFromFishingRodItemId(rodItemId) ?? rodDef?.tier;
523 const poleItemId = rodDef?.poleItemId ?? fishingPoleItemIdForWood(woodTier);
524 const clothTier = rodDef?.clothTier ?? clothTierForWood(woodTier);
525 const yarnId = yarnItemId(clothTier);
526 if (!poleItemId || !yarnId)
527 { return; }
528
529 const inventory = world.ecs.get(handle, Component.inventory);
530 const equipment = world.ecs.get(handle, Component.equipment);
531 let removed = false;
532 let appearanceChanged = false;
533
534 if (inventory?.slots)
535 {
536 const idx = inventory.slots.findIndex((s) => s?.itemId === rodItemId);
537 if (idx >= 0)
538 {
539 const taken = takeFromSlot(inventory.slots, idx, 1);
540 if (taken.ok)
541 {
542 inventory.slots = taken.slots;
543 removed = true;
544 }
545 }
546 }
547 if (!removed && equipment?.slots?.weapon?.itemId === rodItemId)
548 {
549 equipment.slots.weapon = null;
550 removed = true;
551 appearanceChanged = true;
552 }
553 if (!removed)
554 { return; }
555
556 const position = world.ecs.get(handle, Component.position);
557 const poleDef = itemDefinition(poleItemId);
558 const yarnDef = itemDefinition(yarnId);
559 let slots = inventory.slots;
560
561 const poleIns = insertStack(slots, attachOrigins({ itemId: poleItemId, quantity: 1, origins: [] }), poleDef);
562 if (poleIns.ok && poleIns.remainder === 0)
563 { slots = poleIns.slots; }
564 else
565 { spawnGroundStack(world, position.tileX, position.tileY, poleItemId, now, events); }
566
567 const yarnIns = insertStack(slots, attachOrigins({ itemId: yarnId, quantity: 1, origins: [] }), yarnDef);
568 if (yarnIns.ok && yarnIns.remainder === 0)
569 { slots = yarnIns.slots; }
570 else
571 { spawnGroundStack(world, position.tileX, position.tileY, yarnId, now, events); }
572
573 inventory.slots = slots;
574
575 events.push({
576 type: "command-error",
577 sessionId: session.sessionId,
578 message: "Your fishing line broke!"
579 });
580 privates.push({
581 characterId,
582 bag: bagView(world.ecs, handle),
583 ...(appearanceChanged ? { appearanceChanged: true } : {})
584 });
585}
586
587export function stepFishingSpotRespawns (world, now)
588{
589 const respawns = world.fishingSpotRespawns;
590 if (!respawns?.size)
591 { return { events: [] }; }
592 const events = [];
593 for (const [key, entry] of [...respawns.entries()])
594 {
595 if (now < entry.respawnsAt)
596 { continue; }
597 respawns.delete(key);
598 const block = blockAt(world, entry.tileX, entry.tileY);
599 if (!block || block.typeId !== BlockType.fishingSpot)
600 { continue; }
601 const delta = setBlockState(world, entry.tileX, entry.tileY, "fishing-spot");
602 if (delta)
603 { events.push(delta); }
604 }
605 return { events };
606}
607
608export { ClothTier, BaitItemId, baitItemIdForCloth, FISH_SPECIES };