BlueGit

timfa questward

Files

questward / server / src / simulation / spawners.js

spawners.js

spawners.js 17.3 KiB Download Raw
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import
3 {
4 mobCanFight,
5 mobSkillLevels,
6 mobHealthForLevel,
7 mobSpellCastChancePercent
8 } from "../../../shared/definitions/mobCombat.js";
9import
10 {
11 normalizeSpawnerConfig,
12 listAmbientMobTypes,
13 mobDefinition,
14 mobSpriteName,
15 MobId,
16 spawnerEquipmentSlot,
17 isTownGuardMob,
18 isHumanoidMob
19 } from "../../../shared/definitions/mobs.js";
20import { spellDefinition, spellMinMagicLevel, SPRITE_BOLT_SPELL_BY_ELEMENT } from "../../../shared/definitions/spells.js";
21import { MAGIC_ELEMENT_ORDER, magicElementTint } from "../../../shared/definitions/attackTypes.js";
22import { essenceElementDisplayName } from "../../../shared/definitions/essenceItems.js";
23import { LeatherItemId } from "../../../shared/definitions/leatherItems.js";
24import { CENTRAL_EXCHANGE_STAFF } from "../../../shared/market/exchange.js";
25import { emptyEquipment } from "../../../shared/items/inventory.js";
26import { itemDefinition } from "../../../shared/definitions/items.js";
27import { appearanceHairFields, hairFromNameSeed, randomNpcHairColor, randomBrightOrPastelColor } from "../../../shared/appearance/hair.js";
28import { npcDefaultEquipment } from "../../../shared/appearance/npcEquipment.js";
29import { Component } from "../ecs/components.js";
30import { tileToChunk, tileToRegion, parseChunkKey } from "../world/coordinates.js";
31import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
32
33export function collectSpawnRequests (world, now = Date.now())
34{
35 const requests = [];
36 const counts = countBySpawner(world);
37 const staffAlive = staffNamesBySpawner(world);
38 const reserved = new Set();
39 ensurePendingRespawns(world);
40 for (const [key, chunk] of world.chunks)
41 {
42 if (chunk.replica || !chunk.simulating || !chunk.data.open)
43 { continue; }
44 const { chunkX, chunkY, dimensionId: keyDimensionId } = parseChunkKey(key);
45 const dimensionId = normalizeDimensionId(chunk.dimensionId ?? keyDimensionId ?? OVERWORLD_ID);
46 for (const entry of chunk.data.spawners ?? [])
47 {
48 const localX = entry.localX;
49 const localY = entry.localY;
50 const index = localY * CHUNK_SIZE + localX;
51 const rawSpawnerId = typeof entry.config?.spawnerId === "string" && entry.config.spawnerId
52 ? entry.config.spawnerId
53 : `${chunkX}:${chunkY}:${index}`;
54 const scopedSpawnerId = rawSpawnerId.startsWith(`${dimensionId}:`)
55 ? rawSpawnerId
56 : `${dimensionId}:${rawSpawnerId}`;
57 const config = normalizeSpawnerConfig(entry.config, scopedSpawnerId);
58 config.spawnerId = scopedSpawnerId;
59 const flying = !!mobDefinition(config.mobTypeId)?.flying;
60 const originX = chunkX * CHUNK_SIZE + localX;
61 const originY = chunkY * CHUNK_SIZE + localY;
62 const persistent = !!mobDefinition(config.mobTypeId)?.persistent;
63 const delayMs = Math.max(0, (config.respawnDelaySeconds | 0) * 1000);
64
65 if (config.centralExchange)
66 {
67 const alive = staffAlive.get(config.spawnerId) ?? new Set();
68 for (const staff of CENTRAL_EXCHANGE_STAFF)
69 {
70 if (alive.has(staff.name))
71 { continue; }
72 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
73 { break; }
74 if (!consumeSpawnSlot(world, config.spawnerId, delayMs, now))
75 { break; }
76 const tile = pickSpawnTile(
77 world,
78 originX,
79 originY,
80 config.spawnRangeTiles,
81 flying,
82 reserved,
83 dimensionId
84 );
85 if (!tile)
86 { break; }
87 reserved.add(`${tile.tileX},${tile.tileY}`);
88 alive.add(staff.name);
89 staffAlive.set(config.spawnerId, alive);
90 requests.push({
91 ...tile,
92 dimensionId,
93 mobTypeId: MobId.centralExchange,
94 spawnerId: config.spawnerId,
95 originTileX: originX,
96 originTileY: originY,
97 wanderRangeTiles: config.maxWanderRangeTiles,
98 level: config.level,
99 bounty: config.bounty,
100 aggressive: !!config.aggressive,
101 spells: config.spells,
102 persistent,
103 sex: staff.sex,
104 displayName: staff.name,
105 equipment: config.equipment,
106 sells: [],
107 drops: config.drops,
108 buysItems: false,
109 hiddenDiscount: config.hiddenDiscount,
110 centralExchange: true,
111 townGuard: false,
112 dialogueId: config.dialogueId || null,
113 respawnDelaySeconds: config.respawnDelaySeconds
114 });
115 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
116 }
117 continue;
118 }
119
120 while ((counts.get(config.spawnerId) ?? 0) < config.maxAlive)
121 {
122 if (!consumeSpawnSlot(world, config.spawnerId, delayMs, now))
123 { break; }
124 const tile = pickSpawnTile(
125 world,
126 originX,
127 originY,
128 config.spawnRangeTiles,
129 flying,
130 reserved,
131 dimensionId
132 );
133 if (!tile)
134 { break; }
135 reserved.add(`${tile.tileX},${tile.tileY}`);
136 requests.push({
137 ...tile,
138 dimensionId,
139 mobTypeId: config.mobTypeId,
140 spawnerId: config.spawnerId,
141 originTileX: originX,
142 originTileY: originY,
143 wanderRangeTiles: config.maxWanderRangeTiles,
144 level: config.level,
145 bounty: config.bounty,
146 aggressive: isHumanoidMob(config.mobTypeId) || config.townGuard
147 ? !!config.aggressive
148 : undefined,
149 spells: config.spells,
150 persistent,
151 sex: config.sex,
152 displayName: config.displayName,
153 equipment: config.equipment,
154 sells: config.sells,
155 drops: config.drops,
156 buysItems: config.buysItems,
157 hiddenDiscount: config.hiddenDiscount,
158 centralExchange: false,
159 townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId),
160 dialogueId: config.dialogueId || null,
161 respawnDelaySeconds: config.respawnDelaySeconds
162 });
163 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
164 }
165 }
166 }
167 requests.push(...collectAmbientRequests(world, reserved));
168 return requests;
169}
170
171function ensurePendingRespawns (world)
172{
173 if (!world.pendingSpawnerRespawns)
174 { world.pendingSpawnerRespawns = new Map(); }
175 return world.pendingSpawnerRespawns;
176}
177
178/**
179 * Schedule a delayed refill slot after a spawned mob dies.
180 * Delay 0 means the next collect pass may refill immediately (no pending entry).
181 */
182export function scheduleSpawnerRespawn (world, spawnerId, respawnDelaySeconds, now = Date.now())
183{
184 if (!spawnerId)
185 { return; }
186 const delayMs = Math.max(0, (respawnDelaySeconds | 0) * 1000);
187 if (delayMs <= 0)
188 { return; }
189 const pending = ensurePendingRespawns(world);
190 const list = pending.get(spawnerId) ?? [];
191 list.push(now + delayMs);
192 list.sort((a, b) => a - b);
193 pending.set(spawnerId, list);
194}
195
196/**
197 * Decide whether one more mob may spawn for this spawner right now.
198 * - delay 0 / empty pending: allow (initial populate + instant refill)
199 * - otherwise: only if a pending timer is due; consume one due timer
200 */
201function consumeSpawnSlot (world, spawnerId, delayMs, now)
202{
203 if (delayMs <= 0)
204 { return true; }
205 const pending = ensurePendingRespawns(world);
206 const list = pending.get(spawnerId);
207 if (!list?.length)
208 {
209 // No death timers yet — first populate / recovery after unload.
210 return true;
211 }
212 const readyIndex = list.findIndex((readyAt) => readyAt <= now);
213 if (readyIndex < 0)
214 { return false; }
215 list.splice(readyIndex, 1);
216 if (!list.length)
217 { pending.delete(spawnerId); }
218 else
219 { pending.set(spawnerId, list); }
220 return true;
221}
222
223export function mobComponents (request)
224{
225 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
226 const sex = request.sex === "female" || request.sex === "male"
227 ? request.sex
228 : (def.sex ?? "male");
229 const displayName = String(request.displayName || def.displayName || "NPC").trim() || def.displayName;
230 const level = Math.max(1, Math.min(99, Number(request.level) || 1)) | 0;
231 const appearance = {
232 sex,
233 firstName: displayName,
234 lastName: ""
235 };
236 if (def.usePlayerBody)
237 {
238 Object.assign(appearance, appearanceHairFields(hairFromNameSeed(displayName, sex)));
239 }
240 else
241 {
242 const fleeceState = def.shearable?.fleeceState ?? null;
243 const sprite = mobSpriteName(def.mobTypeId, fleeceState);
244 if (sprite)
245 { appearance.sprite = sprite; }
246 }
247
248 if (def.dualChannelAppearance || def.mobTypeId === MobId.fairy)
249 {
250 appearance.dualTint = {
251 /** Red channel — shirt. */
252 shaft: randomBrightOrPastelColor(),
253 /** Blue channel — skirt. */
254 tip: randomBrightOrPastelColor(),
255 /** Green channel — hair. */
256 coat: randomNpcHairColor()
257 };
258 appearance.bloomBody = !!def.bloomBody;
259 }
260
261 let element = request.element ?? null;
262 if ((def.randomElementOnSpawn || def.mobTypeId === MobId.sprite) && !element)
263 {
264 element = MAGIC_ELEMENT_ORDER[Math.floor(Math.random() * MAGIC_ELEMENT_ORDER.length)];
265 }
266 if (element)
267 {
268 const tint = magicElementTint(element);
269 appearance.tint = { r: tint.r, g: tint.g, b: tint.b };
270 appearance.bloomBody = !!def.bloomBody;
271 if (def.mobTypeId === MobId.sprite || def.randomElementOnSpawn)
272 {
273 const label = essenceElementDisplayName(element);
274 appearance.firstName = `${label} Sprite`;
275 appearance.lastName = "";
276 }
277 }
278 else if (def.bloomBody)
279 { appearance.bloomBody = true; }
280
281 const maxHp = mobHealthForLevel(def, level);
282 const components = {
283 position: {
284 tileX: request.tileX,
285 tileY: request.tileY,
286 dimensionId: normalizeDimensionId(request.dimensionId ?? OVERWORLD_ID)
287 },
288 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
289 path: { tiles: [] },
290 appearance,
291 creature: {
292 mobTypeId: def.mobTypeId,
293 level,
294 ...(element ? { element } : {}),
295 ...(def.lightRadiusTiles ? { lightRadiusTiles: def.lightRadiusTiles } : {}),
296 ...(def.shearable
297 ? {
298 fleeceState: def.shearable.fleeceState,
299 woolReadyAt: null
300 }
301 : {})
302 },
303 health: { current: maxHp, max: maxHp }
304 };
305 if (request.spawnerId)
306 {
307 const aggressive = request.aggressive != null
308 ? !!request.aggressive
309 : !!def.aggressive;
310 // Humanoid Aggressive flag forces bounty 0; wildlife can be aggressive and still pay kill bounty.
311 const bounty = request.aggressive === true
312 ? 0
313 : (Math.max(0, Number(request.bounty) || 0) | 0);
314 components.spawnOrigin = {
315 spawnerId: request.spawnerId,
316 originTileX: request.originTileX ?? request.tileX,
317 originTileY: request.originTileY ?? request.tileY,
318 wanderRangeTiles: request.wanderRangeTiles ?? 4,
319 bounty,
320 level,
321 aggressive,
322 centralExchange: !!request.centralExchange,
323 townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
324 stationTileX: null,
325 stationTileY: null,
326 dialogueId: request.dialogueId ? String(request.dialogueId) : null,
327 drops: Array.isArray(request.drops) ? request.drops : [],
328 respawnDelaySeconds: Math.max(0, request.respawnDelaySeconds | 0)
329 };
330 }
331 if (def.persistent)
332 { components.persistent = {}; }
333 if (def.freeFlight)
334 {
335 components.flight = {
336 x: request.tileX + 0.5,
337 y: request.tileY + 0.5,
338 targetX: request.tileX + 0.5,
339 targetY: request.tileY + 0.5,
340 speed: def.flightSpeedTilesPerSec ?? 2.5,
341 nextPickAt: 0,
342 lastAt: 0
343 };
344 }
345 if (mobCanFight(def))
346 {
347 components.combat = { targetEntityId: null, nextSwingAt: 0, seekCover: false, fleeFrom: null };
348 components.skills = { levels: mobSkillLevels(def, level) };
349 }
350
351 const knownSpells = normalizeMobSpells(request.spells, level);
352 if (def.randomElementSpell)
353 {
354 /** Fairies know every elemental sprite bolt and pick one at random each cast. */
355 for (const boltId of Object.values(SPRITE_BOLT_SPELL_BY_ELEMENT))
356 {
357 if (!knownSpells.some((entry) => entry.spellId === boltId))
358 { knownSpells.push({ spellId: boltId }); }
359 }
360 }
361 else if (element && SPRITE_BOLT_SPELL_BY_ELEMENT[element])
362 {
363 const boltId = SPRITE_BOLT_SPELL_BY_ELEMENT[element];
364 if (!knownSpells.some((entry) => entry.spellId === boltId))
365 { knownSpells.push({ spellId: boltId }); }
366 }
367 if (knownSpells.length)
368 {
369 const castChance = (element || def.randomElementSpell) ? 100 : mobSpellCastChancePercent(level);
370 components.spells = {
371 known: knownSpells.map((entry) => entry.spellId),
372 favorites: [],
373 autoCast: false,
374 castChances: Object.fromEntries(knownSpells.map((entry) => [entry.spellId, castChance]))
375 };
376 components.spellcasting = {
377 armedSpellId: null,
378 repeatSpellId: null,
379 repeatTargetEntityId: null,
380 nextCastAt: 0,
381 pendingCast: null
382 };
383 }
384
385 const equipmentSlots = emptyEquipment().slots;
386 const authored = request.equipment ?? {};
387 const defaults = def.usePlayerBody ? npcDefaultEquipment(displayName, sex) : null;
388 for (const slot of Object.keys(equipmentSlots))
389 {
390 const authoredEntry = authored[slot];
391 let { itemId, dyeColor } = spawnerEquipmentSlot(authoredEntry);
392 if (!itemId && defaults?.[slot])
393 {
394 itemId = defaults[slot].itemId;
395 dyeColor = defaults[slot].dyeColor ?? null;
396 }
397 if (!itemId)
398 { continue; }
399 const itemDef = itemDefinition(itemId);
400 if (!itemDef?.equipment || itemDef.equipment.slot !== slot)
401 { continue; }
402 const stack = { itemId, quantity: 1 };
403 if (dyeColor && itemDef.dyeable)
404 { stack.instance = { kind: "clothing", dyeColor }; }
405 equipmentSlots[slot] = stack;
406 }
407 if (def.usePlayerBody || Object.values(equipmentSlots).some(Boolean))
408 { components.equipment = { slots: equipmentSlots }; }
409
410 const catalog = Array.isArray(request.sells)
411 ? request.sells.map((entry) =>
412 {
413 if (entry && typeof entry === "object")
414 {
415 return {
416 itemId: entry.itemId | 0,
417 quantity: Math.max(0, entry.quantity | 0 || 0)
418 };
419 }
420 return { itemId: entry | 0, quantity: 0 };
421 }).filter((line) => line.itemId > 0)
422 : [];
423 const buysItems = !!request.buysItems;
424 const isExchange = !!request.centralExchange || def.centralExchange;
425 if (!isExchange && (catalog.length || buysItems || def.talkable))
426 {
427 components.shop = {
428 catalog,
429 buysItems,
430 hiddenDiscount: Number(request.hiddenDiscount) || 0.9,
431 displayName,
432 remaining: Object.create(null),
433 boughtStock: Object.create(null),
434 restockDay: null
435 };
436 }
437 return components;
438}
439
440function normalizeMobSpells (raw, level)
441{
442 if (!Array.isArray(raw))
443 { return []; }
444 const out = [];
445 const seen = new Set();
446 const lv = Math.max(1, level | 0 || 1);
447 for (const entry of raw)
448 {
449 if (!entry || typeof entry !== "object")
450 { continue; }
451 const spellId = String(entry.spellId ?? "").trim();
452 if (!spellId || seen.has(spellId))
453 { continue; }
454 const def = spellDefinition(spellId);
455 if (!def)
456 { continue; }
457 const minLevel = spellMinMagicLevel(def);
458 if (lv < minLevel)
459 { continue; }
460 seen.add(spellId);
461 out.push({ spellId });
462 }
463 return out;
464}
465
466function collectAmbientRequests (world, reserved = new Set())
467{
468 const requests = [];
469 const ambientTypes = listAmbientMobTypes();
470 if (!ambientTypes.length)
471 { return requests; }
472
473 const loaders = world.ecs.query(Component.position, Component.chunkLoader);
474 if (!loaders.length)
475 { return requests; }
476
477 for (const def of ambientTypes)
478 {
479 const maxPerLoader = Math.max(0, def.ambientMaxPerLoader ?? 1);
480 const alive = countCreatures(world, def.mobTypeId);
481 const budget = maxPerLoader * loaders.length;
482 if (alive >= budget)
483 { continue; }
484
485 for (const loader of loaders)
486 {
487 if (requests.length + alive >= budget)
488 { break; }
489 const dim = normalizeDimensionId(loader.position.dimensionId ?? OVERWORLD_ID);
490 const tile = pickSpawnTile(
491 world,
492 loader.position.tileX,
493 loader.position.tileY,
494 8,
495 !!def.flying,
496 reserved,
497 dim
498 );
499 if (!tile)
500 { continue; }
501 reserved.add(`${tile.tileX},${tile.tileY}`);
502 requests.push({
503 ...tile,
504 dimensionId: dim,
505 mobTypeId: def.mobTypeId,
506 spawnerId: null,
507 level: 1,
508 bounty: 0,
509 spells: [],
510 persistent: false
511 });
512 }
513 }
514 return requests;
515}
516
517function countBySpawner (world)
518{
519 const counts = new Map();
520 for (const entity of world.ecs.query(Component.spawnOrigin))
521 {
522 const id = entity.spawnOrigin.spawnerId;
523 counts.set(id, (counts.get(id) ?? 0) + 1);
524 }
525 return counts;
526}
527
528function staffNamesBySpawner (world)
529{
530 const map = new Map();
531 for (const entity of world.ecs.query(Component.spawnOrigin, Component.appearance))
532 {
533 if (!entity.spawnOrigin?.centralExchange)
534 { continue; }
535 const id = entity.spawnOrigin.spawnerId;
536 const name = entity.appearance?.firstName;
537 if (!id || !name)
538 { continue; }
539 const set = map.get(id) ?? new Set();
540 set.add(name);
541 map.set(id, set);
542 }
543 return map;
544}
545
546function countCreatures (world, mobTypeId)
547{
548 let count = 0;
549 for (const entity of world.ecs.query(Component.creature))
550 {
551 if (entity.creature.mobTypeId === mobTypeId)
552 { count += 1; }
553 }
554 return count;
555}
556
557function pickSpawnTile (world, originX, originY, range, flying = false, reserved = null, dimensionId = OVERWORLD_ID)
558{
559 const dim = normalizeDimensionId(dimensionId);
560 const radius = Math.max(0, range | 0);
561 const tryTile = (tileX, tileY) =>
562 {
563 const key = `${tileX},${tileY}`;
564 if (reserved?.has(key))
565 { return null; }
566 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY), dim))
567 { return null; }
568 if (flying)
569 {
570 if (!chunkIsOpen(world, tileX, tileY, dim))
571 { return null; }
572 return { tileX, tileY, dimensionId: dim };
573 }
574 if (!world.isEnterable(tileX, tileY, dim) || world.occupied(tileX, tileY, dim))
575 { return null; }
576 return { tileX, tileY, dimensionId: dim };
577 };
578 if (radius === 0)
579 { return tryTile(originX, originY); }
580 for (let attempt = 0; attempt < 48; attempt++)
581 {
582 const tile = tryTile(
583 originX + randInt(-radius, radius),
584 originY + randInt(-radius, radius)
585 );
586 if (tile)
587 { return tile; }
588 }
589 return null;
590}
591
592function chunkIsOpen (world, tileX, tileY, dimensionId = OVERWORLD_ID)
593{
594 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
595 return !!data?.open;
596}
597
598function randInt (min, max)
599{
600 return min + Math.floor(Math.random() * (max - min + 1));
601}