BlueGit

timfa questward

Files

questward / server / src / simulation / spawners.js

spawners.js

spawners.js 9.1 KiB Download Raw
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
3import {
4 normalizeSpawnerConfig,
5 listAmbientMobTypes,
6 mobDefinition,
7 mobSpriteName,
8 MobId,
9 spawnerEquipmentSlot
10} from "../../../shared/definitions/mobs.js";
11import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
12import { emptyEquipment } from "../../../shared/items/inventory.js";
13import { itemDefinition } from "../../../shared/definitions/items.js";
14import { Component } from "../ecs/components.js";
15import { tileToChunk, tileToRegion } from "../world/coordinates.js";
16
17export function collectSpawnRequests (world)
18{
19 const requests = [];
20 const counts = countBySpawner(world);
21 const staffAlive = staffNamesBySpawner(world);
22 const reserved = new Set();
23 for (const [key, chunk] of world.chunks)
24 {
25 if (chunk.replica || !chunk.simulating || !chunk.data.open)
26 { continue; }
27 const [chunkX, chunkY] = key.split(",").map(Number);
28 for (const entry of chunk.data.spawners ?? [])
29 {
30 const localX = entry.localX;
31 const localY = entry.localY;
32 const index = localY * CHUNK_SIZE + localX;
33 const config = normalizeSpawnerConfig(
34 entry.config,
35 `${chunkX}:${chunkY}:${index}`
36 );
37 const flying = !!mobDefinition(config.mobTypeId)?.flying;
38 const originX = chunkX * CHUNK_SIZE + localX;
39 const originY = chunkY * CHUNK_SIZE + localY;
40 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
41
42 if (config.centralExchange)
43 {
44 const alive = staffAlive.get(config.spawnerId) ?? new Set();
45 for (const staff of CENTRAL_EXCHANGE_STAFF)
46 {
47 if (alive.has(staff.name))
48 { continue; }
49 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
50 { break; }
51 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
52 if (!tile)
53 { break; }
54 reserved.add(`${tile.tileX},${tile.tileY}`);
55 alive.add(staff.name);
56 staffAlive.set(config.spawnerId, alive);
57 requests.push({
58 ...tile,
59 mobTypeId: MobId.centralExchange,
60 spawnerId: config.spawnerId,
61 originTileX: originX,
62 originTileY: originY,
63 wanderRangeTiles: config.maxWanderRangeTiles,
64 persistent,
65 sex: staff.sex,
66 displayName: staff.name,
67 equipment: config.equipment,
68 sells: [],
69 buysItems: false,
70 hiddenDiscount: config.hiddenDiscount,
71 centralExchange: true
72 });
73 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
74 }
75 continue;
76 }
77
78 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
79 {
80 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles, flying, reserved);
81 if (!tile)
82 { break; }
83 reserved.add(`${tile.tileX},${tile.tileY}`);
84 requests.push({
85 ...tile,
86 mobTypeId: config.mobTypeId,
87 spawnerId: config.spawnerId,
88 originTileX: originX,
89 originTileY: originY,
90 wanderRangeTiles: config.maxWanderRangeTiles,
91 persistent,
92 sex: config.sex,
93 displayName: config.displayName,
94 equipment: config.equipment,
95 sells: config.sells,
96 buysItems: config.buysItems,
97 hiddenDiscount: config.hiddenDiscount,
98 centralExchange: false
99 });
100 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
101 }
102 }
103 }
104 requests.push(...collectAmbientRequests(world, reserved));
105 return requests;
106}
107
108export function mobComponents (request)
109{
110 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
111 const sex = request.sex === "female" || request.sex === "male"
112 ? request.sex
113 : (def.sex ?? "male");
114 const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;
115 const appearance = {
116 sex,
117 firstName: displayName,
118 lastName: ""
119 };
120 if (!def.usePlayerBody)
121 {
122 const sprite = mobSpriteName(def.mobTypeId);
123 if (sprite)
124 { appearance.sprite = sprite; }
125 }
126
127 const components = {
128 position: { tileX: request.tileX, tileY: request.tileY },
129 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
130 path: { tiles: [] },
131 appearance,
132 creature: { mobTypeId: def.mobTypeId },
133 health: { current: def.health ?? 8, max: def.health ?? 8 }
134 };
135 if (request.spawnerId)
136 {
137 components.spawnOrigin = {
138 spawnerId: request.spawnerId,
139 originTileX: request.originTileX ?? request.tileX,
140 originTileY: request.originTileY ?? request.tileY,
141 wanderRangeTiles: request.wanderRangeTiles ?? 4,
142 centralExchange: !!request.centralExchange,
143 stationTileX: null,
144 stationTileY: null
145 };
146 }
147 if (def.persistent)
148 { components.persistent = {}; }
149 if (def.freeFlight)
150 {
151 components.flight = {
152 x: request.tileX + 0.5,
153 y: request.tileY + 0.5,
154 targetX: request.tileX + 0.5,
155 targetY: request.tileY + 0.5,
156 speed: def.flightSpeedTilesPerSec ?? 2.5,
157 nextPickAt: 0,
158 lastAt: 0
159 };
160 }
161 if (mobCanFight(def))
162 {
163 components.combat = { targetEntityId: null, nextSwingAt: 0 };
164 components.skills = { levels: mobSkillLevels(def) };
165 }
166
167 const equipmentSlots = emptyEquipment().slots;
168 const authored = request.equipment ?? {};
169 for (const slot of Object.keys(equipmentSlots))
170 {
171 const { itemId, dyeColor } = spawnerEquipmentSlot(authored[slot]);
172 if (!itemId)
173 { continue; }
174 const itemDef = itemDefinition(itemId);
175 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
176 { continue; }
177 const stack = { itemId, quantity: 1 };
178 if (dyeColor && itemDef.dyeable)
179 { stack.instance = { kind: "clothing", dyeColor }; }
180 equipmentSlots[slot] = stack;
181 }
182 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
183 { components.equipment = { slots: equipmentSlots }; }
184
185 const catalog = Array.isArray(request.sells)
186 ? request.sells.map((entry) =>
187 {
188 if (entry && typeof entry === "object")
189 {
190 return {
191 itemId: entry.itemId | 0,
192 quantity: Math.max(0, entry.quantity | 0 || 0)
193 };
194 }
195 return { itemId: entry | 0, quantity: 0 };
196 }).filter((line) => line.itemId > 0)
197 : [];
198 const buysItems = !!request.buysItems;
199 const isExchange = !!request.centralExchange || def.centralExchange;
200 if (!isExchange && (catalog.length || buysItems || def.talkable))
201 {
202 components.shop = {
203 catalog,
204 buysItems,
205 hiddenDiscount: Number(request.hiddenDiscount) || 0.9,
206 displayName,
207 remaining: Object.create(null),
208 boughtStock: Object.create(null),
209 restockDay: null
210 };
211 }
212 return components;
213}
214
215function collectAmbientRequests (world, reserved = new Set())
216{
217 const requests = [];
218 const ambientTypes = listAmbientMobTypes();
219 if (!ambientTypes.length)
220 { return requests; }
221
222 const loaders = world.ecs.query(Component.position, Component.chunkLoader);
223 if (!loaders.length)
224 { return requests; }
225
226 for (const def of ambientTypes)
227 {
228 const maxPerLoader = Math.max(0, def.ambientMaxPerLoader ?? 1);
229 const alive = countCreatures(world, def.mobTypeId);
230 const budget = maxPerLoader * loaders.length;
231 if (alive >= budget)
232 { continue; }
233
234 for (const loader of loaders)
235 {
236 if (requests.length + alive >= budget)
237 { break; }
238 const tile = pickSpawnTile(
239 world,
240 loader.position.tileX,
241 loader.position.tileY,
242 8,
243 !!def.flying,
244 reserved
245 );
246 if (!tile)
247 { continue; }
248 reserved.add(`${tile.tileX},${tile.tileY}`);
249 requests.push({
250 ...tile,
251 mobTypeId: def.mobTypeId,
252 spawnerId: null,
253 persistent: false
254 });
255 }
256 }
257 return requests;
258}
259
260function countBySpawner (world)
261{
262 const counts = new Map();
263 for (const entity of world.ecs.query(Component.spawnOrigin))
264 {
265 const id = entity.spawnOrigin.spawnerId;
266 counts.set(id, (counts.get(id) ?? 0) + 1);
267 }
268 return counts;
269}
270
271function staffNamesBySpawner (world)
272{
273 const map = new Map();
274 for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance))
275 {
276 if (!entity.spawnOrigin?.centralExchange)
277 { continue; }
278 const id = entity.spawnOrigin.spawnerId;
279 const name = entity.appearance?.firstName;
280 if (!id || !name)
281 { continue; }
282 const set = map.get(id) ?? new Set();
283 set.add(name);
284 map.set(id, set);
285 }
286 return map;
287}
288
289function countCreatures (world, mobTypeId)
290{
291 let count = 0;
292 for (const entity of world.ecs.query(Component.creature))
293 {
294 if (entity.creature.mobTypeId === mobTypeId)
295 { count += 1; }
296 }
297 return count;
298}
299
300function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null)
301{
302 const radius = Math.max(1, range | 0);
303 for (let attempt = 0; attempt < 48; attempt++)
304 {
305 const tileX = originX + randInt(-radius, radius);
306 const tileY = originY + randInt(-radius, radius);
307 const key = `${tileX},${tileY}`;
308 if (reserved?.has(key))
309 { continue; }
310 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
311 { continue; }
312 if (flying)
313 {
314 if (!chunkIsOpen(world, tileX, tileY))
315 { continue; }
316 return { tileX, tileY };
317 }
318 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
319 { continue; }
320 return { tileX, tileY };
321 }
322 return null;
323}
324
325function chunkIsOpen (world, tileX, tileY)
326{
327 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
328 return !!data?.open;
329}
330
331function randInt (min, max)
332{
333 return min + Math.floor(Math.random() * (max - min + 1));
334}