BlueGit

timfa questward

Files

questward / server / src / courier / service.js

service.js

service.js 12.3 KiB Download Raw
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7import { GAIT } from "../../../shared/protocol/constants.js";
8import { decodeChunkBlob } from "../world/chunkData.js";
9
10export class CourierService
11{
12 constructor ({ stateDb, worldDb, simulation })
13 {
14 this.stateDb = stateDb;
15 this.worldDb = worldDb;
16 this.simulation = simulation;
17 this.bankTiles = [];
18 this.refreshBankIndex();
19 }
20
21 refreshBankIndex ()
22 {
23 const revisionId = this.worldDb.getActiveRevisionId();
24 const banks = [];
25 for (const coord of this.worldDb.listChunkCoords(revisionId))
26 {
27 const row = this.worldDb.getChunkVersion(coord.chunk_x, coord.chunk_y, revisionId);
28 if (!row)
29 { continue; }
30 const data = decodeChunkBlob(row.data_blob, this.simulation.settings.defaultGroundTypeId);
31 for (let localY = 0; localY < CHUNK_SIZE; localY++)
32 {
33 for (let localX = 0; localX < CHUNK_SIZE; localX++)
34 {
35 const block = data.blocks[localY * CHUNK_SIZE + localX];
36 if (block?.typeId !== BlockType.bank)
37 { continue; }
38 banks.push({
39 tileX: coord.chunk_x * CHUNK_SIZE + localX,
40 tileY: coord.chunk_y * CHUNK_SIZE + localY
41 });
42 }
43 }
44 }
45 this.bankTiles = banks;
46 }
47
48 nearestBank (tileX, tileY)
49 {
50 if (!this.bankTiles.length)
51 { return null; }
52 let best = null;
53 let bestDist = Infinity;
54 for (const bank of this.bankTiles)
55 {
56 const dist = Math.hypot(bank.tileX - tileX, bank.tileY - tileY);
57 if (dist < bestDist)
58 {
59 bestDist = dist;
60 best = bank;
61 }
62 }
63 return best;
64 }
65
66 /**
67 * Player dispatch: cargo is money or one inventory stack.
68 * destination: { kind: "bank" } | { kind: "player", firstName, lastName }
69 */
70 dispatchFromPlayer ({ characterId, originTileX, originTileY, destination, cargo })
71 {
72 const onlineId = this.simulation.characterEntities.get(characterId);
73 const bag = onlineId
74 ? this.simulation.bagOf(onlineId)
75 : this.stateDb.getBag(characterId);
76 if (!bag)
77 {
78 const error = new Error("No bag.");
79 error.userFacing = true;
80 throw error;
81 }
82
83 let takenCargo;
84 if (cargo?.kind === "item")
85 {
86 const slot = bag.inventory?.[cargo.slotIndex | 0];
87 if (slot?.itemId === ItemId.blankCheque)
88 {
89 const error = new Error("Blank cheques cannot be sent by pigeon.");
90 error.userFacing = true;
91 throw error;
92 }
93 if (slot?.itemId === ItemId.letter)
94 {
95 if (Number(slot.instance?.authorCharacterId) !== Number(characterId))
96 {
97 const error = new Error("You can only send letters you wrote.");
98 error.userFacing = true;
99 throw error;
100 }
101 }
102 const taken = takeFromSlot(bag.inventory, cargo.slotIndex | 0, cargo.quantity ?? null);
103 if (!taken.ok || !taken.taken)
104 {
105 const error = new Error("That item is not available.");
106 error.userFacing = true;
107 throw error;
108 }
109 bag.inventory = taken.slots;
110 const stack = taken.taken;
111 if (stack.itemId === ItemId.letter && stack.instance)
112 { stack.instance = { ...stack.instance, opened: false }; }
113 takenCargo = { kind: "item", stack };
114 }
115 else
116 {
117 const error = new Error("Pigeon cargo must be money or one item stack.");
118 error.userFacing = true;
119 throw error;
120 }
121
122 const dest = this.#resolveDestination(destination, originTileX, originTileY);
123 this.#persistBag(characterId, bag);
124 const transit = this.stateDb.insertCourierTransit({
125 senderCharacterId: characterId,
126 destinationKind: dest.kind,
127 destinationCharacterId: dest.characterId ?? null,
128 cargo: takenCargo,
129 originX: originTileX + 0.5,
130 originY: originTileY + 0.5,
131 destX: dest.tileX + 0.5,
132 destY: dest.tileY + 0.5,
133 traveled: 0,
134 status: "in_transit",
135 entityId: null
136 });
137 return { transit, bag };
138 }
139
140 /** Market / system dispatch already holding cargo (no bag take). */
141 dispatchHeldCargo ({ senderCharacterId, originTileX, originTileY, destination, cargo })
142 {
143 const dest = this.#resolveDestination(destination, originTileX, originTileY);
144 return this.stateDb.insertCourierTransit({
145 senderCharacterId,
146 destinationKind: dest.kind,
147 destinationCharacterId: dest.characterId ?? null,
148 cargo,
149 originX: originTileX + 0.5,
150 originY: originTileY + 0.5,
151 destX: dest.tileX + 0.5,
152 destY: dest.tileY + 0.5,
153 traveled: 0,
154 status: "in_transit",
155 entityId: null
156 });
157 }
158
159 step (now, dt)
160 {
161 const events = [];
162 const settings = this.simulation.settings;
163 for (const transit of this.stateDb.listActiveCourierTransits())
164 {
165 this.#retargetPlayerDest(transit);
166 const advanced = advanceCourierFlight({
167 originX: transit.originX,
168 originY: transit.originY,
169 destX: transit.destX,
170 destY: transit.destY,
171 traveled: transit.traveled,
172 dt,
173 settings
174 });
175 transit.traveled = advanced.traveled;
176 transit.updatedAt = now;
177
178 if (advanced.arrived)
179 {
180 events.push(...this.#deliver(transit, now));
181 continue;
182 }
183
184 events.push(...this.#syncVisiblePigeon(transit, advanced, now));
185 this.stateDb.updateCourierTransit(transit);
186 }
187 return events;
188 }
189
190 #retargetPlayerDest (transit)
191 {
192 if (transit.destinationKind !== "player" || !transit.destinationCharacterId)
193 { return; }
194 const onlineId = this.simulation.characterEntities.get(transit.destinationCharacterId);
195 if (onlineId)
196 {
197 const pos = this.simulation.positionOf(onlineId);
198 if (pos)
199 {
200 transit.destX = pos.tileX + 0.5;
201 transit.destY = pos.tileY + 0.5;
202 }
203 return;
204 }
205 const character = this.stateDb.getCharacter(transit.destinationCharacterId);
206 if (character)
207 {
208 transit.destX = character.tile_x + 0.5;
209 transit.destY = character.tile_y + 0.5;
210 }
211 }
212
213 #resolveDestination (destination, originTileX, originTileY)
214 {
215 if (destination?.kind === "player")
216 {
217 const character = this.stateDb.getCharacterByName(destination.firstName, destination.lastName);
218 if (!character)
219 {
220 const error = new Error("No character with that name.");
221 error.userFacing = true;
222 throw error;
223 }
224 const onlineId = this.simulation.characterEntities.get(character.character_id);
225 const pos = onlineId ? this.simulation.positionOf(onlineId) : null;
226 return {
227 kind: "player",
228 characterId: character.character_id,
229 tileX: pos?.tileX ?? character.tile_x,
230 tileY: pos?.tileY ?? character.tile_y
231 };
232 }
233 if (destination?.kind === "bank")
234 {
235 const bank = this.nearestBank(originTileX, originTileY);
236 if (!bank)
237 {
238 const error = new Error("No bank exists in the world yet.");
239 error.userFacing = true;
240 throw error;
241 }
242 return { kind: "bank", tileX: bank.tileX, tileY: bank.tileY };
243 }
244 const error = new Error("Pigeon destination must be bank or player.");
245 error.userFacing = true;
246 throw error;
247 }
248
249 #syncVisiblePigeon (transit, advanced, now)
250 {
251 const events = [];
252 const tileX = Math.floor(advanced.x);
253 const tileY = Math.floor(advanced.y);
254 if (!this.simulation.chunkIsSimulating(tileX, tileY))
255 {
256 if (transit.entityId)
257 {
258 this.simulation.despawnEntity(transit.entityId);
259 events.push({ type: "entity-despawn", entityId: transit.entityId, tileX, tileY });
260 transit.entityId = null;
261 }
262 return events;
263 }
264
265 if (!transit.entityId || !this.simulation.entityRecord(transit.entityId))
266 {
267 transit.entityId = null;
268 const def = mobDefinition(MobId.pigeon);
269 const entityId = this.simulation.spawnEntity({
270 position: { tileX, tileY },
271 movement: { gait: GAIT.walk, walkCarry: 0 },
272 path: { tiles: [] },
273 flight: {
274 x: advanced.x,
275 y: advanced.y,
276 targetX: transit.destX,
277 targetY: transit.destY,
278 speed: advanced.speed,
279 nextPickAt: now + 60_000,
280 lastAt: now,
281 courierId: transit.courierId
282 },
283 appearance: {
284 sex: def.sex,
285 firstName: def.displayName,
286 lastName: "",
287 sprite: mobSpriteName(MobId.pigeon)
288 },
289 creature: { mobTypeId: MobId.pigeon },
290 health: { current: 1, max: 1 }
291 }, { requireResident: true });
292 if (entityId != null)
293 { transit.entityId = entityId; }
294 return events;
295 }
296
297 const moved = this.simulation.updateCourierFlight(transit.entityId, {
298 x: advanced.x,
299 y: advanced.y,
300 targetX: transit.destX,
301 targetY: transit.destY,
302 speed: advanced.speed,
303 lastAt: now,
304 courierId: transit.courierId
305 }, now);
306 if (moved?.despawned)
307 {
308 transit.entityId = null;
309 events.push({ type: "entity-despawn", entityId: moved.entityId, tileX, tileY });
310 }
311 else if (moved?.event)
312 { events.push(moved.event); }
313 return events;
314 }
315
316 #deliver (transit, now)
317 {
318 const events = [];
319 if (transit.entityId)
320 {
321 this.simulation.despawnEntity(transit.entityId);
322 events.push({
323 type: "entity-despawn",
324 entityId: transit.entityId,
325 tileX: Math.floor(transit.destX),
326 tileY: Math.floor(transit.destY)
327 });
328 transit.entityId = null;
329 }
330
331 if (transit.destinationKind === "bank")
332 { this.#creditVault(transit.senderCharacterId, transit.cargo); }
333 else if (transit.destinationKind === "player")
334 {
335 const delivered = this.#tryDeliverToPlayer(transit.destinationCharacterId, transit.cargo);
336 if (!delivered)
337 {
338 const bank = this.nearestBank(Math.floor(transit.destX), Math.floor(transit.destY))
339 ?? this.nearestBank(Math.floor(transit.originX), Math.floor(transit.originY));
340 if (bank)
341 {
342 transit.originX = transit.destX;
343 transit.originY = transit.destY;
344 transit.destX = bank.tileX + 0.5;
345 transit.destY = bank.tileY + 0.5;
346 transit.traveled = 0;
347 transit.destinationKind = "bank";
348 transit.updatedAt = now;
349 this.stateDb.updateCourierTransit(transit);
350 events.push({
351 type: "pigeon-reroute-bank",
352 courierId: transit.courierId,
353 characterId: transit.destinationCharacterId
354 });
355 return events;
356 }
357 this.#creditVault(transit.destinationCharacterId, transit.cargo);
358 }
359 }
360
361 transit.status = "delivered";
362 transit.traveled = Math.hypot(transit.destX - transit.originX, transit.destY - transit.originY);
363 transit.updatedAt = now;
364 this.stateDb.updateCourierTransit(transit);
365 events.push({
366 type: "pigeon-delivered",
367 courierId: transit.courierId,
368 senderCharacterId: transit.senderCharacterId,
369 destinationKind: transit.destinationKind,
370 destinationCharacterId: transit.destinationCharacterId,
371 cargo: transit.cargo
372 });
373 return events;
374 }
375
376 #normalizeCargo (cargo)
377 {
378 if (cargo?.kind === "money")
379 {
380 return {
381 kind: "item",
382 stack: { itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) }
383 };
384 }
385 return cargo;
386 }
387
388 #tryDeliverToPlayer (characterId, cargo)
389 {
390 cargo = this.#normalizeCargo(cargo);
391 const onlineId = this.simulation.characterEntities.get(characterId);
392 if (onlineId)
393 {
394 if (cargo.kind === "item")
395 {
396 const bag = this.simulation.bagOf(onlineId);
397 if (!bag)
398 { return false; }
399 const def = itemDefinition(cargo.stack.itemId);
400 const result = insertStack(bag.inventory, cargo.stack, def);
401 if (!result.ok || result.remainder)
402 { return false; }
403 bag.inventory = result.slots;
404 this.#persistBag(characterId, bag);
405 return true;
406 }
407 }
408
409 if (cargo.kind === "item")
410 {
411 this.#creditVault(characterId, cargo);
412 return true;
413 }
414 return false;
415 }
416
417 #creditVault (characterId, cargo)
418 {
419 cargo = this.#normalizeCargo(cargo);
420 const onlineId = this.simulation.characterEntities.get(characterId);
421 const bag = onlineId
422 ? this.simulation.bagOf(onlineId)
423 : this.stateDb.getBag(characterId);
424 if (!bag)
425 { return; }
426 if (cargo.kind === "item")
427 {
428 const def = itemDefinition(cargo.stack.itemId);
429 const vault = normalizeVault(
430 bag.vaultReserved != null
431 ? { slots: bag.vault, reserved: bag.vaultReserved }
432 : bag.vault
433 );
434 const result = insertStackGrowable(vault.slots, cargo.stack, def);
435 bag.vault = result.slots;
436 bag.vaultReserved = vault.reserved;
437 this.#persistBag(characterId, bag);
438 }
439 }
440
441 #persistBag (characterId, bag)
442 {
443 this.stateDb.saveBag(characterId, bag);
444 const onlineId = this.simulation.characterEntities.get(characterId);
445 if (onlineId)
446 {
447 this.simulation.applyBag(onlineId, bag);
448 this.simulation.pushInventory(characterId, bag);
449 }
450 }
451}