BlueGit

timfa questward

Files

questward / server / src / simulation / spawners.js

spawners.js

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