Skip to main content

voxel_framework/mobs/
spawner.rs

1//! Rule-driven mob spawning.
2//!
3//! [`MobSpawnerPlugin`] periodically evaluates the rules in [`MobSpawnRules`]
4//! and spawns registered mob kinds around every [`Player`], depending on the
5//! time of day, the terrain at the candidate position and an optional zone
6//! predicate.
7//!
8//!
9//! See [`MobSpawnerPlugin`] for a complete example.
10
11use std::marker::PhantomData;
12use std::sync::Arc;
13
14use bevy::prelude::*;
15
16use super::{MOB_HALF_HEIGHT, MOB_RADIUS, MobKind, MobRegistry, spawn_mob_kind};
17use crate::chunk::Chunk;
18use crate::noise::hash3;
19use crate::player::Player;
20use crate::voxel::VoxelType;
21use crate::world::ChunkManager;
22use crate::world::daycycle::DayCycleConfig;
23use crate::world::voxel_ops::get_voxel_at;
24
25/// `time_of_day` at which [`TimeWindow::Day`] starts (dawn).
26pub const DAY_START: f32 = 0.25;
27/// `time_of_day` at which [`TimeWindow::Day`] ends (dusk).
28pub const DAY_END: f32 = 0.75;
29
30/// Voxels searched above and below the player's height for a ground surface.
31const GROUND_SEARCH_RANGE: i32 = 16;
32/// Gap left between the floor and a freshly spawned mob's capsule.
33const SPAWN_CLEARANCE: f32 = 0.01;
34/// Fraction of a kind's `despawn_distance` that spawn rings are capped to, so
35/// a mob is not despawned by distance right after spawning.
36const DESPAWN_MARGIN: f32 = 0.9;
37/// Narrowest ring a ground rule can use. Ground spawns snap to voxel column
38/// centres (up to ~0.71 away), so a thinner ring may contain no centre at all.
39const MIN_GROUND_RING_WIDTH: f32 = 1.5;
40
41// ─── Rules ────────────────────────────────────────────────────────────────────
42
43/// Part of the day in which a [`SpawnRule`] applies.
44///
45/// Times use [`DayCycleConfig::time_of_day`]: `0.0` midnight, `0.5` noon.
46/// Without a [`DayCycleConfig`] resource only [`TimeWindow::Any`] applies.
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub enum TimeWindow {
49    /// Always applies, with or without a day cycle.
50    #[default]
51    Any,
52    /// From dawn to dusk: `[0.25, 0.75)`.
53    Day,
54    /// From dusk to dawn: everything outside [`TimeWindow::Day`].
55    Night,
56    /// The half-open range `[start, end)`. Bounds are wrapped into `[0, 1)`,
57    /// so `0.9..0.1` and `0.9..1.1` both mean "from 0.9 past midnight to
58    /// 0.1". Empty when `start == end`, the whole day when the span is `1.0`
59    /// or more, and never applies with a non-finite bound.
60    Range {
61        /// First `time_of_day` in the window.
62        start: f32,
63        /// First `time_of_day` after the window.
64        end: f32,
65    },
66}
67
68impl TimeWindow {
69    /// Returns `true` when the window applies at `time_of_day`.
70    ///
71    /// `None` means there is no day cycle; only [`TimeWindow::Any`] applies.
72    pub fn contains(&self, time_of_day: Option<f32>) -> bool {
73        if matches!(self, Self::Any) {
74            return true;
75        }
76        let Some(time) = time_of_day.filter(|t| t.is_finite()) else {
77            return false;
78        };
79        let time = wrap_time(time);
80        match *self {
81            Self::Any => true,
82            Self::Day => (DAY_START..DAY_END).contains(&time),
83            Self::Night => !(DAY_START..DAY_END).contains(&time),
84            Self::Range { start, end } => {
85                if !(start.is_finite() && end.is_finite()) || start == end {
86                    return false;
87                }
88                if end - start >= 1.0 {
89                    return true;
90                }
91                let (start, end) = (wrap_time(start), wrap_time(end));
92                if start <= end {
93                    (start..end).contains(&time)
94                } else {
95                    time >= start || time < end
96                }
97            }
98        }
99    }
100}
101
102/// Wraps a finite time of day into `[0, 1)`.
103fn wrap_time(time: f32) -> f32 {
104    let wrapped = time.rem_euclid(1.0);
105    // `rem_euclid` rounds tiny negative inputs up to exactly 1.0.
106    if wrapped >= 1.0 { 0.0 } else { wrapped }
107}
108
109/// Where a [`SpawnRule`] places mobs.
110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
111pub enum SpawnPlacement {
112    /// Standing on a solid voxel with two free voxels above it, at the centre
113    /// of a voxel column. The ring's `min` is measured horizontally and its
114    /// `max` in 3D, so nothing spawns on ground far below or above the player.
115    #[default]
116    Ground,
117    /// Floating in free space (zero-gravity mobs). The ring is measured in 3D.
118    Air,
119}
120
121/// Distance band around a player in which a rule spawns mobs.
122#[derive(Clone, Copy, Debug, PartialEq)]
123pub struct SpawnRing {
124    /// Closest a mob spawns to the player.
125    pub min: f32,
126    /// Farthest a mob spawns from the player. Also the radius in which live
127    /// mobs count toward [`SpawnRule::cap`].
128    pub max: f32,
129}
130
131impl SpawnRing {
132    /// Creates a ring. Negative and `NaN` distances become `0`, and `max` is
133    /// raised to `min` if it is smaller. An infinite `max` means "as far as
134    /// the kind's despawn distance allows".
135    pub fn new(min: f32, max: f32) -> Self {
136        let clean = |d: f32| if d.is_nan() { 0.0 } else { d.max(0.0) };
137        let min = clean(min).min(f32::MAX);
138        Self {
139            min,
140            max: clean(max).max(min),
141        }
142    }
143}
144
145impl Default for SpawnRing {
146    /// `[12, 32]`: out of arm's reach, well inside the default despawn distance.
147    fn default() -> Self {
148        Self {
149            min: 12.0,
150            max: 32.0,
151        }
152    }
153}
154
155/// Candidate spawn handed to a [`SpawnRule::zone`] predicate.
156#[derive(Clone, Copy, Debug)]
157pub struct SpawnContext<'a> {
158    /// Where the mob would spawn (its centre).
159    pub position: Vec3,
160    /// Position of the player the mob would spawn around.
161    pub player_position: Vec3,
162    /// Current time of day, or `None` without a day cycle.
163    pub time_of_day: Option<f32>,
164    /// Kind that would be spawned.
165    pub kind: &'a MobKind,
166}
167
168/// Predicate deciding whether a candidate position is inside a rule's zone.
169pub type SpawnZone = Arc<dyn Fn(&SpawnContext<'_>) -> bool + Send + Sync>;
170
171/// One spawning rule: which kind appears, where, when and how many.
172///
173/// Built with chained setters:
174///
175/// ```
176/// use voxel_framework::mobs::{SpawnRule, TimeWindow};
177///
178/// let rule = SpawnRule::new("night_slime")
179///     .time(TimeWindow::Night)
180///     .ring(12.0, 32.0)
181///     .cap(6)
182///     .zone(|ctx| ctx.position.y < 80.0)
183///     .despawn_outside_window(true);
184/// assert_eq!(rule.cap, 6);
185/// ```
186#[derive(Clone)]
187pub struct SpawnRule {
188    /// Kind to spawn; must be registered in [`MobRegistry`].
189    pub kind: MobKind,
190    /// Relative chance against other rules that apply. **Default: `1.0`.**
191    pub weight: f32,
192    /// Distance band around the player. **Default: `[12, 32]`.** Capped
193    /// below the kind's `despawn_distance`; ground rules need a ring at least
194    /// 1.5 units wide.
195    pub ring: SpawnRing,
196    /// Part of the day in which the rule applies. **Default: `Any`.**
197    pub time: TimeWindow,
198    /// Ground or free-space placement. **Default: `Ground`.**
199    pub placement: SpawnPlacement,
200    /// Most live mobs of this kind allowed within `ring.max` of one player.
201    /// **Default: `4`.**
202    pub cap: usize,
203    /// Optional extra condition on the candidate position (the hook for
204    /// biomes or regions). **Default: none.**
205    pub zone: Option<SpawnZone>,
206    /// Despawn mobs spawned by this rule once `time` stops applying.
207    /// **Default: `false`.**
208    pub despawn_outside_window: bool,
209}
210
211impl SpawnRule {
212    /// Creates a rule for `kind` with the defaults listed on each field.
213    pub fn new(kind: impl Into<MobKind>) -> Self {
214        Self {
215            kind: kind.into(),
216            weight: 1.0,
217            ring: SpawnRing::default(),
218            time: TimeWindow::Any,
219            placement: SpawnPlacement::Ground,
220            cap: 4,
221            zone: None,
222            despawn_outside_window: false,
223        }
224    }
225
226    /// Sets the relative weight.
227    pub fn weight(mut self, weight: f32) -> Self {
228        self.weight = weight;
229        self
230    }
231
232    /// Sets the distance band; see [`SpawnRing::new`].
233    pub fn ring(mut self, min: f32, max: f32) -> Self {
234        self.ring = SpawnRing::new(min, max);
235        self
236    }
237
238    /// Sets the time window.
239    pub fn time(mut self, time: TimeWindow) -> Self {
240        self.time = time;
241        self
242    }
243
244    /// Sets the placement.
245    pub fn placement(mut self, placement: SpawnPlacement) -> Self {
246        self.placement = placement;
247        self
248    }
249
250    /// Sets the per-player cap.
251    pub fn cap(mut self, cap: usize) -> Self {
252        self.cap = cap;
253        self
254    }
255
256    /// Sets the zone predicate.
257    pub fn zone(
258        mut self,
259        zone: impl Fn(&SpawnContext<'_>) -> bool + Send + Sync + 'static,
260    ) -> Self {
261        self.zone = Some(Arc::new(zone));
262        self
263    }
264
265    /// Sets whether mobs despawn once the time window stops applying.
266    pub fn despawn_outside_window(mut self, despawn: bool) -> Self {
267        self.despawn_outside_window = despawn;
268        self
269    }
270}
271
272impl std::fmt::Debug for SpawnRule {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        f.debug_struct("SpawnRule")
275            .field("kind", &self.kind)
276            .field("weight", &self.weight)
277            .field("ring", &self.ring)
278            .field("time", &self.time)
279            .field("placement", &self.placement)
280            .field("cap", &self.cap)
281            .field("zone", &self.zone.as_ref().map(|_| "<predicate>"))
282            .field("despawn_outside_window", &self.despawn_outside_window)
283            .finish()
284    }
285}
286
287/// Spawn rules and pacing evaluated by [`MobSpawnerPlugin`].
288///
289/// Insert it before or after adding the plugin, or mutate it at runtime.
290#[derive(Resource, Clone, Debug)]
291pub struct MobSpawnRules {
292    /// Rules, evaluated independently for every player.
293    pub rules: Vec<SpawnRule>,
294    /// Seconds between evaluations; `<= 0` pauses spawning.
295    /// **Default: `2.0`.**
296    pub interval_secs: f32,
297    /// Candidate positions tried per player per evaluation.
298    /// **Default: `8`.**
299    pub attempts_per_player: u32,
300    /// Seed of the spawner's deterministic random sequence. **Default: `0`.**
301    pub seed: u32,
302}
303
304impl Default for MobSpawnRules {
305    fn default() -> Self {
306        Self {
307            rules: Vec::new(),
308            interval_secs: 2.0,
309            attempts_per_player: 8,
310            seed: 0,
311        }
312    }
313}
314
315impl MobSpawnRules {
316    /// Adds a rule (builder style).
317    pub fn with_rule(mut self, rule: SpawnRule) -> Self {
318        self.rules.push(rule);
319        self
320    }
321
322    /// Adds a rule.
323    pub fn add(&mut self, rule: SpawnRule) -> &mut Self {
324        self.rules.push(rule);
325        self
326    }
327}
328
329/// Marks a mob that is despawned once its time window stops applying.
330///
331/// Inserted by the spawner for rules with
332/// [`SpawnRule::despawn_outside_window`]. It stores the window itself, so
333/// editing the rules later does not change mobs that already exist.
334#[derive(Component, Clone, Copy, Debug, PartialEq)]
335pub struct DespawnOutsideWindow(pub TimeWindow);
336
337// ─── Pure decision logic ──────────────────────────────────────────────────────
338
339/// Deterministic random sequence keyed by seed, evaluation and player index.
340struct SpawnRng {
341    seed: u32,
342    evaluation: i32,
343    player: i32,
344    counter: i32,
345}
346
347impl SpawnRng {
348    fn new(seed: u32, evaluation: u32, player: usize) -> Self {
349        Self {
350            // Pre-mixed so the seed is not interchangeable with the
351            // evaluation number inside `hash3`.
352            seed: seed.wrapping_mul(0x9e37_79b9).rotate_left(16) ^ 0x85eb_ca6b,
353            evaluation: evaluation as i32,
354            player: player as i32,
355            counter: 0,
356        }
357    }
358
359    /// Next value in `[0, 1)`.
360    fn next_f32(&mut self) -> f32 {
361        let value = hash3(self.evaluation, self.player, self.counter, self.seed);
362        self.counter = self.counter.wrapping_add(1);
363        value.clamp(0.0, 1.0 - f32::EPSILON)
364    }
365}
366
367/// Picks an index with probability proportional to its weight.
368///
369/// `roll` is in `[0, 1)`. Non-positive and non-finite weights never win.
370fn pick_weighted(weights: &[f32], roll: f32) -> Option<usize> {
371    let usable = |w: f32| w.is_finite() && w > 0.0;
372    let total: f32 = weights.iter().copied().filter(|w| usable(*w)).sum();
373    if !total.is_finite() || total <= 0.0 {
374        return None;
375    }
376    let target = roll.clamp(0.0, 1.0) * total;
377    let mut acc = 0.0;
378    let mut last = None;
379    for (index, &weight) in weights.iter().enumerate() {
380        if !usable(weight) {
381            continue;
382        }
383        acc += weight;
384        last = Some(index);
385        if target < acc {
386            return last;
387        }
388    }
389    // Float rounding left `target` at the very end of the range.
390    last
391}
392
393/// Caps `ring` below the distance at which the kind despawns. Returns `None`
394/// when no usable ring is left: nothing inside the cap, an unbounded ring, or
395/// a ground ring too thin to contain a voxel column centre.
396fn effective_ring(
397    ring: SpawnRing,
398    placement: SpawnPlacement,
399    despawn_distance: f32,
400) -> Option<SpawnRing> {
401    let limit = despawn_distance * DESPAWN_MARGIN;
402    let max = if limit.is_nan() {
403        ring.max
404    } else {
405        ring.max.min(limit)
406    };
407    let min_width = match placement {
408        SpawnPlacement::Ground => MIN_GROUND_RING_WIDTH,
409        SpawnPlacement::Air => 0.0,
410    };
411    (max.is_finite() && ring.min <= max && max - ring.min >= min_width)
412        .then_some(SpawnRing { min: ring.min, max })
413}
414
415/// Weight of every rule for one player: the rule's weight when it is
416/// eligible, `0.0` otherwise.
417fn rule_weights(
418    rules: &[SpawnRule],
419    registry: &MobRegistry,
420    time_of_day: Option<f32>,
421    player_position: Vec3,
422    live_mobs: &[(MobKind, Vec3)],
423) -> Vec<f32> {
424    rules
425        .iter()
426        .map(|rule| {
427            if !rule.time.contains(time_of_day) {
428                return 0.0;
429            }
430            let Some(ring) = registry.get(&rule.kind).and_then(|config| {
431                effective_ring(rule.ring, rule.placement, config.despawn_distance)
432            }) else {
433                return 0.0;
434            };
435            let nearby = live_mobs
436                .iter()
437                .filter(|(kind, position)| {
438                    *kind == rule.kind && position.distance(player_position) <= ring.max
439                })
440                .count();
441            if nearby < rule.cap { rule.weight } else { 0.0 }
442        })
443        .collect()
444}
445
446/// Random offset from the player inside `ring`, uniform over the ring's area
447/// (ground) or volume (air).
448fn candidate_offset(ring: SpawnRing, placement: SpawnPlacement, rng: &mut SpawnRng) -> Vec3 {
449    let angle = rng.next_f32() * std::f32::consts::TAU;
450    let t = rng.next_f32();
451    match placement {
452        SpawnPlacement::Ground => {
453            let (min, max) = (ring.min * ring.min, ring.max * ring.max);
454            let distance = (min + (max - min) * t).sqrt();
455            Vec3::new(angle.cos() * distance, 0.0, angle.sin() * distance)
456        }
457        SpawnPlacement::Air => {
458            let (min, max) = (ring.min.powi(3), ring.max.powi(3));
459            let distance = (min + (max - min) * t).cbrt();
460            let y = rng.next_f32() * 2.0 - 1.0;
461            let horizontal = (1.0 - y * y).max(0.0).sqrt();
462            Vec3::new(angle.cos() * horizontal, y, angle.sin() * horizontal) * distance
463        }
464    }
465}
466
467/// Finds where a mob can stand in the voxel column containing `(x, z)`.
468///
469/// Searches outward from `near_y` and returns the centre of a mob resting on
470/// the nearest surface: solid voxel below, two non-solid voxels above, all
471/// loaded. `solid` returns `None` for voxels in unloaded chunks.
472fn find_ground_spawn(
473    x: f32,
474    z: f32,
475    near_y: f32,
476    solid: impl Fn(IVec3) -> Option<bool>,
477) -> Option<Vec3> {
478    if !(x.is_finite() && z.is_finite() && near_y.is_finite()) {
479        return None;
480    }
481    let (vx, vz, y0) = (x.floor() as i32, z.floor() as i32, near_y.floor() as i32);
482    let stands_at = |y: i32| {
483        solid(IVec3::new(vx, y - 1, vz)) == Some(true)
484            && solid(IVec3::new(vx, y, vz)) == Some(false)
485            && solid(IVec3::new(vx, y + 1, vz)) == Some(false)
486    };
487    (0..=GROUND_SEARCH_RANGE)
488        .flat_map(|d| [y0.saturating_add(d), y0.saturating_sub(d)])
489        .find(|&y| stands_at(y))
490        .map(|y| {
491            // Column centre keeps the capsule clear of neighbouring walls.
492            Vec3::new(
493                vx as f32 + 0.5,
494                y as f32 + MOB_RADIUS + MOB_HALF_HEIGHT + SPAWN_CLEARANCE,
495                vz as f32 + 0.5,
496            )
497        })
498}
499
500/// Returns `true` when every voxel touched by a mob capsule centred at
501/// `position` is loaded and not solid.
502fn air_spawn_clear(position: Vec3, solid: impl Fn(IVec3) -> Option<bool>) -> bool {
503    if !position.is_finite() {
504        return false;
505    }
506    let extent = Vec3::new(MOB_RADIUS, MOB_HALF_HEIGHT + MOB_RADIUS, MOB_RADIUS);
507    let min = (position - extent).floor().as_ivec3();
508    let max = (position + extent).floor().as_ivec3();
509    (min.x..=max.x).all(|x| {
510        (min.y..=max.y).all(|y| (min.z..=max.z).all(|z| solid(IVec3::new(x, y, z)) == Some(false)))
511    })
512}
513
514/// Tries up to `attempts` candidates and returns the first valid spawn
515/// position for `rule` around `player_position`.
516fn find_spawn_position(
517    rule: &SpawnRule,
518    ring: SpawnRing,
519    player_position: Vec3,
520    time_of_day: Option<f32>,
521    attempts: u32,
522    rng: &mut SpawnRng,
523    solid: impl Fn(IVec3) -> Option<bool>,
524) -> Option<Vec3> {
525    (0..attempts).find_map(|_| {
526        let candidate = player_position + candidate_offset(ring, rule.placement, rng);
527        let position = match rule.placement {
528            SpawnPlacement::Ground => {
529                let position =
530                    find_ground_spawn(candidate.x, candidate.z, player_position.y, &solid)?;
531                // Snapping to the column centre can leave the ring, and the
532                // surface can be far above or below the player. Keeping the
533                // 3D distance inside `max` means the mob counts toward the
534                // cap and is not despawned by distance right away.
535                let horizontal = position.xz().distance(player_position.xz());
536                let inside =
537                    horizontal >= ring.min && position.distance(player_position) <= ring.max;
538                inside.then_some(position)?
539            }
540            SpawnPlacement::Air => air_spawn_clear(candidate, &solid).then_some(candidate)?,
541        };
542        let context = SpawnContext {
543            position,
544            player_position,
545            time_of_day,
546            kind: &rule.kind,
547        };
548        rule.zone
549            .as_ref()
550            .is_none_or(|zone| zone(&context))
551            .then_some(position)
552    })
553}
554
555// ─── Systems ──────────────────────────────────────────────────────────────────
556
557/// Pacing state of the spawner.
558#[derive(Resource, Default)]
559struct MobSpawnerState {
560    elapsed: f32,
561    evaluations: u32,
562}
563
564#[allow(clippy::too_many_arguments)]
565fn mob_spawner_system<V: VoxelType>(
566    time: Res<Time>,
567    rules: Res<MobSpawnRules>,
568    registry: Res<MobRegistry>,
569    mut state: ResMut<MobSpawnerState>,
570    day_cycle: Option<Res<DayCycleConfig>>,
571    players: Query<(Entity, &Transform), With<Player>>,
572    mobs: Query<(&MobKind, &Transform)>,
573    manager: Res<ChunkManager>,
574    chunks: Query<&Chunk<V>>,
575    mut commands: Commands,
576    mut meshes: ResMut<Assets<Mesh>>,
577    mut materials: ResMut<Assets<StandardMaterial>>,
578) {
579    let interval = rules.interval_secs;
580    if !(interval.is_finite() && interval > 0.0) || rules.rules.is_empty() {
581        return;
582    }
583    state.elapsed += time.delta_secs();
584    if state.elapsed < interval {
585        return;
586    }
587    // One evaluation per interval, even after a long frame.
588    state.elapsed %= interval;
589    state.evaluations = state.evaluations.wrapping_add(1);
590
591    let time_of_day = day_cycle.map(|day| day.time_of_day);
592    let solid = |voxel: IVec3| {
593        get_voxel_at::<V>(voxel.as_vec3() + Vec3::splat(0.5), &manager, &chunks)
594            .map(|v| v.is_solid())
595    };
596
597    // Stable player order keeps the random sequence reproducible.
598    let mut player_positions: Vec<(Entity, Vec3)> = players
599        .iter()
600        .map(|(entity, transform)| (entity, transform.translation))
601        .collect();
602    player_positions.sort_by_key(|(entity, _)| *entity);
603
604    let mut live_mobs: Vec<(MobKind, Vec3)> = mobs
605        .iter()
606        .map(|(kind, transform)| (kind.clone(), transform.translation))
607        .collect();
608
609    for (index, (_, player_position)) in player_positions.into_iter().enumerate() {
610        let mut rng = SpawnRng::new(rules.seed, state.evaluations, index);
611        let weights = rule_weights(
612            &rules.rules,
613            &registry,
614            time_of_day,
615            player_position,
616            &live_mobs,
617        );
618        let Some(rule) = pick_weighted(&weights, rng.next_f32()).map(|i| &rules.rules[i]) else {
619            continue;
620        };
621        // Eligibility already proved the kind is registered and the ring valid.
622        let Some(ring) = registry
623            .get(&rule.kind)
624            .and_then(|config| effective_ring(rule.ring, rule.placement, config.despawn_distance))
625        else {
626            continue;
627        };
628        let Some(position) = find_spawn_position(
629            rule,
630            ring,
631            player_position,
632            time_of_day,
633            rules.attempts_per_player,
634            &mut rng,
635            solid,
636        ) else {
637            continue;
638        };
639        let Some(entity) = spawn_mob_kind(
640            &rule.kind,
641            &registry,
642            position,
643            &mut commands,
644            &mut meshes,
645            &mut materials,
646        ) else {
647            continue;
648        };
649        if rule.despawn_outside_window {
650            commands
651                .entity(entity)
652                .insert(DespawnOutsideWindow(rule.time));
653        }
654        // Count it right away so the next player sees the updated total.
655        live_mobs.push((rule.kind.clone(), position));
656    }
657}
658
659fn mob_window_despawn_system(
660    day_cycle: Option<Res<DayCycleConfig>>,
661    mobs: Query<(Entity, &DespawnOutsideWindow)>,
662    mut commands: Commands,
663) {
664    // Without a readable clock nothing can be "outside" its window.
665    let Some(time_of_day) = day_cycle
666        .map(|day| day.time_of_day)
667        .filter(|time| time.is_finite())
668    else {
669        return;
670    };
671    for (entity, window) in mobs.iter() {
672        if !window.0.contains(Some(time_of_day)) {
673            // Another system may despawn the same mob this frame.
674            commands.entity(entity).try_despawn();
675        }
676    }
677}
678
679// ─── Plugin ───────────────────────────────────────────────────────────────────
680
681/// Spawns registered mob kinds around players according to [`MobSpawnRules`].
682///
683/// Add it next to [`MobPlugin`](super::MobPlugin) for the same voxel type,
684/// register kinds in [`MobRegistry`] and insert a [`MobSpawnRules`] resource.
685///
686/// - It relies on [`ChunkManager`] and `Time` (the core voxel plugins and
687///   Bevy's time plugin). Without `Assets<Mesh>` and
688///   `Assets<StandardMaterial>` (headless apps) the spawner stays idle.
689/// - `Day`, `Night` and `Range` rules read [`DayCycleConfig`]; without
690///   [`DayCyclePlugin`](crate::world::DayCyclePlugin) only
691///   [`TimeWindow::Any`] rules ever apply.
692/// - Every [`Player`] gets its own spawns, and mobs despawn by distance to
693///   the nearest player. Mob AI still assumes a single player.
694///
695/// ```no_run
696/// use bevy::prelude::*;
697/// use voxel_framework::VoxelPlugin;
698/// use voxel_framework::mobs::{
699///     MobConfig, MobPlugin, MobRegistry, MobSpawnRules, MobSpawnerPlugin, SpawnRule, TimeWindow,
700/// };
701/// use voxel_framework::voxel::DefaultTerrainVoxel;
702/// use voxel_framework::world::DayCyclePlugin;
703///
704/// let mut registry = MobRegistry::default();
705/// registry.register("slime", MobConfig::default());
706/// registry
707///     .register_variant("night_slime", "slime", |config| config.chase_speed = 5.0)
708///     .unwrap();
709///
710/// let rules = MobSpawnRules::default()
711///     .with_rule(SpawnRule::new("slime").time(TimeWindow::Day).cap(3))
712///     .with_rule(
713///         SpawnRule::new("night_slime")
714///             .time(TimeWindow::Night)
715///             .ring(12.0, 32.0)
716///             .cap(6)
717///             .despawn_outside_window(true),
718///     );
719///
720/// App::new()
721///     .add_plugins(DefaultPlugins)
722///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
723///     .add_plugins(DayCyclePlugin)
724///     .add_plugins(MobPlugin::<DefaultTerrainVoxel>::new())
725///     .add_plugins(MobSpawnerPlugin::<DefaultTerrainVoxel>::new())
726///     .insert_resource(registry)
727///     .insert_resource(rules)
728///     .run();
729/// ```
730pub struct MobSpawnerPlugin<V: VoxelType> {
731    _m: PhantomData<V>,
732}
733
734impl<V: VoxelType> MobSpawnerPlugin<V> {
735    /// Creates the plugin.
736    pub fn new() -> Self {
737        Self { _m: PhantomData }
738    }
739}
740
741impl<V: VoxelType> Default for MobSpawnerPlugin<V> {
742    fn default() -> Self {
743        Self::new()
744    }
745}
746
747impl<V: VoxelType> Plugin for MobSpawnerPlugin<V> {
748    fn build(&self, app: &mut App) {
749        app.init_resource::<MobRegistry>()
750            .init_resource::<MobSpawnRules>()
751            .init_resource::<MobSpawnerState>()
752            .add_systems(
753                Update,
754                (
755                    mob_spawner_system::<V>.run_if(
756                        resource_exists::<Assets<Mesh>>
757                            .and(resource_exists::<Assets<StandardMaterial>>),
758                    ),
759                    mob_window_despawn_system,
760                ),
761            );
762    }
763}
764
765// ─── Tests ────────────────────────────────────────────────────────────────────
766
767#[cfg(test)]
768mod tests {
769    use super::*;
770    use crate::mobs::MobConfig;
771    use crate::test_support::{filled_chunk, world_with_chunks};
772    use crate::voxel::DefaultVoxel;
773    use bevy::ecs::system::RunSystemOnce;
774    use std::time::Duration;
775
776    /// Flat world: everything below `y = 0` is solid, everything loaded.
777    fn flat(voxel: IVec3) -> Option<bool> {
778        Some(voxel.y < 0)
779    }
780
781    const REST: f32 = MOB_RADIUS + MOB_HALF_HEIGHT + SPAWN_CLEARANCE;
782
783    fn registry() -> MobRegistry {
784        let mut registry = MobRegistry::default();
785        registry.register("slime", MobConfig::default());
786        registry.register("bat", MobConfig::default());
787        registry
788    }
789
790    // ── Time windows ──────────────────────────────────────────────────────
791
792    #[test]
793    fn day_and_night_split_at_dawn_and_dusk() {
794        for (time, is_day) in [(0.0, false), (0.24, false), (0.25, true), (0.5, true)] {
795            assert_eq!(TimeWindow::Day.contains(Some(time)), is_day, "t={time}");
796            assert_eq!(TimeWindow::Night.contains(Some(time)), !is_day, "t={time}");
797        }
798        assert!(!TimeWindow::Day.contains(Some(0.75)));
799        assert!(TimeWindow::Night.contains(Some(0.99)));
800    }
801
802    #[test]
803    fn range_wraps_across_midnight() {
804        let late = TimeWindow::Range {
805            start: 0.9,
806            end: 0.1,
807        };
808        assert!(late.contains(Some(0.95)));
809        assert!(late.contains(Some(0.05)));
810        assert!(late.contains(Some(0.9)));
811        assert!(!late.contains(Some(0.1)));
812        assert!(!late.contains(Some(0.5)));
813
814        let morning = TimeWindow::Range {
815            start: 0.2,
816            end: 0.4,
817        };
818        assert!(morning.contains(Some(0.3)));
819        assert!(!morning.contains(Some(0.4)));
820        assert!(
821            !TimeWindow::Range {
822                start: 0.3,
823                end: 0.3
824            }
825            .contains(Some(0.3))
826        );
827    }
828
829    #[test]
830    fn range_bounds_are_wrapped_into_one_day() {
831        let range = |start, end| TimeWindow::Range { start, end };
832        // Written without wrapping, meaning the same as 0.9..0.1.
833        for window in [range(0.9, 1.1), range(-0.1, 0.1)] {
834            assert!(window.contains(Some(0.95)), "{window:?}");
835            assert!(window.contains(Some(0.05)), "{window:?}");
836            assert!(!window.contains(Some(0.5)), "{window:?}");
837        }
838        // A span of a whole day or more always applies.
839        for time in [0.0, 0.5, 0.99] {
840            assert!(range(0.0, 1.0).contains(Some(time)));
841            assert!(range(0.2, 1.7).contains(Some(time)));
842        }
843        // Dusk to midnight keeps working when `end` is written as 1.0.
844        assert!(range(0.75, 1.0).contains(Some(0.9)));
845        assert!(!range(0.75, 1.0).contains(Some(0.1)));
846        // A clock a hair below zero is midnight, not "1.0".
847        assert!(range(0.0, 0.25).contains(Some(-1e-9)));
848        for window in [range(f32::NAN, 0.5), range(0.1, f32::INFINITY)] {
849            assert!(!window.contains(Some(0.2)), "{window:?}");
850        }
851    }
852
853    #[test]
854    fn only_any_applies_without_a_usable_clock() {
855        for time in [None, Some(f32::NAN), Some(f32::INFINITY)] {
856            assert!(TimeWindow::Any.contains(time));
857            assert!(!TimeWindow::Day.contains(time));
858            assert!(!TimeWindow::Night.contains(time));
859        }
860        // Out-of-range clocks wrap like the day cycle does.
861        assert!(TimeWindow::Day.contains(Some(1.5)));
862        assert!(TimeWindow::Night.contains(Some(-0.1)));
863    }
864
865    // ── Weighted choice ───────────────────────────────────────────────────
866
867    #[test]
868    fn pick_weighted_follows_the_weights() {
869        let weights = [1.0, 0.0, 3.0];
870        assert_eq!(pick_weighted(&weights, 0.0), Some(0));
871        assert_eq!(pick_weighted(&weights, 0.24), Some(0));
872        assert_eq!(pick_weighted(&weights, 0.25), Some(2));
873        assert_eq!(pick_weighted(&weights, 0.999), Some(2));
874        assert_eq!(pick_weighted(&weights, 1.0), Some(2));
875    }
876
877    #[test]
878    fn pick_weighted_ignores_unusable_weights() {
879        assert_eq!(pick_weighted(&[], 0.5), None);
880        assert_eq!(pick_weighted(&[0.0, -2.0, f32::NAN], 0.5), None);
881        assert_eq!(
882            pick_weighted(&[f32::NAN, 2.0, f32::INFINITY, -1.0], 0.9),
883            Some(1)
884        );
885    }
886
887    #[test]
888    fn rng_is_deterministic_and_varies_by_key() {
889        let draw = |seed, evaluation, player| {
890            let mut rng = SpawnRng::new(seed, evaluation, player);
891            [rng.next_f32(), rng.next_f32(), rng.next_f32()]
892        };
893        assert_eq!(draw(7, 3, 0), draw(7, 3, 0));
894        assert_ne!(draw(7, 3, 0), draw(8, 3, 0));
895        assert_ne!(draw(7, 3, 0), draw(7, 4, 0));
896        assert_ne!(draw(7, 3, 0), draw(7, 3, 1));
897        assert!(draw(7, 3, 0).iter().all(|v| (0.0..1.0).contains(v)));
898    }
899
900    // ── Eligibility ───────────────────────────────────────────────────────
901
902    #[test]
903    fn rule_is_ineligible_outside_its_time_window() {
904        let rules = [SpawnRule::new("slime").time(TimeWindow::Night)];
905        let weights = |time| rule_weights(&rules, &registry(), time, Vec3::ZERO, &[]);
906        assert_eq!(weights(Some(0.5)), [0.0]);
907        assert_eq!(weights(Some(0.9)), [1.0]);
908        assert_eq!(weights(None), [0.0]);
909    }
910
911    #[test]
912    fn rule_is_ineligible_for_an_unregistered_kind() {
913        let rules = [SpawnRule::new("ghost"), SpawnRule::new("slime").weight(2.5)];
914        let weights = rule_weights(&rules, &registry(), None, Vec3::ZERO, &[]);
915        assert_eq!(weights, [0.0, 2.5]);
916    }
917
918    #[test]
919    fn cap_counts_only_same_kind_mobs_inside_the_ring() {
920        let rules = [SpawnRule::new("slime").ring(4.0, 20.0).cap(2)];
921        let player = Vec3::new(100.0, 0.0, 0.0);
922        let near = |kind: &str, dx: f32| (MobKind::new(kind), player + Vec3::X * dx);
923        let weights =
924            |mobs: &[(MobKind, Vec3)]| rule_weights(&rules, &registry(), None, player, mobs)[0];
925
926        assert_eq!(weights(&[near("slime", 5.0)]), 1.0);
927        assert_eq!(weights(&[near("slime", 5.0), near("slime", 19.0)]), 0.0);
928        // Other kinds and far-away mobs do not count.
929        assert_eq!(weights(&[near("slime", 5.0), near("bat", 6.0)]), 1.0);
930        assert_eq!(weights(&[near("slime", 5.0), near("slime", 25.0)]), 1.0);
931    }
932
933    #[test]
934    fn ring_is_capped_below_the_despawn_distance() {
935        let ground = |min, max, despawn| {
936            effective_ring(SpawnRing::new(min, max), SpawnPlacement::Ground, despawn)
937        };
938        assert_eq!(
939            ground(10.0, 100.0, 50.0),
940            Some(SpawnRing {
941                min: 10.0,
942                max: 45.0
943            })
944        );
945        assert_eq!(ground(10.0, 30.0, 50.0), Some(SpawnRing::new(10.0, 30.0)));
946        assert_eq!(ground(45.0, 100.0, 50.0), None);
947        // "As far as allowed": an infinite max takes the despawn cap.
948        assert_eq!(
949            ground(12.0, f32::INFINITY, 64.0),
950            Some(SpawnRing {
951                min: 12.0,
952                max: 57.6
953            })
954        );
955        // Nothing bounds the ring.
956        assert_eq!(ground(12.0, f32::INFINITY, f32::INFINITY), None);
957        assert_eq!(
958            ground(12.0, 30.0, f32::NAN),
959            Some(SpawnRing::new(12.0, 30.0))
960        );
961
962        let mut registry = MobRegistry::default();
963        registry.register(
964            "slime",
965            MobConfig {
966                despawn_distance: 10.0,
967                ..Default::default()
968            },
969        );
970        let rules = [SpawnRule::new("slime").ring(12.0, 32.0)];
971        assert_eq!(
972            rule_weights(&rules, &registry, None, Vec3::ZERO, &[]),
973            [0.0]
974        );
975    }
976
977    #[test]
978    fn ground_rules_need_a_ring_wide_enough_for_a_column_centre() {
979        let rules = [
980            SpawnRule::new("slime").ring(12.0, 12.0),
981            SpawnRule::new("slime").ring(12.0, 13.5),
982            SpawnRule::new("slime")
983                .ring(12.0, 12.0)
984                .placement(SpawnPlacement::Air),
985        ];
986        assert_eq!(
987            rule_weights(&rules, &registry(), None, Vec3::ZERO, &[]),
988            [0.0, 1.0, 1.0]
989        );
990    }
991
992    #[test]
993    fn spawn_ring_sanitizes_its_bounds() {
994        assert_eq!(
995            SpawnRing::new(-3.0, f32::NAN),
996            SpawnRing { min: 0.0, max: 0.0 }
997        );
998        assert_eq!(SpawnRing::new(8.0, 2.0), SpawnRing { min: 8.0, max: 8.0 });
999        assert_eq!(SpawnRing::new(8.0, f32::INFINITY).max, f32::INFINITY);
1000    }
1001
1002    // ── Positions ─────────────────────────────────────────────────────────
1003
1004    #[test]
1005    fn candidate_offsets_stay_inside_the_ring() {
1006        let ring = SpawnRing::new(8.0, 16.0);
1007        for evaluation in 0..200 {
1008            let mut rng = SpawnRng::new(1, evaluation, 0);
1009            let ground = candidate_offset(ring, SpawnPlacement::Ground, &mut rng);
1010            assert_eq!(ground.y, 0.0);
1011            let d = ground.length();
1012            assert!((8.0 - 1e-3..=16.0 + 1e-3).contains(&d), "ground d={d}");
1013
1014            let air = candidate_offset(ring, SpawnPlacement::Air, &mut rng);
1015            let d = air.length();
1016            assert!((8.0 - 1e-3..=16.0 + 1e-3).contains(&d), "air d={d}");
1017        }
1018    }
1019
1020    #[test]
1021    fn ground_spawn_rests_on_the_floor_at_the_column_centre() {
1022        let position = find_ground_spawn(3.9, -2.1, 5.0, flat).unwrap();
1023        assert_eq!(position, Vec3::new(3.5, REST, -2.5));
1024    }
1025
1026    #[test]
1027    fn ground_spawn_needs_loaded_terrain_and_headroom() {
1028        // Nothing loaded.
1029        assert_eq!(find_ground_spawn(0.5, 0.5, 2.0, |_| None), None);
1030        // Floor loaded but the air above it is not.
1031        let floor_only = |v: IVec3| (v.y < 0).then_some(true);
1032        assert_eq!(find_ground_spawn(0.5, 0.5, 2.0, floor_only), None);
1033        // Only one free voxel above the floor.
1034        let low_ceiling = |v: IVec3| Some(v.y != 0);
1035        assert_eq!(find_ground_spawn(0.5, 0.5, 0.0, low_ceiling), None);
1036        // No surface within the search range.
1037        assert_eq!(find_ground_spawn(0.5, 0.5, 40.0, flat), None);
1038        assert_eq!(find_ground_spawn(f32::NAN, 0.5, 0.0, flat), None);
1039    }
1040
1041    #[test]
1042    fn ground_spawn_prefers_the_surface_nearest_to_the_player() {
1043        // Cave: floor below y = 0, open for y in 0..3, rock for 3..10, open sky above.
1044        let cave = |v: IVec3| Some(v.y < 0 || (3..10).contains(&v.y));
1045        let in_cave = find_ground_spawn(0.5, 0.5, 1.0, cave).unwrap();
1046        assert!((in_cave.y - REST).abs() < 1e-6, "y={}", in_cave.y);
1047        let on_top = find_ground_spawn(0.5, 0.5, 11.0, cave).unwrap();
1048        assert!((on_top.y - (10.0 + REST)).abs() < 1e-6, "y={}", on_top.y);
1049    }
1050
1051    #[test]
1052    fn air_spawn_needs_a_free_loaded_capsule() {
1053        assert!(air_spawn_clear(Vec3::new(0.5, 5.0, 0.5), flat));
1054        // Feet inside the floor.
1055        assert!(!air_spawn_clear(Vec3::new(0.5, 0.5, 0.5), flat));
1056        assert!(!air_spawn_clear(Vec3::new(0.5, 5.0, 0.5), |_| None));
1057        assert!(!air_spawn_clear(Vec3::splat(f32::NAN), flat));
1058    }
1059
1060    #[test]
1061    fn spawn_position_respects_ring_and_zone() {
1062        let rule = SpawnRule::new("slime").ring(8.0, 16.0);
1063        let player = Vec3::new(40.2, 1.0, -7.7);
1064        for evaluation in 0..100 {
1065            let mut rng = SpawnRng::new(3, evaluation, 0);
1066            if let Some(position) =
1067                find_spawn_position(&rule, rule.ring, player, None, 8, &mut rng, flat)
1068            {
1069                let d = position.xz().distance(player.xz());
1070                assert!((8.0..=16.0).contains(&d), "d={d}");
1071                assert!((position.y - REST).abs() < 1e-6);
1072            }
1073        }
1074
1075        let east_only = rule
1076            .clone()
1077            .zone(|ctx| ctx.position.x > ctx.player_position.x);
1078        let mut found = 0;
1079        for evaluation in 0..100 {
1080            let mut rng = SpawnRng::new(3, evaluation, 0);
1081            if let Some(position) =
1082                find_spawn_position(&east_only, rule.ring, player, None, 8, &mut rng, flat)
1083            {
1084                assert!(position.x > player.x);
1085                found += 1;
1086            }
1087        }
1088        assert!(found > 50, "zone rejected too much: {found}");
1089
1090        let nowhere = rule.clone().zone(|_| false);
1091        let mut rng = SpawnRng::new(3, 0, 0);
1092        assert_eq!(
1093            find_spawn_position(&nowhere, rule.ring, player, None, 8, &mut rng, flat),
1094            None
1095        );
1096    }
1097
1098    #[test]
1099    fn ground_spawn_far_below_the_player_is_rejected() {
1100        // Player 14 units above the floor: a ground mob inside the horizontal
1101        // ring would be farther than `max` in 3D, so it would dodge the cap.
1102        let rule = SpawnRule::new("slime").ring(2.0, 6.0);
1103        let player = Vec3::new(0.5, 14.0, 0.5);
1104        for evaluation in 0..50 {
1105            let mut rng = SpawnRng::new(3, evaluation, 0);
1106            assert_eq!(
1107                find_spawn_position(&rule, rule.ring, player, None, 8, &mut rng, flat),
1108                None
1109            );
1110        }
1111        // A wider ring still spawns, always within `max` in 3D.
1112        let wide = SpawnRule::new("slime").ring(2.0, 24.0);
1113        let mut found = 0;
1114        for evaluation in 0..50 {
1115            let mut rng = SpawnRng::new(3, evaluation, 0);
1116            if let Some(position) =
1117                find_spawn_position(&wide, wide.ring, player, None, 8, &mut rng, flat)
1118            {
1119                assert!(position.distance(player) <= 24.0);
1120                found += 1;
1121            }
1122        }
1123        assert!(found > 0);
1124    }
1125
1126    #[test]
1127    fn air_spawn_stays_in_the_ring_and_in_free_loaded_space() {
1128        let rule = SpawnRule::new("bat")
1129            .ring(8.0, 16.0)
1130            .placement(SpawnPlacement::Air);
1131        let player = Vec3::new(0.5, 30.0, 0.5);
1132        let mut found = 0;
1133        for evaluation in 0..100 {
1134            let mut rng = SpawnRng::new(9, evaluation, 0);
1135            if let Some(position) =
1136                find_spawn_position(&rule, rule.ring, player, None, 8, &mut rng, flat)
1137            {
1138                let d = position.distance(player);
1139                assert!((8.0 - 1e-3..=16.0 + 1e-3).contains(&d), "d={d}");
1140                assert!(air_spawn_clear(position, flat));
1141                found += 1;
1142            }
1143        }
1144        assert!(found > 0);
1145
1146        let mut rng = SpawnRng::new(9, 0, 0);
1147        assert_eq!(
1148            find_spawn_position(&rule, rule.ring, player, None, 8, &mut rng, |_| None),
1149            None,
1150            "nothing loaded"
1151        );
1152    }
1153
1154    #[test]
1155    fn same_inputs_give_the_same_spawn_position() {
1156        let rule = SpawnRule::new("slime").ring(8.0, 16.0);
1157        let find = |seed| {
1158            let mut rng = SpawnRng::new(seed, 5, 0);
1159            find_spawn_position(&rule, rule.ring, Vec3::ZERO, None, 8, &mut rng, flat)
1160        };
1161        assert_eq!(find(11), find(11));
1162        assert_ne!(find(11), find(12));
1163    }
1164
1165    // ── Systems ───────────────────────────────────────────────────────────
1166
1167    const FLOOR_TOP: f32 = 16.0;
1168
1169    /// Solid chunk with a loaded empty chunk above, plus everything the
1170    /// spawner system needs. One evaluation per [`evaluate`] call.
1171    fn spawner_world(rules: MobSpawnRules) -> World {
1172        let mut world = world_with_chunks([
1173            (IVec3::ZERO, filled_chunk(DefaultVoxel::Rock)),
1174            (IVec3::Y, Chunk::<DefaultVoxel>::new()),
1175        ]);
1176        world.insert_resource(Time::<()>::default());
1177        world.insert_resource(Assets::<Mesh>::default());
1178        world.insert_resource(Assets::<StandardMaterial>::default());
1179        world.insert_resource(MobSpawnerState::default());
1180        world.insert_resource(registry());
1181        world.insert_resource(rules);
1182        world
1183    }
1184
1185    fn spawn_player(world: &mut World, position: Vec3) -> Entity {
1186        world
1187            .spawn((Player::default(), Transform::from_translation(position)))
1188            .id()
1189    }
1190
1191    fn evaluate(world: &mut World, times: usize) {
1192        let interval = world.resource::<MobSpawnRules>().interval_secs;
1193        for _ in 0..times {
1194            world
1195                .resource_mut::<Time>()
1196                .advance_by(Duration::from_secs_f32(interval));
1197            world
1198                .run_system_once(mob_spawner_system::<DefaultVoxel>)
1199                .unwrap();
1200            world.run_system_once(mob_window_despawn_system).unwrap();
1201        }
1202    }
1203
1204    fn mobs_of(world: &mut World, kind: &str) -> Vec<Vec3> {
1205        let mut query = world.query::<(&MobKind, &Transform)>();
1206        query
1207            .iter(world)
1208            .filter(|(k, _)| k.as_str() == kind)
1209            .map(|(_, t)| t.translation)
1210            .collect()
1211    }
1212
1213    fn set_time(world: &mut World, time_of_day: f32) {
1214        world.insert_resource(DayCycleConfig {
1215            time_of_day,
1216            ..Default::default()
1217        });
1218    }
1219
1220    #[test]
1221    fn spawner_places_mobs_on_the_floor_inside_the_ring_up_to_the_cap() {
1222        let rules =
1223            MobSpawnRules::default().with_rule(SpawnRule::new("slime").ring(2.0, 6.0).cap(3));
1224        let mut world = spawner_world(rules);
1225        let player = Vec3::new(8.0, FLOOR_TOP + 1.0, 8.0);
1226        spawn_player(&mut world, player);
1227
1228        evaluate(&mut world, 1);
1229        assert_eq!(mobs_of(&mut world, "slime").len(), 1, "one per evaluation");
1230
1231        evaluate(&mut world, 20);
1232        let mobs = mobs_of(&mut world, "slime");
1233        assert_eq!(mobs.len(), 3, "cap reached and held");
1234        for position in mobs {
1235            let d = position.xz().distance(player.xz());
1236            assert!((2.0..=6.0).contains(&d), "d={d}");
1237            assert!((position.y - (FLOOR_TOP + REST)).abs() < 1e-5);
1238        }
1239    }
1240
1241    #[test]
1242    fn spawner_waits_for_the_interval() {
1243        let rules = MobSpawnRules::default().with_rule(SpawnRule::new("slime").ring(2.0, 6.0));
1244        let mut world = spawner_world(rules);
1245        spawn_player(&mut world, Vec3::new(8.0, FLOOR_TOP + 1.0, 8.0));
1246
1247        for _ in 0..3 {
1248            world
1249                .resource_mut::<Time>()
1250                .advance_by(Duration::from_secs_f32(0.5));
1251            world
1252                .run_system_once(mob_spawner_system::<DefaultVoxel>)
1253                .unwrap();
1254        }
1255        assert!(mobs_of(&mut world, "slime").is_empty(), "1.5 s < 2 s");
1256
1257        world
1258            .resource_mut::<Time>()
1259            .advance_by(Duration::from_secs_f32(0.6));
1260        world
1261            .run_system_once(mob_spawner_system::<DefaultVoxel>)
1262            .unwrap();
1263        assert_eq!(mobs_of(&mut world, "slime").len(), 1);
1264    }
1265
1266    #[test]
1267    fn spawner_follows_the_time_of_day() {
1268        let rules = MobSpawnRules::default()
1269            .with_rule(SpawnRule::new("slime").ring(2.0, 6.0).time(TimeWindow::Day))
1270            .with_rule(
1271                SpawnRule::new("bat")
1272                    .ring(2.0, 6.0)
1273                    .time(TimeWindow::Night)
1274                    .despawn_outside_window(true),
1275            );
1276        let mut world = spawner_world(rules);
1277        spawn_player(&mut world, Vec3::new(8.0, FLOOR_TOP + 1.0, 8.0));
1278
1279        // No day cycle: neither rule applies.
1280        evaluate(&mut world, 5);
1281        assert!(mobs_of(&mut world, "slime").is_empty());
1282        assert!(mobs_of(&mut world, "bat").is_empty());
1283
1284        set_time(&mut world, 0.9);
1285        evaluate(&mut world, 5);
1286        assert!(mobs_of(&mut world, "slime").is_empty());
1287        let bats = mobs_of(&mut world, "bat").len();
1288        assert!(bats > 0, "night rule spawns at night");
1289
1290        // Dawn: night mobs marked for it disappear, day mobs appear and stay.
1291        set_time(&mut world, 0.25);
1292        evaluate(&mut world, 5);
1293        assert!(mobs_of(&mut world, "bat").is_empty());
1294        let slimes = mobs_of(&mut world, "slime").len();
1295        assert!(slimes > 0);
1296
1297        set_time(&mut world, 0.9);
1298        evaluate(&mut world, 1);
1299        assert_eq!(
1300            mobs_of(&mut world, "slime").len(),
1301            slimes,
1302            "day mobs are not tied to their window"
1303        );
1304    }
1305
1306    #[test]
1307    fn spawner_serves_every_player() {
1308        let rules =
1309            MobSpawnRules::default().with_rule(SpawnRule::new("slime").ring(1.0, 2.5).cap(1));
1310        let mut world = spawner_world(rules);
1311        let a = Vec3::new(3.5, FLOOR_TOP + 1.0, 3.5);
1312        let b = Vec3::new(12.5, FLOOR_TOP + 1.0, 12.5);
1313        spawn_player(&mut world, a);
1314        spawn_player(&mut world, b);
1315
1316        evaluate(&mut world, 10);
1317
1318        let mobs = mobs_of(&mut world, "slime");
1319        assert_eq!(mobs.len(), 2, "one per player at cap 1");
1320        for player in [a, b] {
1321            assert!(
1322                mobs.iter().any(|m| m.xz().distance(player.xz()) <= 2.5),
1323                "no mob near {player}"
1324            );
1325        }
1326    }
1327
1328    #[test]
1329    fn spawner_is_deterministic_for_a_seed() {
1330        let run = |seed| {
1331            let mut rules = MobSpawnRules::default()
1332                .with_rule(SpawnRule::new("slime").ring(2.0, 6.0).cap(8))
1333                .with_rule(SpawnRule::new("bat").ring(2.0, 6.0).cap(8));
1334            rules.seed = seed;
1335            let mut world = spawner_world(rules);
1336            spawn_player(&mut world, Vec3::new(8.0, FLOOR_TOP + 1.0, 8.0));
1337            evaluate(&mut world, 6);
1338            let mut all = mobs_of(&mut world, "slime");
1339            all.extend(mobs_of(&mut world, "bat"));
1340            all.sort_by(|p, q| p.to_array().partial_cmp(&q.to_array()).unwrap());
1341            (mobs_of(&mut world, "slime").len(), all)
1342        };
1343        assert_eq!(run(42), run(42));
1344        assert_ne!(run(42), run(43));
1345    }
1346
1347    #[test]
1348    fn spawner_does_nothing_when_paused_or_without_players() {
1349        let rules = MobSpawnRules::default().with_rule(SpawnRule::new("slime").ring(2.0, 6.0));
1350        let mut world = spawner_world(rules);
1351        evaluate(&mut world, 5);
1352        assert!(mobs_of(&mut world, "slime").is_empty(), "no players");
1353
1354        spawn_player(&mut world, Vec3::new(8.0, FLOOR_TOP + 1.0, 8.0));
1355        world.resource_mut::<MobSpawnRules>().interval_secs = 0.0;
1356        for _ in 0..5 {
1357            world
1358                .resource_mut::<Time>()
1359                .advance_by(Duration::from_secs(5));
1360            world
1361                .run_system_once(mob_spawner_system::<DefaultVoxel>)
1362                .unwrap();
1363        }
1364        assert!(mobs_of(&mut world, "slime").is_empty(), "paused");
1365    }
1366
1367    #[test]
1368    fn cap_holds_while_the_player_hovers_above_the_ground() {
1369        let rules =
1370            MobSpawnRules::default().with_rule(SpawnRule::new("slime").ring(2.0, 9.0).cap(2));
1371        let mut world = spawner_world(rules);
1372        // 6 units above the floor: only part of the ring reaches the ground.
1373        spawn_player(&mut world, Vec3::new(8.0, FLOOR_TOP + 6.0, 8.0));
1374
1375        evaluate(&mut world, 40);
1376
1377        assert_eq!(mobs_of(&mut world, "slime").len(), 2);
1378    }
1379
1380    #[test]
1381    fn plugin_runs_in_an_app_and_idles_without_asset_stores() {
1382        let mut app = App::new();
1383        app.add_plugins(MinimalPlugins)
1384            .init_resource::<ChunkManager>()
1385            .add_plugins(MobSpawnerPlugin::<DefaultVoxel>::new())
1386            .insert_resource(
1387                MobSpawnRules::default().with_rule(SpawnRule::new("slime").ring(2.0, 6.0)),
1388            );
1389        // No `Assets<Mesh>`: the spawner must skip instead of panicking.
1390        app.update();
1391
1392        app.init_resource::<Assets<Mesh>>()
1393            .init_resource::<Assets<StandardMaterial>>();
1394        app.update();
1395    }
1396
1397    #[test]
1398    fn plugin_initializes_its_resources() {
1399        let mut app = App::new();
1400        app.add_plugins(MobSpawnerPlugin::<DefaultVoxel>::new());
1401        assert!(app.world().contains_resource::<MobSpawnRules>());
1402        assert!(app.world().contains_resource::<MobRegistry>());
1403        assert!(app.world().resource::<MobSpawnRules>().rules.is_empty());
1404    }
1405}