1use 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
25pub const DAY_START: f32 = 0.25;
27pub const DAY_END: f32 = 0.75;
29
30const GROUND_SEARCH_RANGE: i32 = 16;
32const SPAWN_CLEARANCE: f32 = 0.01;
34const DESPAWN_MARGIN: f32 = 0.9;
37const MIN_GROUND_RING_WIDTH: f32 = 1.5;
40
41#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub enum TimeWindow {
49 #[default]
51 Any,
52 Day,
54 Night,
56 Range {
61 start: f32,
63 end: f32,
65 },
66}
67
68impl TimeWindow {
69 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
102fn wrap_time(time: f32) -> f32 {
104 let wrapped = time.rem_euclid(1.0);
105 if wrapped >= 1.0 { 0.0 } else { wrapped }
107}
108
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
111pub enum SpawnPlacement {
112 #[default]
116 Ground,
117 Air,
119}
120
121#[derive(Clone, Copy, Debug, PartialEq)]
123pub struct SpawnRing {
124 pub min: f32,
126 pub max: f32,
129}
130
131impl SpawnRing {
132 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 fn default() -> Self {
148 Self {
149 min: 12.0,
150 max: 32.0,
151 }
152 }
153}
154
155#[derive(Clone, Copy, Debug)]
157pub struct SpawnContext<'a> {
158 pub position: Vec3,
160 pub player_position: Vec3,
162 pub time_of_day: Option<f32>,
164 pub kind: &'a MobKind,
166}
167
168pub type SpawnZone = Arc<dyn Fn(&SpawnContext<'_>) -> bool + Send + Sync>;
170
171#[derive(Clone)]
187pub struct SpawnRule {
188 pub kind: MobKind,
190 pub weight: f32,
192 pub ring: SpawnRing,
196 pub time: TimeWindow,
198 pub placement: SpawnPlacement,
200 pub cap: usize,
203 pub zone: Option<SpawnZone>,
206 pub despawn_outside_window: bool,
209}
210
211impl SpawnRule {
212 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 pub fn weight(mut self, weight: f32) -> Self {
228 self.weight = weight;
229 self
230 }
231
232 pub fn ring(mut self, min: f32, max: f32) -> Self {
234 self.ring = SpawnRing::new(min, max);
235 self
236 }
237
238 pub fn time(mut self, time: TimeWindow) -> Self {
240 self.time = time;
241 self
242 }
243
244 pub fn placement(mut self, placement: SpawnPlacement) -> Self {
246 self.placement = placement;
247 self
248 }
249
250 pub fn cap(mut self, cap: usize) -> Self {
252 self.cap = cap;
253 self
254 }
255
256 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 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#[derive(Resource, Clone, Debug)]
291pub struct MobSpawnRules {
292 pub rules: Vec<SpawnRule>,
294 pub interval_secs: f32,
297 pub attempts_per_player: u32,
300 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 pub fn with_rule(mut self, rule: SpawnRule) -> Self {
318 self.rules.push(rule);
319 self
320 }
321
322 pub fn add(&mut self, rule: SpawnRule) -> &mut Self {
324 self.rules.push(rule);
325 self
326 }
327}
328
329#[derive(Component, Clone, Copy, Debug, PartialEq)]
335pub struct DespawnOutsideWindow(pub TimeWindow);
336
337struct 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 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 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
367fn 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 last
391}
392
393fn 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
415fn 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
446fn 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
467fn 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 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
500fn 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
514fn 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 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#[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 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 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 ®istry,
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 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 ®istry,
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 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 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 commands.entity(entity).try_despawn();
675 }
676 }
677}
678
679pub struct MobSpawnerPlugin<V: VoxelType> {
731 _m: PhantomData<V>,
732}
733
734impl<V: VoxelType> MobSpawnerPlugin<V> {
735 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#[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 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 #[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 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 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 assert!(range(0.75, 1.0).contains(Some(0.9)));
845 assert!(!range(0.75, 1.0).contains(Some(0.1)));
846 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 assert!(TimeWindow::Day.contains(Some(1.5)));
862 assert!(TimeWindow::Night.contains(Some(-0.1)));
863 }
864
865 #[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 #[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, ®istry(), 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, ®istry(), 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, ®istry(), 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 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 assert_eq!(
949 ground(12.0, f32::INFINITY, 64.0),
950 Some(SpawnRing {
951 min: 12.0,
952 max: 57.6
953 })
954 );
955 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, ®istry, 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, ®istry(), 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 #[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 assert_eq!(find_ground_spawn(0.5, 0.5, 2.0, |_| None), None);
1030 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 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 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 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 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 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 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 const FLOOR_TOP: f32 = 16.0;
1168
1169 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 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 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 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 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}